@heycys/gallery 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (292) hide show
  1. package/THIRD-PARTY-NOTICES.md +2 -2
  2. package/browser/editor/components/align.mjs +58 -0
  3. package/browser/editor/components/code/index.mjs +1 -1
  4. package/browser/editor/components/embed/page.mjs +1 -1
  5. package/browser/editor/components/file/page.mjs +4 -4
  6. package/browser/editor/components/heading/index.mjs +7 -6
  7. package/browser/editor/components/icons.mjs +3 -0
  8. package/browser/editor/components/image/index.mjs +2 -0
  9. package/browser/editor/components/image/page.mjs +172 -90
  10. package/browser/editor/components/installed/index.mjs +6 -2
  11. package/browser/editor/components/installed/page.mjs +80 -13
  12. package/browser/editor/components/media/icons.mjs +13 -8
  13. package/browser/editor/components/media/page.mjs +5 -3
  14. package/browser/editor/components/media/toolbar.mjs +12 -3
  15. package/browser/editor/components/paragraph/index.mjs +4 -3
  16. package/browser/editor/components/registry.mjs +17 -5
  17. package/browser/editor/components/table/index.mjs +4 -2
  18. package/browser/editor/page/after/index.mjs +288 -0
  19. package/browser/editor/page/align.mjs +91 -0
  20. package/browser/editor/page/beside.mjs +5 -6
  21. package/browser/editor/page/block-menu/index.mjs +6 -3
  22. package/browser/editor/page/blocks.mjs +3 -1
  23. package/browser/editor/page/board/hint.mjs +64 -27
  24. package/browser/editor/page/board/index.mjs +160 -71
  25. package/browser/editor/page/board/motion.mjs +177 -0
  26. package/browser/editor/page/board/settings.mjs +4 -3
  27. package/browser/editor/page/clipboard/index.mjs +10 -3
  28. package/browser/editor/page/clipboard/own/blocks.mjs +3 -4
  29. package/browser/editor/page/clipboard/own/describe.mjs +6 -2
  30. package/browser/editor/page/commit.mjs +2 -2
  31. package/browser/editor/page/core.mjs +3 -1
  32. package/browser/editor/page/custom-page.mjs +15 -11
  33. package/browser/editor/page/editor.mjs +31 -14
  34. package/browser/editor/page/history.mjs +19 -4
  35. package/browser/editor/page/insert/index.mjs +20 -22
  36. package/browser/editor/page/menu.mjs +15 -7
  37. package/browser/editor/page/page-objects.mjs +3 -7
  38. package/browser/editor/page/present-links.mjs +5 -4
  39. package/browser/editor/page/present-shell.mjs +63 -0
  40. package/browser/editor/page/selection/index.mjs +10 -2
  41. package/browser/editor/page/table/binding.mjs +87 -0
  42. package/browser/editor/page/table/icons.mjs +0 -2
  43. package/browser/editor/page/table/index.mjs +10 -14
  44. package/browser/editor/page/table/views.mjs +5 -52
  45. package/browser/editor/page/table/widths.mjs +82 -10
  46. package/browser/editor/page/typing/index.mjs +44 -12
  47. package/browser/editor/page/typing/leave.mjs +19 -5
  48. package/browser/shared/block-packs.mjs +23 -8
  49. package/browser/shared/component-catalog.mjs +15 -8
  50. package/browser/shared/component-source.mjs +3 -1
  51. package/browser/shared/components/heading.mjs +2 -1
  52. package/browser/shared/components/installed.mjs +1 -1
  53. package/browser/shared/components/page.mjs +2 -0
  54. package/browser/shared/components/paragraph.mjs +8 -1
  55. package/browser/shared/components/table.mjs +1 -0
  56. package/browser/shared/emoji/line-icons.mjs +37 -0
  57. package/browser/shared/http.mjs +9 -0
  58. package/browser/shared/i18n/en.mjs +40 -17
  59. package/browser/shared/outline.mjs +30 -2
  60. package/browser/shared/pack-manifest.mjs +12 -1
  61. package/browser/shared/pages.mjs +169 -57
  62. package/browser/shared/pinyin.mjs +92 -0
  63. package/browser/shared/present-step.mjs +17 -0
  64. package/browser/shared/sidebar-head.mjs +70 -0
  65. package/browser/shared/web-links.mjs +5 -0
  66. package/dist/chunk-2OHANJ6Q.mjs +2 -0
  67. package/dist/{chunk-QOUEFUCH.mjs → chunk-3MBRL2PM.mjs} +1 -1
  68. package/dist/{chunk-NWR2LT5B.mjs → chunk-4OKWZY5E.mjs} +1 -1
  69. package/dist/{chunk-RMECZA2K.mjs → chunk-5K44HLTZ.mjs} +1 -1
  70. package/dist/{chunk-NFMCP2HI.mjs → chunk-5XA2ZBAE.mjs} +2 -2
  71. package/dist/{chunk-OUUP3WKT.mjs → chunk-67N2QJYT.mjs} +1 -1
  72. package/dist/chunk-6KBYRA2C.mjs +2 -0
  73. package/dist/{chunk-SX4LJYT6.mjs → chunk-6N3PX4XX.mjs} +1 -1
  74. package/dist/{chunk-RFDZXFJF.mjs → chunk-7JDX4E65.mjs} +1 -1
  75. package/dist/chunk-7M2BQQGZ.mjs +2 -0
  76. package/dist/{chunk-ZUNVAXLH.mjs → chunk-7OG26PGF.mjs} +1 -1
  77. package/dist/{chunk-B4P2CM2J.mjs → chunk-AHN3NFKJ.mjs} +1 -1
  78. package/dist/chunk-ALZ6ZENZ.mjs +3 -0
  79. package/dist/{chunk-UGWYKHBL.mjs → chunk-AR5D57ZD.mjs} +2 -2
  80. package/dist/{chunk-W3BGBJQW.mjs → chunk-BFJGHSQN.mjs} +1 -1
  81. package/dist/{chunk-HLYV7RIH.mjs → chunk-CMA72MAG.mjs} +1 -1
  82. package/dist/{chunk-D4CKRD3V.mjs → chunk-DAZL73VK.mjs} +2 -2
  83. package/dist/{chunk-6VTU6KEO.mjs → chunk-DJISHPUL.mjs} +1 -1
  84. package/dist/{chunk-BPL64HGA.mjs → chunk-EAIFITAV.mjs} +1 -1
  85. package/dist/chunk-EP25HDAJ.mjs +2 -0
  86. package/dist/{chunk-6EZ7FNIK.mjs → chunk-F4ZA6JRZ.mjs} +1 -1
  87. package/dist/{chunk-3KJHLHUO.mjs → chunk-F6HVDZR4.mjs} +1 -1
  88. package/dist/{chunk-3NJACR4W.mjs → chunk-FDMAXMQA.mjs} +1 -1
  89. package/dist/chunk-FETSREUN.mjs +5 -0
  90. package/dist/{chunk-RKPWLGZ3.mjs → chunk-GHOYKMQ3.mjs} +1 -1
  91. package/dist/chunk-HDWTZ763.mjs +12 -0
  92. package/dist/{chunk-VTKNEYT3.mjs → chunk-HPOI4ZX7.mjs} +1 -1
  93. package/dist/{chunk-OW5NWPOJ.mjs → chunk-HXG7EOPJ.mjs} +1 -1
  94. package/dist/{chunk-V6RIYQZZ.mjs → chunk-ITOH5EGO.mjs} +1 -1
  95. package/dist/{chunk-ZWPMCK7P.mjs → chunk-IV64FFI4.mjs} +1 -1
  96. package/dist/chunk-J43Z6LSS.mjs +2 -0
  97. package/dist/chunk-J5PUIV3Y.mjs +4 -0
  98. package/dist/{chunk-KTKHRC6H.mjs → chunk-JA7G53PC.mjs} +1 -1
  99. package/dist/{chunk-NWFBE2YA.mjs → chunk-JLTZF4LA.mjs} +1 -1
  100. package/dist/{chunk-GY3FAUVM.mjs → chunk-JZT7I2OJ.mjs} +1 -1
  101. package/dist/{chunk-QKXMPUXC.mjs → chunk-K5XATEOO.mjs} +1 -1
  102. package/dist/chunk-L2SUIS5S.mjs +2 -0
  103. package/dist/{chunk-TEZAWDSQ.mjs → chunk-LM4XFQHZ.mjs} +1 -1
  104. package/dist/{chunk-5ZJA7CXT.mjs → chunk-MN7BZL4R.mjs} +1 -1
  105. package/dist/chunk-MTYYHM2G.mjs +15 -0
  106. package/dist/{chunk-HMYTM3GT.mjs → chunk-MXUBKDRO.mjs} +1 -1
  107. package/dist/{chunk-MHW7ZKOU.mjs → chunk-OEXWRJME.mjs} +1 -1
  108. package/dist/{chunk-CRJEG7MT.mjs → chunk-OFHXGWOX.mjs} +1 -1
  109. package/dist/chunk-ORID3AE7.mjs +166 -0
  110. package/dist/{chunk-32ZUEFZ7.mjs → chunk-PGDE24N5.mjs} +1 -1
  111. package/dist/{chunk-UNOYVIYR.mjs → chunk-POTA2FV4.mjs} +1 -1
  112. package/dist/{chunk-N7AZZLGT.mjs → chunk-QE5RG76S.mjs} +18 -17
  113. package/dist/{chunk-N76HWBA3.mjs → chunk-R2ZDLJYT.mjs} +1 -1
  114. package/dist/chunk-SWUTTZCN.mjs +2 -0
  115. package/dist/{chunk-POQSE4C2.mjs → chunk-TR7TWGHB.mjs} +1 -1
  116. package/dist/chunk-U5XL7D6A.mjs +3 -0
  117. package/dist/{chunk-PVER7LSC.mjs → chunk-U7NZI6N4.mjs} +2 -2
  118. package/dist/{chunk-Q47PLKIJ.mjs → chunk-UGWMMEJ5.mjs} +1 -1
  119. package/dist/chunk-UJQJKNGK.mjs +2 -0
  120. package/dist/chunk-UYVCQK3H.mjs +22 -0
  121. package/dist/{chunk-FJYN7RTH.mjs → chunk-VFX2KNHP.mjs} +1 -1
  122. package/dist/{chunk-UBBRTJ2R.mjs → chunk-VS7JIGJW.mjs} +1 -1
  123. package/dist/{chunk-NVRNLK25.mjs → chunk-W7665ZEC.mjs} +2 -2
  124. package/dist/{chunk-NG375ILQ.mjs → chunk-WQDQWCX5.mjs} +1 -1
  125. package/dist/chunk-YLPSMDIS.mjs +5 -0
  126. package/dist/{chunk-VXACTLO3.mjs → chunk-YNAWBAYN.mjs} +1 -1
  127. package/dist/{chunk-ZB4H7ZN4.mjs → chunk-YROX2O22.mjs} +1 -1
  128. package/dist/{chunk-YQGT4AB2.mjs → chunk-ZDLPUOAG.mjs} +1 -1
  129. package/dist/chunk-ZQS6H473.mjs +16 -0
  130. package/dist/{chunk-OJKMINIU.mjs → chunk-ZWWC4KLF.mjs} +15 -15
  131. package/dist/cli.mjs +1 -1
  132. package/dist/server.mjs +1 -1
  133. package/dist/worker.mjs +1 -1
  134. package/kit/board.css +5 -5
  135. package/kit/code.js +15 -15
  136. package/kit/report.css +120 -41
  137. package/kit/runtime.js +45 -7
  138. package/kit/tables.js +2 -0
  139. package/kit/ui.js +2 -0
  140. package/package.json +1 -1
  141. package/packs/gallery/chart-view/kit.js +3 -3
  142. package/packs/gallery/chart-view/writing.md +1 -1
  143. package/packs/gallery/countdown/component.json +1 -1
  144. package/packs/gallery/countdown/kit.js +89 -29
  145. package/packs/gallery/countdown/preview.svg +1 -1
  146. package/packs/gallery/countdown/style.css +88 -100
  147. package/packs/gallery/countdown/writing.md +2 -2
  148. package/packs/gallery/habit/component.json +3 -3
  149. package/packs/gallery/habit/kit.js +114 -75
  150. package/packs/gallery/habit/preview.svg +1 -1
  151. package/packs/gallery/habit/style.css +133 -205
  152. package/packs/gallery/habit/writing.md +2 -2
  153. package/packs/gallery/heatmap/component.json +2 -2
  154. package/packs/gallery/heatmap/kit.js +335 -173
  155. package/packs/gallery/heatmap/preview.svg +1 -1
  156. package/packs/gallery/heatmap/style.css +158 -170
  157. package/packs/gallery/heatmap/writing.md +2 -2
  158. package/packs/gallery/kanban/kit.js +3 -3
  159. package/packs/gallery/kanban/writing.md +1 -1
  160. package/packs/gallery/metric/kit.js +3 -3
  161. package/packs/gallery/metric/writing.md +1 -1
  162. package/packs/gallery/note/component.json +3 -3
  163. package/packs/gallery/note/kit.js +40 -13
  164. package/packs/gallery/note/preview.svg +1 -1
  165. package/packs/gallery/note/style.css +51 -30
  166. package/packs/gallery/note/writing.md +2 -2
  167. package/packs/gallery/recent/component.json +2 -2
  168. package/packs/gallery/recent/kit.js +141 -86
  169. package/packs/gallery/recent/preview.svg +1 -1
  170. package/packs/gallery/recent/style.css +53 -126
  171. package/packs/gallery/recent/writing.md +2 -2
  172. package/packs/gallery/static/component.json +2 -2
  173. package/packs/gallery/static/preview.svg +1 -1
  174. package/packs/gallery/static/style.css +99 -66
  175. package/packs/gallery/static/writing.md +2 -2
  176. package/packs/gallery/stats/component.json +3 -3
  177. package/packs/gallery/stats/kit.js +253 -72
  178. package/packs/gallery/stats/preview.svg +1 -1
  179. package/packs/gallery/stats/style.css +64 -142
  180. package/packs/gallery/stats/writing.md +2 -2
  181. package/packs/gallery/today/component.json +2 -2
  182. package/packs/gallery/today/kit.js +62 -27
  183. package/packs/gallery/today/preview.svg +1 -1
  184. package/packs/gallery/today/style.css +101 -72
  185. package/packs/gallery/today/writing.md +2 -2
  186. package/packs/gallery/todos/component.json +1 -1
  187. package/packs/gallery/todos/kit.js +218 -71
  188. package/packs/gallery/todos/preview.svg +1 -1
  189. package/packs/gallery/todos/style.css +170 -223
  190. package/packs/gallery/todos/writing.md +1 -1
  191. package/packs/gallery/weather/component.json +2 -2
  192. package/packs/gallery/weather/kit.js +165 -90
  193. package/packs/gallery/weather/preview.svg +1 -1
  194. package/packs/gallery/weather/style.css +100 -218
  195. package/packs/gallery/weather/writing.md +1 -1
  196. package/packs/gallery-soft/countdown/component.json +18 -0
  197. package/packs/gallery-soft/countdown/example.html +3 -0
  198. package/packs/gallery-soft/countdown/kit.js +206 -0
  199. package/packs/gallery-soft/countdown/preview.svg +1 -0
  200. package/packs/gallery-soft/countdown/style.css +211 -0
  201. package/packs/gallery-soft/countdown/template.html +3 -0
  202. package/packs/gallery-soft/countdown/writing.md +24 -0
  203. package/packs/gallery-soft/habit/component.json +14 -0
  204. package/packs/gallery-soft/habit/example.html +3 -0
  205. package/packs/gallery-soft/habit/kit.js +366 -0
  206. package/packs/gallery-soft/habit/preview.svg +1 -0
  207. package/packs/gallery-soft/habit/style.css +251 -0
  208. package/packs/gallery-soft/habit/template.html +3 -0
  209. package/packs/gallery-soft/habit/writing.md +23 -0
  210. package/packs/gallery-soft/heatmap/component.json +18 -0
  211. package/packs/gallery-soft/heatmap/example.html +3 -0
  212. package/packs/gallery-soft/heatmap/kit.js +498 -0
  213. package/packs/gallery-soft/heatmap/preview.svg +1 -0
  214. package/packs/gallery-soft/heatmap/style.css +181 -0
  215. package/packs/gallery-soft/heatmap/template.html +3 -0
  216. package/packs/gallery-soft/heatmap/writing.md +23 -0
  217. package/packs/gallery-soft/note/component.json +14 -0
  218. package/packs/gallery-soft/note/example.html +3 -0
  219. package/packs/gallery-soft/note/kit.js +162 -0
  220. package/packs/gallery-soft/note/preview.svg +1 -0
  221. package/packs/gallery-soft/note/style.css +148 -0
  222. package/packs/gallery-soft/note/template.html +3 -0
  223. package/packs/gallery-soft/note/writing.md +20 -0
  224. package/packs/gallery-soft/recent/component.json +13 -0
  225. package/packs/gallery-soft/recent/example.html +1 -0
  226. package/packs/gallery-soft/recent/kit.js +335 -0
  227. package/packs/gallery-soft/recent/preview.svg +1 -0
  228. package/packs/gallery-soft/recent/style.css +160 -0
  229. package/packs/gallery-soft/recent/template.html +1 -0
  230. package/packs/gallery-soft/recent/writing.md +17 -0
  231. package/packs/gallery-soft/static/component.json +13 -0
  232. package/packs/gallery-soft/static/example.html +12 -0
  233. package/packs/gallery-soft/static/preview.svg +1 -0
  234. package/packs/gallery-soft/static/style.css +186 -0
  235. package/packs/gallery-soft/static/template.html +1 -0
  236. package/packs/gallery-soft/static/writing.md +20 -0
  237. package/packs/gallery-soft/stats/component.json +13 -0
  238. package/packs/gallery-soft/stats/example.html +1 -0
  239. package/packs/gallery-soft/stats/kit.js +341 -0
  240. package/packs/gallery-soft/stats/preview.svg +1 -0
  241. package/packs/gallery-soft/stats/style.css +119 -0
  242. package/packs/gallery-soft/stats/template.html +1 -0
  243. package/packs/gallery-soft/stats/writing.md +13 -0
  244. package/packs/gallery-soft/today/component.json +12 -0
  245. package/packs/gallery-soft/today/example.html +1 -0
  246. package/packs/gallery-soft/today/kit.js +222 -0
  247. package/packs/gallery-soft/today/preview.svg +1 -0
  248. package/packs/gallery-soft/today/style.css +178 -0
  249. package/packs/gallery-soft/today/template.html +1 -0
  250. package/packs/gallery-soft/today/writing.md +16 -0
  251. package/packs/gallery-soft/todos/component.json +19 -0
  252. package/packs/gallery-soft/todos/example.html +3 -0
  253. package/packs/gallery-soft/todos/kit.js +527 -0
  254. package/packs/gallery-soft/todos/preview.svg +1 -0
  255. package/packs/gallery-soft/todos/style.css +212 -0
  256. package/packs/gallery-soft/todos/template.html +3 -0
  257. package/packs/gallery-soft/todos/writing.md +32 -0
  258. package/packs/gallery-soft/weather/component.json +19 -0
  259. package/packs/gallery-soft/weather/example.html +3 -0
  260. package/packs/gallery-soft/weather/kit.js +411 -0
  261. package/packs/gallery-soft/weather/preview.svg +1 -0
  262. package/packs/gallery-soft/weather/style.css +185 -0
  263. package/packs/gallery-soft/weather/template.html +3 -0
  264. package/packs/gallery-soft/weather/writing.md +28 -0
  265. package/release.json +9 -9
  266. package/skill/SKILL.md +12 -12
  267. package/skill/references/building-blocks.md +4 -4
  268. package/skill/references/pages-and-data.md +13 -9
  269. package/skill/references/writing-html.md +2 -0
  270. package/web/assets/index-BM_K-Auu.css +1 -0
  271. package/web/assets/index-DRslOBiv.js +15 -0
  272. package/web/index.html +2 -2
  273. package/dist/chunk-2NRBY6AJ.mjs +0 -2
  274. package/dist/chunk-35NQ4PLQ.mjs +0 -2
  275. package/dist/chunk-4AV456RQ.mjs +0 -2
  276. package/dist/chunk-5XYHDBJ5.mjs +0 -2
  277. package/dist/chunk-6A53MZYZ.mjs +0 -2
  278. package/dist/chunk-6EXH3ORZ.mjs +0 -166
  279. package/dist/chunk-BVEFGE4B.mjs +0 -2
  280. package/dist/chunk-D4EURAX4.mjs +0 -4
  281. package/dist/chunk-DQCE7TJY.mjs +0 -5
  282. package/dist/chunk-FWNRPMCJ.mjs +0 -12
  283. package/dist/chunk-FWW4CSAZ.mjs +0 -2
  284. package/dist/chunk-JVHHHGEA.mjs +0 -3
  285. package/dist/chunk-PZDLJJTJ.mjs +0 -3
  286. package/dist/chunk-SXHBYZST.mjs +0 -16
  287. package/dist/chunk-UFNYFFKO.mjs +0 -20
  288. package/dist/chunk-UKSHDZZ6.mjs +0 -2
  289. package/dist/chunk-VJPFVNNW.mjs +0 -15
  290. package/dist/chunk-VS3ZMVGX.mjs +0 -5
  291. package/web/assets/index-BK2e_07w.js +0 -13
  292. package/web/assets/index-CWFI83mF.css +0 -1
