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,80 @@
1
+ /**
2
+ * PdfViewer — the unified reader face of the rewrite.
3
+ *
4
+ * One component owns: zoom, scroll container, page painting per layer, and the
5
+ * mode layout (single / continuous / dual). Modes only choose which layers and
6
+ * columns are rendered; painting and geometry stay identical, which is what the
7
+ * old per-mode canvases kept getting wrong.
8
+ *
9
+ * This module is the extracted target: `client.js` will mount it once per
10
+ * reader and per side preview, then the legacy paint paths can be deleted.
11
+ *
12
+ * Layers:
13
+ * { kind: 'source', doc }
14
+ * { kind: 'translation', doc }
15
+ * { kind: 'masks', boxes } // reveal boxes over `translation`
16
+ * { kind: 'blocks', blocks } // debug block overlay
17
+ *
18
+ * Geometry rules (from docs/READER-REWRITE.md):
19
+ * - centered content uses `safe center`, so a zoomed page can still scroll to
20
+ * its left edge;
21
+ * - the overlay is ONE page-sized translation image clipped by a `clipPath` of
22
+ * rectangle subpaths per mask (v0.49.2). A per-mask canvas drifted because a
23
+ * zoomed page box is wider than the stage; `maskPageStyle` below is the old
24
+ * per-canvas formula, kept only for reference;
25
+ * - repainting is driven by (doc, page, scale, version), not by DOM mounting.
26
+ */
27
+
28
+ /** CSS injected once by the viewer's owner. */
29
+ export const VIEWER_STYLE = `
30
+ .mdv-root { position: relative; width: 100%; height: 100%; display: flex; flex-direction: column; min-height: 0; }
31
+ .mdv-stage { flex: 1 1 auto; min-height: 0; overflow: auto; }
32
+ .mdv-columns { display: flex; gap: 12px; width: 100%; height: 100%; }
33
+ .mdv-column { flex: 1 1 0; min-width: 0; overflow: auto; }
34
+ .mdv-page { position: relative; margin: 0 auto 18px; width: fit-content; }
35
+ .mdv-canvas { display: block; }
36
+ .mdv-layer { position: absolute; inset: 0; pointer-events: none; }
37
+ .mdv-mask { position: absolute; overflow: hidden; border: 1px dashed rgba(40, 140, 235, .9); box-sizing: border-box; }
38
+ .mdv-mask-page { position: absolute; max-width: none; }
39
+ .mdv-block { position: absolute; border: 1px dashed rgba(235, 70, 70, .85); box-sizing: border-box; }
40
+ .mdv-block[data-kind="heading"] { border-color: rgba(60, 130, 235, .95); }
41
+ .mdv-block[data-kind="formula"] { border-color: rgba(40, 160, 90, .95); }
42
+ `
43
+
44
+ /**
45
+ * Paint one page into a canvas at a given scale.
46
+ * @param {object} options - doc, pageNumber, scale, canvas, signal.
47
+ * @returns {Promise<void>} resolves when the page finished painting.
48
+ */
49
+ export async function paintPage(options) {
50
+ const { doc, pageNumber, scale, canvas, signal } = options
51
+ const page = await doc.getPage(pageNumber)
52
+ if (signal !== undefined && signal.aborted) return
53
+ const viewport = page.getViewport({ scale })
54
+ let dpr = Math.min(2, Math.max(1, typeof window === 'undefined' ? 1 : window.devicePixelRatio || 1))
55
+ if (viewport.width * dpr > 8000 || viewport.height * dpr > 8000) dpr = 1
56
+ canvas.width = Math.max(1, Math.floor(viewport.width * dpr))
57
+ canvas.height = Math.max(1, Math.floor(viewport.height * dpr))
58
+ canvas.style.width = `${Math.floor(viewport.width)}px`
59
+ canvas.style.height = `${Math.floor(viewport.height)}px`
60
+ await page.render({
61
+ canvasContext: canvas.getContext('2d'),
62
+ viewport,
63
+ transform: dpr !== 1 ? [dpr, 0, 0, dpr, 0, 0] : undefined,
64
+ }).promise
65
+ }
66
+
67
+ /**
68
+ * Compute the geometry a per-mask translated canvas used to need.
69
+ * @deprecated Superseded by the single-image `clipPath` overlay (v0.49.2).
70
+ * @param {{ x: number, y: number, w: number, h: number }} box - normalized box.
71
+ * @returns {{ left: string, top: string, width: string, height: string }} CSS percentages.
72
+ */
73
+ export function maskPageStyle(box) {
74
+ return {
75
+ left: `${-(box.x / box.w) * 100}%`,
76
+ top: `${-(box.y / box.h) * 100}%`,
77
+ width: `${100 / box.w}%`,
78
+ height: `${100 / box.h}%`,
79
+ }
80
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Durable mirror of the reader's annotations and overlay boxes.
3
+ *
4
+ * The browser's localStorage is the live store (both the reader and the right
5
+ * column edit it directly), but it disappears with site data, a new browser or
6
+ * a new machine. Every edit is therefore mirrored to
7
+ * `<库根>\.pdfdesk\annotations\<书>\<章>.json`, which travels with the library
8
+ * and survives plugin updates — the file format carries its own version so a
9
+ * later release can migrate old files instead of dropping them.
10
+ */
11
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
12
+ import { dirname, join } from 'node:path'
13
+
14
+ /** On-disk schema version; bump together with a migration in `readAnnotations`. */
15
+ export const ANNOTATION_FORMAT = 1
16
+
17
+ /**
18
+ * Reject a value that cannot be one path segment.
19
+ * @param {unknown} value - book id or chapter code from a request body.
20
+ * @returns {string} the value, or '' when it is not a plain segment.
21
+ */
22
+ export function pathSegment(value) {
23
+ if (typeof value !== 'string') return ''
24
+ const trimmed = value.trim()
25
+ if (trimmed === '' || trimmed === '.' || trimmed === '..') return ''
26
+ if (/[\\/:*?"<>|]/.test(trimmed)) return ''
27
+ return trimmed
28
+ }
29
+
30
+ /**
31
+ * The mirror file of one chapter.
32
+ * @param {string} libraryDir - library root.
33
+ * @param {string} book - book id.
34
+ * @param {string} code - chapter code.
35
+ * @returns {string} absolute path.
36
+ */
37
+ export function annotationsFile(libraryDir, book, code) {
38
+ return join(libraryDir, '.pdfdesk', 'annotations', book, `${code}.json`)
39
+ }
40
+
41
+ /**
42
+ * Normalize one page entry from a request body or from an older file.
43
+ * @param {unknown} entry - `{ masks, annots, updatedAt }`.
44
+ * @returns {{ masks: object[], annots: object[], updatedAt: number }} the entry.
45
+ */
46
+ function pageEntry(entry) {
47
+ const source = entry !== null && typeof entry === 'object' ? entry : {}
48
+ const masks = Array.isArray(source.masks) ? source.masks.filter(item => item !== null && typeof item === 'object') : []
49
+ const annots = Array.isArray(source.annots) ? source.annots.filter(item => item !== null && typeof item === 'object') : []
50
+ const stamp = Number(source.updatedAt)
51
+ return { masks, annots, updatedAt: Number.isFinite(stamp) && stamp > 0 ? stamp : Date.now() }
52
+ }
53
+
54
+ /**
55
+ * Read one chapter's mirror.
56
+ * @param {string} libraryDir - library root.
57
+ * @param {string} book - book id.
58
+ * @param {string} code - chapter code.
59
+ * @returns {Promise<{ format: number, pages: Record<string, object>, updatedAt: number }>} the mirror; empty when absent.
60
+ */
61
+ export async function readAnnotations(libraryDir, book, code) {
62
+ let parsed = null
63
+ try {
64
+ parsed = JSON.parse(await readFile(annotationsFile(libraryDir, book, code), 'utf8'))
65
+ } catch {
66
+ return { format: ANNOTATION_FORMAT, pages: {}, updatedAt: 0 }
67
+ }
68
+ const pages = {}
69
+ const raw = parsed !== null && typeof parsed === 'object' && parsed.pages !== null && typeof parsed.pages === 'object'
70
+ ? parsed.pages
71
+ : {}
72
+ for (const [key, value] of Object.entries(raw)) {
73
+ const page = Number.parseInt(key, 10)
74
+ if (!Number.isFinite(page) || page < 1) continue
75
+ pages[String(page)] = pageEntry(value)
76
+ }
77
+ // Format 0 is what an early build wrote (no `format` field): the page shape is
78
+ // the same, so it is adopted as version 1 rather than discarded.
79
+ const format = Number.isFinite(Number(parsed?.format)) && Number(parsed?.format) > 0 ? Number(parsed.format) : 1
80
+ const stamp = Number(parsed?.updatedAt)
81
+ return { format, pages, updatedAt: Number.isFinite(stamp) ? stamp : 0 }
82
+ }
83
+
84
+ /**
85
+ * Write the mirror atomically (temp file + rename), so a crash never leaves a
86
+ * half file that the next read would treat as empty.
87
+ * @param {string} libraryDir - library root.
88
+ * @param {string} book - book id.
89
+ * @param {string} code - chapter code.
90
+ * @param {{ pages: Record<string, object>, updatedAt: number }} record - pages to keep.
91
+ * @returns {Promise<number>} the stored `updatedAt`.
92
+ */
93
+ async function persist(libraryDir, book, code, record) {
94
+ const target = annotationsFile(libraryDir, book, code)
95
+ await mkdir(dirname(target), { recursive: true })
96
+ const temporary = `${target}.tmp`
97
+ await writeFile(temporary, JSON.stringify({ format: ANNOTATION_FORMAT, book, code, ...record }, null, 1), 'utf8')
98
+ await rename(temporary, target)
99
+ return record.updatedAt
100
+ }
101
+
102
+ /**
103
+ * Merge one page into the mirror. The page is replaced wholesale, because the
104
+ * editor's page state is the authority for its own page.
105
+ * @param {string} libraryDir - library root.
106
+ * @param {string} book - book id.
107
+ * @param {string} code - chapter code.
108
+ * @param {number} page - 1-based page number.
109
+ * @param {{ masks?: unknown, annots?: unknown, updatedAt?: unknown }} body - the page payload.
110
+ * @returns {Promise<{ updatedAt: number }>} the mirror's new timestamp.
111
+ */
112
+ export async function writeAnnotations(libraryDir, book, code, page, body) {
113
+ const record = await readAnnotations(libraryDir, book, code)
114
+ record.pages[String(page)] = pageEntry({ ...body, updatedAt: body.updatedAt ?? Date.now() })
115
+ record.updatedAt = Date.now()
116
+ await persist(libraryDir, book, code, record)
117
+ return { updatedAt: record.updatedAt }
118
+ }
119
+
120
+ /**
121
+ * Seed pages the mirror has never seen. Existing pages are left alone, so a
122
+ * browser that still holds the notes can hand them over without a chance of
123
+ * overwriting something newer on disk.
124
+ * @param {string} libraryDir - library root.
125
+ * @param {string} book - book id.
126
+ * @param {string} code - chapter code.
127
+ * @param {Array<{ page: unknown, masks?: unknown, annots?: unknown }>} pages - candidate pages.
128
+ * @returns {Promise<{ added: number }>} how many pages were new.
129
+ */
130
+ export async function seedAnnotations(libraryDir, book, code, pages) {
131
+ const record = await readAnnotations(libraryDir, book, code)
132
+ let added = 0
133
+ for (const item of Array.isArray(pages) ? pages : []) {
134
+ const page = Number.parseInt(String(item?.page ?? ''), 10)
135
+ if (!Number.isFinite(page) || page < 1) continue
136
+ if (record.pages[String(page)] !== undefined) continue
137
+ record.pages[String(page)] = pageEntry(item)
138
+ added += 1
139
+ }
140
+ if (added > 0) {
141
+ record.updatedAt = Date.now()
142
+ await persist(libraryDir, book, code, record)
143
+ }
144
+ return { added }
145
+ }
@@ -0,0 +1,317 @@
1
+ /**
2
+ * Produced files: what a chapter's sessions wrote.
3
+ *
4
+ * The convention is `<artifactDir>/<book id>/<cNN>/` — one directory per
5
+ * chapter, named exactly like the chapter code the session titles use. Listing
6
+ * is deliberately narrow: a chapter that the catalog does not know is refused
7
+ * rather than looked up, so a typo cannot read an unrelated folder, and a file
8
+ * name is only ever joined under that chapter's own directory.
9
+ *
10
+ * The browser never touches the filesystem, so a previewed file arrives here in
11
+ * full, decoded, and bounded: 512 KiB and a hard line cap is enough for notes
12
+ * and extracts, and the response says when it stopped early.
13
+ *
14
+ * @module dsh-pdf-workbench/artifacts
15
+ */
16
+ import { open, readdir, stat } from 'node:fs/promises'
17
+ import { basename, extname, join, resolve, sep } from 'node:path'
18
+
19
+ /** Bytes served for one text preview. */
20
+ export const MAX_TEXT_BYTES = 512 * 1024
21
+
22
+ /** Rows one chapter may list before it says the list is cut. */
23
+ const MAX_ROWS = 300
24
+
25
+ /** A chapter code, canonical form. */
26
+ const CODE = /^c\d{2,3}$/
27
+
28
+ /** One path segment: no separators, no traversal, no drive colon. */
29
+ const SEGMENT = /^[^\\/:*?"<>|]{1,200}$/
30
+
31
+ /** A plain file name as it appears in the chapter's own directory. */
32
+ const FILE_NAME = /^[^\\/:*?"<>|]{1,200}$/
33
+
34
+ /** Extensions rendered as text in the preview. Anything else is listed but not previewed. */
35
+ const TEXT_EXTENSIONS = new Set([
36
+ 'md', 'markdown', 'mdx', 'txt', 'text', 'tex', 'latex', 'log', 'rst',
37
+ 'json', 'jsonl', 'json5', 'csv', 'tsv', 'yml', 'yaml', 'toml', 'ini', 'conf', 'cfg',
38
+ 'py', 'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'c', 'h', 'cc', 'cpp', 'hpp', 'cs', 'java',
39
+ 'rs', 'go', 'rb', 'php', 'sh', 'bash', 'ps1', 'bat', 'cmd',
40
+ 'html', 'htm', 'css', 'scss', 'xml', 'svg', 'sql', 'r', 'jl', 'm', 'lua', 'pl', 'swift', 'kt',
41
+ ])
42
+
43
+ /** Extensions shown as an image badge; the reader does not draw them yet. */
44
+ const IMAGE_EXTENSIONS = new Set(['png', 'jpg', 'jpeg', 'webp', 'gif', 'bmp', 'avif'])
45
+
46
+ /** Decoders tried in order for a preview; UTF-8 first, then the common Chinese Windows code page. */
47
+ const DECODERS = ['utf-8', 'gb18030']
48
+
49
+ /**
50
+ * The kind shown as a badge and used to decide whether the reader can draw it.
51
+ * @param {string} name - file name.
52
+ * @returns {'pdf' | 'text' | 'image' | 'other'} the kind.
53
+ */
54
+ export function kindOf(name) {
55
+ const extension = extname(name).replace(/^\./, '').toLowerCase()
56
+ if (extension === 'pdf') return 'pdf'
57
+ if (TEXT_EXTENSIONS.has(extension)) return 'text'
58
+ if (IMAGE_EXTENSIONS.has(extension)) return 'image'
59
+ return 'other'
60
+ }
61
+
62
+ /**
63
+ * Whether a value can be used as one directory segment.
64
+ * @param {unknown} value - candidate.
65
+ * @returns {boolean} true when safe.
66
+ */
67
+ function isSegment(value) {
68
+ return typeof value === 'string' && SEGMENT.test(value) && value !== '.' && value !== '..'
69
+ }
70
+
71
+ /**
72
+ * Whether a value is a plain file name (not a path).
73
+ * @param {unknown} value - candidate.
74
+ * @returns {boolean} true when safe.
75
+ */
76
+ function isFileName(value) {
77
+ return typeof value === 'string' && FILE_NAME.test(value) && value !== '.' && value !== '..' && basename(value) === value
78
+ }
79
+
80
+ /**
81
+ * Whether `target` really lives under `root`.
82
+ * @param {string} root - directory that must contain the target.
83
+ * @param {string} target - resolved candidate.
84
+ * @returns {boolean} true when contained.
85
+ */
86
+ function isInside(root, target) {
87
+ const normalize = value => value.replace(/[\\/]+$/, '').replace(/\//g, '\\').toLowerCase()
88
+ const parent = normalize(root)
89
+ const child = normalize(target)
90
+ return child === parent || child.startsWith(`${parent}${sep}`)
91
+ }
92
+
93
+ /**
94
+ * The directory a chapter's produced files live in, whether or not it exists.
95
+ * @param {{ artifactDir: string }} config - resolved paths.
96
+ * @param {string} bookId - catalog book id.
97
+ * @param {string} code - canonical chapter code.
98
+ * @returns {string} the absolute directory.
99
+ */
100
+ export function chapterArtifactDir(config, bookId, code) {
101
+ return join(config.artifactDir, bookId, code)
102
+ }
103
+
104
+ /**
105
+ * Describe one file name for the browser.
106
+ * @param {string} name - file name inside the chapter directory.
107
+ * @returns {{ name: string, kind: 'pdf' | 'text' | 'image' | 'other' }} the descriptor.
108
+ */
109
+ function descriptorOf(name) {
110
+ return { name, kind: kindOf(name) }
111
+ }
112
+
113
+ /**
114
+ * Find the catalog row for one chapter, so the listing is scoped to a chapter
115
+ * the workbench actually shows.
116
+ * @param {{ books: object[] }} catalog - the loaded catalog.
117
+ * @param {string} bookId - requested book.
118
+ * @param {string} code - requested chapter.
119
+ * @returns {{ book: object, chapter: object } | null} the rows, or null when either is unknown.
120
+ */
121
+ export function findChapter(catalog, bookId, code) {
122
+ const book = Array.isArray(catalog.books) ? catalog.books.find(item => item.id === bookId) : undefined
123
+ if (book === undefined || !Array.isArray(book.chapters)) return null
124
+ const chapter = book.chapters.find(item => item.code === code)
125
+ if (chapter === undefined) return null
126
+ return { book, chapter }
127
+ }
128
+
129
+ /**
130
+ * List one chapter's produced files.
131
+ * @param {{ artifactDir: string }} config - resolved paths.
132
+ * @param {object} book - catalog book row.
133
+ * @param {object} chapter - catalog chapter row.
134
+ * @returns {Promise<{ dir: string, artifacts: object[], truncated: boolean, missing: boolean }>} the listing.
135
+ */
136
+ export async function listArtifacts(config, book, chapter) {
137
+ if (!isSegment(book.id) || !CODE.test(chapter.code)) {
138
+ return { dir: '', artifacts: [], truncated: false, missing: true }
139
+ }
140
+ const dir = chapterArtifactDir(config, book.id, chapter.code)
141
+ const names = await readingNames(dir)
142
+ if (names === null) return { dir, artifacts: [], truncated: false, missing: true }
143
+ const truncated = names.length > MAX_ROWS
144
+ const rows = await Promise.all(names.slice(0, MAX_ROWS).map(async name => {
145
+ const descriptor = descriptorOf(name)
146
+ try {
147
+ const info = await stat(join(dir, name))
148
+ if (!info.isFile()) return null
149
+ return { ...descriptor, size: info.size, mtime: info.mtimeMs }
150
+ } catch {
151
+ // A file that vanished between readdir and stat is not worth a row.
152
+ return null
153
+ }
154
+ }))
155
+ return {
156
+ dir,
157
+ artifacts: rows.filter(row => row !== null),
158
+ truncated,
159
+ missing: false,
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Count the produced files of every chapter of one book without reading any
165
+ * metadata, so a collapsed row can still say how many it holds. One scan of the
166
+ * book's directories replaces a request per chapter.
167
+ * @param {{ artifactDir: string }} config - resolved paths.
168
+ * @param {object} book - catalog book row.
169
+ * @returns {Promise<Record<string, { n: number, truncated: boolean }>>} counts by chapter code.
170
+ */
171
+ export async function countArtifacts(config, book) {
172
+ const counts = {}
173
+ // An authored index may carry an id that is not a plain directory name; a
174
+ // count is read-only, but it must not walk out of the artifact root either.
175
+ if (!isSegment(book.id)) return counts
176
+ const chapters = Array.isArray(book.chapters) ? book.chapters : []
177
+ await Promise.all(chapters.map(async chapter => {
178
+ if (!CODE.test(chapter.code)) return
179
+ const dir = chapterArtifactDir(config, book.id, chapter.code)
180
+ const names = await readingNames(dir)
181
+ if (names === null || names.length === 0) return
182
+ counts[chapter.code] = { n: Math.min(names.length, MAX_ROWS), truncated: names.length > MAX_ROWS }
183
+ }))
184
+ return counts
185
+ }
186
+
187
+ /**
188
+ * The file names worth listing in one chapter directory.
189
+ * @param {string} dir - the chapter's directory.
190
+ * @returns {Promise<string[] | null>} sorted names, or null when the directory does not exist.
191
+ */
192
+ async function readingNames(dir) {
193
+ let entries
194
+ try {
195
+ entries = await readdir(dir, { withFileTypes: true })
196
+ } catch (error) {
197
+ const code = error !== null && typeof error === 'object' ? error.code : undefined
198
+ // A chapter nobody has written into yet is a normal, empty answer.
199
+ if (code === 'ENOENT' || code === 'ENOTDIR') return null
200
+ throw error
201
+ }
202
+ return entries
203
+ .filter(entry => entry.isFile() || entry.isSymbolicLink())
204
+ .map(entry => entry.name)
205
+ // Office lock files and editor droppings are noise in a reading list.
206
+ .filter(name => !name.startsWith('.') && !name.startsWith('~$'))
207
+ .sort((left, right) => left.localeCompare(right, 'zh'))
208
+ }
209
+
210
+ /**
211
+ * Decode a byte range, preferring UTF-8 but accepting the common Chinese
212
+ * Windows code page when the bytes are not valid UTF-8.
213
+ * @param {Buffer} bytes - the file's leading bytes.
214
+ * @returns {{ text: string, encoding: string }} the decoded text.
215
+ */
216
+ export function decodeText(bytes) {
217
+ let best = { text: '', encoding: DECODERS[0], loss: Number.POSITIVE_INFINITY }
218
+ for (const encoding of DECODERS) {
219
+ let text
220
+ try {
221
+ text = new TextDecoder(encoding).decode(bytes)
222
+ } catch {
223
+ continue
224
+ }
225
+ // Each replacement character is one byte the decoder could not map.
226
+ const loss = (text.match(/\uFFFD/g) ?? []).length
227
+ if (loss < best.loss) best = { text, encoding, loss }
228
+ if (loss === 0) break
229
+ }
230
+ return { text: best.text, encoding: best.encoding }
231
+ }
232
+
233
+ /**
234
+ * Read one produced file for the preview.
235
+ * @param {{ artifactDir: string }} config - resolved paths.
236
+ * @param {object} book - catalog book row.
237
+ * @param {object} chapter - catalog chapter row.
238
+ * @param {string} name - file name inside the chapter directory.
239
+ * @returns {Promise<{ ok: true, name: string, kind: string, size: number, mtime: number, text: string, encoding: string, truncated: boolean } | { ok: false, reason: 'bad-name' | 'not-found' | 'not-text' | 'binary' | 'directory' }>} the preview or why it cannot be drawn.
240
+ */
241
+ export async function readArtifact(config, book, chapter, name) {
242
+ if (!isFileName(name)) return { ok: false, reason: 'bad-name' }
243
+ if (!isSegment(book.id) || !CODE.test(chapter.code)) return { ok: false, reason: 'bad-name' }
244
+ const dir = chapterArtifactDir(config, book.id, chapter.code)
245
+ const target = resolve(dir, name)
246
+ if (!isInside(config.artifactDir, target) || !isInside(dir, target)) return { ok: false, reason: 'bad-name' }
247
+ const kind = kindOf(name)
248
+ if (kind !== 'text') return { ok: false, reason: 'not-text' }
249
+
250
+ let handle
251
+ let info
252
+ try {
253
+ info = await stat(target)
254
+ if (!info.isFile()) return { ok: false, reason: 'directory' }
255
+ handle = await open(target, 'r')
256
+ } catch {
257
+ return { ok: false, reason: 'not-found' }
258
+ }
259
+ try {
260
+ const length = Math.min(info.size, MAX_TEXT_BYTES)
261
+ const buffer = Buffer.alloc(length)
262
+ const { bytesRead } = await handle.read(buffer, 0, length, 0)
263
+ let bytes = buffer.subarray(0, bytesRead)
264
+ const truncated = info.size > bytesRead
265
+ // NUL bytes mean binary; check the raw read so a trimmed tail cannot hide one.
266
+ if (bytes.includes(0)) return { ok: false, reason: 'binary' }
267
+ // A cut inside a multi-byte character leaves an invalid tail; dropping those
268
+ // bytes keeps the encoding probe from mistaking the file for GB18030.
269
+ if (truncated) bytes = trimPartialTail(bytes)
270
+ const { text, encoding } = decodeText(bytes)
271
+ return {
272
+ ok: true,
273
+ name,
274
+ kind,
275
+ size: info.size,
276
+ mtime: info.mtimeMs,
277
+ text,
278
+ encoding,
279
+ truncated,
280
+ }
281
+ } finally {
282
+ await handle.close().catch(() => {})
283
+ }
284
+ }
285
+
286
+ /**
287
+ * Drop an incomplete trailing UTF-8 sequence (at most three bytes).
288
+ * @param {Buffer} bytes - the truncated read.
289
+ * @returns {Buffer} bytes that decode as UTF-8 without a replacement character.
290
+ */
291
+ function trimPartialTail(bytes) {
292
+ for (let drop = 0; drop <= 3 && drop < bytes.length; drop += 1) {
293
+ const candidate = bytes.subarray(0, bytes.length - drop)
294
+ try {
295
+ new TextDecoder('utf-8', { fatal: true }).decode(candidate)
296
+ return candidate
297
+ } catch {
298
+ // Try cutting one more byte.
299
+ }
300
+ }
301
+ return bytes
302
+ }
303
+
304
+ /**
305
+ * Validate the pair the browser asked about and return the catalog rows.
306
+ * @param {{ books: object[] }} catalog - the loaded catalog.
307
+ * @param {unknown} bookId - requested book.
308
+ * @param {unknown} code - requested chapter.
309
+ * @returns {{ ok: true, book: object, chapter: object } | { ok: false, code: string, message: string }} the match or the refusal.
310
+ */
311
+ export function resolveChapter(catalog, bookId, code) {
312
+ if (!isSegment(bookId)) return { ok: false, code: 'invalid-book', message: '书 id 不合法' }
313
+ if (typeof code !== 'string' || !CODE.test(code)) return { ok: false, code: 'invalid-code', message: '章号不合法' }
314
+ const match = findChapter(catalog, bookId, code)
315
+ if (match === null) return { ok: false, code: 'unknown-chapter', message: `书库里没有 ${bookId} ${code}` }
316
+ return { ok: true, ...match }
317
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Read one PDF page's layout blocks with PyMuPDF.
3
+ *
4
+ * pdf.js gives text items only; PyMuPDF already groups them into paragraph
5
+ * blocks and reports span sizes, which is what the paragraph/heading/formula
6
+ * boxes need.
7
+ * @module dsh-pdf-workbench/blocks
8
+ */
9
+ import { execFile } from 'node:child_process'
10
+
11
+ const PYTHONS = [process.env.MATH_DESK_PYTHON, 'python', 'py'].filter(Boolean)
12
+
13
+ function runPython(script, args) {
14
+ return new Promise((resolve, reject) => {
15
+ const tryNext = index => {
16
+ if (index >= PYTHONS.length) {
17
+ reject(new Error('没有可用的 Python'))
18
+ return
19
+ }
20
+ execFile(
21
+ PYTHONS[index],
22
+ [script, ...args],
23
+ { timeout: 60000, windowsHide: true, maxBuffer: 8 * 1024 * 1024 },
24
+ (error, stdout) => {
25
+ if (error === null) resolve(stdout)
26
+ else if (index + 1 < PYTHONS.length) tryNext(index + 1)
27
+ else reject(new Error(`${PYTHONS[index]}: ${error.message}`))
28
+ }
29
+ )
30
+ }
31
+ tryNext(0)
32
+ })
33
+ }
34
+
35
+ /**
36
+ * @param {{ script: string, source: string, pageIndex: number }} options - block reader script and page.
37
+ * @returns {Promise<object[]>} blocks with normalized bbox, kind and text.
38
+ */
39
+ export async function readPageBlocks(options) {
40
+ const output = await runPython(options.script, [options.source, String(options.pageIndex)])
41
+ const parsed = JSON.parse(output)
42
+ if (!Array.isArray(parsed)) throw new Error('块解析返回格式不对')
43
+ return parsed
44
+ }