@@ -0,0 +1,5 @@
1
+ import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
+ import{c as _}from"./chunk-W7665ZEC.mjs";import{n as G,p as Le,r as Ee,s as Ne,t as Ie,x as Oe}from"./chunk-7JDX4E65.mjs";import{c as he,d as pe,e as ue,f as fe,g as we,h as ge,i as me,j as z,l as $e,n as Y,o as ke,q as be,r as ye,s as xe,t as ve,u as Se}from"./chunk-3MBRL2PM.mjs";import{M as Ae}from"./chunk-HPOI4ZX7.mjs";import"./chunk-342HXE3Q.mjs";import"./chunk-EAIFITAV.mjs";import{d as Ce,g as je}from"./chunk-EP25HDAJ.mjs";import"./chunk-AR5D57ZD.mjs";import"./chunk-67N2QJYT.mjs";import{i as ie}from"./chunk-5XA2ZBAE.mjs";import{a as W}from"./chunk-JEUK3ZO7.mjs";import"./chunk-JLTZF4LA.mjs";import{a as re,b as le,e as de,f as K,g as ce}from"./chunk-PUOQ65NC.mjs";import"./chunk-7OG26PGF.mjs";import"./chunk-DJISHPUL.mjs";import"./chunk-ZWWC4KLF.mjs";import"./chunk-IA4PSIMD.mjs";import"./chunk-2OHANJ6Q.mjs";import"./chunk-F4ZA6JRZ.mjs";import"./chunk-7M2BQQGZ.mjs";import"./chunk-ITOH5EGO.mjs";import"./chunk-ZQS6H473.mjs";import"./chunk-QE5RG76S.mjs";import{a as H,b as j,c as P,d as D,f as oe}from"./chunk-UYVCQK3H.mjs";import{a as te,e as B,f as ae}from"./chunk-J5PUIV3Y.mjs";import{b as se}from"./chunk-4OZWXZE5.mjs";import"./chunk-MXUBKDRO.mjs";import"./chunk-HXG7EOPJ.mjs";import"./chunk-ZTHICSSF.mjs";import"./chunk-6N3PX4XX.mjs";import"./chunk-PAREWQGB.mjs";import{j as ne}from"./chunk-BFJGHSQN.mjs";import"./chunk-U5XL7D6A.mjs";import"./chunk-HYMEEXKN.mjs";import"./chunk-UMHUSOPJ.mjs";import"./chunk-R2ZDLJYT.mjs";import"./chunk-VFX2KNHP.mjs";import"./chunk-VS7JIGJW.mjs";import{f as Z,j as ee}from"./chunk-HDWTZ763.mjs";import{b as X,e as _e}from"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";_e();import{existsSync as Ue}from"node:fs";import R from"node:fs/promises";import O from"node:path";import{isInstance as Ke}from"../browser/shared/components/index.mjs";import{ATTRIBUTE as He,INSTANCE as Ye}from"../browser/shared/components/installed.mjs";import{attr as M,hasClass as q,walk as Re}from"../browser/shared/html-tree.mjs";import{assetFile as Qe,imageFile as Te,referencedFile as Me}from"../browser/shared/media.mjs";import{pageAssetAddress as Ve,pageExists as Je,pageFiles as Xe}from"../browser/shared/pages.mjs";import{layoutOf as U}from"../browser/shared/workspace.mjs";var Q=[1280,1920,600],De=["light","dark"],Ze=900,et=3e4,tt=new Set(["iframe","frame","object","embed"]),at=/^\d+$/,ot={x:[0,11],y:[0,1/0],w:[1,12],h:[1,24]};function st(e,{catalog:g,folder:o,slug:h}){let i=[],s=d=>d?.sourceCodeLocation?.startLine??1,n=(d,a)=>i.push({line:typeof d=="number"?d:s(d),what:a}),t=X(e.replace(/^/," "),{sourceCodeLocationInfo:!0}),c=[],f=[];Re(t,d=>{d.tagName&&(d.tagName==="main"&&q(d,"gallery-page")&&c.push(d),q(d,"gallery-board")&&f.push(d),q(d,"gallery-card")&&!q(d.parentNode,"gallery-board")&&n(d,`a card (class gallery-card) that is no board's child: each card stands right in a <div class="gallery-board" data-board-id="\u2026">, which lays it out, and this one is laid out by none`))},{inTemplates:!1}),c.length===0&&(f.length>0||j(e).cards.length>0)&&n(1,`no <main class="gallery-page">: a page's boards stand in one (it is how a block knows it is on a page: context.place "page", and how the page follows the theme)`);let y=new Map;for(let d of f){let a=d.parentNode;for(;a&&!(a.tagName==="main"&&q(a,"gallery-page"));)a=a.parentNode;c.length&&!a&&n(d,`a board outside <main class="gallery-page">: its cards' blocks would not know they are on a page`);let r=M(d,"data-board-id");r===void 0||r===""?n(d,"a board with no data-board-id: write one (main, side\u2026), of lowercase letters, digits and hyphens, once in the page"):H.test(r)?y.has(r)?n(d,`data-board-id="${r}" again (line ${y.get(r)} has it): each board's id is its own`):y.set(r,s(d)):n(d,`data-board-id="${r}": a board's id is lowercase letters, digits and single hyphens (main, side-2)`)}let S=new Map,N=new Map;for(let d of j(e).cards){let{node:a}=d,r=M(a,"data-card-id"),k=r&&H.test(r)?`card ${r}`:"this card";r===void 0||r===""?n(a,"a card with no data-card-id: write one (c<n>, the lowest none holds, or a name of your own), of lowercase letters, digits and hyphens: its place, its writes and the reader's state go by it"):H.test(r)?S.has(r)?n(a,`data-card-id="${r}" again (line ${S.get(r)} has it): each card's id is its own, and the page's writes go by it`):S.set(r,s(a)):n(a,`data-card-id="${r}": a card's id is lowercase letters, digits and single hyphens (c3, water)`);let u=0;Re(a,x=>{x!==a&&Ke(x)&&(u+=1)},{inTemplates:!1}),u===0?n(a,`${k} holds no instance of a custom block (an element with ${He}): a card is one block's instance, gallery/static's for what only shows`):u>1?n(a,`${k} holds ${u} instances: a card holds one (put each on a card of its own)`):d.instance&&d.instance.parentNode!==a&&n(d.instance,`${k}'s instance stands inside another element of the card: write it right in the card's <section>`);let b={};for(let x of["x","y","w","h"]){let A=M(a,`data-${x}`),[L,E]=ot[x];A===void 0?n(a,`${k} has no data-${x}: a card says its place and size in whole cells, data-x data-y data-w data-h`):at.test(A.trim())?Number(A)<L||Number(A)>E?n(a,`${k}'s data-${x}="${A}": ${x} is ${E===1/0?`${L} or more`:`${L} to ${E}`}${x==="w"?" (a row is 12 cells)":""}`):b[x]=Number(A):n(a,`${k}'s data-${x}="${A}" is no whole number`)}b.x!==void 0&&b.w!==void 0&&b.x+b.w>12?n(a,`${k} reaches past the row's end: data-x ${b.x} and data-w ${b.w} make ${b.x+b.w}, and a row is 12 cells (x + w is 12 at most)`):Object.keys(b).length===4&&N.set(d.board,[...N.get(d.board)??[],{id:r??null,...b,line:s(a)}]),d.block&&nt(d.block,g,x=>n(d.instance,`${k}'s block ${d.block}: ${x}`))}for(let d of N.values())for(let a=0;a<d.length;a++)for(let r=a+1;r<d.length;r++){let[k,u]=[d[a],d[r]];k.x<u.x+u.w&&u.x<k.x+k.w&&k.y<u.y+u.h&&u.y<k.y+k.h&&n(u.line,`card ${u.id??"here"} (x ${u.x}, y ${u.y}, ${u.w} \xD7 ${u.h}) shares cells with card ${k.id??`at line ${k.line}`} (x ${k.x}, y ${k.y}, ${k.w} \xD7 ${k.h}): no two cards of a board overlap; move one to a free spot (gallery page add finds one for a new card)`)}return i.push(...it(e,{folder:o,slug:h})),i.sort((d,a)=>d.line-a.line)}function nt(e,g,o){let h=g.packages.get(e);if(h){h.places.includes("page")||o(`a block of documents (its manifest's places has no "page"): on a custom page its card says so and runs nothing`);return}let i=g.problems.get(e);g.settings.disabled.includes(e)?o("turned off in \u8BBE\u7F6E \u203A \u7EC4\u4EF6\u5217\u8868: its card says so and runs nothing (the user turns it on again)"):i?o(`it does not load (${ee("en",i.problem)}): gallery block check ${e} says why`):ae(e)&&B(e)?o(`one of Gallery's own blocks, not yet in this workspace: gallery block add ${B(e).pack===te?B(e).name:e} puts it in`):o("no custom block of that id in this workspace: gallery block list lists them")}function it(e,{folder:g,slug:o}){let h=[],i=`${Ve(o,"assets/")}`;for(let s of ne(e,()=>!0)){let n=s.value.trim(),t=["a","area"].includes(s.node.tagName)&&s.how==="href",c=Me(n)??(n.startsWith(i)?Me(n.slice(i.length-7)):null),f=`"${n.length>60?`${n.slice(0,60)}\u2026`:n}"`,y=s.how==="css"?`<style>'s url() ${f}`:`<${s.node.tagName}>'s ${s.how==="style"?"style url()":s.how} ${f}`;if(c!==null){Qe(c)?tt.has(s.node.tagName)&&!Te(c)?h.push({line:s.line,what:`${y}: a frame of a file of the page's assets/ downloads it and shows nothing, as the server hands out a page's own file that is no picture, stylesheet or script for saving only: write what it shows in the page itself, frame a site by its https address, or offer the file with a link, <a href="${c}" download>`}):Ue(O.join(g,c))||h.push({line:s.line,what:`${y}: ${c} is not in the page's folder (${W(O.join(g,"assets"))}): put the file there${Te(c)?"":", or link to it"}`}):h.push({line:s.line,what:`${y} names a file the server serves none by: the page's own files go right in pages/${o}/assets/, each named with letters, digits, dots, dashes and underscores (assets/cover.png)`});continue}t||!n||/^(?:[a-z][a-z0-9+.-]*:|\/|#|\?)/i.test(n)||h.push({line:s.line,what:`${y} is relative to /pages/${o}, where nothing is served: put the file in pages/${o}/assets/ and write assets/<file>`})}return h}function rt(e,g){let o=P(e).text,h=[];for(let i of j(o).cards){let s=i.block?g.packages.get(i.block):null;if(!s?.settings?.some(f=>f.required)||!s.parts.settings)continue;let n=G(D(o,i),_,{...s,parts:{settings:s.parts.settings}})?.parts.find(({name:f})=>f==="settings"),t={};try{t=n?.text.trim()?JSON.parse(n.text):{}}catch{continue}let c=je(s,t);c.length&&h.push({id:i.id,block:i.block,line:i.node.sourceCodeLocation?.startLine??1,empty:c})}return h}var lt=({id:e,block:g,empty:o})=>`card ${e} (${g}) holds no ${o.map(({key:h,label:i,zh:s})=>`${h} (${s&&s!==i?`${i}, ${s}`:i})`).join(" and no ")} in its settings, which it cannot show anything without: it shows its ask for one (the grip at its top right \u203A \u8BBE\u7F6E\u2026), and no picture of the page shows what it is for. Ask the user for it, or take it from what the workspace says (\u5199\u4F5C\u504F\u597D, the documents), write it in the card's settings part, and tell them in the handoff which you did`,dt=(e,g=!1)=>{let o=h=>M(e.node,`data-${h}`)??"-";return`x ${o("x")}, y ${o("y")}, ${o("w")} \xD7 ${o("h")}${g?` on ${e.board??"-"}`:""}`},Fe=e=>`${e.board},${M(e.node,"data-x")},${M(e.node,"data-y")}`,Pe=e=>`${M(e.node,"data-w")},${M(e.node,"data-h")}`;function ct(e,g,o){let[h,i]=[P(e).text,P(g).text],[s,n]=[j(h).cards,j(i).cards],t=new Set([...s,...n].map(a=>a.board)).size>1,c=a=>dt(a,t),f={added:[],removed:[],moved:[],resized:[],data:[],markup:[],page:null,kept:0};for(let a of s)n.some(r=>r.id===a.id)||f.removed.push({id:a.id,block:a.block,cells:c(a)});for(let a of n)s.some(r=>r.id===a.id)||f.added.push({id:a.id,block:a.block,cells:c(a)});for(let a of n){let r=s.find($=>$.id===a.id);if(!r)continue;let[k,u]=[Fe(r)!==Fe(a),Pe(r)!==Pe(a)];k&&f.moved.push({id:a.id,block:a.block,was:c(r),now:c(a)}),u&&f.resized.push({id:a.id,block:a.block,was:c(r),now:c(a)});let[b,x]=[D(h,r),D(i,a)];if(b===x){!k&&!u&&(f.kept+=1);continue}let A=r.block===a.block?o.packages.get(a.block):null,L=A?{...A,parts:Object.fromEntries(Object.entries(A.parts).filter(([,$])=>$.edit==="data"))}:null,[E,l]=L?[G(b,_,L),G(x,_,L)]:[null,null];if(!E||!l){f.markup.push({id:a.id,block:A?a.block:null});continue}let v=E.parts.flatMap(({name:$,text:m},I)=>m===l.parts[I].text?[]:[{name:$,...Y(m,l.parts[I].text),runs:ke(m,l.parts[I].text)}]);v.length&&f.data.push({id:a.id,block:a.block,parts:v}),E.outside!==l.outside&&f.markup.push({id:a.id,block:a.block})}let y=(a,r)=>{let k="",u=0;for(let b of[...r].sort((x,A)=>x.start-A.start))k+=a.slice(u,b.start),u=b.end;return k+a.slice(u)},[S,N]=[y(h,s),y(i,n)],d=a=>a.replace(/\s+/g," ");return d(S)!==d(N)&&(f.page=Y(S.replace(/^\s*\n/gm,""),N.replace(/^\s*\n/gm,""))),f}var ze="(the user's, on the page)",We="(put there by Gallery)";function ht(e,g){let o=n=>{let t=new Map;for(let c of g)if(c.by===n)for(let[f,y]of Object.entries(c.cards??{}))t.set(f,new Set([...t.get(f)??[],...Array.isArray(y)?y:[]]));return t},h=o("page"),i=o("gallery"),s=n=>t=>{let c=!!h.get(t.id)?.has(n);return{...t,user:c,...!c&&i.get(t.id)?.has(n)?{gallery:!0}:{}}};return{...e,added:e.added.map(s("added")),removed:e.removed.map(s("removed")),moved:e.moved.map(s("cells")),resized:e.resized.map(s("cells")),data:e.data.map(s("content")),markup:e.markup.map(s("content"))}}function pt(e,g){let o=({id:t,block:c})=>`${t}${c?` (${c})`:""}`,h=t=>t.user?` ${ze}`:t.gallery?` ${We}`:"",i=[];for(let t of e.added)i.push(` added ${o(t)} at ${t.cells}${h(t)}`);for(let t of e.removed)i.push(` removed ${o(t)}, which stood at ${t.cells}${h(t)}`);for(let t of e.moved)i.push(` moved ${o(t)}: ${t.was} then ${t.now}${h(t)}`);for(let t of e.resized)e.moved.some(c=>c.id===t.id)||i.push(` resized ${o(t)}: ${t.was} then ${t.now}${h(t)}`);for(let t of e.data)i.push(` data ${o(t)}: ${$e(t.parts)}${h(t)}`,...Le(t.parts).map(c=>` ${c}`));for(let t of e.markup)i.push(` markup ${o(t)}: its markup outside its place and its data parts${t.block?"":" (a block the workspace has not: its markup whole)"}${h(t)}`);if(e.page&&i.push(` page its own HTML outside the cards: -${e.page.removed} +${e.page.added} of its ${e.page.lines} line${e.page.lines===1?"":"s"}`),i.length===0)return[`No change since ${g}: every card where it was, with the data it had.`];let s=["added","removed","moved","resized","data","markup"].some(t=>e[t].some(c=>c.user)),n=["added","removed","moved","resized","data","markup"].some(t=>e[t].some(c=>c.gallery));return[`Changes since ${g}:`,...i,...e.kept?[e.kept===1?" The other card as it was.":` The other ${e.kept} cards as they were.`]:[],...s?[` Each change marked ${ze} is the user's own gesture on the page since then (a move, a resize, a card added or deleted there, what they typed in it), which the page wrote: leave it as it is, never put it back.`]:[],...n?[` Each change marked ${We} is Gallery's own doing, not the user's and not yours: the cards it put on the home page when it made it (\u95EE\u5019\u4E0E\u65E5\u671F, \u4FBF\u7B7E): leave it as it is.`]:[]]}async function ut(e,g){let{qa:o,state:h}=U(e),i=O.join(o,g,"checked.html"),s=await R.readFile(i,"utf8").catch(()=>null);if(s!==null){let{mtime:y}=await R.stat(i);return{text:s,since:`the last check that found nothing (${qe(y)}, local time, ${W(i)})`,at:y.getTime()}}let n=O.join(h,"pages",g),t=(await R.readdir(n).catch(()=>[])).filter(y=>/^\d{15}-\d{4}\.html$/.test(y)).sort();if(t.length===0)return null;let c=O.join(n,t.at(-1)),f=Number(t.at(-1).slice(0,15));return{text:await R.readFile(c,"utf8"),since:`the page as it was before its last write (${qe(new Date(f))}, local time; used because no check has passed yet)`,at:f}}var qe=e=>`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")} ${String(e.getHours()).padStart(2,"0")}:${String(e.getMinutes()).padStart(2,"0")}`;function ft(e,g){let o=t=>`<${t.localName}${t.getAttribute("src")?` src="${t.getAttribute("src").slice(0,80)}"`:""}>`,h=[...document.querySelectorAll(".gallery-board > .gallery-card")].map(t=>{let c=t.parentElement.getBoundingClientRect(),f=t.getBoundingClientRect(),y=[...t.children].find(S=>S.matches(e));return{id:t.getAttribute("data-card-id"),block:y?.getAttribute(g)??null,out:f.width>0&&(f.left<c.left-1||f.right>c.right+1),tall:t.scrollHeight>t.clientHeight+1?{needs:t.scrollHeight,has:t.clientHeight}:null,wide:t.scrollWidth>t.clientWidth+1?{needs:t.scrollWidth,has:t.clientWidth}:null,fallback:!!y?.hasAttribute("data-doc-fallback"),error:(t.querySelector(".doc-kit-error")?.textContent??"").trim()||null,broken:[...t.querySelectorAll("img")].filter(S=>S.complete&&S.naturalWidth===0).map(o)}}),i=[...document.querySelectorAll("img")].filter(t=>!t.closest(".gallery-card")&&t.complete&&t.naturalWidth===0).map(o),s=document.documentElement.scrollWidth,n=[...globalThis.__galleryQueries?.pending.values()??[]].map(({kind:t,block:c,at:f})=>({kind:t,block:c,waited:Date.now()-f}));return{cards:h,broken:i,stuck:n,wide:s>innerWidth+1?s:0,columns:document.querySelector(".gallery-board")?.getAttribute("data-columns")??null}}async function wt(e,{address:g,out:o,readers:h=new Set,wait:i=ge,limits:s={}}){let{loading:n=he,ready:t=et,answer:c=pe,closing:f=de,looking:y=ue}=s,S=new Map,N=new Map,d=[],a=!1,r=(l,v,$,m,I=S)=>{if(a)return;let w=I.get(l)??{card:v,what:$,looks:[]};w.looks.push(m),I.set(l,w)},k="a browser context opened",u=(l,v,$=c)=>(k=v,ye(l,v,$)),b=Q.flatMap(l=>De.map(v=>({width:l,theme:v,view:`${l} ${v}`}))),x=null,A=async({width:l,theme:v,view:$})=>{let m=await u(x.newPage(),"a tab opened");try{m.on("pageerror",p=>r(`error ${z(p)}`,null,`the page threw: ${z(p)}`,$)),m.on("console",p=>{p.type()==="error"&&!/^Failed to load resource/.test(p.text())&&r(`console ${p.text().split(`
3
+ `)[0]}`,null,`the console says ${p.text().split(`
4
+ `)[0]}`,$)}),m.on("response",p=>{let C=new URL(p.url());p.status()>=400&&C.origin===new URL(g).origin&&C.pathname!=="/favicon.ico"&&r(`request ${C.pathname}`,null,`${C.pathname} answered ${p.status()}`,$)}),await u(be(m,{add:p=>r(`dialog ${p}`,null,`it opened a dialog (${p}), which stops a reader's page until it is answered`,$)}),"the tab was set to refuse dialogs"),await u(me(m),"the tab was set to watch the page's reads of the workspace"),await u(m.setViewport({width:l,height:Ze}),`the window went to ${l}px`),await u(m.emulateMediaFeatures([{name:"prefers-color-scheme",value:v}]),`the ${v} theme came`),await u(m.goto(g,{waitUntil:"load",timeout:0}),"the page opened",n),await u(m.waitForSelector("html[data-doc-ready][data-doc-drawn]",{timeout:0}),"the page was drawn (its html got data-doc-drawn)",t),await u(m.evaluate(()=>document.fonts?.ready.then(()=>!0)),"the page's fonts loaded");let I=await u(m.$("main"),"the page's main was found")??await u(m.$("body"),"the page's body was found");await u(I.evaluate(Oe,{still:fe,step:we,wait:i}),"the page held still");let w=await u(m.evaluate(ft,Ye,He),"the page was looked at");for(let{kind:p,block:C,waited:Ge}of w.stuck){let V=w.cards.filter(F=>C?F.block===C:h.has(F.block)),J=F=>`the workspace had not answered ${F} read of "${p}" ${Math.round(Ge/1e3)} s after it asked, so its picture shows it before it drew what it reads, which the picture then does not tell (open the page in Gallery to see it)`;if(V.length)for(let F of V)r(`unanswered ${F.id} ${p}`,F.id,J("its"),$,N);else r(`unanswered ${p}`,null,J("a card's"),$,N)}w.wide&&r("wide",null,`the page is ${w.wide}px wide in a window ${l}px wide: something of its own reaches past the window (a width of its own, a long word), and a reader scrolls it sideways`,$);for(let p of w.broken)r(`broken ${p}`,null,`a picture that does not load: ${p}`,$);for(let p of w.cards){p.fallback&&r(`fallback ${p.id}`,p.id,`its block failed: the card shows what its instance holds, read-only${p.error?` (${p.error.slice(0,200)})`:""}`,$),p.out&&r(`out ${p.id}`,p.id,"it is drawn out of its board",$),p.tall&&r(`tall ${p.id}`,p.id,`what it holds does not fit it: ${p.tall.needs}px high in a card that shows ${p.tall.has}px, the rest scrolling inside the card (give the card more cells, data-h, or a size its block lists; a block whose content grows says card.fit "content")`,$),p.wide&&r(`wide ${p.id}`,p.id,`what it holds is wider than the card: ${p.wide.needs}px in a card ${p.wide.has}px wide`,$);for(let C of p.broken)r(`broken ${p.id} ${C}`,p.id,`a picture that does not load: ${C}`,$)}let T=O.join(o,`${l}-${v}.png`);await u(m.screenshot({path:T,fullPage:!0}),"the page was pictured"),a||d.push(T)}finally{await K(m.close(),f)}},L=l=>({problems:[...S.values()],notes:[...N.values()],pictures:d,unverified:null,stuck:!1,...l}),E=null;try{x=await u(e.createBrowserContext(),"a browser context opened");for(let l of b)E=l,await gt(A(l),y,()=>k);return L({})}catch(l){return await Se(e)?L({unverified:`the browser went while it looked (${z(l)})`}):l.stuck?(r("stopped",null,mt(l,b.indexOf(E??b[0])<b.length-1),(E??b[0]).view),L({stuck:!0})):L({unverified:`the look stopped: ${z(l)}`})}finally{a=!0,await K(x?.close(),f)}}function gt(e,g,o){let h=0,i=new Promise((s,n)=>{h=setTimeout(()=>n(Object.assign(new Error(o()),{stuck:!0,doing:o(),limit:g,whole:!0})),g)});return Promise.race([e,i]).finally(()=>clearTimeout(h))}function mt(e,g){return`${e.whole?`the look was not done in ${xe(e.limit)}, waiting until ${e.doing}`:ve(e)}; the look stopped here and the browser was closed${g?", so the looks after it were not made":""}. A script of the page that never ends does this, and so may a browser that stalled: run the check once more, and if it stops at the same place again, the page holds it up`}function Be(e){let g=[...new Set(e.map(i=>i.split(" ")[0]))],o=[...new Set(e.map(i=>i.split(" ")[1]))],h=i=>i.length<2?i.join(""):`${i.slice(0,-1).join(", ")} and ${i.at(-1)}`;return`at ${h(g)}px${o.length===De.length?"":`, ${h(o)}`}`}async function Ht(e,g){if(g.length!==1)throw new se("gallery page check takes one page's slug.");let[o]=g,h=Xe(o,e);Je(o,e)||(console.error(await Ce(o,e)),process.exit(1));let i=new Date,s=await R.readFile(h.html,"utf8"),n=O.basename(h.html),t=Z(e),{boards:c,cards:f}=j(s);console.log(`${o}: ${W(h.html)}, ${c.length} board${c.length===1?"":"s"} and ${f.length} card${f.length===1?"":"s"}`);let y=[],S=st(s,{catalog:t,folder:h.folder,slug:o});for(let{line:l,what:v}of S)y.push(` FAIL ${n}:${l}: ${v}`);console.log(S.length?`Structure: ${S.length} problem${S.length===1?"":"s"}`:"Structure: nothing wrong (the page's own HTML, scripts and frames its own; every board's and card's id once, one instance a card, the cells on the board and none shared, every block one a page runs, every file of assets/ there)");for(let l of y)console.log(l);for(let l of j(P(s).text).cards)console.log(` ${l.id} ${l.block??"(no instance)"} x ${l.x}, y ${l.y}, ${l.w} \xD7 ${l.h}${c.length>1?` on ${l.board}`:""} ${n}:${l.node.sourceCodeLocation?.startLine}`);let N=rt(s,t);for(let l of N)console.log(` note ${n}:${l.line}: ${lt(l)}`);let d=await ut(e,o),a=d?await oe(U(e).state,o,d.at):[];console.log((d?pt(ht(ct(d.text,s,t),a),d.since):["No earlier version to tell changes against: the next check that finds nothing keeps this one, and says what changed since."]).join(`
5
+ `));let r=new Map(j(P(s).text).cards.map(l=>[l.id,l.node.sourceCodeLocation?.startLine??1])),k=(l,v=null,$=0)=>{if(l)return{line:`FAIL ${o}: ${l} problem${l===1?"":"s"}`,code:1};if(v)return{line:`UNVERIFIED ${o}: ${v}; its structure was checked, and nothing is wrong with it`,code:3};let m=N.length?`; and ${N.length===1?"one card asks":`${N.length} cards ask`} for a setting no one gave (see "note" above): ${N.map(({id:I,empty:w})=>`${I} (${w.map(({key:T})=>T).join(", ")})`).join(", ")}`:"";return{line:`OK ${o}: its structure, and its ${f.length} card${f.length===1?"":"s"} at ${Q.join(", ")}px in light and dark${$?`; but ${$===1?"one card was":`${$} cards were`} pictured before the workspace answered it (see "note" above), so ${$===1?"its picture does":"their pictures do"} not show what ${$===1?"it reads":"they read"}`:""}${m}`,code:0}},u=await ie({command:`gallery page check ${o}`}),b=async(l,v,$=0)=>{let{line:m,code:I}=k(l,v,$);if(console.log(m),I===0){let w=O.join(U(e).qa,o,"checked.html");await R.mkdir(O.dirname(w),{recursive:!0}),await R.writeFile(w,s),await R.utimes(w,i,i)}process.exitCode=I};if(!u.ok)return b(S.length,`${u.message}, so the page was not looked at`);let x=re();if(!x)return b(S.length,"no Chrome, Edge or Chromium found (GALLERY_BROWSER=<its executable> picks one), so the page was not looked at");await Ie(e);let A=await Ee(e,{directory:h.folder,files:h,text:s}),L=O.join(U(e).qa,o,"check"),E=null;try{let{pageAloneOf:l}=await import("./chunk-UJQJKNGK.mjs"),v=l(u.port,A.slug);console.log(`Looked at: ${v} (a scratch copy of ${o}, gone at the end: nothing a block does as it opens writes ${n}), at ${Q.join(", ")}px, light and dark`);try{E=await ce({executablePath:x,args:le()})}catch(w){return b(S.length,`the browser ${x} did not start, twice (${z(w)}), so the page was not looked at`)}await R.rm(L,{recursive:!0,force:!0}),await R.mkdir(L,{recursive:!0});let $=new Set([...t.packages.values()].filter(({needs:w})=>w?.includes("workspace")).map(({id:w})=>w)),m=await wt(E.browser,{address:v,out:L,readers:$});m.stuck&&(await E.close(),E=null);for(let{card:w,what:T,looks:p}of m.problems)console.log(` FAIL ${n}:${w?r.get(w)??1:1}: ${w?`card ${w}: `:""}${T} (${Be(p)})`);let I=new Map(j(s).cards.map(w=>[w.id,w.block]));for(let{card:w,what:T,looks:p}of m.notes)console.log(` note ${n}:${w?r.get(w)??1:1}: ${w?`card ${w}${I.get(w)?` (${I.get(w)})`:""}: `:""}${T} (${Be(p)})`);return m.pictures.length&&(console.log(`Pictures of the page in ${W(L)}: ${m.pictures.map(w=>O.basename(w)).join(", ")}`),console.log(Ae([{folder:O.dirname(L),files:m.pictures}]))),b(S.length+m.problems.length,m.unverified,new Set(m.notes.map(({card:w})=>w??"")).size)}finally{await E?.close(),await Ne(e,A.slug)}}export{We as GALLERYS_MARK,Q as LOOK_WIDTHS,De as THEMES,ze as USERS_MARK,ut as baselineOf,pt as changesSaid,rt as emptyRequired,lt as emptyRequiredSaid,wt as look,ht as markedTheUsers,ct as pageChanges,Ht as pageCheckCommand,st as structureProblems};
@@ -1,3 +1,3 @@
1
1
  import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{a}from"./chunk-JEUK3ZO7.mjs";import"./chunk-V6RIYQZZ.mjs";import{f as D}from"./chunk-SXHBYZST.mjs";import{b as d,f as J,i as k}from"./chunk-4OZWXZE5.mjs";import{c as F}from"./chunk-JVHHHGEA.mjs";import"./chunk-HYMEEXKN.mjs";import{a as A}from"./chunk-UMHUSOPJ.mjs";import"./chunk-N76HWBA3.mjs";import"./chunk-FJYN7RTH.mjs";import"./chunk-UBBRTJ2R.mjs";import"./chunk-FWNRPMCJ.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";import{existsSync as E}from"node:fs";import R from"node:fs/promises";import m from"node:path";import{iconKind as q}from"../browser/shared/emoji/icon-value.mjs";import{writeAtomic as z}from"../browser/shared/files.mjs";import{reportsDirectory as C}from"../browser/shared/paths.mjs";import{roleOf as M}from"../browser/shared/reports.mjs";import{documentDirectory as P,documentFiles as T,pageSlug as U}from"../browser/shared/workspace.mjs";var K=o=>o.replace(/\s+/g," ").trim(),_=o=>o.replace(/^[a-z]:\/(?:[^/]+\/)*?(?=icons\/(?:tabler\/)?[^/]+$)/i,"/"),h=o=>o===null?"none":JSON.stringify(o);async function ie(o){let{positional:u,values:c}=J({values:["--title","--icon","--description"],argv:o});if(u.length!==1)throw new d("Name one document, then what to set: --title, --icon, --description.");if(!["--title","--icon","--description"].some(e=>c.has(e)))throw new d('Say what to set: --title "<title>", --icon <emoji|none|\u2026>, --description "<text>".');let n=c.has("--title")?K(c.get("--title")):void 0,p=c.has("--description")?K(c.get("--description")):void 0;if(n==="")throw new d("--title takes the words of the title: a document's title is never empty.");if(p==="")throw new d("--description takes words: a document's description is never empty.");let t;if(c.has("--icon")){let e=_(c.get("--icon").trim()),f=e==="none"?"none":q(e);if(!f||/["<>&]/.test(e))throw new d(`Not a page icon: ${e} (an emoji, none, an icon of the \u56FE\u6807 tab as /icons/<name>_<color>.svg, or a picture of the document's assets/).`);if(f==="glyph"&&!F(e))throw new d(`No such icon of the \u56FE\u6807 tab: ${e}.`);t=f==="none"?null:e}let{slug:w}=await k(u[0]),$=P(w,C);(w===await U(C)||await M($)==="instructions")&&(console.error(`${u[0]} is the \u5199\u4F5C\u504F\u597D page: only the user changes it.`),process.exit(1));let{html:r,json:s}=T($);E(r)||(console.error(`No document "${u[0]}": ${a(r)} does not exist (gallery list lists those there are).`),process.exit(1)),t&&q(t)==="image"&&!E(m.join($,...t.split("/")))&&(console.error(`No picture ${t} in ${a($)}: put it in its assets/ first.`),process.exit(1));let i;try{if(i=JSON.parse(await R.readFile(s,"utf8")),!i||typeof i!="object"||Array.isArray(i))throw new Error("not an object")}catch(e){console.error(`${a(s)} does not read (${e.code??e.message}): mend it first.`),process.exit(1)}let b=null,N=!1;for(let e=1;n!==void 0||t!==void 0;e++){let f=await R.readFile(r,"utf8"),v=A(f),y=D(v,{title:n,icon:t});if(y.missing&&(console.error(`${a(r)} has no title to ${n!==void 0?"set":"put the icon before"}: write it as an h1.doc-title in the page's header (writing-html.md, "The page").`),process.exit(1)),b=y.before,y.text===v)break;if(await z(r,y.text,{expect:f})){N=!0;break}e===3&&(console.error(`${a(r)} kept changing while it was being written (the page saving, or an Agent writing it?): nothing written. Run gallery set again.`),process.exit(1))}let l={...i};n!==void 0&&(l.title=n),p!==void 0&&(l.description=p),t===null?delete l.icon:t!==void 0&&(l.icon=t);let x=JSON.stringify(l)!==JSON.stringify(i);x&&await z(s,`${JSON.stringify(l,null,2)}
2
+ import{a}from"./chunk-JEUK3ZO7.mjs";import"./chunk-ITOH5EGO.mjs";import{f as D}from"./chunk-ZQS6H473.mjs";import{b as d,f as J,i as k}from"./chunk-4OZWXZE5.mjs";import{c as F}from"./chunk-U5XL7D6A.mjs";import"./chunk-HYMEEXKN.mjs";import{a as A}from"./chunk-UMHUSOPJ.mjs";import"./chunk-R2ZDLJYT.mjs";import"./chunk-VFX2KNHP.mjs";import"./chunk-VS7JIGJW.mjs";import"./chunk-HDWTZ763.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";import{existsSync as E}from"node:fs";import R from"node:fs/promises";import m from"node:path";import{iconKind as q}from"../browser/shared/emoji/icon-value.mjs";import{writeAtomic as z}from"../browser/shared/files.mjs";import{reportsDirectory as C}from"../browser/shared/paths.mjs";import{roleOf as M}from"../browser/shared/reports.mjs";import{documentDirectory as P,documentFiles as T,pageSlug as U}from"../browser/shared/workspace.mjs";var K=o=>o.replace(/\s+/g," ").trim(),_=o=>o.replace(/^[a-z]:\/(?:[^/]+\/)*?(?=icons\/(?:tabler\/)?[^/]+$)/i,"/"),h=o=>o===null?"none":JSON.stringify(o);async function ie(o){let{positional:u,values:c}=J({values:["--title","--icon","--description"],argv:o});if(u.length!==1)throw new d("Name one document, then what to set: --title, --icon, --description.");if(!["--title","--icon","--description"].some(e=>c.has(e)))throw new d('Say what to set: --title "<title>", --icon <emoji|none|\u2026>, --description "<text>".');let n=c.has("--title")?K(c.get("--title")):void 0,p=c.has("--description")?K(c.get("--description")):void 0;if(n==="")throw new d("--title takes the words of the title: a document's title is never empty.");if(p==="")throw new d("--description takes words: a document's description is never empty.");let t;if(c.has("--icon")){let e=_(c.get("--icon").trim()),f=e==="none"?"none":q(e);if(!f||/["<>&]/.test(e))throw new d(`Not a page icon: ${e} (an emoji, none, an icon of the \u56FE\u6807 tab as /icons/<name>_<color>.svg, or a picture of the document's assets/).`);if(f==="glyph"&&!F(e))throw new d(`No such icon of the \u56FE\u6807 tab: ${e}.`);t=f==="none"?null:e}let{slug:w}=await k(u[0]),$=P(w,C);(w===await U(C)||await M($)==="instructions")&&(console.error(`${u[0]} is the \u5199\u4F5C\u504F\u597D page: only the user changes it.`),process.exit(1));let{html:r,json:s}=T($);E(r)||(console.error(`No document "${u[0]}": ${a(r)} does not exist (gallery list lists those there are).`),process.exit(1)),t&&q(t)==="image"&&!E(m.join($,...t.split("/")))&&(console.error(`No picture ${t} in ${a($)}: put it in its assets/ first.`),process.exit(1));let i;try{if(i=JSON.parse(await R.readFile(s,"utf8")),!i||typeof i!="object"||Array.isArray(i))throw new Error("not an object")}catch(e){console.error(`${a(s)} does not read (${e.code??e.message}): mend it first.`),process.exit(1)}let b=null,N=!1;for(let e=1;n!==void 0||t!==void 0;e++){let f=await R.readFile(r,"utf8"),v=A(f),y=D(v,{title:n,icon:t});if(y.missing&&(console.error(`${a(r)} has no title to ${n!==void 0?"set":"put the icon before"}: write it as an h1.doc-title in the page's header (writing-html.md, "The page").`),process.exit(1)),b=y.before,y.text===v)break;if(await z(r,y.text,{expect:f})){N=!0;break}e===3&&(console.error(`${a(r)} kept changing while it was being written (the page saving, or an Agent writing it?): nothing written. Run gallery set again.`),process.exit(1))}let l={...i};n!==void 0&&(l.title=n),p!==void 0&&(l.description=p),t===null?delete l.icon:t!==void 0&&(l.icon=t);let x=JSON.stringify(l)!==JSON.stringify(i);x&&await z(s,`${JSON.stringify(l,null,2)}
3
3
  `);let S=m.basename(r),g=[];n!==void 0&&g.push(` title: ${h(b.title)} \u2192 ${h(n)} (${S}'s h1 and <title>, ${m.basename(s)})`),t!==void 0&&g.push(` icon: ${h(b.icon)} \u2192 ${h(t)} (${S}'s header, ${m.basename(s)})`),p!==void 0&&g.push(` description: ${h(typeof i.description=="string"?i.description:null)} \u2192 ${h(p)} (${m.basename(s)})`);let j=[...N?[a(r)]:[],...x?[a(s)]:[]];if(j.length===0){console.log(`Nothing to change: ${w} has ${g.length===1?"that already":"those already"}.`);return}console.log(`Set ${w}:`);for(let e of g)console.log(e);let O=j.length===1;console.log(`Re-read ${j.join(", ")} before editing ${O?"it":"them"}: gallery set wrote ${O?"it":"them"} (${[...N?[`${S}: its header`]:[],...x?[`${m.basename(s)}: ${["title","icon","description"].filter(e=>JSON.stringify(l[e])!==JSON.stringify(i[e])).join(", ")}`]:[]].join("; ")}).`)}export{ie as run};
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{c as O,d as P,e as b,l as C}from"./chunk-NFMCP2HI.mjs";import{a as q}from"./chunk-KTKHRC6H.mjs";import{a as u,f as S,g as w,i as E,j as I,k as H}from"./chunk-NAMN3RAF.mjs";import{a as h,b as R}from"./chunk-JEUK3ZO7.mjs";import{b as D,f as L,g as T}from"./chunk-4OZWXZE5.mjs";import{b as N}from"./chunk-PAREWQGB.mjs";import{existsSync as g}from"node:fs";import i from"node:path";import{reportsDirectory as c}from"../browser/shared/paths.mjs";import{idHolder as z,isDocSlug as B,keptName as G,layoutOf as A,listTrash as J}from"../browser/shared/workspace.mjs";import{parentIn as K}from"../browser/shared/outline.mjs";import{joinDefaultTree as Q,joinedLine as V}from"../browser/shared/drafts.mjs";var W="\u65B0\u6587\u6863";async function F(t,n=c){if(G(t))return`"${t}" is a name the workspace keeps for itself: choose another slug.`;if(g(i.join(A(n).preferencesPage,t)))return`"${t}" is the \u5199\u4F5C\u504F\u597D page's slug: choose another slug.`;if(g(i.join(A(n).customPages,t)))return`"${t}" is a custom page's slug (documents and custom pages share one set of names: gallery page list lists them): choose another slug.`;if(g(i.join(n,t)))return`Document already exists: ${h(i.join(n,t))}`;if((await J(n)).some(r=>r.slug===t))return`"${t}" is the slug of something in the trash: choose another slug.`;if(B(t)){let r=await z(t,n);if(r)return`"${t}" would have the page id (${t.slice(4)}) of "${r}" in this workspace, and two documents may not share an address: choose another slug.`}return null}async function fe(t){let{positional:n,options:r,values:U}=L({options:["--no-preview","--no-browser","--first"],values:["--under","--after"],argv:t}),[e,y,$=W]=n;if(n.length<2||n.length>3||!e||!y?.trim()||!$.trim())throw new D("Name the slug and the title (then a description, if you choose one), each quoted when it has spaces.");T(e);let s=H(U,r,{top:!1}),x=await F(e);x&&(console.error(x),process.exit(1));let M=s.under!==void 0||s.after!==void 0||s.first,l=null;if(M){let o=await u(),a=async(X,_)=>{let p=await S(X,_,o);return p.refused&&(console.error(`${p.refused} Nothing made.`),process.exit(1)),p.slug},f=s.under!==void 0?await a(s.under,"--under"):void 0,d=s.after!==void 0?await a(s.after,"--after"):null;d!==null&&f!==void 0&&K(o.children,d)!==f&&(console.error(`${w(o,e,"level",{parent:f,after:d})} Nothing made.`),process.exit(1)),l={parent:f,after:d,first:s.first}}try{await N(e,y,$)}catch(o){if(o.code!=="EEXIST")throw o;console.error(await F(e)??`Document already exists: ${h(i.join(c,e))}`),process.exit(1)}if(await import("./chunk-4AV456RQ.mjs").then(({noteNew:o})=>o(e)),console.log(`Created ${h(i.join(c,e,"doc.html"))} and doc.json`),l){let o=await E(e,l),a=await u();o.ok?console.log(`Placed it ${I(a,o)}.`):(console.log(`Not placed (${w(a,e,o.reason,{...l,message:o.message})}): it is at the top level, last; gallery move ${e} puts it where it goes.`),process.exitCode=1)}let v=V(await Q(c,e));v&&console.log(v);for(let o of await R())console.log(o);let j=q(c);j&&console.log(j);let m=await C(e,{skipped:b(r),command:`gallery new ${e}`});console.log(O(m,"replace the starter section with the document's skeleton (each section's heading) as soon as you can outline it, then write it a section at a time, as ordinary HTML, so that the user watches it grow (gallery check fails while the starter section remains).")),console.log(`Hand in: gallery export ${e}, then gallery qa ${e}`);let k=await P(m,r);k&&console.log(k);for(let o of m)console.log(o)}export{W as a,F as b,fe as c};
2
+ import{c as O,d as P,e as b,l as C}from"./chunk-5XA2ZBAE.mjs";import{a as q}from"./chunk-JA7G53PC.mjs";import{a as u,f as S,g as w,i as E,j as I,k as H}from"./chunk-NAMN3RAF.mjs";import{a as h,b as R}from"./chunk-JEUK3ZO7.mjs";import{b as D,f as L,g as T}from"./chunk-4OZWXZE5.mjs";import{b as N}from"./chunk-PAREWQGB.mjs";import{existsSync as g}from"node:fs";import i from"node:path";import{reportsDirectory as c}from"../browser/shared/paths.mjs";import{idHolder as z,isDocSlug as B,keptName as G,layoutOf as A,listTrash as J}from"../browser/shared/workspace.mjs";import{parentIn as K}from"../browser/shared/outline.mjs";import{joinDefaultTree as Q,joinedLine as V}from"../browser/shared/drafts.mjs";var W="\u65B0\u6587\u6863";async function F(t,n=c){if(G(t))return`"${t}" is a name the workspace keeps for itself: choose another slug.`;if(g(i.join(A(n).preferencesPage,t)))return`"${t}" is the \u5199\u4F5C\u504F\u597D page's slug: choose another slug.`;if(g(i.join(A(n).customPages,t)))return`"${t}" is a custom page's slug (documents and custom pages share one set of names: gallery page list lists them): choose another slug.`;if(g(i.join(n,t)))return`Document already exists: ${h(i.join(n,t))}`;if((await J(n)).some(r=>r.slug===t))return`"${t}" is the slug of something in the trash: choose another slug.`;if(B(t)){let r=await z(t,n);if(r)return`"${t}" would have the page id (${t.slice(4)}) of "${r}" in this workspace, and two documents may not share an address: choose another slug.`}return null}async function fe(t){let{positional:n,options:r,values:U}=L({options:["--no-preview","--no-browser","--first"],values:["--under","--after"],argv:t}),[e,y,$=W]=n;if(n.length<2||n.length>3||!e||!y?.trim()||!$.trim())throw new D("Name the slug and the title (then a description, if you choose one), each quoted when it has spaces.");T(e);let s=H(U,r,{top:!1}),x=await F(e);x&&(console.error(x),process.exit(1));let M=s.under!==void 0||s.after!==void 0||s.first,l=null;if(M){let o=await u(),a=async(X,_)=>{let p=await S(X,_,o);return p.refused&&(console.error(`${p.refused} Nothing made.`),process.exit(1)),p.slug},f=s.under!==void 0?await a(s.under,"--under"):void 0,d=s.after!==void 0?await a(s.after,"--after"):null;d!==null&&f!==void 0&&K(o.children,d)!==f&&(console.error(`${w(o,e,"level",{parent:f,after:d})} Nothing made.`),process.exit(1)),l={parent:f,after:d,first:s.first}}try{await N(e,y,$)}catch(o){if(o.code!=="EEXIST")throw o;console.error(await F(e)??`Document already exists: ${h(i.join(c,e))}`),process.exit(1)}if(await import("./chunk-SWUTTZCN.mjs").then(({noteNew:o})=>o(e)),console.log(`Created ${h(i.join(c,e,"doc.html"))} and doc.json`),l){let o=await E(e,l),a=await u();o.ok?console.log(`Placed it ${I(a,o)}.`):(console.log(`Not placed (${w(a,e,o.reason,{...l,message:o.message})}): it is at the top level, last; gallery move ${e} puts it where it goes.`),process.exitCode=1)}let v=V(await Q(c,e));v&&console.log(v);for(let o of await R())console.log(o);let j=q(c);j&&console.log(j);let m=await C(e,{skipped:b(r),command:`gallery new ${e}`});console.log(O(m,"replace the starter section with the document's skeleton (each section's heading) as soon as you can outline it, then write it a section at a time, as ordinary HTML, so that the user watches it grow (gallery check fails while the starter section remains).")),console.log(`Hand in: gallery export ${e}, then gallery qa ${e}`);let k=await P(m,r);k&&console.log(k);for(let o of m)console.log(o)}export{W as a,F as b,fe as c};
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{b as Q}from"./chunk-ZB4H7ZN4.mjs";import{c as _,d as z,e as B,l as G}from"./chunk-NFMCP2HI.mjs";import"./chunk-KTKHRC6H.mjs";import"./chunk-YI43RG4P.mjs";import{i as q}from"./chunk-NAMN3RAF.mjs";import{a as b,b as J}from"./chunk-JEUK3ZO7.mjs";import{a as Z}from"./chunk-B4P2CM2J.mjs";import{a as ee}from"./chunk-VJPFVNNW.mjs";import"./chunk-PZDLJJTJ.mjs";import"./chunk-IA4PSIMD.mjs";import{c as V,d as Y,e as M}from"./chunk-D4CKRD3V.mjs";import"./chunk-UKSHDZZ6.mjs";import"./chunk-6EZ7FNIK.mjs";import"./chunk-35NQ4PLQ.mjs";import"./chunk-V6RIYQZZ.mjs";import{b as W,h as X}from"./chunk-SXHBYZST.mjs";import"./chunk-RKPWLGZ3.mjs";import"./chunk-N7AZZLGT.mjs";import{b as T,f as C,g as H}from"./chunk-4OZWXZE5.mjs";import"./chunk-ZTHICSSF.mjs";import{k as U}from"./chunk-SX4LJYT6.mjs";import{b as K}from"./chunk-PAREWQGB.mjs";import"./chunk-W3BGBJQW.mjs";import"./chunk-JVHHHGEA.mjs";import"./chunk-HYMEEXKN.mjs";import"./chunk-UMHUSOPJ.mjs";import"./chunk-N76HWBA3.mjs";import"./chunk-FJYN7RTH.mjs";import"./chunk-UBBRTJ2R.mjs";import"./chunk-FWNRPMCJ.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";import v from"node:fs/promises";import se from"node:os";import x from"node:path";import{IMPORT_EXT as re,kindOf as ie}from"../browser/shared/import-types.mjs";import{reportsDirectory as O}from"../browser/shared/paths.mjs";import{kebab as S}from"../browser/shared/web-links.mjs";import{documentDirectory as oe,documentFiles as E,newDocSlug as ae}from"../browser/shared/workspace.mjs";var ce=Object.values(re).flat().join(" "),j=(d,g)=>`${d} ${g}${d===1?"":"s"}`;function fe(d,g,p){let n=(f,r=g)=>(r.match(f)??[]).length,c=n(/<ol class="doc-flow"/g,p),$=n(/<li id="fn-\d+"/g,p),w=[[n(/<section class="doc-section"/g),"section"],[n(/<h[2-4][\s>]/g),"heading"],[n(/<p[\s>]/g),"paragraph"],[n(/<(?:ul|ol)[\s>]/g),"list"],[n(/<table\b/g),"table"],[n(/class="doc-math-(?:inline|block)"/g,p),"formula"],[n(/<div class="doc-code"/g),"code block"],[n(/<figure class="doc-image"/g),"picture"],[c,"flow"],[$,"footnote"]].filter(([f])=>f>0).map(([f,r])=>j(f,r)),h=(d.raws?.length??0)-c-($?1:0);return h>0&&w.push(`${j(h,"HTML block")} kept as written`),w}async function Se(d){let{positional:g,options:p}=C({options:["--no-preview","--no-browser"],argv:d}),[n,c,$]=g;if(g.length<1||g.length>3||!n)throw new T("Name the file; then the slug and the title, if you choose them.");let w=ie(n);if(!w)throw new T(`Not a kind of file gallery import takes: ${n} (${ce}).`);c!==void 0&&H(c);let h=x.resolve(n);await v.stat(h).then(i=>i.isFile(),()=>!1)||(console.error(`No such file: ${n}`),process.exit(1));let f=c!==void 0?await Q(c):null;f&&(console.error(f),process.exit(1));let r=x.basename(h),F=await v.mkdtemp(x.join(se.tmpdir(),"gallery-import-")),L,y,R;try{let i,u=[];if(w==="markdown")i=[{...await Y(h,F),from:r,children:[]}];else try{({pages:i,skipped:u}=await V([{file:h,name:r}],F))}catch(e){console.error(`${r} could not be read: ${e.message}`),process.exit(1)}i.length===0&&(console.error(`Nothing in ${r} could be read as a page${u.length?` (not taken: ${u.join(", ")})`:""}.`),process.exit(1)),$?.trim()&&(i[0]={...i[0],title:$.replace(/\s+/g," ").trim()});let I=new Map,te=ee({edits:{},reports:{},reportsDirectory:O});y=(await Z(i,{create:async(e,t,l,{lang:s})=>{let{directory:o}=await K(e,t,l,{blank:!0,lang:s});I.set(e,await v.readFile(E(o).html,"utf8"))},slugOf:(e,t)=>{if(t===0&&c!==void 0)return c;let l=S(e.title)||S(e.from?.replace(/\.[^.]+$/,"")??"")||S(r.replace(/\.[^.]+$/,""));return l?te.freeSlug(l):ae(O)},folderOf:e=>oe(e,O),fill:e=>M(e),place:(e,t)=>q(e,{parent:t})})).made;let P=[],A=(e,t)=>{P.push({page:e,depth:t});for(let l of e.children??[])A(l,t+1)};for(let e of i)A(e,0);let m=await Promise.all(P.map(async({page:e,depth:t},l)=>{let s=y[l],o=oe(s,O),a=E(o).html,k=await v.readFile(a,"utf8"),ne=(await M({source:I.get(s),nodes:e.nodes,icon:e.icon,own:e.own})).replace(/<p>\u{E000}\d+\u{E001}<\/p>/gu,""),le=X(W(k,{finish:U}).text);return{slug:s,depth:t,page:e,directory:o,htmlFile:a,made:fe(e,ne,k),readOnly:le}}));if(L={slug:y[0]},m.length===1){let[{page:e,directory:t,htmlFile:l,made:s,readOnly:o}]=m;if(console.log(`Created ${b(l)} and ${x.basename(E(t).json)} from ${r}`),console.log(`Title: ${e.title}`),console.log(`Made: ${s.length?s.join(", "):"nothing but the title"}${e.files.length?` (${j(e.files.length,"file")} in ${b(x.join(t,"assets"))})`:""}`),e.notes?.length){console.log(`Not brought as the file has it (${e.notes.length}):`);for(let a of e.notes)console.log(` ${a.line?`line ${a.line}: `:""}${a.text}`)}if(o.length){console.log(`Text the preview leaves read-only (${o.length}), by doc.html's lines as gallery check gives them:`);for(let a of o)console.log(` ${a}`)}}else{console.log(`Created ${j(m.length,"document")} from ${r} (each nested as in the file):`);for(let{slug:l,depth:s,page:o,htmlFile:a,made:k}of m)console.log(`${" ".repeat(s+1)}${l} ${o.title} ${b(a)}`),console.log(`${" ".repeat(s+2)}Made: ${k.length?k.join(", "):"nothing but the title"}${o.files.length?` (${j(o.files.length,"file")} in its assets/)`:""}`);let e=m.flatMap(({slug:l,page:s})=>(s.notes??[]).map(o=>` ${l}: ${o.line?`line ${o.line}: `:""}${o.text}`));e.length&&console.log(`Not brought as the file has it (${e.length}):
2
+ import{b as Q}from"./chunk-YROX2O22.mjs";import{c as _,d as z,e as B,l as G}from"./chunk-5XA2ZBAE.mjs";import"./chunk-JA7G53PC.mjs";import"./chunk-YI43RG4P.mjs";import{i as q}from"./chunk-NAMN3RAF.mjs";import{a as b,b as J}from"./chunk-JEUK3ZO7.mjs";import{a as Z}from"./chunk-AHN3NFKJ.mjs";import{a as ee}from"./chunk-MTYYHM2G.mjs";import"./chunk-ALZ6ZENZ.mjs";import"./chunk-IA4PSIMD.mjs";import{c as V,d as Y,e as M}from"./chunk-DAZL73VK.mjs";import"./chunk-2OHANJ6Q.mjs";import"./chunk-F4ZA6JRZ.mjs";import"./chunk-7M2BQQGZ.mjs";import"./chunk-ITOH5EGO.mjs";import{b as W,h as X}from"./chunk-ZQS6H473.mjs";import"./chunk-GHOYKMQ3.mjs";import"./chunk-QE5RG76S.mjs";import{b as T,f as C,g as H}from"./chunk-4OZWXZE5.mjs";import"./chunk-ZTHICSSF.mjs";import{k as U}from"./chunk-6N3PX4XX.mjs";import{b as K}from"./chunk-PAREWQGB.mjs";import"./chunk-BFJGHSQN.mjs";import"./chunk-U5XL7D6A.mjs";import"./chunk-HYMEEXKN.mjs";import"./chunk-UMHUSOPJ.mjs";import"./chunk-R2ZDLJYT.mjs";import"./chunk-VFX2KNHP.mjs";import"./chunk-VS7JIGJW.mjs";import"./chunk-HDWTZ763.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";import v from"node:fs/promises";import se from"node:os";import x from"node:path";import{IMPORT_EXT as re,kindOf as ie}from"../browser/shared/import-types.mjs";import{reportsDirectory as O}from"../browser/shared/paths.mjs";import{kebab as S}from"../browser/shared/web-links.mjs";import{documentDirectory as oe,documentFiles as E,newDocSlug as ae}from"../browser/shared/workspace.mjs";var ce=Object.values(re).flat().join(" "),j=(d,g)=>`${d} ${g}${d===1?"":"s"}`;function fe(d,g,p){let n=(f,r=g)=>(r.match(f)??[]).length,c=n(/<ol class="doc-flow"/g,p),$=n(/<li id="fn-\d+"/g,p),w=[[n(/<section class="doc-section"/g),"section"],[n(/<h[2-4][\s>]/g),"heading"],[n(/<p[\s>]/g),"paragraph"],[n(/<(?:ul|ol)[\s>]/g),"list"],[n(/<table\b/g),"table"],[n(/class="doc-math-(?:inline|block)"/g,p),"formula"],[n(/<div class="doc-code"/g),"code block"],[n(/<figure class="doc-image"/g),"picture"],[c,"flow"],[$,"footnote"]].filter(([f])=>f>0).map(([f,r])=>j(f,r)),h=(d.raws?.length??0)-c-($?1:0);return h>0&&w.push(`${j(h,"HTML block")} kept as written`),w}async function Se(d){let{positional:g,options:p}=C({options:["--no-preview","--no-browser"],argv:d}),[n,c,$]=g;if(g.length<1||g.length>3||!n)throw new T("Name the file; then the slug and the title, if you choose them.");let w=ie(n);if(!w)throw new T(`Not a kind of file gallery import takes: ${n} (${ce}).`);c!==void 0&&H(c);let h=x.resolve(n);await v.stat(h).then(i=>i.isFile(),()=>!1)||(console.error(`No such file: ${n}`),process.exit(1));let f=c!==void 0?await Q(c):null;f&&(console.error(f),process.exit(1));let r=x.basename(h),F=await v.mkdtemp(x.join(se.tmpdir(),"gallery-import-")),L,y,R;try{let i,u=[];if(w==="markdown")i=[{...await Y(h,F),from:r,children:[]}];else try{({pages:i,skipped:u}=await V([{file:h,name:r}],F))}catch(e){console.error(`${r} could not be read: ${e.message}`),process.exit(1)}i.length===0&&(console.error(`Nothing in ${r} could be read as a page${u.length?` (not taken: ${u.join(", ")})`:""}.`),process.exit(1)),$?.trim()&&(i[0]={...i[0],title:$.replace(/\s+/g," ").trim()});let I=new Map,te=ee({edits:{},reports:{},reportsDirectory:O});y=(await Z(i,{create:async(e,t,l,{lang:s})=>{let{directory:o}=await K(e,t,l,{blank:!0,lang:s});I.set(e,await v.readFile(E(o).html,"utf8"))},slugOf:(e,t)=>{if(t===0&&c!==void 0)return c;let l=S(e.title)||S(e.from?.replace(/\.[^.]+$/,"")??"")||S(r.replace(/\.[^.]+$/,""));return l?te.freeSlug(l):ae(O)},folderOf:e=>oe(e,O),fill:e=>M(e),place:(e,t)=>q(e,{parent:t})})).made;let P=[],A=(e,t)=>{P.push({page:e,depth:t});for(let l of e.children??[])A(l,t+1)};for(let e of i)A(e,0);let m=await Promise.all(P.map(async({page:e,depth:t},l)=>{let s=y[l],o=oe(s,O),a=E(o).html,k=await v.readFile(a,"utf8"),ne=(await M({source:I.get(s),nodes:e.nodes,icon:e.icon,own:e.own})).replace(/<p>\u{E000}\d+\u{E001}<\/p>/gu,""),le=X(W(k,{finish:U}).text);return{slug:s,depth:t,page:e,directory:o,htmlFile:a,made:fe(e,ne,k),readOnly:le}}));if(L={slug:y[0]},m.length===1){let[{page:e,directory:t,htmlFile:l,made:s,readOnly:o}]=m;if(console.log(`Created ${b(l)} and ${x.basename(E(t).json)} from ${r}`),console.log(`Title: ${e.title}`),console.log(`Made: ${s.length?s.join(", "):"nothing but the title"}${e.files.length?` (${j(e.files.length,"file")} in ${b(x.join(t,"assets"))})`:""}`),e.notes?.length){console.log(`Not brought as the file has it (${e.notes.length}):`);for(let a of e.notes)console.log(` ${a.line?`line ${a.line}: `:""}${a.text}`)}if(o.length){console.log(`Text the preview leaves read-only (${o.length}), by doc.html's lines as gallery check gives them:`);for(let a of o)console.log(` ${a}`)}}else{console.log(`Created ${j(m.length,"document")} from ${r} (each nested as in the file):`);for(let{slug:l,depth:s,page:o,htmlFile:a,made:k}of m)console.log(`${" ".repeat(s+1)}${l} ${o.title} ${b(a)}`),console.log(`${" ".repeat(s+2)}Made: ${k.length?k.join(", "):"nothing but the title"}${o.files.length?` (${j(o.files.length,"file")} in its assets/)`:""}`);let e=m.flatMap(({slug:l,page:s})=>(s.notes??[]).map(o=>` ${l}: ${o.line?`line ${o.line}: `:""}${o.text}`));e.length&&console.log(`Not brought as the file has it (${e.length}):
3
3
  ${e.join(`
4
4
  `)}`);let t=m.flatMap(({slug:l,readOnly:s})=>s.map(o=>` ${l}: ${o}`));t.length&&console.log(`Text the preview leaves read-only (${t.length}), by doc.html's lines as gallery check gives them:
5
5
  ${t.join(`
@@ -0,0 +1,16 @@
1
+ import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
+ import{a as We}from"./chunk-UMHUSOPJ.mjs";import{d as Ue,e as Vt,g as Xt,j as ze,k as qe,l as Je,m as Zt}from"./chunk-VFX2KNHP.mjs";import{B as Pe,c as lt,d as Ke,q as St,r as He,y as Jt,z as ft}from"./chunk-VS7JIGJW.mjs";import{b as rt,e as fn}from"./chunk-A55HN5OK.mjs";fn();import dn from"node:path";import{attr as w,curlyQuoted as un}from"../browser/shared/html-tree.mjs";import{FOLDED_LINES as Ve,LINE_START as Xe,NOWRAP as Qt,lineStart as mn,validFolded as hn}from"../browser/shared/code-lines.mjs";import{COLORS as gn}from"../browser/shared/colors.mjs";import{FLOWS as pn,instanceSlots as at,isInstance as it,isSlot as fs,matchesNode as pt}from"../browser/shared/components/index.mjs";import{HEADED as dt}from"../browser/shared/components/dialog.mjs";import{pageLanguage as Nn}from"../browser/shared/components/page.mjs";import{SHEETS_LABEL as Ze,shortSheets as On}from"../browser/shared/components/sheets.mjs";import{iconMarkup as Qe,iconValueOf as ds}from"../browser/shared/emoji/icon-value.mjs";import{escapeText as mt}from"../browser/shared/escape.mjs";import{COLUMN_GAP as $n,READING_WIDTH as Tt,SPAN as Ye,SPAN_SIZE as ut}from"../browser/shared/media.mjs";import{kitNamespace as us}from"../browser/shared/old-names.mjs";import{CHART_DATA as wn,CHART_SOURCE as tt,TABLE_READERS as bn,nextChartKey as kn}from"../browser/shared/table-chart.mjs";import{ALIGNS as Yt}from"../browser/editor/components/align.mjs";import{BLOCK_COLORS as ie}from"../browser/editor/components/colors.mjs";import{DETAILS as Ln,DIALOG as ee,PAGE as ms,SECTION as yn,SHEETS as vn}from"../browser/editor/components/kit.mjs";import{DIALOG_TRIGGER as Cn}from"../browser/editor/components/dialog/index.mjs";import{CHECKED as ce,FLOW as ht,TODO as se}from"../browser/editor/components/list/index.mjs";import{texSource as xn}from"../browser/editor/components/math/index.mjs";import{BOX_CLASSES as hs,HOLDS_ONE as Sn,UNIT_KINDS as Tn}from"../browser/editor/components/registry.mjs";import{HEADER_LOOK as ts}from"../browser/editor/components/table/index.mjs";import{backgroundColor as En,parseColor as An,textColor as In}from"../browser/editor/page/clipboard/import/colors.mjs";var re=new Set(["script","style","template","textarea","noscript","code","svg","math","select","option","button","iframe","video","audio","canvas","object","picture"]),jt=["doc-figure","doc-code","doc-diff","doc-math-inline","doc-math-block","doc-link-mention","doc-sheet-tabs","doc-state-fields","doc-filter-row","doc-image","doc-file","doc-bookmark","doc-embed","doc-icon","doc-title","doc-table-meta"],le=new Set(["p","h1","h2","h3","h4","h5","h6","li","td","th","dt","dd","blockquote","figcaption","caption","summary"]),Et=new Set(["main","section","div","article","aside","blockquote","li","details","dialog"]),_n=new Set(gn.map(({name:e})=>e)),C=e=>(w(e,"class")??"").split(/\s+/).filter(Boolean),es=e=>C(e).every(n=>ie.includes(n)),jn=ie.filter(e=>e.startsWith("doc-highlight-")),ct=e=>C(e).some(n=>!us(n)),D=e=>e.nodeName==="#text",Bt=/^[\s\u200b-\u200d\u2060\ufeff]*$/,V=e=>D(e)&&Bt.test(e.value),y=e=>(e.childNodes??[]).filter(n=>n.tagName),Z=e=>(e.attrs??[]).map(n=>n.name),F=(e,n)=>Z(e).every(f=>n.includes(f)),Bn=[yn.match,Ln.match,ee.match,vn.match,"table.doc-table"].join(", ");function gs(e){let n=C(e);return n.some(f=>jt.includes(f))||Ke(e)||pt(e,Bn)||hs.some(([f])=>n.includes(f))||Tn.some(f=>f.class&&n.includes(f.class)&&(!f.tag||[f.tag].flat().includes(e.tagName)))}var Mn=e=>{for(let n=e.parentNode;n?.tagName&&n.tagName!=="main";n=n.parentNode)if(n.tagName==="figure")return!0;return!1},ps=new Set(["thead","tbody","tfoot","tr","colgroup","col"]),fe=e=>ct(e)&&e.tagName!=="figure"&&!le.has(e.tagName)&&!ps.has(e.tagName)&&!gs(e),Ns=new Set([...lt].filter(e=>!["header","main","dialog","form","fieldset","caption","dd","dt","figcaption","summary","li","td","th",...ps].includes(e))),Rn=/\\\(([\s\S]*?)\\\)/g,wt=e=>xn(e)&&/\S/.test(e);function Dn(e,n=!0){let f=n?e:/^\s*(?:\\\[[\s\S]*?\\\]|\$\$[\s\S]*?\$\$)/.exec(e)?.[0]??"";return/[<>]/.test(f)&&wt(f.replace(/</g,"\\lt ").replace(/>/g,"\\gt "))}var ne=new Set(["br","wbr","img","input"]),Os=new Set([...lt,"script","style","template","noscript","link","meta"]),$s=new Set(["input","select","textarea","button","label","option"]),Gn=new Set([...lt,"hgroup","search","center","dir","listing","xmp","plaintext"]),oe=e=>y(e).some(n=>Gn.has(n.tagName)||oe(n)),ws=new Set(["main","section","div","article","aside","blockquote"]),Fn=pn.join(", "),bs=e=>ws.has(e.tagName)&&!ct(e)&&(C(e).length===0||pt(e,Fn))||fs(e),et=e=>D(e)?!Bt.test(e.value):(e.childNodes??[]).some(et),Kn=hs.filter(([,e])=>Sn.has(e)).map(([e])=>e),Hn=e=>bs(e)&&C(e).some(n=>Kn.includes(n)),ks=e=>e.childNodes.some(n=>D(n)&&!Bt.test(n.value))&&y(e).some(n=>lt.has(n.tagName)),Pn=/^[ \t\n\r\f]*/;function te(e){let n=[],f=[];for(let u of e)u.tagName&&Os.has(u.tagName)?(n.push(f),f=[]):f.push(u);n.push(f);let p=u=>!u.tagName&&!et(u),O=u=>(D(u)||u.tagName&&!$s.has(u.tagName))&&et(u);return n.map(u=>{let $=u.findIndex(m=>!p(m));return $<0?[]:u.slice($,u.findLastIndex(m=>!p(m))+1)}).filter(u=>u.some(O))}function Wn(e){let n=[],f=p=>{for(let O of p.childNodes??[])O.tagName==="style"?n.push(O.childNodes.map(u=>u.value??"").join("")):O.tagName&&O.tagName!=="template"&&f(O)};return f(e),n.flatMap(p=>[...p.replace(/\/\*[\s\S]*?(?:\*\/|$)/g," ").matchAll(/([^{};]*)\{/g)].map(([,O])=>O))}var Un=(e,{tags:n=[],classes:f=[]})=>{let p=[...n.map(u=>`(?<![\\w.#-])${u}`),...f.map(u=>`\\.${u}`)],O=p.length?new RegExp(`(?:${p.join("|")})(?![\\w-])`,"i"):null;return!!O&&e.some(u=>O.test(u))};function zn(e){let n=[],f=p=>{for(let O of p.childNodes??[])O.tagName==="script"?n.push(O.childNodes.map(u=>u.value??"").join("")):O.tagName&&O.tagName!=="template"&&f(O)};return f(e),n.join(`
3
+ `)}var de=["contains-task-list","task-list-item"],ue=["task-list-item"],Ls=["task-list-item-checkbox"],me=(e,n)=>C(e).every(f=>n.includes(f));function ys(e){let n=e.childNodes.find(f=>!V(f));return n?.tagName==="input"&&F(n,["type","checked","disabled","class"])&&w(n,"type")?.toLowerCase()==="checkbox"&&me(n,Ls)&&n.sourceCodeLocation?.startTag?n:null}var vs=e=>e.tagName==="li"&&me(e,ue)&&w(e,ce)===void 0&&e.sourceCodeLocation?.startTag&&ys(e),qn=e=>e.tagName==="ul"&&me(e,de)&&y(e).length>0&&e.childNodes.every(n=>n.tagName==="li"||V(n))&&y(e).every(vs),Jn={classes:[...new Set([...de,...ue,...Ls])]},Vn=/checkbox|task-list/i,ae=e=>e.tagName==="ol"&&(w(e,"data-doc-chart")==="flow"||w(e,"data-flow")!==void 0&&w(e,"data-doc-chart")===void 0),Xn=e=>e?.tagName==="ol"&&!ct(e)&&(C(e).includes(ht)||ae(e)),Zn=e=>e.tagName==="li"&&Xn(e.parentNode),_t="doc-icon",Qn=e=>e.some(n=>n.tagName==="strong"||n.tagName==="b")&&e.every(n=>n.tagName==="strong"||n.tagName==="b"||D(n)&&Bt.test(n.value)||n.nodeName==="#comment"),Yn=/^(?:inherit|unset|currentcolor|none)$/i,to=/^(?:inherit|initial|unset|revert|revert-layer|transparent|none)$/i,P=e=>e.replace(/\s+/g," ").trim(),ss=/^\s*--doc-(?:table-height|span)\s*:/i,eo=/^(?:p|h[1-4])$/,so=/^(center|right)$/i;function It(e){let n=e.replace(/\/\*[\s\S]*?(?:\*\/|$)/g," "),f=[],p="",O=0,u=0;for(let $=0;$<=n.length;$++){let m=n[$];p?m==="\\"?$++:m===p&&(p=""):m==='"'||m==="'"?p=m:m==="("?O++:m===")"?O=Math.max(0,O-1):(m===";"&&O===0||$===n.length)&&(f.push(n.slice(u,$)),u=$+1)}return f.filter($=>$.trim())}function Cs(e){let n=new Map;for(let r of It(e)){let N=r.indexOf(":"),i=P(N<0?r:r.slice(0,N)).toLowerCase();n.set(i==="background-color"?"background":i,N<0?"":P(r.slice(N+1).replace(/!\s*important\s*$/i,"")))}let f=[],p=[],O,u,$=new Set,m=(r,N,i)=>{if((r==="color"?Yn:to).test(N))return;let d=An(N);if(!d||d.a===0&&r==="color"){f.push(r);return}if(d.a===0)return;let g=i(N,{nearest:!0})?.replace(/_background$/,"");if(!g||!_n.has(g)){p.push(`${r} ${N} left out: the ${r==="color"?"text's":"page's"} own is the nearest`);return}return i(N)?.replace(/_background$/,"")!==g&&p.push(`${r} ${N} written as the kit's ${g}${r==="color"?"":" highlight"}`),g};for(let[r,N]of n)r==="color"?O=m(r,N,In):r==="background"?u=m(r,N,En):r==="font-weight"&&/^(?:bold|bolder|[6-9]\d\d)$/i.test(N)?$.add("strong"):r==="font-style"&&/^(?:italic|oblique)\b/i.test(N)?$.add("em"):(r==="text-decoration"||r==="text-decoration-line")&&/^(?:(?:underline|line-through|solid)\s*)+$/i.test(N)&&/underline|line-through/i.test(N)?(/underline/i.test(N)&&$.add("u"),/line-through/i.test(N)&&$.add("s")):f.push(r);if(f.length)return{foreign:[...new Set(f)]};let v=[];O&&v.push([`<span class="doc-text-${O}">`,"</span>"]),u&&v.push([`<span class="doc-highlight-${u}">`,"</span>"]);for(let r of["strong","em","u","s"])$.has(r)&&v.push([`<${r}>`,`</${r}>`]);return{open:v.map(([r])=>r).join(""),close:v.map(([,r])=>r).reverse().join(""),notes:p}}var ns=/^(?:language|lang)-([\w#+.-]+)$/,no=new Set(["data-language","data-lang","data-block-id"]),oo=[{name:Xe,names:[Xe,"data-start"],value:e=>mn(e)?.toString()??null,says:"the number of its first line is a whole number from 1"},{name:"data-line-numbers",names:["data-line-numbers"],value:e=>/^\s*(?:true|false)\s*$/i.test(e)?e.trim().toLowerCase():null,says:"false hides its line numbers, true shows them"},{name:Ve,names:[Ve],value:e=>hn(P(e))?P(e):null,says:"its folded lines are their numbers from 1, spaces between"}],os="data-title",as="data-wrap",ao=e=>y(e).length===1&&y(e)[0].tagName==="code"&&e.childNodes.every(n=>n.tagName||V(n))?y(e)[0]:null,io=new Set(["a","abbr","b","bdi","bdo","cite","code","data","del","dfn","em","font","i","ins","kbd","mark","q","s","samp","small","span","strike","strong","sub","sup","time","tt","u","var","br","wbr"]),co=new Set(["code","kbd","samp","tt","var"]);function xs(e){for(let n of e.childNodes){if(D(n))continue;if(!n.tagName)return"a comment in its <figcaption>";if(["img","picture","svg"].includes(n.tagName))return"a picture in its <figcaption>";if(!io.has(n.tagName))return`a <${n.tagName}> in its <figcaption>`;if(!n.sourceCodeLocation?.startTag||!(n.sourceCodeLocation.endTag||ne.has(n.tagName)))return`a <${n.tagName}> not closed in its <figcaption>`;let f=xs(n);if(f)return f}return""}function is(e){let n=y(e),f=n.filter(v=>v.tagName==="pre"),p=n.filter(v=>v.tagName==="figcaption");if(!f.length)return null;let[O]=f,[u=null]=p,$=e.childNodes.find(v=>!v.tagName&&!V(v)),m=f.length>1||p.length>1||n.length>f.length+p.length?"more than the pre and one <figcaption> in its <figure>":$?D($)?"words in its <figure> outside its caption":"a comment in its <figure>":u?Z(u).length?`its <figcaption> has an attribute of its own (${Z(u).join(", ")})`:u.sourceCodeLocation?.endTag?xs(u):"its <figcaption> is not closed in the file":"";return m?{pre:O,caption:u,why:m}:{pre:O,caption:u}}function At(e){let n=(e.attrs??[]).filter(({value:p})=>p.trim()),f=e.tagName==="abbr";return n.map(p=>`${p.name} ${JSON.stringify(P(p.value))} dropped: ${f&&p.name==="title"?"write the full name in the text":"write it in the text if the reader needs it"}`)}var z=e=>e.replace(/&/g,"&amp;").replace(/"/g,"&quot;");function ro(e){let n=new Set,f=p=>{for(let O of p.childNodes??[])if(O.tagName){for(let u of[tt,...bn])w(O,u)!==void 0&&n.add(w(O,u));f(O.tagName==="template"?O.content:O)}};return f(e),n}function lo(e){let n=new Map,f=p=>{for(let O of p.childNodes??[]){if(!O.tagName)continue;let u=w(O,"id");u!==void 0&&n.set(u,(n.get(u)??0)+1),f(O.tagName==="template"?O.content:O)}};return f(e),n}var fo=/^[A-Za-z][\w-]{0,63}$/;function uo(e){let n=We(e),f=rt(n,{sourceCodeLocationInfo:!0}),p=bt(f);if(!p)return{text:n,changes:[]};let O=[],u=[],$=t=>n.slice(0,t).split(`
4
+ `).length,m=(t,s,o=[],l={})=>{let a=$(t.sourceCodeLocation.startOffset);o.length||u.push({line:a,rule:s,...l});for(let c of o)u.push({line:a,rule:s,note:c,...l})},v=0,r=(t,s,o,{opens:l=null,closes:a=null,move:c=null,leaves:h=!1}={})=>O.push({start:t,end:s,text:o,order:v++,opens:l,closes:a,move:c,leaves:h}),N=(t,s,o,l)=>{r(t,t,o,{opens:s}),r(s,s,l,{closes:t})},i=t=>t.sourceCodeLocation?.startTag,d=t=>t.sourceCodeLocation?.endTag,g=(t,s,{drop:o=[]}={})=>{let l=C(t).filter(h=>!o.includes(h)),a=[...l,...s.filter(h=>!l.includes(h))],c=t.sourceCodeLocation.attrs?.class;if(a.join(" ")!==C(t).join(" "))if(c&&a.length)r(c.startOffset,c.endOffset,`class="${z(a.join(" "))}"`);else if(c)x(t,"class");else{let h=i(t).startOffset+1+t.tagName.length;r(h,h,` class="${z(a.join(" "))}"`)}},x=(t,s)=>{let o=t.sourceCodeLocation.attrs[s],l=o.startOffset;for(;/[ \t\n\r\f]/.test(n[l-1]??"");)l--;r(l,o.endOffset,"")},A=(t,s,{classes:o=[],drop:l=[]}={})=>{let a=t.sourceCodeLocation,c=Object.entries(a.attrs??{}).filter(([L])=>L!=="class"&&!l.includes(L)).map(([,L])=>` ${n.slice(L.startOffset,L.endOffset)}`).join(""),h=[...o,...C(t).filter(L=>!o.includes(L))];return`<${s}${h.length?` class="${z(h.join(" "))}"`:""}${c}>`},M,q=t=>Un(M??=Wn(f),t),Q,Ms=t=>t.test(Q??=zn(f)),K=(t,s,o)=>{r(i(t).startOffset,i(t).endOffset,s),d(t)&&r(d(t).startOffset,d(t).endOffset,o)},Rt=t=>K(t,"",""),W=t=>!!(i(t)&&(d(t)||t.tagName==="img")),ge,pe=t=>{let s=w(t,"id");if(t.tagName!=="dialog"||!F(t,["id"])||!fo.test(s??"")||!W(t))return!1;let o=y(t);return!(o.length?Ns.has(o[0].tagName)&&W(o[0]):t.childNodes.some(a=>!V(a)&&a.nodeName!=="#comment"))||o.some(a=>a.tagName==="form")?!1:(ge??=lo(f),ge.get(s)===1)},Rs=t=>{let s=y(t)[0];return!pt(s,ee.short)||Z(s).length?null:t.childNodes.slice(0,t.childNodes.indexOf(s)).every(V)?s:null},Ne=t=>t.tagName==="dialog"&&(C(t).includes("doc-dialog")||pe(t)),Dt=(t,s=[])=>{for(let o of t.childNodes??[])if(o!==p){if(it(o)){at(o).forEach(l=>Dt(l,s));continue}Ne(o)&&W(o)?s.push(o):Dt(o,s)}return s},Gt=d(p)?Dt(f):[],Oe,Ds=t=>(Oe??=new Set((function s(o,l=[]){for(let a of o.childNodes??[])if(a.tagName){if(it(a)){at(a).forEach(c=>s(c,l));continue}Ne(a)&&l.push(w(a,"id")),s(a,l)}return l})({childNodes:[p,...Gt]})),/^#./.test(t??"")&&Oe.has(t.slice(1))),Gs=t=>{let[s,...o]=y(t);if(!s||o.length||!C(s).includes("doc-dialog-panel"))return null;let[l,a,...c]=y(s);if(c.length||!l||!a||!C(l).includes(dt.header)||!C(a).includes("doc-dialog-content"))return null;let h=T=>T.childNodes.some(_=>!_.tagName&&!V(_)&&_.nodeName!=="#comment");if(h(s)||h(l)||!W(l)||!i(a))return null;let L=y(l),b=L.filter(T=>C(T).includes(dt.title)),S=L.filter(T=>!b.includes(T)),E=T=>(C(T).includes(dt.close)||w(T,dt.closeAttribute)!==void 0)&&W(T);return b.length!==1||!W(b[0])||S.length>1||!S.every(E)?null:{header:l,title:b[0],close:S[0]??null,content:a}},Nt,$e=(t,s=[])=>{for(let o of t.childNodes??[])if(o.tagName){for(let{name:l,value:a}of o.attrs)l!=="id"&&l!=="class"&&s.push(a);(o.tagName==="script"||o.tagName==="style")&&s.push(o.childNodes.map(l=>l.value??"").join("")),$e(o,s)}return s},Fs=(t,s)=>{Nt??=$e(f).join(`
5
+ `);let o=0;for(let l=Nt.indexOf(t);l>=0;l=Nt.indexOf(t,l+t.length))!/[\w-]/.test(Nt[l-1]??"")&&!/[\w-]/.test(Nt[l+t.length]??"")&&o++;return o>(s?1:0)};function Ks(t){let s=Gs(t);if(!s)return;let{header:o,title:l,close:a,content:c}=s,h=w(l,"id"),L=!!h&&w(t,"aria-labelledby")?.trim()===h;L&&x(t,"aria-labelledby"),r(i(o).startOffset,i(o).endOffset,n.slice(i(c).startOffset,i(c).endOffset));let b=i(l).startOffset+1;r(b,b+l.tagName.length,"h3"),g(l,[],{drop:[dt.title]}),h!==void 0&&!(h&&Fs(h,L))&&x(l,"id"),r(d(l).startOffset,d(l).endOffset,"</h3>"),a&&r(a.sourceCodeLocation.startOffset,a.sourceCodeLocation.endOffset,""),r(d(o).startOffset,d(o).endOffset,""),r(i(c).startOffset,i(c).endOffset,"")}let Ft=t=>{for(let s of t.childNodes??[]){if(it(s)){at(s).forEach(Ft);continue}s.tagName&&pt(s,ee.match)&&Ks(s),Ft(s)}},we=new Set;function be(t){let s=t.tagName;if(!W(t))return!1;let o=[];if(s==="mark"&&F(t,[]))K(t,'<span class="doc-highlight-yellow">',"</span>");else if((s==="del"||s==="strike")&&F(t,["cite","datetime"]))K(t,"<s>","</s>"),o=At(t);else if(s==="ins"&&F(t,["cite","datetime"]))K(t,"<u>","</u>"),o=At(t);else{if(["kbd","samp","tt","var"].includes(s)&&F(t,[]))return K(t,"<code>","</code>"),we.add(t),m(t,s),!0;if(s==="a"&&F(t,["href"])&&Ds(w(t,"href")))return g(t,[Cn]),m(t,"dialog link"),!1;if(s==="small"&&F(t,[]))K(t,'<span class="doc-text-gray">',"</span>");else if(s==="q"&&F(t,["cite"]))K(t,"\u201C","\u201D"),o=At(t);else if(["abbr","cite","dfn","time","bdi","data"].includes(s)&&F(t,["title","datetime","value"]))Rt(t),o=At(t);else if(s==="span"&&F(t,[])||s==="font"&&F(t,["color"])&&!w(t,"color")?.trim())Rt(t);else if(s==="span"&&F(t,["style"])||s==="font"&&F(t,["color"])){let l=Cs(s==="span"?w(t,"style")??"":`color: ${w(t,"color")}`);if(l.foreign)return!1;K(t,l.open,l.close),o=l.notes}else return!1}return we.add(t),m(t,s,o),!1}function Hs(t){let{startOffset:s,endOffset:o}=t.sourceCodeLocation,l=n.slice(s,o);for(let a of l.matchAll(Rn))N(s+a.index,s+a.index+a[0].length,'<span class="doc-math-inline">',"</span>"),u.push({line:$(s+a.index),rule:"formula"})}let Kt=new Set,ke=new Set;function kt(t,s=()=>!1){for(let o of te(t)){if(!o.every(b=>b.tagName?i(b)&&(d(b)||ne.has(b.tagName))&&!oe(b):b.sourceCodeLocation))continue;let l=o[0].sourceCodeLocation.startOffset,a=o.at(-1).sourceCodeLocation.endOffset,c=n.slice(l,a),h=l+Pn.exec(c)[0].length,L=a-/[ \t\n\r\f]*$/.exec(c)[0].length;if(o.every(D)&&wt(n.slice(h,L)))N(h,L,'<div class="doc-math-block">',"</div>"),u.push({line:$(h),rule:"display formula"}),o.forEach(b=>ke.add(b));else if(s(o)){let b=Qn(o);N(h,L,b?"<p>":"<p><strong>",b?"</p>":"</strong></p>"),u.push({line:$(h),rule:"step title",...ye(o[0].parentNode)}),o.forEach(S=>Kt.add(S))}else N(h,L,"<p>","</p>"),u.push({line:$(h),rule:"loose words"}),o.forEach(b=>Kt.add(b))}}let Ps=t=>t[0].parentNode.childNodes.slice(0,t[0].parentNode.childNodes.indexOf(t[0])).every(s=>!s.tagName||C(s).includes(_t)),Le=new Set,ye=t=>Le.has(t.parentNode)?{}:(Le.add(t.parentNode),{note:"a step's own words written as its title, the first block of its node: <li><p><strong>\u2026</strong></p> then its content (a paragraph, a list\u2026)</li>"}),Ws=t=>{if(kt(t.childNodes,Ps),t.childNodes.filter(a=>a.tagName&&!C(a).includes(_t)).length>0||te(t.childNodes).length>0||!i(t)||!d(t))return;let l=t.childNodes.filter(a=>a.tagName).at(-1)?.sourceCodeLocation?.endOffset??i(t).endOffset;r(l,l,"<p></p>"),u.push({line:$(l),rule:"step title",...ye(t)})},Ht,ve=()=>{Ht??=ro(f);let t=kn(Ht);return Ht.add(t),t},Us=(t,s)=>`<div data-doc-chart="${z(w(t,"data-doc-chart"))}" ${wn}="${z(s)}"></div>`,Ot=n.includes(`\r
6
+ `)?`\r
7
+ `:`
8
+ `,Ce=t=>/^[ \t]*/.exec(n.slice(n.lastIndexOf(`
9
+ `,t-1)+1))[0];function xe(t,s,o,l=null){let a=Se(t),c=a?ft(n,a.sourceCodeLocation.startOffset,a.sourceCodeLocation.endOffset):null,h=!!c&&(c.start!==a.sourceCodeLocation.startOffset||c.end!==a.sourceCodeLocation.endOffset),L=a?{from:i(a).endOffset,to:d(a).startOffset}:null,b=_=>`<figure class="doc-figure">${_?`<h3>${_}</h3>`:""}${Us(t,o)}</figure>`,S=_=>L?_:_(""),E=h?`${Ot}${Ce(i(s).startOffset)}`:"",T=!!(l??d(s));if(T){let _=l?d(t).endOffset:d(s).endOffset;r(_,_,S(G=>`${l??""}${E}${b(G)}`),{closes:i(s).startOffset,move:L}),u.push({line:$(_),rule:"chart",key:o})}else r(i(s).startOffset,i(s).startOffset,S(_=>`${b(_)}${E}`),{opens:i(s).endOffset,move:L}),u.push({line:$(i(s).startOffset),rule:"chart",key:o});return c&&r(c.start,c.end,""),T&&!!l}let[zs]=ts,Se=t=>{let s=t.childNodes.find(o=>!V(o));return s?.tagName!=="caption"||!W(s)||Z(s).length>0||!et(s)||!s.childNodes.every(o=>D(o)||o.tagName&&!Os.has(o.tagName)&&!$s.has(o.tagName)&&!oe(o))||s.childNodes.every(D)&&wt(n.slice(i(s).endOffset,d(s).startOffset))||q({tags:["caption"]})?null:s},qs=t=>{let s=w(t,"rowspan");return s===void 0||/^\s*\d+\s*$/.test(s)&&Number(s)===1},Js=t=>(w(t,"scope")??"").trim().toLowerCase()==="row";function Vs(t){let s=y(t).filter(h=>["thead","tbody","tfoot"].includes(h.tagName)),o=s.flatMap(h=>y(h)).flatMap(h=>y(h)).filter(h=>h.tagName==="th"&&i(h)),l=!q({tags:["th","thead"]});if(l)for(let h of o)Js(h)||g(h,ie.some(L=>C(h).includes(L))?[zs]:ts);let a=l||!o.length?[]:["its th as written (no header look, no thead): the document's own <style> styles th"],c=h=>h.length>0&&h.every(L=>L.tagName==="tr"&&W(L));for(let h of s){let L=y(h);if(h.tagName!=="tbody"||!c(L))continue;let[b,...S]=L,E=l&&s.length===1&&S.length>0&&y(b).length>0&&y(b).every(G=>G.tagName==="th"&&qs(G)),T=i(h);if(T){if(!E||!d(h))continue;r(T.startOffset,T.endOffset,"<thead>"),r(b.sourceCodeLocation.endOffset,b.sourceCodeLocation.endOffset,`</thead>${n.slice(T.startOffset,T.endOffset)}`),m(b,"header row");continue}E&&(N(b.sourceCodeLocation.startOffset,b.sourceCodeLocation.endOffset,"<thead>","</thead>"),m(b,"header row"));let _=E?S:L;N(_[0].sourceCodeLocation.startOffset,_.at(-1).sourceCodeLocation.endOffset,"<tbody>","</tbody>")}return a}let Pt,Xs=()=>{Pt??=(function s(o,l=new Set){for(let a of o.childNodes??[])a.tagName&&(w(a,"data-doc-sheets")!==void 0&&l.add(w(a,"data-doc-sheets")),s(a.tagName==="template"?a.content:a,l));return l})(f);let t=1;for(;Pt.has(`tabs-${t}`);)t++;return Pt.add(`tabs-${t}`),`tabs-${t}`},Te=new Set,Zs=t=>{let s=[],o=a=>a.childNodes.map(c=>D(c)?c.sourceCodeLocation?n.slice(c.sourceCodeLocation.startOffset,c.sourceCodeLocation.endOffset):c.value:c.tagName?(i(c)&&s.push(P(n.slice(i(c).startOffset,i(c).endOffset))),c.tagName==="br"?" ":o(c)):"").join(""),l=a=>a.childNodes.map(c=>D(c)?c.value:c.tagName==="br"?" ":c.tagName?l(c):"").join("");return{raw:P(o(t)),plain:P(l(t)),left:[...new Set(s)]}},Qs=(t,s,o)=>{let l=t.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").slice(0,48).replace(/-+$/,"")||`tab-${s+1}`,a=l;for(let c=2;o.has(a);c++)a=`${l}-${c}`;return o.add(a),a};function Ys(t,s){let o=Nn(n),l=Ze[o]??Ze.zh,a=w(t,"data-doc-sheets")?.trim()?null:Xs(),c=new Set,h=[],L=s.map(({section:S,heading:E},T)=>{let{raw:_,plain:G,left:Y}=Zs(E),st=Qs(G,T,c);Z(E).length&&h.push(`${Z(E).join(", ")} of the heading "${G}" left out: a tab is its name alone`);for(let nt of Y)h.push(`${nt} in the heading "${G}" left out: a tab's name is plain text`);K(S,`<div data-doc-sheet="${st}">`,"</div>"),Te.add(E);let{startOffset:J,endOffset:X}=E.sourceCodeLocation,U=ft(n,J,X);return r(U.start,U.end,Ot.repeat(n.slice(U.start,U.end).split(`
10
+ `).length-1)),Pe({sheet:st,title:_})}),b=A(t,t.tagName,{classes:["doc-sheet-shell"],drop:a?["data-doc-sheets"]:[]});a&&(b=b.replace(/>$/,` data-doc-sheets="${a}">`)),w(t,"aria-label")===void 0&&(b=b.replace(/>$/,` aria-label="${l}">`)),r(i(t).startOffset,i(t).endOffset,`${b}<div class="doc-sheet-tabs" aria-label="${l}">${L.join("")}</div>`),m(t,"sheets",h)}let tn=t=>{let s=y(t)[0];return y(t).length===1&&s.tagName==="a"&&C(s).join(" ")==="doc-bookmark"&&F(s,["class","href","title","target","rel"])&&!!w(s,"href")?.trim()&&W(s)&&s.childNodes.every(D)&&t.childNodes.every(o=>o===s||V(o))};function en(t){let s=y(t)[0],o=w(s,"href").trim(),l=P(w(s,"title")??""),a=o;try{a=new URL(o).hostname||o}catch{}let c=[],h=w(s,"target");h!==void 0&&h.trim()!=="_blank"&&c.push(`target ${JSON.stringify(P(h))} left out: a bookmark opens its page in a new tab`);let L=w(s,"rel");L!==void 0&&L.split(/\s+/).some(E=>E&&!["noopener","noreferrer"].includes(E.toLowerCase()))&&c.push(`rel ${JSON.stringify(P(L))} left out: a bookmark's link is rel="noopener noreferrer"`),r(i(t).startOffset,i(t).endOffset,A(t,"figure",{classes:["doc-bookmark"]}));let b=et(s)?"":mt(a);r(i(s).startOffset,i(s).endOffset,`<a class="doc-bookmark-card" href="${z(o)}" target="_blank" rel="noopener noreferrer"><span class="doc-bookmark-text"><span class="doc-bookmark-title">${b}`);let S=l?`<span class="doc-bookmark-description">${mt(l)}</span>`:"";r(d(s).startOffset,d(s).endOffset,`</span>${S}<span class="doc-bookmark-url"><span class="doc-bookmark-href">${mt(o)}</span></span></span></a>`),r(d(t).startOffset,d(t).endOffset,"<figcaption></figcaption></figure>"),m(t,"bookmark",c)}let sn=t=>{let s=t?.parentNode;if(!t?.tagName||!C(t).includes("doc-column")||!s?.tagName||!C(s).includes("doc-columns"))return null;let o=c=>Number(/--doc-column-ratio\s*:\s*(\d*\.?\d+)/i.exec(w(c,"style")??"")?.[1]??1)||1,l=y(s).filter(c=>C(c).includes("doc-column")),a=l.reduce((c,h)=>c+o(h),0);return(Tt-$n*(l.length-1))/Tt*(o(t)/a)},Wt=(t,s,o)=>{let l=w(t,"width"),a=/^\s*(\d+(?:\.\d+)?)\s*(px|%)?\s*$/i.exec(l??""),c=(s?w(s,"style")??"":"").trim().replace(/;\s*$/,""),h=t.sourceCodeLocation.attrs?.width;if(!a||!h||/--doc-span\s*:/i.test(c))return null;let L=a[2]==="%",b=L?sn(o):null,S=L?Number(a[1])/100*(b??1):Number(a[1])/Tt,E=Math.round(Math.min(ut.max,Math.max(ut.min,S))*1e3)/1e3,T=h.startOffset;for(;/[ \t\n\r\f]/.test(n[T-1]??"");)T--;r(T,h.endOffset,"");let _=S<ut.min||S>ut.max?`, within ${ut.min} to ${ut.max}`:"",G=L?b===null?"a share of the width it stands in":`a share of the width it stands in, its column ${Math.round(b*1e3)/1e3} of the reading width`:`${Number(a[1])}px of the ${Tt}px reading width`;return{attribute:` style="${z(`${c?`${c}; `:""}${Ye}: ${E}`)}"`,note:`width="${l}" written as ${Ye}: ${E} on its figure (${G}${_}; at most the width it stands in)`}},Ut=(t,s)=>{let o=t?A(t,"figure",{classes:["doc-image"],drop:s?.attribute?["style"]:[]}):'<figure class="doc-image">';return s?.attribute?`${o.slice(0,-1)}${s.attribute}>`:o},nn=t=>y(t).filter(s=>s.tagName==="img").length===1&&y(t).every(s=>s.tagName==="img"||s.tagName==="figcaption")&&t.childNodes.every(s=>s.tagName||V(s)),on=t=>y(t).length===1&&y(t)[0].tagName==="img"&&t.childNodes.every(s=>s.tagName||V(s)),an=t=>t.childNodes.length>0&&t.childNodes.every(D)&&wt(n.slice(i(t).endOffset,d(t).startOffset)),zt=new Set,Ee=()=>q(Jn)||Ms(Vn),Ae=t=>qn(t)&&!Ee();function Ie(t,s=null,o=null,l=[]){let a=ao(t),c=[t,a].filter(Boolean),h=[s,...c].filter(Boolean),L=c.flatMap(C).map(k=>ns.exec(k)?.[1]).find(Boolean)??h.map(k=>w(k,"data-language")??w(k,"data-lang")).find(Boolean),b=k=>h.find(I=>I.sourceCodeLocation.attrs?.[k]),S=(k,I)=>{let B=k?.sourceCodeLocation.attrs[I];return B?` ${n.slice(B.startOffset,B.endOffset)}`:""},E=b("id"),T=[...l],_=new Map(h.map(k=>[k,new Set])),G=k=>k.flatMap(I=>h.filter(B=>w(B,I)!==void 0).map(B=>(_.get(B).add(I),{element:B,name:I,value:w(B,I)}))),Y=(k,I)=>T.push(`${k.name} ${JSON.stringify(P(k.value))} left out (its <${k.element.tagName}>'s): ${I}`),st=oo.flatMap(({name:k,names:I,value:B,says:H})=>{let ot=G(I),R=ot.find(j=>B(j.value)!==null);for(let j of ot)j!==R&&Y(j,B(j.value)===null?H:`the block takes its <${R.element.tagName}>'s ${R.name}`);return R?[` ${k}="${z(B(R.value))}"`]:[]}),J=G([as]),X=J.find(k=>/^\s*(?:true|false)\s*$/i.test(k.value));for(let k of J)k!==X&&Y(k,X?`the block takes its <${X.element.tagName}>'s ${as}`:"false keeps its long lines on one line (they scroll), true wraps them");let U=X?X.value.trim().toLowerCase()==="false":c.some(k=>C(k).includes(Qt)),nt=c.flatMap(C).find(k=>jn.includes(k)),Be=G([os]),yt=o?null:Be[0],Me=yt?mt(P(yt.value)):"";for(let k of Be)k!==yt&&Y(k,o?"its caption is its title":`the block takes its <${yt.element.tagName}>'s ${os}`);let Re=k=>Object.keys(k.sourceCodeLocation.attrs??{}).filter(I=>I!=="class"&&!no.has(I)&&!(I==="id"&&k===E)&&!_.get(k).has(I)),De=k=>{let I=C(k).filter(j=>!ns.test(j)&&j!==Qt&&j!==nt),B=Re(k),ot=(k.attrs.find(j=>j.name==="style")?.value??"").split(";").map(j=>j.trim()).filter(Boolean).every(j=>/^--doc-code-height\s*:/i.test(j)),R=[...I.length?[`class ${JSON.stringify(I.join(" "))}`]:[],...B.filter(j=>!(j==="style"&&ot))];return R.length&&T.push(`${R.join(", ")} kept on its <${k.tagName}>`),`<${k.tagName}${I.length?` class="${z(I.join(" "))}"`:""}${B.map(j=>S(k,j)).join("")}>`},qt=s?Re(s):[],Ge=`<div class="doc-code${U?` ${Qt}`:""}${nt?` ${nt}`:""}"${S(E,"id")}${S(b("data-block-id"),"data-block-id")}${L?` data-language="${z(L.toLowerCase())}"`:""}${st.join("")}${qt.map(k=>S(s,k)).join("")}>`;qt.length&&T.push(`${qt.join(", ")} kept on the block (its <figure>'s)`);let Fe=De(t),vt=k=>a?`${k}${Fe}`:`${k}${Fe}<code>`,Ct=a&&W(a)?"</pre>":"</code></pre>",xt=k=>`<div class="doc-code-title">${k}</div>`;if(!s)K(t,vt(`${Ge}${xt(Me)}`),`${Ct}</div>`);else if(K(s,Ge,"</div>"),!o)K(t,vt(xt(Me)),Ct);else{let{startOffset:k,endOffset:I}=o.sourceCodeLocation,B={from:i(o).endOffset,to:d(o).startOffset},H=R=>R.replace(/[ \t\n\r\f]+/g," ").trim(),ot=(R,j)=>n.slice(R,j).split(`
11
+ `).length-1;if(k<t.sourceCodeLocation.startOffset)r(k,I,R=>`${xt(H(R))}${Ot.repeat(ot(k,I))}`,{move:B}),K(t,vt(""),Ct);else{let R=ft(n,k,I),j=ot(R.start,R.end),rn=j?`${Ot.repeat(j)}${Ce(i(t).startOffset)}`:"";r(i(t).startOffset,i(t).endOffset,ln=>vt(`${xt(H(ln))}${rn}`),{move:B}),r(R.start,R.end,""),d(t)&&r(d(t).startOffset,d(t).endOffset,Ct)}}if(a&&Z(a).length&&r(i(a).startOffset,i(a).endOffset,De(a)),o){let k=new Set,I=B=>{for(let H of y(B))(!co.has(H.tagName)||Z(H).length)&&k.add(P(n.slice(i(H).startOffset,i(H).endOffset))),ne.has(H.tagName)?r(i(H).startOffset,i(H).endOffset,H.tagName==="br"?" ":""):(Rt(H),I(H))};I(o);for(let B of k)T.push(`${B} in its caption left out: a code block's title is plain text`)}m(s??t,"code",T)}function _e(t,s){let o=t.tagName;if(!W(t))return!1;if((o==="p"||o==="div"&&C(t).length===0)&&an(t))return K(t,A(t,"div",{classes:["doc-math-block"]}),"</div>"),m(t,"display formula"),!0;if(o==="figure"&&C(t).length===0&&nn(t)){let c=Wt(y(t).find(h=>h.tagName==="img"),t,s);return r(i(t).startOffset,i(t).endOffset,Ut(t,c)),y(t).some(h=>h.tagName==="figcaption")||r(d(t).startOffset,d(t).startOffset,"<figcaption></figcaption>"),m(t,"figure",c?[c.note]:[]),!0}if(o==="img"&&Et.has(s?.tagName)){let c=Wt(t,null,s);return N(i(t).startOffset,i(t).endOffset,Ut(null,c),"<figcaption></figcaption></figure>"),m(t,"picture",c?[c.note]:[]),!0}if(o==="p"&&Et.has(s?.tagName)&&tn(t))return en(t),!0;if(w(t,"data-doc-sheets")!==void 0){let c=On(t)?.tabs;return c&&Ys(t,c),!1}if(o==="p"&&on(t)){let c=Wt(y(t)[0],t,s);return K(t,Ut(t,c),"<figcaption></figcaption></figure>"),m(t,"picture",c?[c.note]:[]),!0}let l=o==="figure"&&C(t).length===0?is(t):null;if(l&&!l.why&&W(l.pre))return Ie(l.pre,t,l.caption),!0;if(o==="pre"&&!C(s??{}).includes("doc-code")){let h=s?.tagName==="figure"&&C(s).length===0&&y(s).some(b=>b.tagName==="figcaption")?is(s):null,L=h?.pre===t?h.why:"";return Ie(t,null,null,L?[`its <figure>'s caption stays a caption beside it: ${L}; a <figure> holding the pre and one <figcaption> of words alone makes them its title`]:[]),!0}if(o==="figure")return!Et.has(s?.tagName)||Mn(t)?!0:(g(t,["doc-figure"]),m(t,"figure"),ct(t));let a=o==="table"&&C(s??{}).includes("doc-table-wrap");if(o==="table"&&w(t,"data-doc-chart")!==void 0&&!Et.has((a?s.parentNode:s)?.tagName))return!1;if(o==="table"&&w(t,"data-doc-chart")!==void 0&&a&&i(s)){let c=w(s,tt)??ve();if(xe(t,s,c),w(s,tt)===void 0){let h=i(s).endOffset-1;r(h,h,` ${tt}="${z(c)}"`)}return r(i(t).startOffset,i(t).endOffset,A(t,"table",{drop:["data-doc-chart"]})),!1}if(o==="table"&&(!ct(t)||gs(t))&&!C(s??{}).includes("doc-table-wrap")){let c=t.sourceCodeLocation.attrs?.["data-block-id"],h=w(t,"data-doc-chart")!==void 0,b=(w(t,tt)?.trim()||null)??(h?ve():null),S=w(t,"style"),E=S===void 0?[]:It(S).filter(U=>ss.test(U)),T=E.length?It(S).filter(U=>!ss.test(U)):[],_=U=>` style="${z(U.map(nt=>nt.trim()).join("; "))}"`,G=`<div class="doc-table-wrap"${c?` ${n.slice(c.startOffset,c.endOffset)}`:""}${b?` ${tt}="${z(b)}"`:""}${E.length?_(E):""}>`,Y=A(t,"table",{classes:["doc-table"],drop:["data-block-id",...w(t,tt)!==void 0?[tt]:[],...h?["data-doc-chart"]:[],...E.length?["style"]:[]]}),st=T.length?`${Y.slice(0,-1)}${_(T)}>`:Y,J=h?null:Se(t),X=!1;if(h&&(X=xe(t,t,b,"</div>")),J){let U=n.slice(i(t).endOffset,J.sourceCodeLocation.startOffset);r(i(t).startOffset,i(J).endOffset,'<p class="doc-note">'),r(d(J).startOffset,d(J).endOffset,`</p>${U}${G}${st}`),m(J,"caption")}else r(i(t).startOffset,i(t).startOffset,G,{opens:d(t).endOffset}),r(i(t).startOffset,i(t).endOffset,st);return X||r(d(t).endOffset,d(t).endOffset,"</div>",{closes:i(t).startOffset}),m(t,"table",Vs(t)),!1}if(o==="details"&&es(t)){let c=y(t)[0]?.tagName==="summary"?y(t)[0]:null;return!c||!W(c)||(r(i(t).startOffset,i(t).endOffset,A(t,"details",{classes:["doc-details"]})),y(c).some(h=>C(h).includes("doc-details-summary-label"))||N(i(c).endOffset,d(c).startOffset,'<span class="doc-details-summary-label">',"</span>"),N(d(c).endOffset,d(t).startOffset,'<div class="doc-details-content">',"</div>"),kt(t.childNodes.slice(t.childNodes.indexOf(c)+1)),m(t,"details")),!1}if(o==="dialog"&&pe(t)){let c=Rs(t);return r(i(t).startOffset,i(t).endOffset,A(t,"dialog",{classes:["doc-dialog"]})),N(i(t).endOffset,d(t).startOffset,'<div class="doc-dialog-panel"><div class="doc-dialog-content">',"</div></div>"),c&&K(c,"<h3>","</h3>"),kt(t.childNodes.slice(c?t.childNodes.indexOf(c)+1:0)),m(t,"dialog"),!1}if(o==="aside"&&es(t)&&!q({tags:["aside"]}))return g(t,["doc-panel"]),zt.add(t),m(t,"aside"),!1;if(o==="ul"&&Ae(t)){g(t,[se],{drop:de});for(let c of y(t))je(c);return m(t,"task list"),!1}if(ae(t)&&!ct(t))return r(i(t).startOffset,i(t).endOffset,A(t,"ol",{classes:[ht],drop:["data-doc-chart","data-flow"]})),m(t,"flowchart"),!1;if(o==="ul"&&C(t).includes(se)&&!ct(t)){let c=y(t).filter(vs);if(c.length&&!Ee()){for(let h of c)je(h);m(t,"task list")}return!1}return cn(t),!1}function cn(t){let s=w(t,"style");if(s===void 0||!eo.test(t.tagName))return;let o=It(s).map(S=>{let E=S.indexOf(":"),T=P(E<0?S:S.slice(0,E)).toLowerCase();return{declaration:S.trim(),name:T,value:E<0?"":P(S.slice(E+1).replace(/!\s*important\s*$/i,""))}}),l=o.filter(({name:S})=>S==="text-align").at(-1),a=l&&so.exec(l.value)?.[1].toLowerCase();if(!a)return;let c=o.filter(S=>S.name!=="text-align").map(({declaration:S})=>S),{class:h,style:L}=t.sourceCodeLocation.attrs,b=Object.values(Yt);c.length===0&&!h?r(L.startOffset,L.endOffset,`class="${Yt[a]}"`):(g(t,[Yt[a]],{drop:b}),c.length?r(L.startOffset,L.endOffset,`style="${z(c.join("; "))}"`):x(t,"style")),m(t,"alignment")}function je(t){let s=ys(t);if(g(t,[],{drop:ue}),w(s,"checked")!==void 0){let a=i(t).startOffset+1+t.tagName.length;r(a,a,` ${ce}`)}let{startOffset:o,endOffset:l}=s.sourceCodeLocation;r(o,l+(n[l]===" "?1:0),"")}function $t(t,s=null,o=!1){let l=()=>te(t.childNodes).length>0;bs(t)&&(ks(t)||(zt.has(t)||Hn(t))&&l())?kt(t.childNodes):Zn(t)&&i(t)&&Ws(t);for(let a of t.childNodes??[]){if(D(a)){a.sourceCodeLocation&&a.value.includes("\\(")&&!ke.has(a)&&Hs(a);continue}if(!(!a.tagName||re.has(a.tagName)||Te.has(a))){if(it(a)){for(let c of at(a))zt.add(c),$t(c,c);continue}if(!(w(a,"data-doc-chart")!==void 0&&a.tagName!=="table"&&!ae(a)||w(a,"contenteditable")!==void 0)&&!C(a).some(c=>jt.includes(c))){if(a.tagName==="pre"){_e(a,t);continue}if(!(fe(a)&&!Ae(a))){if(Kt.has(a)){be(a)||$t(a,a,!0);continue}_e(a,t)||o&&be(a)||$t(a,a,o||le.has(a.tagName))}}}}}$t(p,p),$t({childNodes:Gt}),n.includes(dt.header)&&Ft(f);for(let t of Gt){let{startOffset:s,endOffset:o}=t.sourceCodeLocation,l=ft(n,s,o),a=d(p).startOffset,c=l.end>o?Jt(n,a):null;r(a,a,h=>c===null?h:`${h}${Ot}${c}`,{move:{from:s,to:o}}),r(l.start,l.end,"",{leaves:!0}),m(t,"card outside main")}if(!O.length)return{text:n,changes:[]};let Lt=O;for(let t of O.filter(s=>s.move)){let{from:s,to:o}=t.move,l=Lt.filter(a=>!a.move&&!a.leaves&&a.start>=s&&a.end<=o);Lt=Lt.filter(a=>!l.includes(a)),t.text=t.text(cs(n.slice(s,o),l,s)),t.move=null}return{text:cs(n,Lt),changes:u.sort((t,s)=>t.line-s.line)}}function cs(e,n,f=0){let p=m=>m.closes!==null?0:m.opens!==null?2:1,O=(m,v)=>p(m)-p(v)||(m.closes!==null?v.closes-m.closes||v.order-m.order:0)||(m.opens!==null?v.opens-m.opens:0)||m.order-v.order,u=[...n].sort((m,v)=>v.start-m.start||v.end-m.end||(m.start===m.end?O(v,m):v.order-m.order)),$=e;for(let{start:m,end:v,text:r}of u)$=$.slice(0,m-f)+r+$.slice(v-f);return $}function Ss(e,{finish:n=f=>f}={}){let{text:f,changes:p}=uo(e);return{text:p.length?n(f):f,changes:p}}function zo(e,{finish:n,next:f,metadata:p=null}={}){let O=Zt(e);if(O.length)return{text:e,changes:[],added:0,given:[],repeated:O,title:null,icon:null};let u=Ss(e,{finish:n}),{text:$,added:m,given:v}=ze(u.text,f),r=Es($,p);return{...r,changes:u.changes,added:m,given:Je(r.text,v),repeated:O}}function qo(e){return Zt(e).length?[]:qe(Ss(e).text)}var Ts=e=>e.units.find(n=>n.kind==="icon"&&e.boxes[n.box]?.kind==="header")??null;function Es(e,n=null){let f=rt(e,{sourceCodeLocationInfo:!0}),p=bt(f),O=p&&gt(p,r=>pt(r,ms.title)),u=O?.sourceCodeLocation?.endTag?St(e.slice(O.sourceCodeLocation.startTag.endOffset,O.sourceCodeLocation.endTag.startOffset)):"",$=e,m=null;if(u){let r=gt(f,x=>x.tagName==="head"),i=(r&&gt(r,x=>x.tagName==="title"))?.sourceCodeLocation,d=typeof n?.title=="string"?n.title:null,g=!1;if(i?.startTag&&i.endTag){let x=St(e.slice(i.startTag.endOffset,i.endTag.startOffset));if(!(d&&d!==u&&d.includes(u)?x.split(d).join("\0").includes(u):x.includes(u))){let M=d&&d!==u&&He(e,{from:d,to:u})||{start:i.startTag.endOffset,end:i.endTag.startOffset,text:mt(u)};$=e.slice(0,M.start)+M.text+e.slice(M.end),g=!0}}(g||d!==null&&d!==u)&&(m={from:d,to:u,page:g})}let v=null;if(p&&n&&typeof n=="object"){let r=Xt(e),N=Ts(r),i=N?ds(e.slice(N.start,N.end)):null,d=n.icon??null;N?i!==null&&i!==d&&(v={from:d,to:i}):v=d===null?null:{from:d,to:d,missing:!0}}return{text:$,title:m,icon:v}}function Jo(e,{title:n,icon:f}={}){let p=N=>{let i=bt(rt(N,{sourceCodeLocationInfo:!0})),d=i&&gt(i,g=>pt(g,ms.title));return d?.sourceCodeLocation?.endTag?d.sourceCodeLocation:null},O=N=>Ts(Xt(N)),u=p(e);if(!u)return{missing:!0};let $=St(e.slice(u.startTag.endOffset,u.endTag.startOffset)),m=O(e),v={title:$,icon:m?ds(e.slice(m.start,m.end)):null},r=e;if(f!==void 0&&f!==v.icon){if(m&&f===null){let N=ft(r,m.start,m.end);r=r.slice(0,N.start)+r.slice(N.end)}else if(m){let N=/\sdata-block-id="[^"]*"/.exec(/^<[^>]*>/.exec(r.slice(m.start,m.end))?.[0]??"")?.[0]??"";r=r.slice(0,m.start)+Qe(f,N)+r.slice(m.end)}else{let N=Jt(r,u.startTag.startOffset);r=r.slice(0,u.startTag.startOffset)+Qe(f)+(N===null?"":`
12
+ ${N}`)+r.slice(u.startTag.startOffset)}u=p(r)}return n!==void 0&&(r=r.slice(0,u.startTag.endOffset)+mt(n)+r.slice(u.endTag.startOffset),r=Es(r,{title:$||null}).text),{text:r,before:v}}var rs={table:"a table is the kit's framed table","header row":"a header row is a thead, its cells highlighted",caption:"a table's caption is a note line above it (p.doc-note)",figure:"a figure is the kit's card",picture:"a picture is the kit's picture block",details:"a details is the kit's disclosure",dialog:"a dialog is a detail card",aside:"an aside is a highlight panel","task list":"a task list is the kit's to-do list",flowchart:"a marked list is a flowchart",sheets:"headings become tabs",bookmark:"a link card is a bookmark",alignment:"a text-align in a paragraph's or a heading's style is the kit's class","display formula":"a display formula is the kit's math block","card outside main":"a card outside main moved to main's end"};function Vo(e,n,{dryRun:f=!1,pending:p=!1,reread:O=!f&&!p}={}){let u=new Map;for(let{rule:N,line:i}of n)u.set(N,[...new Set([...u.get(N)??[],i])]);let $=[...u].map(([N,i])=>`${N} (line${i.length>1?"s":""} ${i.join(", ")})`).join(", "),m=dn.resolve(e),v=[...u.keys()].filter(N=>rs[N]).map(N=>rs[N]).join("; "),r=`${v?`; ${v}`:""}; the words and numbers are unchanged`;return[p?`natural ${m}: ${$} not rewritten yet: the export rewrites them in this file as the kit's markup (nothing to fix)${r}`:`natural ${m}: ${$}${f?" would be":""} rewritten in this file as the kit's markup (nothing to fix)${r}`,...n.filter(N=>N.note).map(({line:N,rule:i,note:d})=>` line ${N}, ${i}: ${d}`),...O?[" re-read the file before editing it"]:[]]}var ls="strong, em, b, i, u, s, code, a, sub, sup and br, the kit's colors (doc-text-*, doc-highlight-*) and formulas",he=`write a to-do list as ul.${se} \u203A li, li[${ce}] for a checked item (a GFM task list, every item starting with its box, is made one unless the document's own style or script uses GFM's classes or the boxes)`,As=e=>C(e).every(us),Is=e=>y(e).flatMap(n=>[...n.tagName==="span"&&!(F(n,["class"])&&As(n))?[n]:[],...Is(n)]),_s=e=>y(e).some(n=>n.tagName==="img"||_s(n)),js=e=>y(e).flatMap(n=>n.tagName==="img"?[n]:js(n)),Bs=e=>y(e).some(n=>n.tagName==="svg"||n.tagName==="canvas"||Bs(n)),Mt=e=>y(e).some(n=>n.tagName==="input"&&w(n,"type")?.toLowerCase()==="checkbox"||Mt(n)),mo=(e,n)=>{if(e==="tag:img")return"a picture amid the words: give it a paragraph of its own";if(e==="picture"){let f=js(n).map(Ue).find(Boolean);return`a picture in a cell written another way${f?` (${f})`:""}: the preview edits <img src="assets/<file>" alt="\u2026" width="N"> (N pixels, or no width), no other attribute`}if(e==="tag:span"){let f=Is(n).filter(p=>F(p,["style","class"])&&w(p,"style")!==void 0&&As(p)).map(p=>Cs(w(p,"style")).foreign).find(Boolean);return f?`a span with a style the kit has no format for (${f.join(", ")}): left as written`:`a <span> with a class or attribute of the document's own (the preview edits ${ls})`}return e==="tag:input"&&Mt(n)?`a checkbox amid the words: ${he}`:e.startsWith("tag:")&&lt.has(e.slice(4))?`a block (<${e.slice(4)}>) amid the words: give the words a paragraph of their own`:e.startsWith("tag:")?`<${e.slice(4)}> amid the words (the preview edits ${ls})`:e==="comment"?"an HTML comment amid the words":e==="markup"?"an element not closed in the file (the parser closed it)":e==="mention"?'a page block written another way: the preview edits only <a class="doc-link-mention" href="../<slug>/doc.html"><span class="doc-link-mention-icon"></span>title</a>, its title plain words, no other attribute':e==="link"?"a javascript: or data: link":e},ho=new Set([...ws,"details"]);function Xo(e){let n=rt(e,{sourceCodeLocationInfo:!0}),f=bt(n);if(!f)return[];let p=N=>e.slice(0,N).split(`
13
+ `).length,O=new Map,u=[],$=N=>{ho.has(N.tagName)&&N.sourceCodeLocation?.startTag&&ks(N)&&u.push({line:p(N.sourceCodeLocation.startOffset),text:`<${N.tagName}>: words straight in it, outside any paragraph: give them a <p> (the preview cannot reach them, nor move its blocks one by one)`})},m=(N,i=()=>!1)=>{for(let d of y(N)){if(i(d))continue;let g=d.sourceCodeLocation?.startTag;g&&O.set(g.endOffset-1,d),m(d,i)}},v=N=>{for(let i of N.childNodes??[]){if(!i.tagName||re.has(i.tagName))continue;if(it(i)){m(i,fs),at(i).forEach(v);continue}if(w(i,"data-doc-chart")!==void 0||C(i).some(x=>jt.includes(x))||fe(i))continue;let d=i.sourceCodeLocation?.startTag;d&&O.set(d.endOffset-1,i);let g=i.sourceCodeLocation?.endTag;if(le.has(i.tagName)&&d&&i.childNodes.some(x=>D(x)&&/\\\[|\$\$/.test(x.value))&&!(g&&i.childNodes.every(D)&&wt(e.slice(d.endOffset,g.startOffset)))){let x=Dn(e.slice(d.endOffset,g?g.startOffset:i.sourceCodeLocation.endOffset),!!g);u.push({line:p(d.startOffset),text:x?`<${i.tagName}>: the formula holds a bare < or >: write \\lt / \\gt (or &lt; / &gt;)`:`<${i.tagName}>: a display formula (\\[\u2026\\] or $$\u2026$$) amid the words: give it a paragraph of its own`})}i.tagName==="caption"&&d&&(et(i)||y(i).length>0)&&u.push({line:p(d.startOffset),text:'<caption>: the preview cannot edit a table caption; write the line above the table as <p class="doc-note">'}),$(i),v(i)}};$(f),v(f);let r=new Set;for(let{at:N,reason:i}of Vt(e).locks){let d=O.get(N);if(!d)continue;let g=i==="tag:input"&&d.tagName==="li"&&Mt(d)&&d.parentNode?.sourceCodeLocation?.startTag?d.parentNode:null;g&&r.has(g)||(g&&r.add(g),g?u.push({line:p(g.sourceCodeLocation.startOffset),text:`<${g.tagName}>: checkboxes in its items: ${he}`}):u.push({line:p(d.sourceCodeLocation.startOffset),text:`<${d.tagName}>: ${mo(i,d)}`}))}return u.sort((N,i)=>N.line-i.line).map(({line:N,text:i})=>`line ${N}: ${i}`)}function Zo(e){let n=rt(e,{sourceCodeLocationInfo:!0}),f=bt(n);if(!f)return[];let p=d=>e.slice(0,d).split(`
14
+ `).length,O=[],u=[],$=d=>{for(let g of d.childNodes??[])g.tagName==="style"?u.push((g.childNodes??[]).map(x=>x.value??"").join("")):$(g)};$(n);let m=u.join(`
15
+ `).replace(/\/\*[\s\S]*?\*\//g,""),v=d=>new RegExp(`\\.${d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w-])`).test(m),r=d=>{for(let g of y(d).filter(x=>x.tagName==="colgroup"&&w(x,"data-doc-columns")===void 0)){let x=[g,...y(g)].filter(M=>w(M,"width")!==void 0||/(?:^|;)\s*(?:min-|max-)?width\s*:/i.test(w(M,"style")??"")),A=(g.sourceCodeLocation?g:y(g)[0])?.sourceCodeLocation;x.length&&A&&O.push({line:p(A.startOffset),text:`<${g.sourceCodeLocation?"colgroup":"col"}> widths: the kit sizes columns itself; a merged table uses yours`})}},N=d=>{for(let g of d.childNodes??[]){if(!g.tagName||re.has(g.tagName))continue;if(it(g)){at(g).forEach(N);continue}if(w(g,"data-doc-chart")!==void 0||C(g).some(A=>jt.includes(A)))continue;if(fe(g)){let A=g.sourceCodeLocation,M=un(e,g).some(({name:q})=>q==="class");if(Ns.has(g.tagName)&&A?.startTag&&!M&&(et(g)||_s(g))&&!Bs(g)&&!C(g).some(v)){let q=(g.tagName==="ul"||g.tagName==="ol")&&Mt(g)?`; for its checkboxes, ${he}`:"";O.push({line:p(A.startOffset),text:`<${g.tagName} class="${w(g,"class").trim()}"> is a whole block (\u6574\u4F53\u5757): the reader moves it whole and edits its words in place; right for a layout of yours that is no figure (a figure, a diagram or a timeline, goes in <figure class="doc-figure">); drop its class only if its contents were meant as ordinary blocks${q}`})}continue}g.tagName==="table"&&r(g);let x=g.tagName==="ol"&&C(g).includes(ht)?y(g).find(A=>A.tagName!=="li"&&A.sourceCodeLocation):null;if(x&&O.push({line:p(x.sourceCodeLocation.startOffset),text:`<ol class="${ht}"> holds a <${x.tagName}> outside its items: a flowchart's steps are its <li>s (what one holds after its words, a paragraph or a list, is that step's content)`}),g.tagName==="ol"&&C(g).includes(ht))for(let A of y(g).filter(M=>M.tagName==="li")){let M=y(A).find(Q=>!C(Q).includes(_t)),q=M?A.childNodes.slice(0,A.childNodes.indexOf(M)):[];M&&M.tagName!=="p"&&M.sourceCodeLocation&&!q.some(Q=>!C(Q).includes(_t)&&et(Q))&&O.push({line:p(M.sourceCodeLocation.startOffset),text:`a step of <ol class="${ht}"> begins with a <${M.tagName}>: a step's first block is its title, a paragraph (<p><strong>\u2026</strong></p>), the blocks after it its content`})}N(g)}};return N(f),i(f,(d,g)=>O.push({line:d,text:`a ${go[g]} in the text: the page shows it as a break or an empty line, not as a character (a tool that decodes \\u2028 or \\u2029 escapes writes one); write the break the text means (<br>, a new paragraph, a new line in code) or take it out`})),O.sort((d,g)=>d.line-g.line).map(({line:d,text:g})=>`line ${d}: ${g}`);function i(d,g){for(let x of d.childNodes??[])if(!(x.tagName==="script"||x.tagName==="style")){if(it(x)){at(x).forEach(A=>i(A,g));continue}if(D(x)&&x.sourceCodeLocation&&/[\u2028\u2029]/.test(x.value)){let{startOffset:A,endOffset:M}=x.sourceCodeLocation,Q=e.slice(A,M).search(/[\u2028\u2029]/);g(p(A+Math.max(Q,0)),x.value.match(/[\u2028\u2029]/)[0])}i(x,g)}}}function Qo(e){let n=$=>e.slice(0,$).split(`
16
+ `).length,f=$=>D($)?$.value:($.childNodes??[]).map(f).join(""),p=$=>f($).replace(/\s+/g," ").trim(),O=$=>y($).find(m=>/^h[1-6]$/.test(m.tagName)),u=[];for(let $ of Vt(e).units){if($.keep?.reason!=="script"||!$.keep.own)continue;let m=$.node.parentNode;for(;m&&m.tagName!=="section";)m=m.parentNode;let v=$.tag==="section"&&O($.node)?` ${p(O($.node))}`:"",r=m?.tagName&&O(m)?` in ${p(O(m))}`:"";u.push({line:n($.elStart),text:`<${$.tag}>${v}${r} kept by the script: ${$.keep.names.join(", ")} (the reader cannot delete or convert it; rename any of these the script does not select it by)`})}return u.sort(($,m)=>$.line-m.line).map(({line:$,text:m})=>`line ${$}: ${m}`)}var go={"\u2028":"line separator (U+2028)","\u2029":"paragraph separator (U+2029)"};function bt(e){return gt(e,n=>n.tagName==="main")}function gt(e,n){if(e.tagName&&n(e))return e;for(let f of e.childNodes??[]){let p=gt(f,n);if(p)return p}return null}export{uo as a,Ss as b,zo as c,qo as d,Es as e,Jo as f,Vo as g,Xo as h,Zo as i,Qo as j};
@@ -1,20 +1,20 @@
1
1
  import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{a as Ee,b as Re}from"./chunk-IA4PSIMD.mjs";import{b as Te}from"./chunk-6EZ7FNIK.mjs";import{a as ye,b as je,c as pt,d as Me,e as Ae,f as Ne}from"./chunk-V6RIYQZZ.mjs";import{b as Se,c as ve,e as Oe,g as Ht}from"./chunk-SXHBYZST.mjs";import{a as me}from"./chunk-UMHUSOPJ.mjs";import{a as ge,d as ke,e as be,f as $e,g as xe}from"./chunk-N76HWBA3.mjs";import{e as pe,f as we,g as he,h as Ct}from"./chunk-FJYN7RTH.mjs";import{a as _,m as de}from"./chunk-UBBRTJ2R.mjs";import{g as le,u as ue}from"./chunk-FWNRPMCJ.mjs";var vn=3e4,On=12e4,jn=1500,Fe=1e4,Ie=l=>l.reduce((i,{key:w,tag:u})=>i.set(`${w}
2
+ import{a as Re,b as Ie}from"./chunk-IA4PSIMD.mjs";import{b as Ee}from"./chunk-F4ZA6JRZ.mjs";import{a as ge,b as Me,c as pt,d as Ae,e as Ne,f as Te}from"./chunk-ITOH5EGO.mjs";import{b as ve,c as Oe,e as je,g as Ht}from"./chunk-ZQS6H473.mjs";import{a as pe}from"./chunk-UMHUSOPJ.mjs";import{a as ke,d as be,e as $e,f as xe,g as Se}from"./chunk-R2ZDLJYT.mjs";import{e as we,f as he,g as ye,h as Ct}from"./chunk-VFX2KNHP.mjs";import{a as _,m as me}from"./chunk-VS7JIGJW.mjs";import{g as ue,u as de}from"./chunk-HDWTZ763.mjs";var On=3e4,jn=12e4,Mn=1500,De=1e4,Fe=l=>l.reduce((i,{key:w,tag:u})=>i.set(`${w}
3
3
  ${u}`,(i.get(`${w}
4
- ${u}`)??0)+1),new Map);function De({now:l=Date.now,hold:i=vn,limit:w=On,quiet:u=jn}={}){let k=new Map,d=new Map,O=new Map,h=new Map,f=new Map;return{wrote(p,b){h.set(p,_(b))},judge(p,{source:b,mtime:I}){if(b===null)return k.delete(p),O.delete(p),{held:!1,signs:[],wait:0,own:!1};let N=_(b),$=f.get(p)?.hash===N?f.get(p).signs:null;$||($=je(b),f.set(p,{hash:N,signs:$}));let Z=l(),W=(J,Q=!1)=>(k.delete(p),d.set(p,Ie($)),O.set(p,b),{held:!1,signs:[],wait:J,own:Q});if(h.get(p)===N)return W(0,!0);let L=d.get(p)??new Map,H=Ie($);if([...H].some(([J,Q])=>Q>(L.get(J)??0))){let J=Math.min(I,Z),Q=k.get(p)??J;k.set(p,Q);let st=Math.min(i-(Z-J),w-(Z-Q));if(st>0)return{held:!0,signs:$.filter(({key:s,tag:g})=>H.get(`${s}
4
+ ${u}`)??0)+1),new Map);function Pe({now:l=Date.now,hold:i=On,limit:w=jn,quiet:u=Mn}={}){let k=new Map,d=new Map,O=new Map,h=new Map,c=new Map;return{wrote(p,b){h.set(p,_(b))},judge(p,{source:b,mtime:I}){if(b===null)return k.delete(p),O.delete(p),{held:!1,signs:[],wait:0,own:!1};let N=_(b),$=c.get(p)?.hash===N?c.get(p).signs:null;$||($=Me(b),c.set(p,{hash:N,signs:$}));let Z=l(),W=(J,Q=!1)=>(k.delete(p),d.set(p,Fe($)),O.set(p,b),{held:!1,signs:[],wait:J,own:Q});if(h.get(p)===N)return W(0,!0);let L=d.get(p)??new Map,H=Fe($);if([...H].some(([J,Q])=>Q>(L.get(J)??0))){let J=Math.min(I,Z),Q=k.get(p)??J;k.set(p,Q);let st=Math.min(i-(Z-J),w-(Z-Q));if(st>0)return{held:!0,signs:$.filter(({key:s,tag:g})=>H.get(`${s}
5
5
  ${g}`)>(L.get(`${s}
6
- ${g}`)??0)),wait:st,own:!1,taken:O.get(p)}}return W(Math.min(u,Math.max(0,u-(Z-I))))}}}import{createHmac as Xn,randomBytes as qt}from"node:crypto";import{existsSync as tr,mkdirSync as er,readFileSync as nr,writeFileSync as rr}from"node:fs";import z from"node:fs/promises";import P from"node:path";import{FILE as or}from"../browser/shared/annotations.mjs";import{escapeTyped as ar}from"../browser/shared/escape.mjs";import{writeAtomic as Ft}from"../browser/shared/files.mjs";import{sendJson as C}from"../browser/shared/http.mjs";import{REQUEST_ID as Qt}from"../browser/shared/ids.mjs";import{UPLOAD_REQUEST_LIMIT as sr}from"../browser/shared/media.mjs";import{reportsDirectory as ir}from"../browser/shared/paths.mjs";import{sameDirectory as cr}from"../browser/shared/preview-server.mjs";import{slugPattern as rt}from"../browser/shared/reports.mjs";import{TODO_MOST as fr}from"../browser/shared/workspace-query.mjs";import{documentDirectory as lr,documentFiles as Mt,isDocumentSource as ur}from"../browser/shared/workspace.mjs";import zt from"node:fs/promises";import Pe from"node:path";import{checkAnnotations as Mn,cleanAnchor as An,cleanItem as Je,FILE as Nn,itemsText as Tn,readItems as En,treeText as _e}from"../browser/shared/annotations.mjs";import{writeAtomic as Rn}from"../browser/shared/files.mjs";import{slugPattern as In}from"../browser/shared/reports.mjs";import{documentDirectory as Le,documentFiles as Fn}from"../browser/shared/workspace.mjs";var Dn=600*1e3,Pn=600*1e3;function Jn(l){let{units:i,boxes:w}=he(l),u=[...i].sort((h,f)=>h.elStart-f.elStart),k=new Map(u.map((h,f)=>[h.id,f])),d=new Map(u.map(h=>[h.id,_e(h.node)])),O={h2:null,h3:null,h4:null};return u.map(h=>{let f=[];for(let N=h;N;N=N.parent===null?null:i[N.parent]){let $=w[N.box];if($?.kind==="panel"&&$.key!==null){let W=i.find(L=>L.kind==="tab"&&L.parent===$.unit&&L.key===$.key);W&&f.unshift({tab:d.get(W.id)})}let Z=$?.unit===null||$?.unit===void 0?null:i[$.unit];if(Z?.tag==="details"&&$.kind==="details"){let W=Z.node.childNodes.find(L=>L.tagName==="summary");W&&f.push({details:_e(W)})}}let p=f.find(N=>N.tab)?.tab,b=f.find(N=>N.details)?.details,I=[p,O.h2,O.h3,O.h4,b].filter(Boolean);return h.tag==="h2"?Object.assign(O,{h2:d.get(h.id),h3:null,h4:null}):h.tag==="h3"?Object.assign(O,{h3:d.get(h.id),h4:null}):h.tag==="h4"&&(O.h4=d.get(h.id)),{id:h.blockId,text:d.get(h.id),parent:h.parent===null?null:k.get(h.parent)??null,where:I,heading:/^h[2-4]$/.test(h.tag)}})}function Ue({reportsDirectory:l,read:i,write:w=Rn,dropped:u=()=>{},now:k=Date.now}){let d=new Map,O=new Map,h=new Map,f=(s,g)=>{let r=h.get(s);if(r?.text===g)return r.units;let a=Jn(g);return h.set(s,{text:g,units:a}),a},p=s=>Pe.join(Le(s,l),Nn),b=s=>typeof s=="string"&&In.test(s);async function I(s){let g=await zt.readFile(p(s),"utf8").catch(()=>null);return{text:g,items:g===null?[]:En(g)}}async function N(s,g,r){let a=Tn(g);return a===r||(a===null?await zt.rm(p(s),{force:!0}):await w(p(s),a)),$(a)}let $=s=>s===null?"":_(s),Z=s=>{let g=d.get(s)??new Map;for(let[r,a]of g)k()-a>Dn&&g.delete(r);return[...g.keys()]},W=(s,g)=>g.forEach(r=>d.get(s)?.delete(r)),L=s=>{let g=O.get(s)??O.set(s,new Map).get(s);for(let[r,a]of g)k()-a>Pn&&g.delete(r);return g};async function H(s,{keep:g=null,items:r=null,before:a=void 0}={}){let S=r?{items:r,text:a}:await I(s),v=await i(s).catch(()=>null);if(!v)return{items:S.items,units:[],places:new Map,version:$(S.text),missing:!0};let D=f(s,v.text),T=L(s),x=Mn(S.items,D,{keep:new Set([...T.keys(),g])});for(let M of T.keys())x.waiting.has(M)||T.delete(M);if(x.dropped.length>0){let M=d.get(s)??d.set(s,new Map).get(s);for(let ot of x.dropped)M.set(ot.id,k())}let A=x.changed||r?await N(s,x.items,S.text):$(S.text);return x.dropped.length>0&&u(s,x.dropped),{items:x.items,units:D,places:x.places,version:A,missing:!1}}let F=(s,{items:g,version:r})=>({ok:!0,version:r,items:g,dropped:Z(s)});async function J(s){if(!b(s))return[400,{ok:!1,reason:"body"}];let g=await H(s);return g.missing?[404,{ok:!1,reason:"missing"}]:[200,F(s,g)]}async function Q(s){if(!b(s))return[400,{ok:!1,reason:"body"}];let g=await H(s);if(g.missing)return[404,{ok:!1,reason:"missing"}];let r=null,a=Fn(Le(s,l));try{r=JSON.parse(await zt.readFile(a.json,"utf8"))}catch{}let S=await i(s).catch(()=>null),v=/<h1\b[^>]*>([\s\S]*?)<\/h1>/i.exec(S?.text??"")?.[1]?.replace(/<[^>]*>/g,"").trim(),D=typeof r?.title=="string"&&r.title.trim()?r.title.trim():v||s,T=g.units.some(A=>A.heading),x=g.items.map(A=>{let M=g.units[g.places.get(A.id)?.at],ot=M?.where?.length?M.where:M?.heading?[M.text]:[];return{where:ot,top:T&&ot.length===0,blocks:A.anchor.blocks.filter(B=>g.units.some(nt=>nt.id===B)),whole:A.anchor.kind==="blocks",quote:A.anchor.quote,text:A.text}});return[200,{ok:!0,title:D,path:Pe.resolve(a.html),items:x}]}async function st(s){let{slug:g}=s??{};if(!b(g))return[400,{ok:!1,reason:"body"}];if(!await i(g).catch(()=>null))return[404,{ok:!1,reason:"missing"}];let r=await I(g);if(s.anchors&&typeof s.anchors=="object"&&!Array.isArray(s.anchors)){let T=r.items.map(A=>{let M=Object.hasOwn(s.anchors,A.id)?An(s.anchors[A.id]):null;return M&&M.kind===A.anchor.kind?{...A,anchor:M}:A}),x=await N(g,T,r.text);return[200,F(g,{items:T,version:x})]}let a=r.items,S=null,v=null;if(s.put!==void 0){let T=a.find(A=>A.id===s.put?.id),x=Je({...s.put,created:T?.created??s.put?.created});if(!x)return[400,{ok:!1,reason:"item"}];a=T?a.map(A=>A.id===x.id?x:A):[...a,x],S=x.id,T||L(g).set(x.id,k()),W(g,[x.id])}else if(typeof s.remove=="string")a=a.filter(T=>T.id!==s.remove);else if(s.clear===!0)v=a,a=[];else if(Array.isArray(s.restore)){let T=new Map(a.map(M=>[M.id,M])),x=s.restore.map(M=>Je(M,M?.updated)).filter(M=>M&&!(T.get(M.id)?.updated>M.updated)),A=new Set(x.map(M=>M.id));for(let M of A)T.has(M)||L(g).set(M,k());a=[...a.filter(M=>!A.has(M.id)),...x],W(g,[...A])}else return[400,{ok:!1,reason:"body"}];let D=await H(g,{keep:S,items:a,before:r.text});return[200,{...F(g,D),...v?{removed:v}:{}}]}async function q(s){if(!b(s))return;let{text:g}=await I(s);g!==null&&await H(s)}return{list:J,copy:Q,change:st,afterWrite:q}}import wt from"node:fs/promises";import ht from"node:path";import{writeAtomic as We}from"../browser/shared/files.mjs";import{slugPattern as Gt}from"../browser/shared/reports.mjs";var It=1,Ot={seen:"seen.html",base:"base.html",state:"state.json"},_n=4,Ln=1800*1e3;function Be({stateDirectory:l=null,shown:i,folderOf:w,isPage:u=()=>!1,log:k=null,now:d=Date.now,quiet:O=Ln}){let h=new Map,f=r=>ht.join(l,"changes",r),p=Promise.resolve(),b=r=>{let a=p.then(r);return p=a.catch(S=>k?.(`changes: ${S.message}`)),a};async function I(r){if(!l)return h.get(r)?.state??null;try{let a=JSON.parse(await wt.readFile(ht.join(f(r),Ot.state),"utf8"));return a?.v===It&&typeof a.seen=="string"?a:null}catch{return null}}async function N(r,a){return l?wt.readFile(ht.join(f(r),Ot[a]),"utf8").catch(()=>null):h.get(r)?.[a]??null}async function $(r,a,S={}){if(!l){let v=h.get(r)??{};h.set(r,{...v,...S,state:a});return}await wt.mkdir(f(r),{recursive:!0});for(let[v,D]of Object.entries(S))D===null?await wt.rm(ht.join(f(r),Ot[v]),{force:!0}):await We(ht.join(f(r),Ot[v]),D);await We(ht.join(f(r),Ot.state),`${JSON.stringify(a)}
7
- `)}async function Z(r){h.delete(r),l&&await wt.rm(f(r),{recursive:!0,force:!0,maxRetries:3})}let W=async r=>Math.round((await wt.stat(w(r)).catch(()=>null))?.birthtimeMs??0),L=r=>r?.base?`${r.since}|${r.writes}`:null,H=r=>Number.isFinite(r?.draft)&&d()-r.draft<O?r.draft:null,F=(r,a,S,v=H(r))=>[{v:It,born:r?.born??0,seen:a,...v===null?{}:{draft:v}},{seen:S,base:null}];async function J(r){let a=await I(r);if(!a)return null;let S=await W(r);return a.born&&S&&a.born!==S?(await Z(r),null):a}async function Q(r,a){if(typeof a!="string"||!Gt.test(r)||u(r))return!1;let S=_(a),v=await J(r);if(!v)return await $(r,{v:It,born:await W(r),seen:S},{seen:a}),!1;if(v.seen===S)return!1;let D=await N(r,"seen"),T=new Date(d()).toISOString();if(D===null)return await $(r,...F(v,S,a)),!1;let x=i(D),A=i(a);if(!v.base){if(!pt(x,A))return await $(r,...F(v,S,a)),!1;if(H(v)!==null||Me(x))return await $(r,...F(v,S,a,d())),!1;let{draft:B,...nt}=v;return await $(r,{...nt,seen:S,base:_(x),since:T,at:T,writes:1},{seen:a,base:x}),!0}let M=await N(r,"base");if(M===null||!pt(M,A))return await $(r,...F(v,S,a)),!0;let ot=pt(x,A)!==null;return await $(r,{...v,seen:S,...ot?{at:T,writes:v.writes+1}:{}},{seen:a}),ot}async function st(r,a,S,v){if(!Gt.test(r)||u(r))return!1;let D=await J(r),T=_(a);if(!D?.base)return await $(r,...F(D??{born:await W(r)},T,a,v?null:H(D))),!1;let x=await N(r,"base");if(x!==null&&S)try{x=S(x)}catch(A){k?.(`changes: ${r}: the baseline did not take the edit (${A.message})`)}return x===null||!pt(x,i(a))?(await $(r,...F(D,T,a)),!0):(await $(r,{...D,seen:T,base:_(x)},{seen:a,base:x}),!1)}async function q(r,a){if(!Gt.test(r)||u(r))return{ended:!1,moved:!1};let S=typeof a=="string"?await Q(r,a):!1,v=await J(r);if(v?.draft===void 0)return{ended:!1,moved:S};let{draft:D,...T}=v;return await $(r,T),{ended:H(v)!==null,moved:S}}let s=new Map;async function g(r,a){await Q(r,a);let S=i(a),v=_(S),D=await J(r);if(!D?.base)return{pending:!1,version:v};let T=`${r} ${D.base} ${v}`,x=s.get(T);if(x===void 0){let A=await N(r,"base");for(x=A===null?null:pt(A,S),s.set(T,x);s.size>_n;)s.delete(s.keys().next().value)}return x?{pending:!0,version:v,stamp:L(D),since:D.since,writes:D.writes,...x}:{pending:!1,version:v}}return{look:(r,a)=>b(()=>Q(r,a)),wrote:(r,a,S=null,{reader:v=!1}={})=>b(()=>st(r,a,S,v)),endDraft:(r,a=null)=>b(()=>q(r,a)),read:(r,a)=>b(()=>g(r,a)),stamp:r=>b(async()=>L(await J(r))),snapshot:r=>b(async()=>{let a=await J(r);return a?{state:a,seen:await N(r,"seen"),base:await N(r,"base")}:null}),clear:r=>b(async()=>{let a=await J(r);a?.base&&await $(r,{v:It,born:a.born,seen:a.seen},{base:null})}),restore:(r,a)=>b(async()=>{a?.state&&await $(r,a.state,{seen:a.seen,base:a.base})}),forget:r=>b(()=>Z(r)),idle:()=>b(async()=>{})}}import{randomBytes as Un}from"node:crypto";import ct from"node:fs/promises";import yt from"node:path";import{FILE as Wn,readItems as Bn}from"../browser/shared/annotations.mjs";import{writeAtomic as Yn}from"../browser/shared/files.mjs";import{documentDirectory as Zn}from"../browser/shared/workspace.mjs";var Cn=20,Ce=/^\d{8}T\d{6}Z-[a-f0-9]{8}\.json$/,Ye=80,He=({stateDirectory:l,slug:i})=>yt.join(l,"dropped-annotations",i),ze=l=>({id:l.id,text:l.text,quote:l.anchor?.quote??"",kind:l.anchor?.kind??"text"});async function Ge({stateDirectory:l,reportsDirectory:i,slug:w,time:u,items:k}){let d=He({stateDirectory:l,reportsDirectory:i,slug:w});await ct.mkdir(d,{recursive:!0});let O=u.replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z");await Yn(yt.join(d,`${O}-${Un(4).toString("hex")}.json`),JSON.stringify({time:u,items:k}));let h=(await ct.readdir(d)).filter(f=>Ce.test(f)).sort();await Promise.all(h.slice(0,Math.max(0,h.length-Cn)).map(f=>ct.rm(yt.join(d,f),{force:!0})))}async function Vr({stateDirectory:l,reportsDirectory:i,slug:w}){let u=He({stateDirectory:l,reportsDirectory:i,slug:w}),k=(await ct.readdir(u).catch(()=>[])).filter(h=>Ce.test(h)).sort();if(k.length===0)return[];let d=new Set(Bn(await ct.readFile(yt.join(Zn(w,i),Wn),"utf8").catch(()=>"")).map(h=>h.id)),O=[];for(let h of k){let f=yt.join(u,h);try{let p=JSON.parse(await ct.readFile(f,"utf8")),b=Array.isArray(p?.items)?p.items.filter(I=>typeof I?.id=="string"&&!d.has(I.id)):[];typeof p?.time=="string"&&b.length&&O.push({time:p.time,items:b})}catch{}await ct.rm(f,{force:!0}).catch(()=>{})}return O}var Hn=(l,i=new Date)=>{let w=new Date(l),u=d=>String(d).padStart(2,"0"),k=`${u(w.getHours())}:${u(w.getMinutes())}`;return w.toDateString()===i.toDateString()?k:`${w.getFullYear()}-${u(w.getMonth()+1)}-${u(w.getDate())} ${k}`},Ze=l=>{let i=String(l??"").replace(/\s+/g," ").trim();return JSON.stringify(i.length>Ye?`${i.slice(0,Ye-1)}\u2026`:i)};function Kt(l,{time:i=null,items:w},{today:u=new Date}={}){let k=yt.resolve(l),d=`${w.length} \u6279\u6CE8 (annotation${w.length===1?"":"s"})`;return[`annotations ${k}: ${i?`at ${Hn(i,u)}, `:""}Gallery deleted ${d} whose words are gone from the document (rewritten or deleted):`,...w.map(({id:O,text:h,quote:f,kind:p})=>` ${O} ${Ze(h)} on ${p==="blocks"?"the blocks ":""}${Ze(f)}`)]}function qr(l,i,{today:w=new Date}={}){return i.length?[...i.flatMap(u=>Kt(l,u,{today:w}))," they were the reader's: say in your hand-off which your edit carried out and which you left, and never write them back"]:[]}import{randomBytes as zn}from"node:crypto";import gt from"node:fs/promises";import jt from"node:path";import{writeAtomic as Gn}from"../browser/shared/files.mjs";var Kn=20,Ke=/^\d{8}T\d{6}Z-[a-f0-9]{8}\.json$/,Qe=({stateDirectory:l,slug:i})=>jt.join(l,"rewrites",i);async function Ve({stateDirectory:l,reportsDirectory:i,slug:w,time:u,changes:k}){let d=Qe({stateDirectory:l,reportsDirectory:i,slug:w});await gt.mkdir(d,{recursive:!0});let O=u.replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z");await Gn(jt.join(d,`${O}-${zn(4).toString("hex")}.json`),JSON.stringify({time:u,changes:k}));let h=(await gt.readdir(d)).filter(f=>Ke.test(f)).sort();await Promise.all(h.slice(0,Math.max(0,h.length-Kn)).map(f=>gt.rm(jt.join(d,f),{force:!0})))}async function qe({stateDirectory:l,reportsDirectory:i,slug:w}){let u=Qe({stateDirectory:l,reportsDirectory:i,slug:w}),k=(await gt.readdir(u).catch(()=>[])).filter(O=>Ke.test(O)).sort(),d=[];for(let O of k){let h=jt.join(u,O);try{let f=JSON.parse(await gt.readFile(h,"utf8"));typeof f?.time=="string"&&Array.isArray(f.changes)&&d.push(f)}catch{}await gt.rm(h,{force:!0}).catch(()=>{})}return d}var Qn=(l,i=new Date)=>{let w=new Date(l),u=d=>String(d).padStart(2,"0"),k=`${u(w.getHours())}:${u(w.getMinutes())}`;return w.toDateString()===i.toDateString()?k:`${w.getFullYear()}-${u(w.getMonth()+1)}-${u(w.getDate())} ${k}`};function oo(l,i,{today:w=new Date}={}){if(!i.length)return[];let u=jt.resolve(l),k=[];for(let{time:d,changes:O}of i){let h=[];for(let{line:f,rule:p,key:b}of[...O].sort((I,N)=>I.line-N.line)){let I=`line ${f} ${p}${b?` ${b}`:""}`;h.includes(I)||h.push(I)}k.push(`preview ${u}: at ${Qn(d,w)}, when the reader edited the page, the preview wrote your natural HTML as the kit's markup: ${h.join(", ")}`),k.push(...O.filter(f=>f.note).map(({line:f,rule:p,note:b})=>` line ${f}, ${p}: ${b}`))}return k.push(" re-read the file before editing it (those lines are the file's as you had left it)"),k}import{todoRef as Vn}from"../browser/shared/workspace-query.mjs";var qn=(l,i)=>l.length===i.length&&l.every((w,u)=>w===i[u]);function Xe(l,i,w,u){let k=Re(i),d=Ee(w,{at:!0}),O=null,h=f=>(O??=pe(w).units).find(p=>p.elStart===f)??null;return u.map(f=>{let p=Vn(f?.ref);if(!p||p.slug!==l||typeof f.done!="boolean")return{reason:"ref"};let b=p.block?d.find(N=>N.block===p.block)??null:null;if(b&&b.text!==p.text)return{reason:"changed"};if(!b){let N=d.filter($=>$.text===p.text&&qn($.path,p.path));if(p.version===k)b=N.find($=>$.nth===p.nth)??null;else{if(N.length>1)return{reason:"ambiguous"};b=N[0]??null}}if(!b)return{reason:"changed"};let I=h(b.at);return I?{unit:I,done:b.done,want:f.done}:{reason:"locked"}})}function tn(l,i){let w=new Map,u=i.map(f=>{if(!f.unit)return!1;let p=w.has(f.unit.id)?w.get(f.unit.id):f.done;return w.set(f.unit.id,f.want),p!==f.want}),k=new Map;for(let f of i)f.unit&&w.get(f.unit.id)!==f.done&&k.set(f.unit.id,f);if(k.size===0)return{commit:null,changed:u};let d=[],O=[],h=new Map;for(let[f,p]of k){let b=`todo${d.length}`,I=p.unit.blockId?{key:b,id:p.unit.blockId}:{key:b,open:f,hash:de(l,p.unit)};d.push({key:b,unit:I,attribute:"data-checked",value:w.get(f)?"":null}),O.push(I),h.set(f,b)}return{commit:{units:d,touch:O,keys:h},changed:u}}import{EMPTY_STYLE as dr,emptyWordsScript as mr,showEmpty as pr}from"../browser/editor/components/placeholder.mjs";import{TOKENS as wr}from"../browser/editor/page/look.mjs";import{MARGIN_STYLE as hr,earlyMarginScript as yr}from"../browser/editor/page/margin.mjs";var Vt=/^[a-f0-9]{16}$/,Xt=2*1024*1024,gr=sr,en=50,nn=/^\d{8}T\d{6}Z-[a-f0-9]{16}\.html$/,kr=30,rn=3,on=200,ft="\u6587\u4EF6\u4E00\u518D\u88AB\u4FEE\u6539\uFF08\u4F8B\u5982 AI \u6B63\u5728\u5199\u5165\uFF09\uFF0C\u7A0D\u540E\u518D\u540C\u6B65",br="\u8FD9\u6B21\u7684\u4FEE\u6539\u592A\u5927\uFF0C\u4E00\u6B21\u5B58\u4E0D\u4E0B",$r=250,lt=Symbol("again"),xr="/__gallery/edit/src/editor/page/editor.mjs",Sr=l=>new Promise(i=>setTimeout(i,l));function vr(l,i=Xt){return new Promise((w,u)=>{let k=[],d=0;l.on("data",O=>{d+=O.length,d>i?k.length=0:k.push(O)}),l.on("end",()=>d>i?u(new Error("too-large")):w(Buffer.concat(k).toString("utf8"))),l.on("error",u)})}function Or(l){if(!l)return qt(16).toString("hex");let i=P.join(l,"token");try{let u=nr(i,"utf8").trim();if(/^[a-f0-9]{32}$/.test(u))return u}catch{}let w=qt(16).toString("hex");try{er(l,{recursive:!0,mode:448}),rr(i,w,{mode:384})}catch{}return w}function Uo({reportsDirectory:l=ir,stateDirectory:i=null,write:w=Ft,ids:u=!0,finish:k=p=>p,log:d=null,settling:O={},reviewing:h={},onChanges:f=()=>{}}={}){let p=Or(i),b=De(O),I=O.wait??Fe,N=new Map,$=async(t,n,e,o="reader")=>{let c=await w(t,n,e);if(c!==!1&&ur(P.basename(t))){let y=P.basename(P.dirname(t));b.wrote(y,n),N.set(y,{hash:_(n),by:o})}return c},Z=t=>lr(t,l),W=t=>Mt(Z(t)).html,L=new Map,H=i&&P.join(i,"snapshots"),F=Promise.resolve(),J=Promise.resolve(),Q=async(t,n,e,{by:o="time"}={})=>{let c=(await z.readdir(t)).filter(m=>n.test(m));if(c.length<=e)return;let y=o==="name"?c.sort():(await Promise.all(c.map(async m=>({name:m,time:(await z.stat(P.join(t,m))).mtimeMs})))).sort((m,j)=>m.time-j.time).map(({name:m})=>m);await Promise.all(y.slice(0,y.length-e).map(m=>z.rm(P.join(t,m),{force:!0})))},st=(t,n)=>{H&&(F=F.then(async()=>{let e=P.join(H,`${t}.html`),o=new Date;try{await z.utimes(e,o,o);return}catch{}await z.mkdir(H,{recursive:!0}),await Ft(e,n),await Q(H,/^[a-f0-9]{16}\.html$/,en)}).catch(()=>{}))},q=(t,n)=>{i&&(F=F.then(async()=>{let e=P.join(i,"history",t),o=_(n);if(await z.mkdir(e,{recursive:!0}),(await z.readdir(e)).filter(m=>nn.test(m)).sort().at(-1)?.endsWith(`-${o}.html`))return;let y=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z");await Ft(P.join(e,`${y}-${o}.html`),n),await Q(e,nn,kr,{by:"name"})}).catch(()=>{}))},s=new Map,g=t=>i&&P.join(i,"receipts",t),r=(t,n,e,o)=>{for(s.set(`${t} ${n}`,{digest:e,answer:o});s.size>on*4;)s.delete(s.keys().next().value);let c=g(t);c&&(F=F.then(async()=>{await z.mkdir(c,{recursive:!0}),await Ft(P.join(c,`${n}.json`),JSON.stringify({digest:e,answer:o})),await Q(c,{test:y=>y.endsWith(".json")&&Qt.test(y.slice(0,-5))},on)}).catch(()=>{}))},a=async(t,n)=>{let e=s.get(`${t} ${n}`);if(e)return e;let o=g(t);if(!o)return null;await F;try{let c=JSON.parse(await z.readFile(P.join(o,`${n}.json`),"utf8"));return typeof c?.digest=="string"&&c.answer?.ok?c:null}catch{return null}},S=new Map,v=(t,n)=>{let e=new Date().toISOString();if(!i)return void S.set(t,[...S.get(t)??[],{time:e,changes:n}].slice(-20));F=F.then(()=>Ve({stateDirectory:i,reportsDirectory:l,slug:t,time:e,changes:n})).catch(()=>{})},D=async t=>{if(!i){let n=S.get(t)??[];return S.delete(t),n}return await F,qe({stateDirectory:i,reportsDirectory:l,slug:t})},T=(t,n)=>{for(L.delete(t),L.set(t,n);L.size>en;)L.delete(L.keys().next().value);st(t,n)},x=async t=>{if(L.has(t))return L.get(t);if(!H||!Vt.test(t))return null;await F;let n=await z.readFile(P.join(H,`${t}.html`),"utf8").catch(()=>null);return n===null||_(n)!==t?null:(T(t,n),n)},A=new Map,M=t=>{let n=A.get(t);if(n)return n;let e=Se(t,{finish:k});for(A.set(t,e);A.size>8;)A.delete(A.keys().next().value);return e},ot=P.join(P.resolve(l),".gallery","pages"),B=Be({...h,stateDirectory:i,shown:t=>M(t).text,folderOf:Z,log:d,isPage:t=>P.resolve(Z(t)).startsWith(ot+P.sep)}),nt=(t,n)=>n.then(e=>{e&&f(t)},e=>d?.(`${t}: the Agent's changes not kept (${e.message})`));async function Dt(t,n=void 0){if(typeof t!="string"||!rt.test(t))return null;let e=W(t),o=n!==void 0?n:await z.readFile(e,"utf8").catch(()=>null);if(o===null)return null;let{text:c,changes:y}=M(o);return{file:e,source:o,text:c,version:_(c),changes:y}}async function it(t){if(typeof t!="string"||!rt.test(t))return{source:null,held:!1,signs:[],wait:0,own:!1};let n=W(t),e=await z.readFile(n,"utf8").catch(()=>null),o=(await z.stat(n).catch(()=>null))?.mtimeMs??0;return{source:e,...b.judge(t,{source:e,mtime:o})}}async function kt(t,n=Date.now()+I){for(;;){let e=await it(t);if(!e.held||Date.now()>=n)return e;await Sr(Math.max(0,Math.min($r,n-Date.now())))}}async function Pt(t,{wait:n=I}={}){let e=await kt(t,Date.now()+n),o=await Dt(t,e.held&&e.taken!==void 0?e.taken:e.source);return o&&{...o,held:e.held===!0}}function an(t,n,{editor:e=xr,kitTags:o=()=>[]}={}){let{html:c,map:y}=ye(n);T(y.version,n);let m=le(l),j=ue(m).map(({assets:Y,...X})=>({...X,kit:o(Y)})),E=`<script type="application/json" id="doc-edit-map" data-doc-dev>${JSON.stringify({slug:t,token:p,...y,components:j,hidden:m.settings.hidden}).replace(/</g,"\\u003c")}</script>
6
+ ${g}`)??0)),wait:st,own:!1,taken:O.get(p)}}return W(Math.min(u,Math.max(0,u-(Z-I))))}}}import{createHmac as tr,randomBytes as qt}from"node:crypto";import{existsSync as er,mkdirSync as nr,readFileSync as rr,writeFileSync as or}from"node:fs";import z from"node:fs/promises";import P from"node:path";import{FILE as ar}from"../browser/shared/annotations.mjs";import{escapeTyped as sr}from"../browser/shared/escape.mjs";import{writeAtomic as Ft}from"../browser/shared/files.mjs";import{sendJson as C}from"../browser/shared/http.mjs";import{REQUEST_ID as Qt}from"../browser/shared/ids.mjs";import{UPLOAD_REQUEST_LIMIT as ir}from"../browser/shared/media.mjs";import{reportsDirectory as cr}from"../browser/shared/paths.mjs";import{sameDirectory as fr}from"../browser/shared/preview-server.mjs";import{slugPattern as rt}from"../browser/shared/reports.mjs";import{TODO_MOST as lr}from"../browser/shared/workspace-query.mjs";import{documentDirectory as ur,documentFiles as Mt,isDocumentSource as dr}from"../browser/shared/workspace.mjs";import zt from"node:fs/promises";import Je from"node:path";import{checkAnnotations as An,cleanAnchor as Nn,cleanItem as _e,FILE as Tn,itemsText as En,readItems as Rn,treeText as Le}from"../browser/shared/annotations.mjs";import{writeAtomic as In}from"../browser/shared/files.mjs";import{slugPattern as Fn}from"../browser/shared/reports.mjs";import{documentDirectory as Ue,documentFiles as Dn}from"../browser/shared/workspace.mjs";var Pn=600*1e3,Jn=600*1e3;function _n(l){let{units:i,boxes:w}=ye(l),u=[...i].sort((h,c)=>h.elStart-c.elStart),k=new Map(u.map((h,c)=>[h.id,c])),d=new Map(u.map(h=>[h.id,Le(h.node)])),O={h2:null,h3:null,h4:null};return u.map(h=>{let c=[];for(let N=h;N;N=N.parent===null?null:i[N.parent]){let $=w[N.box];if($?.kind==="panel"&&$.key!==null){let W=i.find(L=>L.kind==="tab"&&L.parent===$.unit&&L.key===$.key);W&&c.unshift({tab:d.get(W.id)})}let Z=$?.unit===null||$?.unit===void 0?null:i[$.unit];if(Z?.tag==="details"&&$.kind==="details"){let W=Z.node.childNodes.find(L=>L.tagName==="summary");W&&c.push({details:Le(W)})}}let p=c.find(N=>N.tab)?.tab,b=c.find(N=>N.details)?.details,I=[p,O.h2,O.h3,O.h4,b].filter(Boolean);return h.tag==="h2"?Object.assign(O,{h2:d.get(h.id),h3:null,h4:null}):h.tag==="h3"?Object.assign(O,{h3:d.get(h.id),h4:null}):h.tag==="h4"&&(O.h4=d.get(h.id)),{id:h.blockId,text:d.get(h.id),parent:h.parent===null?null:k.get(h.parent)??null,where:I,heading:/^h[2-4]$/.test(h.tag)}})}function We({reportsDirectory:l,read:i,write:w=In,dropped:u=()=>{},now:k=Date.now}){let d=new Map,O=new Map,h=new Map,c=(s,g)=>{let r=h.get(s);if(r?.text===g)return r.units;let a=_n(g);return h.set(s,{text:g,units:a}),a},p=s=>Je.join(Ue(s,l),Tn),b=s=>typeof s=="string"&&Fn.test(s);async function I(s){let g=await zt.readFile(p(s),"utf8").catch(()=>null);return{text:g,items:g===null?[]:Rn(g)}}async function N(s,g,r){let a=En(g);return a===r||(a===null?await zt.rm(p(s),{force:!0}):await w(p(s),a)),$(a)}let $=s=>s===null?"":_(s),Z=s=>{let g=d.get(s)??new Map;for(let[r,a]of g)k()-a>Pn&&g.delete(r);return[...g.keys()]},W=(s,g)=>g.forEach(r=>d.get(s)?.delete(r)),L=s=>{let g=O.get(s)??O.set(s,new Map).get(s);for(let[r,a]of g)k()-a>Jn&&g.delete(r);return g};async function H(s,{keep:g=null,items:r=null,before:a=void 0}={}){let S=r?{items:r,text:a}:await I(s),v=await i(s).catch(()=>null);if(!v)return{items:S.items,units:[],places:new Map,version:$(S.text),missing:!0};let D=c(s,v.text),T=L(s),x=An(S.items,D,{keep:new Set([...T.keys(),g])});for(let M of T.keys())x.waiting.has(M)||T.delete(M);if(x.dropped.length>0){let M=d.get(s)??d.set(s,new Map).get(s);for(let ot of x.dropped)M.set(ot.id,k())}let A=x.changed||r?await N(s,x.items,S.text):$(S.text);return x.dropped.length>0&&u(s,x.dropped),{items:x.items,units:D,places:x.places,version:A,missing:!1}}let F=(s,{items:g,version:r})=>({ok:!0,version:r,items:g,dropped:Z(s)});async function J(s){if(!b(s))return[400,{ok:!1,reason:"body"}];let g=await H(s);return g.missing?[404,{ok:!1,reason:"missing"}]:[200,F(s,g)]}async function Q(s){if(!b(s))return[400,{ok:!1,reason:"body"}];let g=await H(s);if(g.missing)return[404,{ok:!1,reason:"missing"}];let r=null,a=Dn(Ue(s,l));try{r=JSON.parse(await zt.readFile(a.json,"utf8"))}catch{}let S=await i(s).catch(()=>null),v=/<h1\b[^>]*>([\s\S]*?)<\/h1>/i.exec(S?.text??"")?.[1]?.replace(/<[^>]*>/g,"").trim(),D=typeof r?.title=="string"&&r.title.trim()?r.title.trim():v||s,T=g.units.some(A=>A.heading),x=g.items.map(A=>{let M=g.units[g.places.get(A.id)?.at],ot=M?.where?.length?M.where:M?.heading?[M.text]:[];return{where:ot,top:T&&ot.length===0,blocks:A.anchor.blocks.filter(B=>g.units.some(nt=>nt.id===B)),whole:A.anchor.kind==="blocks",quote:A.anchor.quote,text:A.text}});return[200,{ok:!0,title:D,path:Je.resolve(a.html),items:x}]}async function st(s){let{slug:g}=s??{};if(!b(g))return[400,{ok:!1,reason:"body"}];if(!await i(g).catch(()=>null))return[404,{ok:!1,reason:"missing"}];let r=await I(g);if(s.anchors&&typeof s.anchors=="object"&&!Array.isArray(s.anchors)){let T=r.items.map(A=>{let M=Object.hasOwn(s.anchors,A.id)?Nn(s.anchors[A.id]):null;return M&&M.kind===A.anchor.kind?{...A,anchor:M}:A}),x=await N(g,T,r.text);return[200,F(g,{items:T,version:x})]}let a=r.items,S=null,v=null;if(s.put!==void 0){let T=a.find(A=>A.id===s.put?.id),x=_e({...s.put,created:T?.created??s.put?.created});if(!x)return[400,{ok:!1,reason:"item"}];a=T?a.map(A=>A.id===x.id?x:A):[...a,x],S=x.id,T||L(g).set(x.id,k()),W(g,[x.id])}else if(typeof s.remove=="string")a=a.filter(T=>T.id!==s.remove);else if(s.clear===!0)v=a,a=[];else if(Array.isArray(s.restore)){let T=new Map(a.map(M=>[M.id,M])),x=s.restore.map(M=>_e(M,M?.updated)).filter(M=>M&&!(T.get(M.id)?.updated>M.updated)),A=new Set(x.map(M=>M.id));for(let M of A)T.has(M)||L(g).set(M,k());a=[...a.filter(M=>!A.has(M.id)),...x],W(g,[...A])}else return[400,{ok:!1,reason:"body"}];let D=await H(g,{keep:S,items:a,before:r.text});return[200,{...F(g,D),...v?{removed:v}:{}}]}async function q(s){if(!b(s))return;let{text:g}=await I(s);g!==null&&await H(s)}return{list:J,copy:Q,change:st,afterWrite:q}}import wt from"node:fs/promises";import ht from"node:path";import{writeAtomic as Be}from"../browser/shared/files.mjs";import{slugPattern as Gt}from"../browser/shared/reports.mjs";var It=1,Ot={seen:"seen.html",base:"base.html",state:"state.json"},Ln=4,Un=1800*1e3;function Ye({stateDirectory:l=null,shown:i,folderOf:w,isPage:u=()=>!1,log:k=null,now:d=Date.now,quiet:O=Un}){let h=new Map,c=r=>ht.join(l,"changes",r),p=Promise.resolve(),b=r=>{let a=p.then(r);return p=a.catch(S=>k?.(`changes: ${S.message}`)),a};async function I(r){if(!l)return h.get(r)?.state??null;try{let a=JSON.parse(await wt.readFile(ht.join(c(r),Ot.state),"utf8"));return a?.v===It&&typeof a.seen=="string"?a:null}catch{return null}}async function N(r,a){return l?wt.readFile(ht.join(c(r),Ot[a]),"utf8").catch(()=>null):h.get(r)?.[a]??null}async function $(r,a,S={}){if(!l){let v=h.get(r)??{};h.set(r,{...v,...S,state:a});return}await wt.mkdir(c(r),{recursive:!0});for(let[v,D]of Object.entries(S))D===null?await wt.rm(ht.join(c(r),Ot[v]),{force:!0}):await Be(ht.join(c(r),Ot[v]),D);await Be(ht.join(c(r),Ot.state),`${JSON.stringify(a)}
7
+ `)}async function Z(r){h.delete(r),l&&await wt.rm(c(r),{recursive:!0,force:!0,maxRetries:3})}let W=async r=>Math.round((await wt.stat(w(r)).catch(()=>null))?.birthtimeMs??0),L=r=>r?.base?`${r.since}|${r.writes}`:null,H=r=>Number.isFinite(r?.draft)&&d()-r.draft<O?r.draft:null,F=(r,a,S,v=H(r))=>[{v:It,born:r?.born??0,seen:a,...v===null?{}:{draft:v}},{seen:S,base:null}];async function J(r){let a=await I(r);if(!a)return null;let S=await W(r);return a.born&&S&&a.born!==S?(await Z(r),null):a}async function Q(r,a){if(typeof a!="string"||!Gt.test(r)||u(r))return!1;let S=_(a),v=await J(r);if(!v)return await $(r,{v:It,born:await W(r),seen:S},{seen:a}),!1;if(v.seen===S)return!1;let D=await N(r,"seen"),T=new Date(d()).toISOString();if(D===null)return await $(r,...F(v,S,a)),!1;let x=i(D),A=i(a);if(!v.base){if(!pt(x,A))return await $(r,...F(v,S,a)),!1;if(H(v)!==null||Ae(x))return await $(r,...F(v,S,a,d())),!1;let{draft:B,...nt}=v;return await $(r,{...nt,seen:S,base:_(x),since:T,at:T,writes:1},{seen:a,base:x}),!0}let M=await N(r,"base");if(M===null||!pt(M,A))return await $(r,...F(v,S,a)),!0;let ot=pt(x,A)!==null;return await $(r,{...v,seen:S,...ot?{at:T,writes:v.writes+1}:{}},{seen:a}),ot}async function st(r,a,S,v){if(!Gt.test(r)||u(r))return!1;let D=await J(r),T=_(a);if(!D?.base)return await $(r,...F(D??{born:await W(r)},T,a,v?null:H(D))),!1;let x=await N(r,"base");if(x!==null&&S)try{x=S(x)}catch(A){k?.(`changes: ${r}: the baseline did not take the edit (${A.message})`)}return x===null||!pt(x,i(a))?(await $(r,...F(D,T,a)),!0):(await $(r,{...D,seen:T,base:_(x)},{seen:a,base:x}),!1)}async function q(r,a){if(!Gt.test(r)||u(r))return{ended:!1,moved:!1};let S=typeof a=="string"?await Q(r,a):!1,v=await J(r);if(v?.draft===void 0)return{ended:!1,moved:S};let{draft:D,...T}=v;return await $(r,T),{ended:H(v)!==null,moved:S}}let s=new Map;async function g(r,a){await Q(r,a);let S=i(a),v=_(S),D=await J(r);if(!D?.base)return{pending:!1,version:v};let T=`${r} ${D.base} ${v}`,x=s.get(T);if(x===void 0){let A=await N(r,"base");for(x=A===null?null:pt(A,S),s.set(T,x);s.size>Ln;)s.delete(s.keys().next().value)}return x?{pending:!0,version:v,stamp:L(D),since:D.since,writes:D.writes,...x}:{pending:!1,version:v}}return{look:(r,a)=>b(()=>Q(r,a)),wrote:(r,a,S=null,{reader:v=!1}={})=>b(()=>st(r,a,S,v)),endDraft:(r,a=null)=>b(()=>q(r,a)),read:(r,a)=>b(()=>g(r,a)),stamp:r=>b(async()=>L(await J(r))),snapshot:r=>b(async()=>{let a=await J(r);return a?{state:a,seen:await N(r,"seen"),base:await N(r,"base")}:null}),clear:r=>b(async()=>{let a=await J(r);a?.base&&await $(r,{v:It,born:a.born,seen:a.seen},{base:null})}),restore:(r,a)=>b(async()=>{a?.state&&await $(r,a.state,{seen:a.seen,base:a.base})}),forget:r=>b(()=>Z(r)),idle:()=>b(async()=>{})}}import{randomBytes as Wn}from"node:crypto";import ct from"node:fs/promises";import yt from"node:path";import{FILE as Bn,readItems as Yn}from"../browser/shared/annotations.mjs";import{writeAtomic as Zn}from"../browser/shared/files.mjs";import{documentDirectory as Cn}from"../browser/shared/workspace.mjs";var Hn=20,He=/^\d{8}T\d{6}Z-[a-f0-9]{8}\.json$/,Ze=80,ze=({stateDirectory:l,slug:i})=>yt.join(l,"dropped-annotations",i),Ge=l=>({id:l.id,text:l.text,quote:l.anchor?.quote??"",kind:l.anchor?.kind??"text"});async function Ke({stateDirectory:l,reportsDirectory:i,slug:w,time:u,items:k}){let d=ze({stateDirectory:l,reportsDirectory:i,slug:w});await ct.mkdir(d,{recursive:!0});let O=u.replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z");await Zn(yt.join(d,`${O}-${Wn(4).toString("hex")}.json`),JSON.stringify({time:u,items:k}));let h=(await ct.readdir(d)).filter(c=>He.test(c)).sort();await Promise.all(h.slice(0,Math.max(0,h.length-Hn)).map(c=>ct.rm(yt.join(d,c),{force:!0})))}async function qr({stateDirectory:l,reportsDirectory:i,slug:w}){let u=ze({stateDirectory:l,reportsDirectory:i,slug:w}),k=(await ct.readdir(u).catch(()=>[])).filter(h=>He.test(h)).sort();if(k.length===0)return[];let d=new Set(Yn(await ct.readFile(yt.join(Cn(w,i),Bn),"utf8").catch(()=>"")).map(h=>h.id)),O=[];for(let h of k){let c=yt.join(u,h);try{let p=JSON.parse(await ct.readFile(c,"utf8")),b=Array.isArray(p?.items)?p.items.filter(I=>typeof I?.id=="string"&&!d.has(I.id)):[];typeof p?.time=="string"&&b.length&&O.push({time:p.time,items:b})}catch{}await ct.rm(c,{force:!0}).catch(()=>{})}return O}var zn=(l,i=new Date)=>{let w=new Date(l),u=d=>String(d).padStart(2,"0"),k=`${u(w.getHours())}:${u(w.getMinutes())}`;return w.toDateString()===i.toDateString()?k:`${w.getFullYear()}-${u(w.getMonth()+1)}-${u(w.getDate())} ${k}`},Ce=l=>{let i=String(l??"").replace(/\s+/g," ").trim();return JSON.stringify(i.length>Ze?`${i.slice(0,Ze-1)}\u2026`:i)};function Kt(l,{time:i=null,items:w},{today:u=new Date}={}){let k=yt.resolve(l),d=`${w.length} \u6279\u6CE8 (annotation${w.length===1?"":"s"})`;return[`annotations ${k}: ${i?`at ${zn(i,u)}, `:""}Gallery deleted ${d} whose words are gone from the document (rewritten or deleted):`,...w.map(({id:O,text:h,quote:c,kind:p})=>` ${O} ${Ce(h)} on ${p==="blocks"?"the blocks ":""}${Ce(c)}`)]}function Xr(l,i,{today:w=new Date}={}){return i.length?[...i.flatMap(u=>Kt(l,u,{today:w}))," they were the reader's: say in your hand-off which your edit carried out and which you left, and never write them back"]:[]}import{randomBytes as Gn}from"node:crypto";import gt from"node:fs/promises";import jt from"node:path";import{writeAtomic as Kn}from"../browser/shared/files.mjs";var Qn=20,Qe=/^\d{8}T\d{6}Z-[a-f0-9]{8}\.json$/,Ve=({stateDirectory:l,slug:i})=>jt.join(l,"rewrites",i);async function qe({stateDirectory:l,reportsDirectory:i,slug:w,time:u,changes:k}){let d=Ve({stateDirectory:l,reportsDirectory:i,slug:w});await gt.mkdir(d,{recursive:!0});let O=u.replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z");await Kn(jt.join(d,`${O}-${Gn(4).toString("hex")}.json`),JSON.stringify({time:u,changes:k}));let h=(await gt.readdir(d)).filter(c=>Qe.test(c)).sort();await Promise.all(h.slice(0,Math.max(0,h.length-Qn)).map(c=>gt.rm(jt.join(d,c),{force:!0})))}async function Xe({stateDirectory:l,reportsDirectory:i,slug:w}){let u=Ve({stateDirectory:l,reportsDirectory:i,slug:w}),k=(await gt.readdir(u).catch(()=>[])).filter(O=>Qe.test(O)).sort(),d=[];for(let O of k){let h=jt.join(u,O);try{let c=JSON.parse(await gt.readFile(h,"utf8"));typeof c?.time=="string"&&Array.isArray(c.changes)&&d.push(c)}catch{}await gt.rm(h,{force:!0}).catch(()=>{})}return d}var Vn=(l,i=new Date)=>{let w=new Date(l),u=d=>String(d).padStart(2,"0"),k=`${u(w.getHours())}:${u(w.getMinutes())}`;return w.toDateString()===i.toDateString()?k:`${w.getFullYear()}-${u(w.getMonth()+1)}-${u(w.getDate())} ${k}`};function ao(l,i,{today:w=new Date}={}){if(!i.length)return[];let u=jt.resolve(l),k=[];for(let{time:d,changes:O}of i){let h=[];for(let{line:c,rule:p,key:b}of[...O].sort((I,N)=>I.line-N.line)){let I=`line ${c} ${p}${b?` ${b}`:""}`;h.includes(I)||h.push(I)}k.push(`preview ${u}: at ${Vn(d,w)}, when the reader edited the page, the preview wrote your natural HTML as the kit's markup: ${h.join(", ")}`),k.push(...O.filter(c=>c.note).map(({line:c,rule:p,note:b})=>` line ${c}, ${p}: ${b}`))}return k.push(" re-read the file before editing it (those lines are the file's as you had left it)"),k}import{todoRef as qn}from"../browser/shared/workspace-query.mjs";var Xn=(l,i)=>l.length===i.length&&l.every((w,u)=>w===i[u]);function tn(l,i,w,u){let k=Ie(i),d=Re(w,{at:!0}),O=null,h=c=>(O??=we(w).units).find(p=>p.elStart===c)??null;return u.map(c=>{let p=qn(c?.ref);if(!p||p.slug!==l||typeof c.done!="boolean")return{reason:"ref"};let b=p.block?d.find(N=>N.block===p.block)??null:null;if(b&&b.text!==p.text)return{reason:"changed"};if(!b){let N=d.filter($=>$.text===p.text&&Xn($.path,p.path));if(p.version===k)b=N.find($=>$.nth===p.nth)??null;else{if(N.length>1)return{reason:"ambiguous"};b=N[0]??null}}if(!b)return{reason:"changed"};let I=h(b.at);return I?{unit:I,done:b.done,want:c.done}:{reason:"locked"}})}function en(l,i){let w=new Map,u=i.map(c=>{if(!c.unit)return!1;let p=w.has(c.unit.id)?w.get(c.unit.id):c.done;return w.set(c.unit.id,c.want),p!==c.want}),k=new Map;for(let c of i)c.unit&&w.get(c.unit.id)!==c.done&&k.set(c.unit.id,c);if(k.size===0)return{commit:null,changed:u};let d=[],O=[],h=new Map;for(let[c,p]of k){let b=`todo${d.length}`,I=p.unit.blockId?{key:b,id:p.unit.blockId}:{key:b,open:c,hash:me(l,p.unit)};d.push({key:b,unit:I,attribute:"data-checked",value:w.get(c)?"":null}),O.push(I),h.set(c,b)}return{commit:{units:d,touch:O,keys:h},changed:u}}import{EMPTY_STYLE as mr,emptyWordsScript as pr,showEmpty as wr}from"../browser/editor/components/placeholder.mjs";import{TOKENS as hr}from"../browser/editor/page/look.mjs";import{MARGIN_STYLE as yr,earlyMarginScript as gr}from"../browser/editor/page/margin.mjs";var Vt=/^[a-f0-9]{16}$/,Xt=2*1024*1024,kr=ir,nn=50,rn=/^\d{8}T\d{6}Z-[a-f0-9]{16}\.html$/,br=30,on=3,an=200,ft="\u6587\u4EF6\u4E00\u518D\u88AB\u4FEE\u6539\uFF08\u4F8B\u5982 AI \u6B63\u5728\u5199\u5165\uFF09\uFF0C\u7A0D\u540E\u518D\u540C\u6B65",$r="\u8FD9\u6B21\u7684\u4FEE\u6539\u592A\u5927\uFF0C\u4E00\u6B21\u5B58\u4E0D\u4E0B",xr=250,lt=Symbol("again"),Sr="/__gallery/edit/src/editor/page/editor.mjs",vr=l=>new Promise(i=>setTimeout(i,l));function Or(l,i=Xt){return new Promise((w,u)=>{let k=[],d=0;l.on("data",O=>{d+=O.length,d>i?k.length=0:k.push(O)}),l.on("end",()=>d>i?u(new Error("too-large")):w(Buffer.concat(k).toString("utf8"))),l.on("error",u)})}function jr(l){if(!l)return qt(16).toString("hex");let i=P.join(l,"token");try{let u=rr(i,"utf8").trim();if(/^[a-f0-9]{32}$/.test(u))return u}catch{}let w=qt(16).toString("hex");try{nr(l,{recursive:!0,mode:448}),or(i,w,{mode:384})}catch{}return w}function Wo({reportsDirectory:l=cr,stateDirectory:i=null,write:w=Ft,ids:u=!0,finish:k=p=>p,log:d=null,settling:O={},reviewing:h={},onChanges:c=()=>{}}={}){let p=jr(i),b=Pe(O),I=O.wait??De,N=new Map,$=async(t,n,e,o="reader")=>{let f=await w(t,n,e);if(f!==!1&&dr(P.basename(t))){let y=P.basename(P.dirname(t));b.wrote(y,n),N.set(y,{hash:_(n),by:o})}return f},Z=t=>ur(t,l),W=t=>Mt(Z(t)).html,L=new Map,H=i&&P.join(i,"snapshots"),F=Promise.resolve(),J=Promise.resolve(),Q=async(t,n,e,{by:o="time"}={})=>{let f=(await z.readdir(t)).filter(m=>n.test(m));if(f.length<=e)return;let y=o==="name"?f.sort():(await Promise.all(f.map(async m=>({name:m,time:(await z.stat(P.join(t,m))).mtimeMs})))).sort((m,j)=>m.time-j.time).map(({name:m})=>m);await Promise.all(y.slice(0,y.length-e).map(m=>z.rm(P.join(t,m),{force:!0})))},st=(t,n)=>{H&&(F=F.then(async()=>{let e=P.join(H,`${t}.html`),o=new Date;try{await z.utimes(e,o,o);return}catch{}await z.mkdir(H,{recursive:!0}),await Ft(e,n),await Q(H,/^[a-f0-9]{16}\.html$/,nn)}).catch(()=>{}))},q=(t,n)=>{i&&(F=F.then(async()=>{let e=P.join(i,"history",t),o=_(n);if(await z.mkdir(e,{recursive:!0}),(await z.readdir(e)).filter(m=>rn.test(m)).sort().at(-1)?.endsWith(`-${o}.html`))return;let y=new Date().toISOString().replace(/[-:]/g,"").replace(/\.\d+Z$/,"Z");await Ft(P.join(e,`${y}-${o}.html`),n),await Q(e,rn,br,{by:"name"})}).catch(()=>{}))},s=new Map,g=t=>i&&P.join(i,"receipts",t),r=(t,n,e,o)=>{for(s.set(`${t} ${n}`,{digest:e,answer:o});s.size>an*4;)s.delete(s.keys().next().value);let f=g(t);f&&(F=F.then(async()=>{await z.mkdir(f,{recursive:!0}),await Ft(P.join(f,`${n}.json`),JSON.stringify({digest:e,answer:o})),await Q(f,{test:y=>y.endsWith(".json")&&Qt.test(y.slice(0,-5))},an)}).catch(()=>{}))},a=async(t,n)=>{let e=s.get(`${t} ${n}`);if(e)return e;let o=g(t);if(!o)return null;await F;try{let f=JSON.parse(await z.readFile(P.join(o,`${n}.json`),"utf8"));return typeof f?.digest=="string"&&f.answer?.ok?f:null}catch{return null}},S=new Map,v=(t,n)=>{let e=new Date().toISOString();if(!i)return void S.set(t,[...S.get(t)??[],{time:e,changes:n}].slice(-20));F=F.then(()=>qe({stateDirectory:i,reportsDirectory:l,slug:t,time:e,changes:n})).catch(()=>{})},D=async t=>{if(!i){let n=S.get(t)??[];return S.delete(t),n}return await F,Xe({stateDirectory:i,reportsDirectory:l,slug:t})},T=(t,n)=>{for(L.delete(t),L.set(t,n);L.size>nn;)L.delete(L.keys().next().value);st(t,n)},x=async t=>{if(L.has(t))return L.get(t);if(!H||!Vt.test(t))return null;await F;let n=await z.readFile(P.join(H,`${t}.html`),"utf8").catch(()=>null);return n===null||_(n)!==t?null:(T(t,n),n)},A=new Map,M=t=>{let n=A.get(t);if(n)return n;let e=ve(t,{finish:k});for(A.set(t,e);A.size>8;)A.delete(A.keys().next().value);return e},ot=P.join(P.resolve(l),".gallery","pages"),B=Ye({...h,stateDirectory:i,shown:t=>M(t).text,folderOf:Z,log:d,isPage:t=>P.resolve(Z(t)).startsWith(ot+P.sep)}),nt=(t,n)=>n.then(e=>{e&&c(t)},e=>d?.(`${t}: the Agent's changes not kept (${e.message})`));async function Dt(t,n=void 0){if(typeof t!="string"||!rt.test(t))return null;let e=W(t),o=n!==void 0?n:await z.readFile(e,"utf8").catch(()=>null);if(o===null)return null;let{text:f,changes:y}=M(o);return{file:e,source:o,text:f,version:_(f),changes:y}}async function it(t){if(typeof t!="string"||!rt.test(t))return{source:null,held:!1,signs:[],wait:0,own:!1};let n=W(t),e=await z.readFile(n,"utf8").catch(()=>null),o=(await z.stat(n).catch(()=>null))?.mtimeMs??0;return{source:e,...b.judge(t,{source:e,mtime:o})}}async function kt(t,n=Date.now()+I){for(;;){let e=await it(t);if(!e.held||Date.now()>=n)return e;await vr(Math.max(0,Math.min(xr,n-Date.now())))}}async function Pt(t,{wait:n=I}={}){let e=await kt(t,Date.now()+n),o=await Dt(t,e.held&&e.taken!==void 0?e.taken:e.source);return o&&{...o,held:e.held===!0}}function sn(t,n,{editor:e=Sr,kitTags:o=()=>[]}={}){let{html:f,map:y}=ge(n);T(y.version,n);let m=ue(l),j=de(m).map(({assets:Y,...X})=>({...X,kit:o(Y)})),E=`<script type="application/json" id="doc-edit-map" data-doc-dev>${JSON.stringify({slug:t,token:p,...y,components:j,hidden:m.settings.hidden}).replace(/</g,"\\u003c")}</script>
8
8
  <script data-doc-dev>document.currentScript.remove(); import(${JSON.stringify(e)});</script>`,U=`<style data-doc-dev>.doc-display { display: none; }</style>
9
- <style data-doc-dev data-ge-palette>${wr}</style>
10
- <style data-doc-dev>${dr}</style>
11
- <script data-doc-dev>${mr()}</script>
9
+ <style data-doc-dev data-ge-palette>${hr}</style>
10
+ <style data-doc-dev>${mr}</style>
11
+ <script data-doc-dev>${pr()}</script>
12
12
  <script data-doc-dev>document.currentScript.remove(); document.documentElement.setAttribute("data-ge-order", "file");</script>
13
- <style data-doc-dev data-ge-margin-style>${hr}</style>
14
- <script data-doc-dev>document.currentScript.remove(); ${yr(t,{notes:tr(P.join(Z(t),or))})}</script>`;return{html:pr(c),snippet:E,head:U}}let sn=t=>T(_(t),t);async function ut(t,n=Xt){if(t.method!=="POST")return{error:[405,{ok:!1,reason:"method"}]};let e=t.headers.host??"",o=t.socket.localPort;if(e!==`127.0.0.1:${o}`&&e!==`localhost:${o}`)return{error:[403,{ok:!1,reason:"host"}]};if(t.headers.origin!==`http://${e}`)return{error:[403,{ok:!1,reason:"origin"}]};if(t.headers["x-gallery-token"]!==p)return{error:[403,{ok:!1,reason:"token"}]};if(!/^application\/json\b/i.test(t.headers["content-type"]??""))return{error:[415,{ok:!1,reason:"type"}]};try{return{body:JSON.parse(await vr(t,n))}}catch(c){return{error:c.message==="too-large"?[413,{ok:!1,reason:"body",message:br}]:[400,{ok:!1,reason:"body"}]}}}async function Jt(t,n){let{slug:e,opening:o,known:c=null,texts:y=[],units:m=[],touch:j=[],pageIds:R=null,request:E=null,agent:U=!1}=t;if(typeof e!="string"||!rt.test(e)||![y,m,j].every(Array.isArray))return[400,{ok:!1,reason:"body"}];if(E!==null&&(typeof E!="string"||!Qt.test(E)))return[400,{ok:!1,reason:"body"}];let Y=E===null?null:_(JSON.stringify([o??null,y,m,j])),X=await te(t);if(X)return X;let G=et=>(E!==null&&r(e,E,Y,et),[200,et]),K=W(e),tt=typeof o=="string"&&Vt.test(o)?await x(o):null,V=et=>Xn("sha256",p).update(`${e}
15
- ${et}`).digest("hex").slice(0,32);for(let et=1;;et++){let{source:at,held:Tt}=await it(e);if(at===null)return[404,{ok:!1,reason:"missing"}];if(Tt)return Date.now()<n?lt:[409,{ok:!1,reason:"busy",message:ft}];nt(e,B.look(e,at));let{text:vt,changes:Zt}=M(at),ae=[],Et=ke({current:vt,opening:tt,texts:y,units:m,touch:j,ids:u?()=>{let Rt=typeof u=="function"?u():Ct();return ae.push(Rt),Rt}:!1,seal:V,pageIds:R}),{title:se,icon:ie,...ce}=Et,mt=Et.text===vt?vt:k(Et.text);mt!==Et.text&&(ce.version=_(mt));let fe={...ce,foreign:typeof c=="string"&&_(vt)!==c};if(mt===vt)return G({ok:!0,...fe,wrote:!1,notes:[]});if(q(e,at),!await $(K,mt,{expect:at},U===!0?"agent":"reader")){if(et===rn)return[409,{ok:!1,reason:"busy",message:ft}];continue}q(e,mt),nt(e,B.wrote(e,mt,Rt=>{let Sn=0;return Ae(Rt,{opening:tt,texts:y,units:m,touch:j,pageIds:R,seal:V,ids:u?()=>ae[Sn++]??(typeof u=="function"?u():Ct()):!1})},{reader:U!==!0})),Zt.length&&(d&&d(Ht(K,Zt).join(`
16
- `)),v(e,Zt));let xn=[...se?await At(P.dirname(K),se):[],...ie!==void 0?await _t(P.dirname(K),ie):[]];return G({ok:!0,...fe,wrote:!0,notes:xn})}}async function cn(t,n){return typeof t!="string"||!rt.test(t)?[404,{ok:!1,reason:"missing",message:"\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"}]:!Array.isArray(n)||n.length===0||n.length>fr?[400,{ok:!1,reason:"body"}]:Lt({slug:t},async(e,o)=>{let{source:c,held:y}=await it(t);if(c===null)return[404,{ok:!1,reason:"missing",message:"\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"}];if(y)return Date.now()<o?lt:[409,{ok:!1,reason:"busy",message:ft}];let{text:m}=M(c),j=Xe(t,c,m,n),{commit:R,changed:E}=tn(m,j),U=j.map((V,et)=>V.reason?{ok:!1,reason:V.reason}:{ok:!0,changed:E[et],block:V.unit.blockId??null});if(!R)return[200,{ok:!0,results:U,wrote:!1}];let Y=_(m);T(Y,m);let X=await Jt({slug:t,opening:Y,units:R.units,touch:R.touch},o);if(X===lt)return lt;let[G,K]=X;if(!K.ok)return[G,K];let tt=new Map((K.units??[]).map(V=>[V.key,V]));return[200,{ok:!0,wrote:K.wrote===!0,results:U.map((V,et)=>{if(!V.ok)return V;let at=R.keys.get(j[et].unit.id);if(at===void 0)return V;let Tt=tt.get(at);return Tt?.status!=="applied"?{ok:!1,reason:Tt?.reason==="ambiguous"?"ambiguous":"changed"}:{...V,block:K.ids?.[at]??V.block}})}]})}async function te({slug:t,opening:n,texts:e=[],units:o=[],touch:c=[],request:y=null}){if(typeof t!="string"||!rt.test(t)||typeof y!="string"||!Qt.test(y)||![e,o,c].every(Array.isArray))return null;let m=await a(t,y);return m?m.digest===_(JSON.stringify([n??null,e,o,c]))?[200,{...m.answer,again:!0}]:[409,{ok:!1,reason:"request",message:"\u540C\u4E00\u6B21\u4FDD\u5B58\u7684\u5185\u5BB9\u4E0D\u4E00\u81F4"}]:null}async function fn(t,n){let{slug:e,opening:o,texts:c=[],units:y=[],instances:m=[],pageIds:j=null}=t;if(typeof e!="string"||!rt.test(e)||!Array.isArray(c)||!Array.isArray(y)||!Array.isArray(m))return[400,{ok:!1,reason:"body"}];let{source:R,held:E}=await it(e);if(E)return Date.now()<n?lt:[409,{ok:!1,reason:"busy",message:ft}];let U=await Dt(e,R);if(U===null)return[404,{ok:!1,reason:"missing"}];let{text:Y,version:X}=U,G=typeof o=="string"&&Vt.test(o)?await x(o):null;return[200,{ok:!0,version:X,reverted:xe({current:Y,opening:G,texts:c,pageIds:j}),units:be({current:Y,units:y}),parts:$e({current:Y,instances:m,pageIds:j})}]}let ln=600*1e3,bt=new Map;async function ee(t,n){let e=Z(t),o=null;try{o=JSON.parse(await z.readFile(Mt(e).json,"utf8"))}catch{}let{title:c,icon:y}=Oe(n,o);c&&typeof o?.title=="string"&&o.title!==c.to&&await At(e,{from:o.title,to:c.to,synced:!0}),y&&!y.missing&&await _t(e,y.to)}async function un(t,n){let{slug:e,action:o,stamp:c=null,undo:y=null}=t;if(typeof e!="string"||!rt.test(e)||!["accept","revert","undo"].includes(o))return[400,{ok:!1,reason:"body"}];let m=W(e),{source:j,held:R}=await it(e);if(j===null)return[404,{ok:!1,reason:"missing"}];if(R)return Date.now()<n?lt:[409,{ok:!1,reason:"busy",message:ft}];if(o==="undo"){for(let[K,tt]of bt)Date.now()-tt.at>ln&&bt.delete(K);let G=typeof y=="string"?bt.get(y):null;return!G||G.slug!==e?[404,{ok:!1,reason:"gone",message:"\u64A4\u9500\u5DF2\u7ECF\u8FC7\u671F"}]:j!==G.after?[409,{ok:!1,reason:"moved-on",message:"\u64A4\u56DE\u4E4B\u540E\u6587\u6863\u53C8\u6539\u8FC7\u4E86\uFF0C\u6CA1\u6CD5\u64A4\u9500"}]:(q(e,j),await $(m,G.before,{expect:j})?(q(e,G.before),bt.delete(y),await ee(e,G.before),await B.restore(e,G.saved),await B.wrote(e,G.before),f(e),[200,{ok:!0,version:_(M(G.before).text)}]):[409,{ok:!1,reason:"busy",message:ft}])}await B.look(e,j);let E=await B.snapshot(e),U=E?.state?.base?`${E.state.since}|${E.state.writes}`:null;if(U===null)return[200,{ok:!0,none:!0}];if(U!==c)return[409,{ok:!1,reason:"changed",message:"Agent \u521A\u521A\u53C8\u6539\u4E86\u6587\u6863\uFF0C\u518D\u770B\u4E00\u773C"}];if(o==="accept")return await B.clear(e),f(e),[200,{ok:!0}];let Y=E.base;if(q(e,j),!await $(m,Y,{expect:j}))return[409,{ok:!1,reason:"busy",message:ft}];q(e,Y),await ee(e,Y);let X=qt(8).toString("hex");return bt.set(X,{slug:e,before:j,after:Y,saved:E,at:Date.now()}),await B.clear(e),await B.wrote(e,Y),f(e),[200,{ok:!0,version:_(M(Y).text),undo:X}]}async function dn(t,n){let e=await ut(t);if(e.error)return C(n,...e.error);let o=e.body??{};try{if(o.action!=="read")return C(n,...await Lt(o,un));if(typeof o.slug!="string"||!rt.test(o.slug))return C(n,400,{ok:!1,reason:"body"});let c=await Pt(o.slug,{wait:0});return c===null?C(n,404,{ok:!1,reason:"missing"}):C(n,200,{ok:!0,...await B.read(o.slug,c.source)})}catch(c){return C(n,500,{ok:!1,reason:"write",message:c.message})}}async function At(t,{from:n,to:e,synced:o}){let c=["\u6807\u9898\u5DF2\u66F4\u65B0",...o?[]:["\u5355\u72EC\u6253\u5F00\u6216\u5BFC\u51FA\u65F6\u7684\u9875\u9762\u540D\u79F0\u539F\u672C\u5C31\u548C\u6807\u9898\u4E0D\u540C\uFF0C\u6CA1\u6709\u8DDF\u7740\u6539"]],y=Mt(t).json,m=await z.readFile(y,"utf8").catch(()=>""),j=null;try{j=JSON.parse(m)}catch{}if(j?.title!==n)return[...c,"\u641C\u7D22\u548C\u4FA7\u680F\u91CC\uFF08\u6CA1\u6253\u5F00\u8FD9\u4EFD\u6587\u6863\u65F6\uFF09\u7684\u6587\u6863\u540D\u539F\u672C\u5C31\u548C\u6807\u9898\u4E0D\u540C\uFF0C\u6CA1\u6709\u8DDF\u7740\u6539"];let R=new RegExp(`("title"\\s*:\\s*)${JSON.stringify(n).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`),E=R.test(m)?m.replace(R,(U,Y)=>Y+JSON.stringify(e)):`${JSON.stringify({...j,title:e},null,2)}
17
- `;try{await $(y,E)}catch(U){return d?.(`${P.basename(y)}'s title was not written (${U.code??U.message}): ${y}`),[...c,"\u641C\u7D22\u548C\u4FA7\u680F\u91CC\uFF08\u6CA1\u6253\u5F00\u8FD9\u4EFD\u6587\u6863\u65F6\uFF09\u7684\u6587\u6863\u540D\u6CA1\u80FD\u8DDF\u7740\u6539"]}return c}async function _t(t,n){let e=Mt(t).json,o=null;try{o=JSON.parse(await z.readFile(e,"utf8"))}catch{}if(!o||typeof o!="object")return d?.(`${P.basename(e)} could not be read, so its icon was not written: ${e}`),["\u9875\u9762\u56FE\u6807\u5DF2\u66F4\u6362\uFF0C\u4F46\u641C\u7D22\u548C\u4FA7\u680F\u91CC\uFF08\u6CA1\u6253\u5F00\u8FD9\u4EFD\u6587\u6863\u65F6\uFF09\u7684\u56FE\u6807\u6CA1\u80FD\u8DDF\u7740\u6362"];if((o.icon??null)===n)return[];let{icon:c,...y}=o,m=n===null?y:{...y,icon:n};try{await $(e,`${JSON.stringify(m,null,2)}
18
- `)}catch(j){return d?.(`${P.basename(e)}'s icon was not written (${j.code??j.message}): ${e}`),["\u9875\u9762\u56FE\u6807\u5DF2\u66F4\u6362\uFF0C\u4F46\u641C\u7D22\u548C\u4FA7\u680F\u91CC\uFF08\u6CA1\u6253\u5F00\u8FD9\u4EFD\u6587\u6863\u65F6\uFF09\u7684\u56FE\u6807\u6CA1\u80FD\u8DDF\u7740\u6362"]}return[]}async function mn(t,n){let e=typeof n=="string"?n.replace(/\s+/g," ").trim():"";if(!e)return{ok:!1,reason:"title",message:"\u6807\u9898\u4E0D\u80FD\u4E3A\u7A7A"};let o=W(t),c=await z.readFile(o,"utf8").catch(()=>null);if(c===null)return{ok:!1,reason:"missing"};nt(t,B.look(t,c));let y=me(c),m=we(y).find(E=>E.kind==="title");if(!m)return{ok:!1,reason:"no-title",message:"\u8FD9\u4EFD\u6587\u6863\u6CA1\u6709\u6807\u9898"};let j=ar(e),R=ge({current:y,edits:[{id:m.id,parts:[{keep:!0,html:j}]}],ids:u});return R.ok?R.text!==c&&!await $(o,R.text,{expect:c})?{ok:!1,reason:"changed-again"}:(R.text!==c&&nt(t,B.wrote(t,R.text,E=>Ne(E,j))),{ok:!0,title:e,notes:R.title?await At(P.dirname(o),R.title):[]}):{ok:!1,reason:"conflict"}}let $t=t=>(n,e)=>{let o=J.then(()=>t(n));return J=o.catch(()=>{}),o.then(([c,y])=>C(e,c,y),c=>C(e,500,{ok:!1,reason:"write",message:c.message}))},ne=(t,{early:n=null}={})=>async(e,o)=>{let c=await ut(e);if(c.error)return C(o,...c.error);let y=c.body??{};try{let m=n&&await n(y);return m?C(o,...m):C(o,...await Lt(y,t))}catch(m){return C(o,500,{ok:!1,reason:"write",message:m.message})}};async function Lt(t,n){let e=Date.now()+I;for(;;){await kt(t.slug,e);let o=J.then(()=>n(t,e));J=o.catch(()=>{});let c=await o;if(c!==lt)return c}}async function Ut(t,{reader:n=!1}={}){if(typeof t!="string"||!rt.test(t))return{ok:!1,reason:"missing",message:"\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"};let e=Z(t),{html:o,json:c}=Mt(e);for(let y=1;;y++){let{source:m,held:j}=n?await it(t):{source:await z.readFile(o,"utf8").catch(()=>null),held:!1};if(m===null)return{ok:!1,reason:"missing",message:"\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"};if(j)return{ok:!1,reason:"busy",message:"\u6587\u4EF6\u4E00\u518D\u88AB\u4FEE\u6539\uFF08\u4F8B\u5982 AI \u6B63\u5728\u5199\u5165\uFF09\uFF0C\u6CA1\u6709\u5199\u5165"};nt(t,B.look(t,m));let R=null;try{R=JSON.parse(await z.readFile(c,"utf8"))}catch{}let{text:E,changes:U,added:Y,given:X,repeated:G,title:K,icon:tt}=ve(m,{finish:k,next:typeof u=="function"?u:void 0,metadata:R});if(E!==m){if(q(t,m),!await $(o,E,{expect:m},n?"reader":"agent")){if(y===rn)return{ok:!1,reason:"busy",message:"\u6587\u4EF6\u4E00\u518D\u88AB\u4FEE\u6539\uFF08\u4F8B\u5982 AI \u6B63\u5728\u5199\u5165\uFF09\uFF0C\u6CA1\u6709\u5199\u5165"};continue}q(t,E),nt(t,B.wrote(t,E)),n&&U.length&&(d&&d(Ht(o,U).join(`
19
- `)),v(t,U))}return K&&typeof R?.title=="string"&&R.title!==K.to&&await At(e,{from:R.title,to:K.to,synced:K.page}),tt&&!tt.missing&&await _t(e,tt.to),{ok:!0,changes:E===m?[]:U,added:E===m?0:Y,given:E===m?[]:X,repeated:G,written:E!==m,title:K,icon:tt}}}let pn=async(t,{reader:n=!1}={})=>{n&&await kt(t);let e=J.then(()=>Ut(t,{reader:n}));return J=e.catch(()=>{}),e};async function Wt(t){let n=await ut(t);if(n.error)return{refused:n.error};let{slug:e,workspace:o}=n.body??{};return typeof e!="string"||!rt.test(e)||typeof o!="string"?{refused:[400,{ok:!1,reason:"body"}]}:cr(o,l)?{slug:e}:{refused:[409,{ok:!1,reason:"elsewhere",message:"\u8FD9\u4E2A\u9884\u89C8\u670D\u52A1\u5668\u7BA1\u7684\u662F\u53E6\u4E00\u4E2A\u76EE\u5F55\u7684\u6587\u6863"}]}}async function wn(t,n){try{let e=J.then(async()=>{let{slug:y,refused:m}=await Wt(t);if(m)return{answer:m};let j=await Ut(y);return{slug:j.ok?y:null,answer:[j.ok?200:j.reason==="missing"?404:409,j]}});J=e.catch(()=>{});let{slug:o,answer:c}=await e;return o&&await Yt(o),C(n,...c)}catch(e){return C(n,500,{ok:!1,reason:"write",message:e.message})}}async function hn(t){let{slug:n,refused:e}=await Wt(t);return e||(await Yt(n),[200,{ok:!0}])}async function re(t){let{source:n}=await kt(t),{ended:e,moved:o}=await B.endDraft(t,n);return o&&f(t),e}async function yn(t){let{slug:n,refused:e}=await Wt(t);return e||[200,{ok:!0,ended:await re(n)}]}let dt=Te({reportsDirectory:l}),xt=Ue({reportsDirectory:l,read:t=>Pt(t,{wait:0}),write:$,dropped:(t,n)=>{let e=n.map(ze);d&&d(Kt(P.join(Z(t),"annotations.json"),{items:e}).join(`
20
- `)),i&&(F=F.then(()=>Ge({stateDirectory:i,reportsDirectory:l,slug:t,time:new Date().toISOString(),items:e})).catch(()=>{}))}}),oe=Promise.resolve(),Bt=t=>{let n=oe.then(t);return oe=n.catch(()=>{}),n},gn=t=>(n,e)=>Bt(()=>t(n)).then(([o,c])=>C(e,o,c),o=>C(e,500,{ok:!1,reason:"write",message:o.message})),kn=300,St=new Map;async function Yt(t){let n=St.get(t);n&&(clearTimeout(n.timer),St.delete(t));let e=Bt(()=>xt.afterWrite(t));n&&e.then(n.resolve,n.reject),await e.catch(o=>d?.(`${t}: annotations not checked: ${o.message}`)),await F}let bn=t=>{let n=t.headers.host??"",e=t.socket.localPort;return n!==`127.0.0.1:${e}`&&n!==`localhost:${e}`?[403,{ok:!1,reason:"host"}]:t.headers["x-gallery-token"]!==p?[403,{ok:!1,reason:"token"}]:null};async function $n(t){if(t.method==="GET"){let e=bn(t);if(e)return e;let o=new URL(t.url??"/","http://localhost").searchParams;return o.get("as")==="copy"?xt.copy(o.get("slug")):xt.list(o.get("slug"))}let n=await ut(t);return n.error??xt.change(n.body)}let Nt=(t,n=Xt)=>async e=>{let o=await ut(e,n);return o.error??t(o.body)};return{token:p,preview:an,opened:sn,check:ut,upload:$t(Nt(dt.upload,gr)),addEmoji:$t(Nt(dt.addEmoji)),unfurl:$t(Nt(dt.unfurl)),annotations:gn($n),checkAnnotations(t){let n=St.get(t);return n||(n={timer:0},n.done=new Promise((e,o)=>Object.assign(n,{resolve:e,reject:o})),St.set(t,n)),clearTimeout(n.timer),n.timer=setTimeout(()=>{St.delete(t),Bt(()=>xt.afterWrite(t)).then(n.resolve,n.reject)},kn),n.done},frameable:$t(Nt(dt.frameable)),listEmojis:dt.listEmojis,readEmoji:dt.readEmoji,respond:$t,keepVersion:q,renameReport:mn,read:Dt,settled:it,writerOf:(t,n)=>typeof n=="string"&&N.get(t)?.hash===_(n)?N.get(t).by:null,whenTaken:kt,readTaken:Pt,takeRewrites:D,handIn:pn,handInReport:Ut,handInRequest:wn,settleRequest:(t,n)=>hn(t).then(([e,o])=>C(n,e,o),e=>C(n,500,{ok:!1,reason:"write",message:e.message})),settleNotes:Yt,roundRequest:(t,n)=>yn(t).then(([e,o])=>C(n,e,o),e=>C(n,500,{ok:!1,reason:"write",message:e.message})),beginRound:re,commit:ne(Jt,{early:te}),handleCommit:Jt,setTodos:cn,reverted:ne(fn),changes:dn,noteTaken:(t,n)=>B.look(t,n),forgetChanges:t=>B.forget(t),stored:async()=>{await B.idle(),await F}}}export{Vr as a,qr as b,qe as c,oo as d,vn as e,On as f,jn as g,Uo as h};
13
+ <style data-doc-dev data-ge-margin-style>${yr}</style>
14
+ <script data-doc-dev>document.currentScript.remove(); ${gr(t,{notes:er(P.join(Z(t),ar))})}</script>`;return{html:wr(f),snippet:E,head:U}}let cn=t=>T(_(t),t);function te(t){if(t.method!=="POST")return[405,{ok:!1,reason:"method"}];let n=t.headers.host??"",e=t.socket.localPort;return n!==`127.0.0.1:${e}`&&n!==`localhost:${e}`?[403,{ok:!1,reason:"host"}]:t.headers.origin!==`http://${n}`?[403,{ok:!1,reason:"origin"}]:t.headers["x-gallery-token"]!==p?[403,{ok:!1,reason:"token"}]:null}async function ut(t,n=Xt){let e=te(t);if(e)return{error:e};if(!/^application\/json\b/i.test(t.headers["content-type"]??""))return{error:[415,{ok:!1,reason:"type"}]};try{return{body:JSON.parse(await Or(t,n))}}catch(o){return{error:o.message==="too-large"?[413,{ok:!1,reason:"body",message:$r}]:[400,{ok:!1,reason:"body"}]}}}async function Jt(t,n){let{slug:e,opening:o,known:f=null,texts:y=[],units:m=[],touch:j=[],pageIds:R=null,request:E=null,agent:U=!1}=t;if(typeof e!="string"||!rt.test(e)||![y,m,j].every(Array.isArray))return[400,{ok:!1,reason:"body"}];if(E!==null&&(typeof E!="string"||!Qt.test(E)))return[400,{ok:!1,reason:"body"}];let Y=E===null?null:_(JSON.stringify([o??null,y,m,j])),X=await ee(t);if(X)return X;let G=et=>(E!==null&&r(e,E,Y,et),[200,et]),K=W(e),tt=typeof o=="string"&&Vt.test(o)?await x(o):null,V=et=>tr("sha256",p).update(`${e}
15
+ ${et}`).digest("hex").slice(0,32);for(let et=1;;et++){let{source:at,held:Tt}=await it(e);if(at===null)return[404,{ok:!1,reason:"missing"}];if(Tt)return Date.now()<n?lt:[409,{ok:!1,reason:"busy",message:ft}];nt(e,B.look(e,at));let{text:vt,changes:Zt}=M(at),se=[],Et=be({current:vt,opening:tt,texts:y,units:m,touch:j,ids:u?()=>{let Rt=typeof u=="function"?u():Ct();return se.push(Rt),Rt}:!1,seal:V,pageIds:R}),{title:ie,icon:ce,...fe}=Et,mt=Et.text===vt?vt:k(Et.text);mt!==Et.text&&(fe.version=_(mt));let le={...fe,foreign:typeof f=="string"&&_(vt)!==f};if(mt===vt)return G({ok:!0,...le,wrote:!1,notes:[]});if(q(e,at),!await $(K,mt,{expect:at},U===!0?"agent":"reader")){if(et===on)return[409,{ok:!1,reason:"busy",message:ft}];continue}q(e,mt),nt(e,B.wrote(e,mt,Rt=>{let vn=0;return Ne(Rt,{opening:tt,texts:y,units:m,touch:j,pageIds:R,seal:V,ids:u?()=>se[vn++]??(typeof u=="function"?u():Ct()):!1})},{reader:U!==!0})),Zt.length&&(d&&d(Ht(K,Zt).join(`
16
+ `)),v(e,Zt));let Sn=[...ie?await At(P.dirname(K),ie):[],...ce!==void 0?await _t(P.dirname(K),ce):[]];return G({ok:!0,...le,wrote:!0,notes:Sn})}}async function fn(t,n){return typeof t!="string"||!rt.test(t)?[404,{ok:!1,reason:"missing",message:"\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"}]:!Array.isArray(n)||n.length===0||n.length>lr?[400,{ok:!1,reason:"body"}]:Lt({slug:t},async(e,o)=>{let{source:f,held:y}=await it(t);if(f===null)return[404,{ok:!1,reason:"missing",message:"\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"}];if(y)return Date.now()<o?lt:[409,{ok:!1,reason:"busy",message:ft}];let{text:m}=M(f),j=tn(t,f,m,n),{commit:R,changed:E}=en(m,j),U=j.map((V,et)=>V.reason?{ok:!1,reason:V.reason}:{ok:!0,changed:E[et],block:V.unit.blockId??null});if(!R)return[200,{ok:!0,results:U,wrote:!1}];let Y=_(m);T(Y,m);let X=await Jt({slug:t,opening:Y,units:R.units,touch:R.touch},o);if(X===lt)return lt;let[G,K]=X;if(!K.ok)return[G,K];let tt=new Map((K.units??[]).map(V=>[V.key,V]));return[200,{ok:!0,wrote:K.wrote===!0,results:U.map((V,et)=>{if(!V.ok)return V;let at=R.keys.get(j[et].unit.id);if(at===void 0)return V;let Tt=tt.get(at);return Tt?.status!=="applied"?{ok:!1,reason:Tt?.reason==="ambiguous"?"ambiguous":"changed"}:{...V,block:K.ids?.[at]??V.block}})}]})}async function ee({slug:t,opening:n,texts:e=[],units:o=[],touch:f=[],request:y=null}){if(typeof t!="string"||!rt.test(t)||typeof y!="string"||!Qt.test(y)||![e,o,f].every(Array.isArray))return null;let m=await a(t,y);return m?m.digest===_(JSON.stringify([n??null,e,o,f]))?[200,{...m.answer,again:!0}]:[409,{ok:!1,reason:"request",message:"\u540C\u4E00\u6B21\u4FDD\u5B58\u7684\u5185\u5BB9\u4E0D\u4E00\u81F4"}]:null}async function ln(t,n){let{slug:e,opening:o,texts:f=[],units:y=[],instances:m=[],pageIds:j=null}=t;if(typeof e!="string"||!rt.test(e)||!Array.isArray(f)||!Array.isArray(y)||!Array.isArray(m))return[400,{ok:!1,reason:"body"}];let{source:R,held:E}=await it(e);if(E)return Date.now()<n?lt:[409,{ok:!1,reason:"busy",message:ft}];let U=await Dt(e,R);if(U===null)return[404,{ok:!1,reason:"missing"}];let{text:Y,version:X}=U,G=typeof o=="string"&&Vt.test(o)?await x(o):null;return[200,{ok:!0,version:X,reverted:Se({current:Y,opening:G,texts:f,pageIds:j}),units:$e({current:Y,units:y}),parts:xe({current:Y,instances:m,pageIds:j})}]}let un=600*1e3,bt=new Map;async function ne(t,n){let e=Z(t),o=null;try{o=JSON.parse(await z.readFile(Mt(e).json,"utf8"))}catch{}let{title:f,icon:y}=je(n,o);f&&typeof o?.title=="string"&&o.title!==f.to&&await At(e,{from:o.title,to:f.to,synced:!0}),y&&!y.missing&&await _t(e,y.to)}async function dn(t,n){let{slug:e,action:o,stamp:f=null,undo:y=null}=t;if(typeof e!="string"||!rt.test(e)||!["accept","revert","undo"].includes(o))return[400,{ok:!1,reason:"body"}];let m=W(e),{source:j,held:R}=await it(e);if(j===null)return[404,{ok:!1,reason:"missing"}];if(R)return Date.now()<n?lt:[409,{ok:!1,reason:"busy",message:ft}];if(o==="undo"){for(let[K,tt]of bt)Date.now()-tt.at>un&&bt.delete(K);let G=typeof y=="string"?bt.get(y):null;return!G||G.slug!==e?[404,{ok:!1,reason:"gone",message:"\u64A4\u9500\u5DF2\u7ECF\u8FC7\u671F"}]:j!==G.after?[409,{ok:!1,reason:"moved-on",message:"\u64A4\u56DE\u4E4B\u540E\u6587\u6863\u53C8\u6539\u8FC7\u4E86\uFF0C\u6CA1\u6CD5\u64A4\u9500"}]:(q(e,j),await $(m,G.before,{expect:j})?(q(e,G.before),bt.delete(y),await ne(e,G.before),await B.restore(e,G.saved),await B.wrote(e,G.before),c(e),[200,{ok:!0,version:_(M(G.before).text)}]):[409,{ok:!1,reason:"busy",message:ft}])}await B.look(e,j);let E=await B.snapshot(e),U=E?.state?.base?`${E.state.since}|${E.state.writes}`:null;if(U===null)return[200,{ok:!0,none:!0}];if(U!==f)return[409,{ok:!1,reason:"changed",message:"Agent \u521A\u521A\u53C8\u6539\u4E86\u6587\u6863\uFF0C\u518D\u770B\u4E00\u773C"}];if(o==="accept")return await B.clear(e),c(e),[200,{ok:!0}];let Y=E.base;if(q(e,j),!await $(m,Y,{expect:j}))return[409,{ok:!1,reason:"busy",message:ft}];q(e,Y),await ne(e,Y);let X=qt(8).toString("hex");return bt.set(X,{slug:e,before:j,after:Y,saved:E,at:Date.now()}),await B.clear(e),await B.wrote(e,Y),c(e),[200,{ok:!0,version:_(M(Y).text),undo:X}]}async function mn(t,n){let e=await ut(t);if(e.error)return C(n,...e.error);let o=e.body??{};try{if(o.action!=="read")return C(n,...await Lt(o,dn));if(typeof o.slug!="string"||!rt.test(o.slug))return C(n,400,{ok:!1,reason:"body"});let f=await Pt(o.slug,{wait:0});return f===null?C(n,404,{ok:!1,reason:"missing"}):C(n,200,{ok:!0,...await B.read(o.slug,f.source)})}catch(f){return C(n,500,{ok:!1,reason:"write",message:f.message})}}async function At(t,{from:n,to:e,synced:o}){let f=["\u6807\u9898\u5DF2\u66F4\u65B0",...o?[]:["\u5355\u72EC\u6253\u5F00\u6216\u5BFC\u51FA\u65F6\u7684\u9875\u9762\u540D\u79F0\u539F\u672C\u5C31\u548C\u6807\u9898\u4E0D\u540C\uFF0C\u6CA1\u6709\u8DDF\u7740\u6539"]],y=Mt(t).json,m=await z.readFile(y,"utf8").catch(()=>""),j=null;try{j=JSON.parse(m)}catch{}if(j?.title!==n)return[...f,"\u641C\u7D22\u548C\u4FA7\u680F\u91CC\uFF08\u6CA1\u6253\u5F00\u8FD9\u4EFD\u6587\u6863\u65F6\uFF09\u7684\u6587\u6863\u540D\u539F\u672C\u5C31\u548C\u6807\u9898\u4E0D\u540C\uFF0C\u6CA1\u6709\u8DDF\u7740\u6539"];let R=new RegExp(`("title"\\s*:\\s*)${JSON.stringify(n).replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}`),E=R.test(m)?m.replace(R,(U,Y)=>Y+JSON.stringify(e)):`${JSON.stringify({...j,title:e},null,2)}
17
+ `;try{await $(y,E)}catch(U){return d?.(`${P.basename(y)}'s title was not written (${U.code??U.message}): ${y}`),[...f,"\u641C\u7D22\u548C\u4FA7\u680F\u91CC\uFF08\u6CA1\u6253\u5F00\u8FD9\u4EFD\u6587\u6863\u65F6\uFF09\u7684\u6587\u6863\u540D\u6CA1\u80FD\u8DDF\u7740\u6539"]}return f}async function _t(t,n){let e=Mt(t).json,o=null;try{o=JSON.parse(await z.readFile(e,"utf8"))}catch{}if(!o||typeof o!="object")return d?.(`${P.basename(e)} could not be read, so its icon was not written: ${e}`),["\u9875\u9762\u56FE\u6807\u5DF2\u66F4\u6362\uFF0C\u4F46\u641C\u7D22\u548C\u4FA7\u680F\u91CC\uFF08\u6CA1\u6253\u5F00\u8FD9\u4EFD\u6587\u6863\u65F6\uFF09\u7684\u56FE\u6807\u6CA1\u80FD\u8DDF\u7740\u6362"];if((o.icon??null)===n)return[];let{icon:f,...y}=o,m=n===null?y:{...y,icon:n};try{await $(e,`${JSON.stringify(m,null,2)}
18
+ `)}catch(j){return d?.(`${P.basename(e)}'s icon was not written (${j.code??j.message}): ${e}`),["\u9875\u9762\u56FE\u6807\u5DF2\u66F4\u6362\uFF0C\u4F46\u641C\u7D22\u548C\u4FA7\u680F\u91CC\uFF08\u6CA1\u6253\u5F00\u8FD9\u4EFD\u6587\u6863\u65F6\uFF09\u7684\u56FE\u6807\u6CA1\u80FD\u8DDF\u7740\u6362"]}return[]}async function pn(t,n){let e=typeof n=="string"?n.replace(/\s+/g," ").trim():"";if(!e)return{ok:!1,reason:"title",message:"\u6807\u9898\u4E0D\u80FD\u4E3A\u7A7A"};let o=W(t),f=await z.readFile(o,"utf8").catch(()=>null);if(f===null)return{ok:!1,reason:"missing"};nt(t,B.look(t,f));let y=pe(f),m=he(y).find(E=>E.kind==="title");if(!m)return{ok:!1,reason:"no-title",message:"\u8FD9\u4EFD\u6587\u6863\u6CA1\u6709\u6807\u9898"};let j=sr(e),R=ke({current:y,edits:[{id:m.id,parts:[{keep:!0,html:j}]}],ids:u});return R.ok?R.text!==f&&!await $(o,R.text,{expect:f})?{ok:!1,reason:"changed-again"}:(R.text!==f&&nt(t,B.wrote(t,R.text,E=>Te(E,j))),{ok:!0,title:e,notes:R.title?await At(P.dirname(o),R.title):[]}):{ok:!1,reason:"conflict"}}let $t=t=>(n,e)=>{let o=J.then(()=>t(n));return J=o.catch(()=>{}),o.then(([f,y])=>C(e,f,y),f=>C(e,500,{ok:!1,reason:"write",message:f.message}))},re=(t,{early:n=null}={})=>async(e,o)=>{let f=await ut(e);if(f.error)return C(o,...f.error);let y=f.body??{};try{let m=n&&await n(y);return m?C(o,...m):C(o,...await Lt(y,t))}catch(m){return C(o,500,{ok:!1,reason:"write",message:m.message})}};async function Lt(t,n){let e=Date.now()+I;for(;;){await kt(t.slug,e);let o=J.then(()=>n(t,e));J=o.catch(()=>{});let f=await o;if(f!==lt)return f}}async function Ut(t,{reader:n=!1}={}){if(typeof t!="string"||!rt.test(t))return{ok:!1,reason:"missing",message:"\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"};let e=Z(t),{html:o,json:f}=Mt(e);for(let y=1;;y++){let{source:m,held:j}=n?await it(t):{source:await z.readFile(o,"utf8").catch(()=>null),held:!1};if(m===null)return{ok:!1,reason:"missing",message:"\u627E\u4E0D\u5230\u8FD9\u4EFD\u6587\u6863"};if(j)return{ok:!1,reason:"busy",message:"\u6587\u4EF6\u4E00\u518D\u88AB\u4FEE\u6539\uFF08\u4F8B\u5982 AI \u6B63\u5728\u5199\u5165\uFF09\uFF0C\u6CA1\u6709\u5199\u5165"};nt(t,B.look(t,m));let R=null;try{R=JSON.parse(await z.readFile(f,"utf8"))}catch{}let{text:E,changes:U,added:Y,given:X,repeated:G,title:K,icon:tt}=Oe(m,{finish:k,next:typeof u=="function"?u:void 0,metadata:R});if(E!==m){if(q(t,m),!await $(o,E,{expect:m},n?"reader":"agent")){if(y===on)return{ok:!1,reason:"busy",message:"\u6587\u4EF6\u4E00\u518D\u88AB\u4FEE\u6539\uFF08\u4F8B\u5982 AI \u6B63\u5728\u5199\u5165\uFF09\uFF0C\u6CA1\u6709\u5199\u5165"};continue}q(t,E),nt(t,B.wrote(t,E)),n&&U.length&&(d&&d(Ht(o,U).join(`
19
+ `)),v(t,U))}return K&&typeof R?.title=="string"&&R.title!==K.to&&await At(e,{from:R.title,to:K.to,synced:K.page}),tt&&!tt.missing&&await _t(e,tt.to),{ok:!0,changes:E===m?[]:U,added:E===m?0:Y,given:E===m?[]:X,repeated:G,written:E!==m,title:K,icon:tt}}}let wn=async(t,{reader:n=!1}={})=>{n&&await kt(t);let e=J.then(()=>Ut(t,{reader:n}));return J=e.catch(()=>{}),e};async function Wt(t){let n=await ut(t);if(n.error)return{refused:n.error};let{slug:e,workspace:o}=n.body??{};return typeof e!="string"||!rt.test(e)||typeof o!="string"?{refused:[400,{ok:!1,reason:"body"}]}:fr(o,l)?{slug:e}:{refused:[409,{ok:!1,reason:"elsewhere",message:"\u8FD9\u4E2A\u9884\u89C8\u670D\u52A1\u5668\u7BA1\u7684\u662F\u53E6\u4E00\u4E2A\u76EE\u5F55\u7684\u6587\u6863"}]}}async function hn(t,n){try{let e=J.then(async()=>{let{slug:y,refused:m}=await Wt(t);if(m)return{answer:m};let j=await Ut(y);return{slug:j.ok?y:null,answer:[j.ok?200:j.reason==="missing"?404:409,j]}});J=e.catch(()=>{});let{slug:o,answer:f}=await e;return o&&await Yt(o),C(n,...f)}catch(e){return C(n,500,{ok:!1,reason:"write",message:e.message})}}async function yn(t){let{slug:n,refused:e}=await Wt(t);return e||(await Yt(n),[200,{ok:!0}])}async function oe(t){let{source:n}=await kt(t),{ended:e,moved:o}=await B.endDraft(t,n);return o&&c(t),e}async function gn(t){let{slug:n,refused:e}=await Wt(t);return e||[200,{ok:!0,ended:await oe(n)}]}let dt=Ee({reportsDirectory:l}),xt=We({reportsDirectory:l,read:t=>Pt(t,{wait:0}),write:$,dropped:(t,n)=>{let e=n.map(Ge);d&&d(Kt(P.join(Z(t),"annotations.json"),{items:e}).join(`
20
+ `)),i&&(F=F.then(()=>Ke({stateDirectory:i,reportsDirectory:l,slug:t,time:new Date().toISOString(),items:e})).catch(()=>{}))}}),ae=Promise.resolve(),Bt=t=>{let n=ae.then(t);return ae=n.catch(()=>{}),n},kn=t=>(n,e)=>Bt(()=>t(n)).then(([o,f])=>C(e,o,f),o=>C(e,500,{ok:!1,reason:"write",message:o.message})),bn=300,St=new Map;async function Yt(t){let n=St.get(t);n&&(clearTimeout(n.timer),St.delete(t));let e=Bt(()=>xt.afterWrite(t));n&&e.then(n.resolve,n.reject),await e.catch(o=>d?.(`${t}: annotations not checked: ${o.message}`)),await F}let $n=t=>{let n=t.headers.host??"",e=t.socket.localPort;return n!==`127.0.0.1:${e}`&&n!==`localhost:${e}`?[403,{ok:!1,reason:"host"}]:t.headers["x-gallery-token"]!==p?[403,{ok:!1,reason:"token"}]:null};async function xn(t){if(t.method==="GET"){let e=$n(t);if(e)return e;let o=new URL(t.url??"/","http://localhost").searchParams;return o.get("as")==="copy"?xt.copy(o.get("slug")):xt.list(o.get("slug"))}let n=await ut(t);return n.error??xt.change(n.body)}let Nt=(t,n=Xt)=>async e=>{let o=await ut(e,n);return o.error??t(o.body)};return{token:p,preview:sn,opened:cn,check:ut,checkHeaders:te,upload:$t(Nt(dt.upload,kr)),addEmoji:$t(Nt(dt.addEmoji)),unfurl:$t(Nt(dt.unfurl)),annotations:kn(xn),checkAnnotations(t){let n=St.get(t);return n||(n={timer:0},n.done=new Promise((e,o)=>Object.assign(n,{resolve:e,reject:o})),St.set(t,n)),clearTimeout(n.timer),n.timer=setTimeout(()=>{St.delete(t),Bt(()=>xt.afterWrite(t)).then(n.resolve,n.reject)},bn),n.done},frameable:$t(Nt(dt.frameable)),listEmojis:dt.listEmojis,readEmoji:dt.readEmoji,respond:$t,keepVersion:q,renameReport:pn,read:Dt,settled:it,writerOf:(t,n)=>typeof n=="string"&&N.get(t)?.hash===_(n)?N.get(t).by:null,whenTaken:kt,readTaken:Pt,takeRewrites:D,handIn:wn,handInReport:Ut,handInRequest:hn,settleRequest:(t,n)=>yn(t).then(([e,o])=>C(n,e,o),e=>C(n,500,{ok:!1,reason:"write",message:e.message})),settleNotes:Yt,roundRequest:(t,n)=>gn(t).then(([e,o])=>C(n,e,o),e=>C(n,500,{ok:!1,reason:"write",message:e.message})),beginRound:oe,commit:re(Jt,{early:ee}),handleCommit:Jt,setTodos:fn,reverted:re(ln),changes:mn,noteTaken:(t,n)=>B.look(t,n),forgetChanges:t=>B.forget(t),stored:async()=>{await B.idle(),await F}}}export{qr as a,Xr as b,Xe as c,ao as d,On as e,jn as f,Mn as g,Wo as h};
package/dist/cli.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{a,b,c,d,e}from"./chunk-RKPWLGZ3.mjs";import"./chunk-N7AZZLGT.mjs";import"./chunk-5L7RYZCL.mjs";export{e as main,d as notOurs,b as readCommandLine,c as unwritable,a as versionOf};
2
+ import{a,b,c,d,e}from"./chunk-GHOYKMQ3.mjs";import"./chunk-QE5RG76S.mjs";import"./chunk-5L7RYZCL.mjs";export{e as main,d as notOurs,b as readCommandLine,c as unwritable,a as versionOf};
package/dist/server.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  import { createRequire as __galleryRequire } from "node:module"; import { fileURLToPath as __galleryPath } from "node:url"; const require = __galleryRequire(import.meta.url); const __filename = __galleryPath(import.meta.url); const __dirname = __galleryPath(new URL(".", import.meta.url));
2
- import{a as o}from"./chunk-6EXH3ORZ.mjs";import"./chunk-DR73Y2UJ.mjs";import"./chunk-NWFBE2YA.mjs";import"./chunk-PUOQ65NC.mjs";import"./chunk-ZUNVAXLH.mjs";import"./chunk-6VTU6KEO.mjs";import"./chunk-OJKMINIU.mjs";import"./chunk-B4P2CM2J.mjs";import"./chunk-VJPFVNNW.mjs";import"./chunk-PZDLJJTJ.mjs";import"./chunk-IA4PSIMD.mjs";import"./chunk-UKSHDZZ6.mjs";import"./chunk-6EZ7FNIK.mjs";import"./chunk-35NQ4PLQ.mjs";import"./chunk-V6RIYQZZ.mjs";import"./chunk-SXHBYZST.mjs";import"./chunk-UFNYFFKO.mjs";import"./chunk-D4EURAX4.mjs";import"./chunk-HMYTM3GT.mjs";import"./chunk-OW5NWPOJ.mjs";import"./chunk-ZTHICSSF.mjs";import"./chunk-SX4LJYT6.mjs";import"./chunk-PAREWQGB.mjs";import"./chunk-W3BGBJQW.mjs";import"./chunk-JVHHHGEA.mjs";import"./chunk-HYMEEXKN.mjs";import"./chunk-UMHUSOPJ.mjs";import"./chunk-N76HWBA3.mjs";import"./chunk-FJYN7RTH.mjs";import"./chunk-UBBRTJ2R.mjs";import"./chunk-FWNRPMCJ.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";var t=process.argv.indexOf("--port"),r=t===-1?Number.NaN:Number(process.argv[t+1]);(!Number.isInteger(r)||r<=0||r>=65536)&&(console.error("Usage: node dist/server.mjs --port <n> (GALLERY_WORKSPACE names the workspace). The gallery command starts it: gallery open."),process.exit(2));try{let{port:e}=await o({port:r});console.log(`[gallery] ${new Date().toISOString()} listening on http://127.0.0.1:${e}/ (pid ${process.pid})`)}catch(e){console.error(`[gallery] could not start on port ${r}: ${e.message}`),process.exit(1)}
2
+ import{a as o}from"./chunk-ORID3AE7.mjs";import"./chunk-DR73Y2UJ.mjs";import"./chunk-JLTZF4LA.mjs";import"./chunk-PUOQ65NC.mjs";import"./chunk-7OG26PGF.mjs";import"./chunk-DJISHPUL.mjs";import"./chunk-ZWWC4KLF.mjs";import"./chunk-AHN3NFKJ.mjs";import"./chunk-MTYYHM2G.mjs";import"./chunk-ALZ6ZENZ.mjs";import"./chunk-IA4PSIMD.mjs";import"./chunk-2OHANJ6Q.mjs";import"./chunk-F4ZA6JRZ.mjs";import"./chunk-7M2BQQGZ.mjs";import"./chunk-ITOH5EGO.mjs";import"./chunk-ZQS6H473.mjs";import"./chunk-UYVCQK3H.mjs";import"./chunk-J5PUIV3Y.mjs";import"./chunk-MXUBKDRO.mjs";import"./chunk-HXG7EOPJ.mjs";import"./chunk-ZTHICSSF.mjs";import"./chunk-6N3PX4XX.mjs";import"./chunk-PAREWQGB.mjs";import"./chunk-BFJGHSQN.mjs";import"./chunk-U5XL7D6A.mjs";import"./chunk-HYMEEXKN.mjs";import"./chunk-UMHUSOPJ.mjs";import"./chunk-R2ZDLJYT.mjs";import"./chunk-VFX2KNHP.mjs";import"./chunk-VS7JIGJW.mjs";import"./chunk-HDWTZ763.mjs";import"./chunk-A55HN5OK.mjs";import"./chunk-5L7RYZCL.mjs";var t=process.argv.indexOf("--port"),r=t===-1?Number.NaN:Number(process.argv[t+1]);(!Number.isInteger(r)||r<=0||r>=65536)&&(console.error("Usage: node dist/server.mjs --port <n> (GALLERY_WORKSPACE names the workspace). The gallery command starts it: gallery open."),process.exit(2));try{let{port:e}=await o({port:r});console.log(`[gallery] ${new Date().toISOString()} listening on http://127.0.0.1:${e}/ (pid ${process.pid})`)}catch(e){console.error(`[gallery] could not start on port ${r}: ${e.message}`),process.exit(1)}