@poe-platform/safe-bash 0.1.806 → 0.1.807

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 (856) hide show
  1. package/README.md +4 -0
  2. package/dist/image-ast/portable.d.ts +8 -0
  3. package/dist/image-ast/portable.js +2 -0
  4. package/dist/safe-bash/chunks/{chunk-KRA6WK4Z.js → chunk-3Y54SR4R.js} +6 -6
  5. package/dist/safe-bash/chunks/{chunk-OYJI4L4J.js → chunk-PPAA3LJS.js} +1 -1
  6. package/dist/safe-bash/chunks/{chunk-SCROOJV7.js → chunk-XZ2Y4RWC.js} +2 -2
  7. package/dist/safe-bash/command-chunks/{biff-AU4VGVMD-6EQ64QPG.js → biff-YBHP7ZES-M7TU7NA5.js} +1211 -1205
  8. package/dist/safe-bash/command-chunks/chunk-2A6TBB4F.js +14 -0
  9. package/dist/safe-bash/command-chunks/chunk-2AF7J6FE.js +372 -0
  10. package/dist/safe-bash/command-chunks/{chunk-AITNVBXO.js → chunk-2ANW3FXH.js} +4 -4
  11. package/dist/safe-bash/command-chunks/chunk-2B6XWO6A.js +730 -0
  12. package/dist/safe-bash/command-chunks/chunk-2BKOSQD3.js +11 -0
  13. package/dist/safe-bash/command-chunks/chunk-2EUH5B6A.js +127 -0
  14. package/dist/safe-bash/command-chunks/chunk-2FOLUJLI.js +400 -0
  15. package/dist/safe-bash/command-chunks/{chunk-CZLX3KVF.js → chunk-2GILUQJY.js} +4 -6
  16. package/dist/safe-bash/command-chunks/chunk-2HHGDJ7J.js +280 -0
  17. package/dist/safe-bash/command-chunks/chunk-2NE2GPSF.js +546 -0
  18. package/dist/safe-bash/command-chunks/chunk-2P7BLWWI.js +272 -0
  19. package/dist/safe-bash/command-chunks/chunk-2PSVE7I5.js +101 -0
  20. package/dist/safe-bash/command-chunks/chunk-2UUFZMOH.js +503 -0
  21. package/dist/safe-bash/command-chunks/chunk-2VGAC6S6.js +393 -0
  22. package/dist/safe-bash/command-chunks/chunk-2W54TAGI.js +162 -0
  23. package/dist/safe-bash/command-chunks/chunk-326A5G42.js +328 -0
  24. package/dist/safe-bash/command-chunks/chunk-36KIT4DU.js +218 -0
  25. package/dist/safe-bash/command-chunks/chunk-3CHQG25N.js +455 -0
  26. package/dist/safe-bash/command-chunks/chunk-3JQ3RF2O.js +72 -0
  27. package/dist/safe-bash/command-chunks/chunk-3MLJWSYL.js +92 -0
  28. package/dist/safe-bash/command-chunks/{chunk-ASYR2LU7.js → chunk-3RQCLLQA.js} +5 -5
  29. package/dist/safe-bash/command-chunks/chunk-3SEQG5JH.js +521 -0
  30. package/dist/safe-bash/command-chunks/chunk-3SWT2KYH.js +78 -0
  31. package/dist/safe-bash/command-chunks/chunk-3VETFXYR.js +170 -0
  32. package/dist/safe-bash/command-chunks/chunk-3W6PTHHB.js +65 -0
  33. package/dist/safe-bash/command-chunks/chunk-457CU3IC.js +8 -0
  34. package/dist/safe-bash/command-chunks/chunk-45BW6MGM.js +250 -0
  35. package/dist/safe-bash/command-chunks/chunk-47MFDPH4.js +419 -0
  36. package/dist/safe-bash/command-chunks/chunk-4ATHODCG.js +444 -0
  37. package/dist/safe-bash/command-chunks/chunk-4DJICIFV.js +227 -0
  38. package/dist/safe-bash/command-chunks/chunk-4FNQPK7C.js +385 -0
  39. package/dist/safe-bash/command-chunks/chunk-4LXDJES2.js +65 -0
  40. package/dist/safe-bash/command-chunks/chunk-4QRXKUD2.js +662 -0
  41. package/dist/safe-bash/command-chunks/chunk-4QYNOBWZ.js +455 -0
  42. package/dist/safe-bash/command-chunks/{chunk-MWNWT6HG.js → chunk-4XFFIKA3.js} +5 -5
  43. package/dist/safe-bash/command-chunks/chunk-5AU5ENL5.js +180 -0
  44. package/dist/safe-bash/command-chunks/chunk-5DFZAJHL.js +324 -0
  45. package/dist/safe-bash/command-chunks/chunk-5GEFJROP.js +270 -0
  46. package/dist/safe-bash/command-chunks/chunk-5HWX4XYW.js +263 -0
  47. package/dist/safe-bash/command-chunks/chunk-5LKNP4IF.js +872 -0
  48. package/dist/safe-bash/command-chunks/chunk-5OEHUIVE.js +240 -0
  49. package/dist/safe-bash/command-chunks/chunk-6EHVFKM7.js +171 -0
  50. package/dist/safe-bash/command-chunks/chunk-6JTPLJ3B.js +155 -0
  51. package/dist/safe-bash/command-chunks/chunk-6KLUPQ65.js +496 -0
  52. package/dist/safe-bash/command-chunks/chunk-6NS5RXQ7.js +285 -0
  53. package/dist/safe-bash/command-chunks/chunk-6PJIQEH4.js +3472 -0
  54. package/dist/safe-bash/command-chunks/chunk-763ECQWB.js +566 -0
  55. package/dist/safe-bash/command-chunks/chunk-7DADVPKN.js +23 -0
  56. package/dist/safe-bash/command-chunks/chunk-7LEADSSA.js +164 -0
  57. package/dist/safe-bash/command-chunks/chunk-7MMSBVUP.js +732 -0
  58. package/dist/safe-bash/command-chunks/chunk-7OXNWLSL.js +35 -0
  59. package/dist/safe-bash/command-chunks/chunk-7PZASWL6.js +354 -0
  60. package/dist/safe-bash/command-chunks/{chunk-ZBR3UH4P.js → chunk-7QH3WAMQ.js} +2 -2
  61. package/dist/safe-bash/command-chunks/{chunk-CB3HTIDK.js → chunk-7SOE7XIS.js} +11 -11
  62. package/dist/safe-bash/command-chunks/chunk-7Y3ZQ6FE.js +56 -0
  63. package/dist/safe-bash/command-chunks/chunk-A2YEQYCC.js +289 -0
  64. package/dist/safe-bash/command-chunks/chunk-A3XE767Q.js +502 -0
  65. package/dist/safe-bash/command-chunks/{chunk-MWY75E3F.js → chunk-A6LCBGE6.js} +187 -187
  66. package/dist/safe-bash/command-chunks/{chunk-HFUL6E5I.js → chunk-A7CE4EIU.js} +33 -151
  67. package/dist/safe-bash/command-chunks/chunk-A7EMM3SB.js +297 -0
  68. package/dist/safe-bash/command-chunks/{chunk-G3YO3JIN.js → chunk-ABH5FMMA.js} +1 -1
  69. package/dist/safe-bash/command-chunks/chunk-AEJZEGW7.js +1376 -0
  70. package/dist/safe-bash/command-chunks/chunk-AELXRNM6.js +207 -0
  71. package/dist/safe-bash/command-chunks/chunk-AEZIPWRI.js +260 -0
  72. package/dist/safe-bash/command-chunks/{chunk-AHD3CGAY.js → chunk-AFPXADZG.js} +4 -4
  73. package/dist/safe-bash/command-chunks/chunk-AIOB34IX.js +201 -0
  74. package/dist/safe-bash/command-chunks/chunk-AJEYCC4X.js +262 -0
  75. package/dist/safe-bash/command-chunks/chunk-ALMHXDKZ.js +321 -0
  76. package/dist/safe-bash/command-chunks/chunk-AQ6RTM2M.js +309 -0
  77. package/dist/safe-bash/command-chunks/chunk-AQNFEGMZ.js +481 -0
  78. package/dist/safe-bash/command-chunks/{chunk-2AKKYY5G.js → chunk-ASZ4EMKE.js} +1 -1
  79. package/dist/safe-bash/command-chunks/chunk-AYJGINE5.js +144 -0
  80. package/dist/safe-bash/command-chunks/{chunk-MRFW2E6B.js → chunk-B4UWZCQR.js} +1 -1
  81. package/dist/safe-bash/command-chunks/chunk-BDYKJTBQ.js +43 -0
  82. package/dist/safe-bash/command-chunks/chunk-BERVTMQB.js +41 -0
  83. package/dist/safe-bash/command-chunks/chunk-BZOY2UMP.js +275 -0
  84. package/dist/safe-bash/command-chunks/{chunk-W47KIMSP.js → chunk-C2EYJT4S.js} +1 -1
  85. package/dist/safe-bash/command-chunks/chunk-CK5Q6RDE.js +342 -0
  86. package/dist/safe-bash/command-chunks/chunk-CKEODJVT.js +992 -0
  87. package/dist/safe-bash/command-chunks/{chunk-Z7UIOPHJ.js → chunk-DCMSPMMD.js} +1 -1
  88. package/dist/safe-bash/command-chunks/chunk-DE66JRWJ.js +352 -0
  89. package/dist/safe-bash/command-chunks/chunk-DKNNYPOI.js +409 -0
  90. package/dist/safe-bash/command-chunks/chunk-DV745GFU.js +294 -0
  91. package/dist/safe-bash/command-chunks/chunk-DXX2Z2QA.js +33 -0
  92. package/dist/safe-bash/command-chunks/chunk-E7AYF54A.js +473 -0
  93. package/dist/safe-bash/command-chunks/chunk-EDSFQJAU.js +159 -0
  94. package/dist/safe-bash/command-chunks/{chunk-UQ3KEUCF.js → chunk-ESD5ZD74.js} +7 -1
  95. package/dist/safe-bash/command-chunks/chunk-EUXUCRCI.js +1739 -0
  96. package/dist/safe-bash/command-chunks/chunk-F2ORFLCH.js +3669 -0
  97. package/dist/safe-bash/command-chunks/chunk-FANIWOBM.js +311 -0
  98. package/dist/safe-bash/command-chunks/chunk-FOO3AXFK.js +47 -0
  99. package/dist/safe-bash/command-chunks/chunk-FRZ5P5AB.js +131 -0
  100. package/dist/safe-bash/command-chunks/chunk-FZSQMMYV.js +276 -0
  101. package/dist/safe-bash/command-chunks/{chunk-P6NUIMMX.js → chunk-G5F2VSQ7.js} +1 -1
  102. package/dist/safe-bash/command-chunks/chunk-GGOZXIGH.js +299 -0
  103. package/dist/safe-bash/command-chunks/chunk-GIESJLR2.js +241 -0
  104. package/dist/safe-bash/command-chunks/chunk-GLPIFP7N.js +385 -0
  105. package/dist/safe-bash/command-chunks/chunk-GZ2N24A2.js +342 -0
  106. package/dist/safe-bash/command-chunks/chunk-H2NWPMNW.js +216 -0
  107. package/dist/safe-bash/command-chunks/chunk-HHLVI2CB.js +3949 -0
  108. package/dist/safe-bash/command-chunks/chunk-HJDE7ZNV.js +82 -0
  109. package/dist/safe-bash/command-chunks/chunk-HOAM3F5I.js +124 -0
  110. package/dist/safe-bash/command-chunks/chunk-HPKUFWHW.js +482 -0
  111. package/dist/safe-bash/command-chunks/chunk-HPMVMOD2.js +109 -0
  112. package/dist/safe-bash/command-chunks/chunk-HQAHDJPX.js +8 -0
  113. package/dist/safe-bash/command-chunks/chunk-HR2Y6YEP.js +12 -0
  114. package/dist/safe-bash/command-chunks/chunk-HUNXIAOL.js +62 -0
  115. package/dist/safe-bash/command-chunks/chunk-I4JWZOSP.js +244 -0
  116. package/dist/safe-bash/command-chunks/chunk-I6AMDG2T.js +85 -0
  117. package/dist/safe-bash/command-chunks/chunk-IB2Q5CL3.js +288 -0
  118. package/dist/safe-bash/command-chunks/chunk-IFNLDOJ4.js +316 -0
  119. package/dist/safe-bash/command-chunks/chunk-IKHBXETN.js +174 -0
  120. package/dist/safe-bash/command-chunks/chunk-IOSWG5JS.js +228 -0
  121. package/dist/safe-bash/command-chunks/chunk-IQFRPIXH.js +317 -0
  122. package/dist/safe-bash/command-chunks/chunk-IR6ZKAUH.js +582 -0
  123. package/dist/safe-bash/command-chunks/chunk-IW7PEB4I.js +297 -0
  124. package/dist/safe-bash/command-chunks/chunk-JGGRMERW.js +36 -0
  125. package/dist/safe-bash/command-chunks/chunk-JHAY3KYC.js +520 -0
  126. package/dist/safe-bash/command-chunks/{chunk-UO25D4WG.js → chunk-JITDS55R.js} +22 -22
  127. package/dist/safe-bash/command-chunks/chunk-JJK3CU7Z.js +6 -0
  128. package/dist/safe-bash/command-chunks/{chunk-XKZWUMH4.js → chunk-JN7GNI2C.js} +1 -1
  129. package/dist/safe-bash/command-chunks/chunk-JQ3EJKHF.js +160 -0
  130. package/dist/safe-bash/command-chunks/chunk-JQE256UO.js +292 -0
  131. package/dist/safe-bash/command-chunks/chunk-JQZ3BXWY.js +382 -0
  132. package/dist/safe-bash/command-chunks/{chunk-7DLR4HCC.js → chunk-JWSOFSGI.js} +22 -22
  133. package/dist/safe-bash/command-chunks/chunk-K3CDZMUN.js +168 -0
  134. package/dist/safe-bash/command-chunks/{chunk-SUYSZJI3.js → chunk-K5COUQAQ.js} +4 -4
  135. package/dist/safe-bash/command-chunks/chunk-K7HUXUN2.js +489 -0
  136. package/dist/safe-bash/command-chunks/chunk-KB3CY3QO.js +62 -0
  137. package/dist/safe-bash/command-chunks/chunk-KCBVOYAY.js +92 -0
  138. package/dist/safe-bash/command-chunks/chunk-KD25ICP4.js +366 -0
  139. package/dist/safe-bash/command-chunks/chunk-KDKQ5D55.js +180 -0
  140. package/dist/safe-bash/command-chunks/chunk-KNKDUEDW.js +521 -0
  141. package/dist/safe-bash/command-chunks/chunk-KR2PQ7GD.js +174 -0
  142. package/dist/safe-bash/command-chunks/chunk-KS6WUDPM.js +153 -0
  143. package/dist/safe-bash/command-chunks/{chunk-XFHUSZBM.js → chunk-KUGV3SSL.js} +5 -5
  144. package/dist/safe-bash/command-chunks/chunk-L2JAP5KO.js +249 -0
  145. package/dist/safe-bash/command-chunks/chunk-L2KEA6SN.js +271 -0
  146. package/dist/safe-bash/command-chunks/chunk-L3WY5ASN.js +526 -0
  147. package/dist/safe-bash/command-chunks/chunk-L4XEXXVQ.js +399 -0
  148. package/dist/safe-bash/command-chunks/chunk-LDTUZIJK.js +90 -0
  149. package/dist/safe-bash/command-chunks/chunk-LHDB4QO5.js +479 -0
  150. package/dist/safe-bash/command-chunks/chunk-LHL6RWGJ.js +548 -0
  151. package/dist/safe-bash/command-chunks/chunk-LHRXDH45.js +164 -0
  152. package/dist/safe-bash/command-chunks/chunk-LQOKYG3O.js +153 -0
  153. package/dist/safe-bash/command-chunks/chunk-LRDME6WV.js +12 -0
  154. package/dist/safe-bash/command-chunks/chunk-LWVDJB5S.js +305 -0
  155. package/dist/safe-bash/command-chunks/chunk-M57GLLK4.js +27 -0
  156. package/dist/safe-bash/command-chunks/chunk-MAHX3IW3.js +108 -0
  157. package/dist/safe-bash/command-chunks/{chunk-LQZSR6DT.js → chunk-MDV7W5AS.js} +2 -2
  158. package/dist/safe-bash/command-chunks/chunk-MG7AJD5E.js +168 -0
  159. package/dist/safe-bash/command-chunks/chunk-MHJ3DQUE.js +213 -0
  160. package/dist/safe-bash/command-chunks/chunk-MLGNBD7V.js +552 -0
  161. package/dist/safe-bash/command-chunks/chunk-MN2M33JK.js +237 -0
  162. package/dist/safe-bash/command-chunks/chunk-MOL3TRBT.js +32 -0
  163. package/dist/safe-bash/command-chunks/chunk-MQFXMBGD.js +75 -0
  164. package/dist/safe-bash/command-chunks/chunk-MQPWE22J.js +171 -0
  165. package/dist/safe-bash/command-chunks/chunk-MQU6Q75R.js +523 -0
  166. package/dist/safe-bash/command-chunks/chunk-MWAAMNAM.js +353 -0
  167. package/dist/safe-bash/command-chunks/chunk-MZ4BTMTI.js +240 -0
  168. package/dist/safe-bash/command-chunks/chunk-N4DY4FPA.js +679 -0
  169. package/dist/safe-bash/command-chunks/chunk-N74TJL6X.js +183 -0
  170. package/dist/safe-bash/command-chunks/chunk-NA5Q4V2H.js +304 -0
  171. package/dist/safe-bash/command-chunks/chunk-NSM366N6.js +22 -0
  172. package/dist/safe-bash/command-chunks/chunk-NY4ZPV3N.js +523 -0
  173. package/dist/safe-bash/command-chunks/chunk-NYBF2BVE.js +17 -0
  174. package/dist/safe-bash/command-chunks/chunk-OBK24KGM.js +24 -0
  175. package/dist/safe-bash/command-chunks/{chunk-GDAS4LY7.js → chunk-OEKLEUUW.js} +4 -4
  176. package/dist/safe-bash/command-chunks/chunk-OGWJD5QP.js +404 -0
  177. package/dist/safe-bash/command-chunks/chunk-OIPATOZW.js +154 -0
  178. package/dist/safe-bash/command-chunks/chunk-OP6J3OLL.js +243 -0
  179. package/dist/safe-bash/command-chunks/chunk-OTTMIB3C.js +266 -0
  180. package/dist/safe-bash/command-chunks/{chunk-OZHPB4KD.js → chunk-OU4VE5CR.js} +12 -12
  181. package/dist/safe-bash/command-chunks/chunk-P42REFYL.js +228 -0
  182. package/dist/safe-bash/command-chunks/{chunk-YJ3TFZB2.js → chunk-PQOAM5SC.js} +1 -1
  183. package/dist/safe-bash/command-chunks/chunk-PQOIOVF2.js +444 -0
  184. package/dist/safe-bash/command-chunks/chunk-PRQEVUNE.js +205 -0
  185. package/dist/safe-bash/command-chunks/{chunk-W5OR7COJ.js → chunk-PVLPWVRH.js} +21 -21
  186. package/dist/safe-bash/command-chunks/{chunk-BNG4ZMZ3.js → chunk-PXL4NBYP.js} +1 -78
  187. package/dist/safe-bash/command-chunks/chunk-Q6W5FRZG.js +41 -0
  188. package/dist/safe-bash/command-chunks/{chunk-KLCHCSIV.js → chunk-QGD64UHJ.js} +1 -1
  189. package/dist/safe-bash/command-chunks/chunk-QHS7PDG3.js +188 -0
  190. package/dist/safe-bash/command-chunks/chunk-QXCSASIE.js +151 -0
  191. package/dist/safe-bash/command-chunks/chunk-QYCBVKFT.js +255 -0
  192. package/dist/safe-bash/command-chunks/chunk-R4TYL2G6.js +1529 -0
  193. package/dist/safe-bash/command-chunks/chunk-RAXJVM4U.js +625 -0
  194. package/dist/safe-bash/command-chunks/chunk-RBFZYSZZ.js +207 -0
  195. package/dist/safe-bash/command-chunks/chunk-RJHVJZ4H.js +185 -0
  196. package/dist/safe-bash/command-chunks/chunk-RKPPUYZE.js +213 -0
  197. package/dist/safe-bash/command-chunks/chunk-RMJNV6Q7.js +23 -0
  198. package/dist/safe-bash/command-chunks/{chunk-MR2RLUPV.js → chunk-RQHQCJMV.js} +11 -9
  199. package/dist/safe-bash/command-chunks/chunk-RR6QQ25D.js +71 -0
  200. package/dist/safe-bash/command-chunks/{chunk-JW3KIZU6.js → chunk-RUXY7GN5.js} +1 -1
  201. package/dist/safe-bash/command-chunks/chunk-RZC7QHL6.js +112 -0
  202. package/dist/safe-bash/command-chunks/chunk-RZJRR4UJ.js +1677 -0
  203. package/dist/safe-bash/command-chunks/chunk-S4OBYRNI.js +639 -0
  204. package/dist/safe-bash/command-chunks/{chunk-DQNDEWCI.js → chunk-S65T5JJO.js} +12 -12
  205. package/dist/safe-bash/command-chunks/chunk-S6PPBBXX.js +77 -0
  206. package/dist/safe-bash/command-chunks/chunk-SCG4LK5U.js +265 -0
  207. package/dist/safe-bash/command-chunks/chunk-SDTC2BLK.js +143 -0
  208. package/dist/safe-bash/command-chunks/chunk-SEK43FRN.js +357 -0
  209. package/dist/safe-bash/command-chunks/chunk-SH45NZ2P.js +194 -0
  210. package/dist/safe-bash/command-chunks/chunk-SM733XRT.js +250 -0
  211. package/dist/safe-bash/command-chunks/chunk-SSRGI476.js +116 -0
  212. package/dist/safe-bash/command-chunks/chunk-SUUD352U.js +127 -0
  213. package/dist/safe-bash/command-chunks/{chunk-B5F2KQYA.js → chunk-SWUVHT7G.js} +1 -1
  214. package/dist/safe-bash/command-chunks/chunk-TBAH4XGI.js +38 -0
  215. package/dist/safe-bash/command-chunks/chunk-TBVWTZTR.js +469 -0
  216. package/dist/safe-bash/command-chunks/chunk-TGHQGJNR.js +144 -0
  217. package/dist/safe-bash/command-chunks/{chunk-Q6JLT2EY.js → chunk-TL3KDYEM.js} +8 -110
  218. package/dist/safe-bash/command-chunks/chunk-TVAEX4WQ.js +473 -0
  219. package/dist/safe-bash/command-chunks/chunk-TZ2J6LGM.js +163 -0
  220. package/dist/safe-bash/command-chunks/chunk-UICO7H6S.js +186 -0
  221. package/dist/safe-bash/command-chunks/chunk-UJTJFMIN.js +501 -0
  222. package/dist/safe-bash/command-chunks/chunk-UMWWCLBG.js +109 -0
  223. package/dist/safe-bash/command-chunks/chunk-UPXFSGQG.js +134 -0
  224. package/dist/safe-bash/command-chunks/chunk-UWUYSXYT.js +272 -0
  225. package/dist/safe-bash/command-chunks/{chunk-5FMXQUDY.js → chunk-UZOGSYJP.js} +1 -1
  226. package/dist/safe-bash/command-chunks/chunk-V3RGA5PS.js +125 -0
  227. package/dist/safe-bash/command-chunks/chunk-VEUQWV2V.js +287 -0
  228. package/dist/safe-bash/command-chunks/chunk-VGKYTZT5.js +161 -0
  229. package/dist/safe-bash/command-chunks/chunk-VQUEIEVP.js +410 -0
  230. package/dist/safe-bash/command-chunks/chunk-VU3YUC3U.js +169 -0
  231. package/dist/safe-bash/command-chunks/chunk-W32KW66B.js +27 -0
  232. package/dist/safe-bash/command-chunks/chunk-W543LSYH.js +899 -0
  233. package/dist/safe-bash/command-chunks/chunk-W5YFDYHO.js +387 -0
  234. package/dist/safe-bash/command-chunks/chunk-W6DV2CLS.js +267 -0
  235. package/dist/safe-bash/command-chunks/chunk-WAKYUXVQ.js +215 -0
  236. package/dist/safe-bash/command-chunks/chunk-WGOL3MM6.js +125 -0
  237. package/dist/safe-bash/command-chunks/{chunk-N2A7V3WY.js → chunk-WHNYT34N.js} +3 -3
  238. package/dist/safe-bash/command-chunks/chunk-WOZCIRJ5.js +169 -0
  239. package/dist/safe-bash/command-chunks/chunk-WVB6ONZS.js +232 -0
  240. package/dist/safe-bash/command-chunks/chunk-WVESNAND.js +25 -0
  241. package/dist/safe-bash/command-chunks/chunk-XDEA3TL5.js +322 -0
  242. package/dist/safe-bash/command-chunks/chunk-XFEUWSYG.js +357 -0
  243. package/dist/safe-bash/command-chunks/chunk-XFMJ4RMS.js +2849 -0
  244. package/dist/safe-bash/command-chunks/chunk-XH6DXJHX.js +196 -0
  245. package/dist/safe-bash/command-chunks/chunk-XNJ67APB.js +6 -0
  246. package/dist/safe-bash/command-chunks/chunk-XP6BHGZ6.js +227 -0
  247. package/dist/safe-bash/command-chunks/chunk-XXFHTGV2.js +142 -0
  248. package/dist/safe-bash/command-chunks/chunk-Y5GI5PVT.js +139 -0
  249. package/dist/safe-bash/command-chunks/chunk-Y6KHC3JB.js +177 -0
  250. package/dist/safe-bash/command-chunks/{chunk-2UWPMSME.js → chunk-Y72LPXST.js} +8 -8
  251. package/dist/safe-bash/command-chunks/chunk-YDRWQZNB.js +69 -0
  252. package/dist/safe-bash/command-chunks/{chunk-P4OJBL2B.js → chunk-YFZ6FPIC.js} +1 -1
  253. package/dist/safe-bash/command-chunks/chunk-YH4DC4RP.js +171 -0
  254. package/dist/safe-bash/command-chunks/chunk-YH7KKMMN.js +463 -0
  255. package/dist/safe-bash/command-chunks/{chunk-MN3BB4WW.js → chunk-YP3WWV5N.js} +4 -4
  256. package/dist/safe-bash/command-chunks/chunk-YPVBU7QF.js +2817 -0
  257. package/dist/safe-bash/command-chunks/chunk-YQYVEVUE.js +1621 -0
  258. package/dist/safe-bash/command-chunks/chunk-YRNBIU5U.js +175 -0
  259. package/dist/safe-bash/command-chunks/chunk-Z7ESJVFP.js +10 -0
  260. package/dist/safe-bash/command-chunks/chunk-ZTAFAHY3.js +653 -0
  261. package/dist/safe-bash/command-chunks/chunk-ZXKOMB24.js +85 -0
  262. package/dist/safe-bash/command-chunks/{clipboard-XCSQACOK-SHFXT53F.js → clipboard-6SDGQGC3-TVJ3CG7A.js} +4 -4
  263. package/dist/safe-bash/command-chunks/{command-engine-4TEGTXCQ.js → command-engine-KMLHVFMA.js} +356 -316
  264. package/dist/safe-bash/command-chunks/{engine-QDC5VCGO-LYAAFESF.js → engine-EOYR2WTY-KUFLFTDE.js} +2 -4
  265. package/dist/safe-bash/command-chunks/{gnumeric-OCFH63UT-YI7SG7TN.js → gnumeric-ABKSRBZJ-MPIIPXKP.js} +3 -3
  266. package/dist/safe-bash/command-chunks/inspection-command-ULEU7ZVV.js +7 -0
  267. package/dist/safe-bash/command-chunks/model-store-JUFU3RSW.js +54 -0
  268. package/dist/safe-bash/command-chunks/pdf-22JDKKAR-UDWNSWYB.js +338 -0
  269. package/dist/safe-bash/command-chunks/{pptx-XG3YSXWZ-XAG36NAB.js → pptx-YDKHIGCD-H7FU4VMJ.js} +2 -2
  270. package/dist/safe-bash/commands/bc/index.browser.js +2 -2
  271. package/dist/safe-bash/commands/diffpdf/index.d.ts +2 -0
  272. package/dist/safe-bash/commands/diffpdf/index.js +2 -0
  273. package/dist/safe-bash/commands/dot/index.d.ts +2 -0
  274. package/dist/safe-bash/commands/dot/index.js +2 -0
  275. package/dist/safe-bash/commands/llm/collections.browser.js +6 -0
  276. package/dist/safe-bash/commands/llm/collections.d.ts +2 -0
  277. package/dist/safe-bash/commands/llm/collections.js +2 -0
  278. package/dist/safe-bash/commands/pandoc/index.browser.js +1 -1
  279. package/dist/safe-bash/commands/rsvg-convert/index.d.ts +2 -0
  280. package/dist/safe-bash/commands/rsvg-convert/index.js +2 -0
  281. package/dist/safe-bash/commands/safejs/io.d.ts +1 -1
  282. package/dist/safe-bash/commands/safejs/io.js +1 -1
  283. package/dist/safe-bash/commands/safejs/options.d.ts +1 -1
  284. package/dist/safe-bash/commands/safejs/options.js +1 -1
  285. package/dist/safe-bash/commands/safejs/render.d.ts +1 -1
  286. package/dist/safe-bash/commands/safejs/render.js +1 -1
  287. package/dist/safe-bash/commands/safejs/runtime.d.ts +1 -1
  288. package/dist/safe-bash/commands/safejs/runtime.js +1 -1
  289. package/dist/safe-bash/commands/safejs/types.d.ts +1 -1
  290. package/dist/safe-bash/commands/safejs/types.js +1 -1
  291. package/dist/safe-bash/commands/wdiff/index.d.ts +2 -0
  292. package/dist/safe-bash/commands/wdiff/index.js +2 -0
  293. package/dist/safe-bash/core.d.ts +4 -0
  294. package/dist/safe-bash/core.js +4 -0
  295. package/dist/safe-bash/full-core.browser.js +59 -35
  296. package/dist/safe-bash/optional-host.browser.js +7 -7
  297. package/dist/safe-bash/plugins/index.browser.js +7 -7
  298. package/dist/safe-bash/registry-entry.browser.js +6 -6
  299. package/dist/safe-bash/search.browser.js +2 -2
  300. package/dist/safe-bash/shell-entry.browser.js +3 -3
  301. package/dist/safe-bash-checksum-engine/index.js +83 -40
  302. package/dist/safe-bash-checksum-engine/md5.d.ts +2 -0
  303. package/dist/safe-bash-checksum-engine/md5.js +7 -0
  304. package/dist/safe-bash-command-awk/awk-inspection.js +2 -2
  305. package/dist/safe-bash-command-awk/awk-runtime.js +2 -2
  306. package/dist/safe-bash-command-awk/awk.js +7 -7
  307. package/dist/safe-bash-command-awk/index.js +7 -7
  308. package/dist/safe-bash-command-chmod/command.js +1 -1
  309. package/dist/safe-bash-command-chmod/index.js +1 -1
  310. package/dist/safe-bash-command-csvkit/index.js +6 -6
  311. package/dist/safe-bash-command-diff/index.js +3 -3
  312. package/dist/safe-bash-command-diffpdf/LICENSE +21 -0
  313. package/dist/safe-bash-command-diffpdf/index.d.ts +12 -0
  314. package/dist/safe-bash-command-diffpdf/index.js +107 -0
  315. package/dist/safe-bash-command-docx/command.d.ts +36 -0
  316. package/dist/{safe-bash-docx-engine → safe-bash-command-docx}/discovery.d.ts +4 -4
  317. package/dist/safe-bash-command-docx/index.js +1 -1
  318. package/dist/{safe-bash-docx-engine → safe-bash-command-docx}/inspection-command.d.ts +6 -6
  319. package/dist/safe-bash-command-docx/sdk.d.ts +4 -0
  320. package/dist/safe-bash-command-docx/sdk.js +24 -0
  321. package/dist/safe-bash-command-dot/LICENSE +21 -0
  322. package/dist/safe-bash-command-dot/index.d.ts +14 -0
  323. package/dist/safe-bash-command-dot/index.js +1298 -0
  324. package/dist/safe-bash-command-du/arguments.d.ts +1 -1
  325. package/dist/safe-bash-command-du/arguments.js +1 -1
  326. package/dist/safe-bash-command-du/du.js +2 -2
  327. package/dist/safe-bash-command-du/index.js +2 -2
  328. package/dist/safe-bash-command-factor/command.js +2 -2
  329. package/dist/safe-bash-command-factor/index.js +2 -2
  330. package/dist/safe-bash-command-ffmpeg/index.js +16 -16
  331. package/dist/safe-bash-command-imagemagick/index.js +21 -53
  332. package/dist/safe-bash-command-llm/collections-embed.d.ts +23 -0
  333. package/dist/safe-bash-command-llm/collections.d.ts +38 -0
  334. package/dist/safe-bash-command-llm/collections.js +423 -0
  335. package/dist/safe-bash-command-llm/command.js +4 -2
  336. package/dist/safe-bash-command-llm/index.js +12 -8
  337. package/dist/safe-bash-command-llm/openai.js +4 -3
  338. package/dist/safe-bash-command-llm/providers/index.js +6 -4
  339. package/dist/safe-bash-command-llm/providers/openai.js +4 -3
  340. package/dist/safe-bash-command-node/commands/node/browser.js +9 -12
  341. package/dist/safe-bash-command-node/commands/node/buffer.js +2 -2
  342. package/dist/safe-bash-command-node/commands/node/default-runtime.js +9 -12
  343. package/dist/safe-bash-command-node/commands/node/filesystem.js +3 -3
  344. package/dist/safe-bash-command-node/commands/node/safejs.js +9 -12
  345. package/dist/safe-bash-command-node/commands/node/source-maps.js +2 -2
  346. package/dist/safe-bash-command-node/commands/node/timers.js +3 -3
  347. package/dist/safe-bash-command-node/commands/safejs/io.d.ts +1 -35
  348. package/dist/safe-bash-command-node/commands/safejs/io.js +3 -7
  349. package/dist/safe-bash-command-node/commands/safejs/options.d.ts +2 -22
  350. package/dist/safe-bash-command-node/commands/safejs/options.js +1 -1
  351. package/dist/safe-bash-command-node/commands/safejs/render.d.ts +1 -1
  352. package/dist/safe-bash-command-node/commands/safejs/render.js +3 -5
  353. package/dist/safe-bash-command-node/commands/safejs/runtime.d.ts +2 -25
  354. package/dist/safe-bash-command-node/commands/safejs/runtime.js +1 -7
  355. package/dist/safe-bash-command-node/commands/safejs/types.d.ts +2 -85
  356. package/dist/safe-bash-command-node/commands/safejs/types.js +1 -1
  357. package/dist/safe-bash-command-node/integrations/safejs/filesystem.d.ts +2 -5
  358. package/dist/safe-bash-command-node/integrations/safejs/filesystem.js +3 -3
  359. package/dist/safe-bash-command-node/integrations/safejs/shell.js +1 -1
  360. package/dist/safe-bash-command-node/integrations/safejs/values.d.ts +1 -7
  361. package/dist/safe-bash-command-node/integrations/safejs/values.js +1 -1
  362. package/dist/safe-bash-command-openssl/index.js +15452 -420
  363. package/dist/safe-bash-command-pandoc/command.js +1 -1
  364. package/dist/safe-bash-command-pandoc/index.js +1 -1
  365. package/dist/safe-bash-command-patch/index.js +5 -5
  366. package/dist/safe-bash-command-patch/patch.js +4 -4
  367. package/dist/safe-bash-command-playwright-cli/index.js +25 -25
  368. package/dist/safe-bash-command-playwright-cli/playwright/abilities.js +8 -8
  369. package/dist/safe-bash-command-playwright-cli/playwright/controller.js +16 -16
  370. package/dist/safe-bash-command-playwright-cli/playwright/index.js +25 -25
  371. package/dist/safe-bash-command-playwright-cli/playwright/standard-capabilities.js +4 -4
  372. package/dist/{safe-bash-pptx-engine → safe-bash-command-pptx}/command-engine.d.ts +5 -13
  373. package/dist/safe-bash-command-pptx/engine.d.ts +4 -0
  374. package/dist/safe-bash-command-pptx/engine.js +37 -0
  375. package/dist/safe-bash-command-pptx/index.js +1 -1
  376. package/dist/safe-bash-command-python/executor.js +15 -15
  377. package/dist/safe-bash-command-python/index.js +15 -15
  378. package/dist/safe-bash-command-python/jspi.js +4 -4
  379. package/dist/safe-bash-command-qrencode/index.js +1 -4
  380. package/dist/safe-bash-command-rsvg-convert/LICENSE +21 -0
  381. package/dist/safe-bash-command-rsvg-convert/index.d.ts +13 -0
  382. package/dist/safe-bash-command-rsvg-convert/index.js +84 -0
  383. package/dist/safe-bash-command-safejs/LICENSE +21 -0
  384. package/dist/safe-bash-command-safejs/filesystem.d.ts +5 -0
  385. package/dist/safe-bash-command-safejs/filesystem.js +7 -0
  386. package/dist/safe-bash-command-safejs/index.d.ts +4 -0
  387. package/dist/safe-bash-command-safejs/index.js +19 -0
  388. package/dist/safe-bash-command-safejs/io.d.ts +35 -0
  389. package/dist/safe-bash-command-safejs/io.js +12 -0
  390. package/dist/safe-bash-command-safejs/options.d.ts +22 -0
  391. package/dist/safe-bash-command-safejs/options.js +11 -0
  392. package/dist/safe-bash-command-safejs/render.d.ts +1 -0
  393. package/dist/safe-bash-command-safejs/render.js +9 -0
  394. package/dist/safe-bash-command-safejs/runtime.d.ts +25 -0
  395. package/dist/safe-bash-command-safejs/runtime.js +13 -0
  396. package/dist/safe-bash-command-safejs/types.d.ts +85 -0
  397. package/dist/safe-bash-command-safejs/types.js +7 -0
  398. package/dist/safe-bash-command-safejs/values.d.ts +7 -0
  399. package/dist/safe-bash-command-safejs/values.js +19 -0
  400. package/dist/safe-bash-command-sips/index.js +1 -14
  401. package/dist/safe-bash-command-ssconvert/index.js +413 -546
  402. package/dist/safe-bash-command-ssconvert/rendering/chart/axis.d.ts +1 -26
  403. package/dist/safe-bash-command-ssconvert/rendering/chart/error-bar.d.ts +1 -39
  404. package/dist/safe-bash-command-ssconvert/rendering/chart/layout.d.ts +1 -24
  405. package/dist/safe-bash-command-ssconvert/rendering/chart/line.d.ts +1 -23
  406. package/dist/safe-bash-command-ssconvert/rendering/chart/marker.d.ts +1 -35
  407. package/dist/safe-bash-command-ssconvert/rendering/chart/pie.d.ts +1 -32
  408. package/dist/safe-bash-command-ssconvert/rendering/images/index.d.ts +1 -26
  409. package/dist/safe-bash-command-ssconvert/rendering/print/header-footer.d.ts +1 -16
  410. package/dist/safe-bash-command-ssconvert/rendering/print/layout.d.ts +1 -65
  411. package/dist/safe-bash-command-ssconvert/rendering/print/pagination.d.ts +1 -34
  412. package/dist/safe-bash-command-tar/create.js +4 -4
  413. package/dist/safe-bash-command-tar/extract.js +4 -4
  414. package/dist/safe-bash-command-tar/index.js +16 -14
  415. package/dist/safe-bash-command-tar/modes.js +6 -6
  416. package/dist/safe-bash-command-tar/options.d.ts +3 -1
  417. package/dist/safe-bash-command-tar/options.js +1 -1
  418. package/dist/safe-bash-command-unzip/index.js +4 -4
  419. package/dist/safe-bash-command-wdiff/LICENSE +21 -0
  420. package/dist/safe-bash-command-wdiff/index.d.ts +12 -0
  421. package/dist/safe-bash-command-wdiff/index.js +123 -0
  422. package/dist/safe-bash-compression-engine/bounded-codec.js +2 -2
  423. package/dist/safe-bash-compression-engine/codec-loader.js +1 -1
  424. package/dist/safe-bash-compression-engine/files.js +5 -5
  425. package/dist/safe-bash-compression-engine/index.js +4 -4
  426. package/dist/safe-bash-compression-engine/operand.js +5 -5
  427. package/dist/safe-bash-compression-engine/stream.js +4 -4
  428. package/dist/safe-bash-compression-engine/zstd-decode.js +3 -3
  429. package/dist/safe-bash-contracts/escaping.js +2 -2
  430. package/dist/safe-bash-contracts/index.js +15 -15
  431. package/dist/safe-bash-docx-engine/admission.js +31 -0
  432. package/dist/safe-bash-docx-engine/ancillary-resources.js +38 -0
  433. package/dist/safe-bash-docx-engine/archive.js +24 -0
  434. package/dist/safe-bash-docx-engine/argument-json.js +25 -0
  435. package/dist/safe-bash-docx-engine/batch-operations.d.ts +7 -0
  436. package/dist/safe-bash-docx-engine/batch-operations.js +95 -0
  437. package/dist/safe-bash-docx-engine/batch-result-schema.d.ts +2 -0
  438. package/dist/safe-bash-docx-engine/batch-result-schema.js +145 -0
  439. package/dist/safe-bash-docx-engine/batch.js +106 -0
  440. package/dist/safe-bash-docx-engine/bookmarks.js +43 -0
  441. package/dist/safe-bash-docx-engine/budget.js +18 -0
  442. package/dist/safe-bash-docx-engine/charts.js +35 -0
  443. package/dist/safe-bash-docx-engine/command-option-rules.d.ts +1 -0
  444. package/dist/safe-bash-docx-engine/command-option-rules.js +24 -0
  445. package/dist/safe-bash-docx-engine/command-properties.d.ts +1 -0
  446. package/dist/safe-bash-docx-engine/command-properties.js +18 -0
  447. package/dist/safe-bash-docx-engine/command-selection.d.ts +1 -0
  448. package/dist/safe-bash-docx-engine/command-selection.js +15 -0
  449. package/dist/safe-bash-docx-engine/comments.js +53 -0
  450. package/dist/safe-bash-docx-engine/control-bindings.js +45 -0
  451. package/dist/safe-bash-docx-engine/control-repeat.js +46 -0
  452. package/dist/safe-bash-docx-engine/controls.js +52 -0
  453. package/dist/safe-bash-docx-engine/create.js +36 -0
  454. package/dist/safe-bash-docx-engine/diagrams.js +43 -0
  455. package/dist/safe-bash-docx-engine/diff.js +33 -0
  456. package/dist/safe-bash-docx-engine/discovery-result-schema.d.ts +72 -0
  457. package/dist/safe-bash-docx-engine/discovery-result-schema.js +36 -0
  458. package/dist/safe-bash-docx-engine/document-properties.js +43 -0
  459. package/dist/safe-bash-docx-engine/equations.js +53 -0
  460. package/dist/safe-bash-docx-engine/extract.js +40 -0
  461. package/dist/safe-bash-docx-engine/fields.js +48 -0
  462. package/dist/safe-bash-docx-engine/font-inventory.js +40 -0
  463. package/dist/safe-bash-docx-engine/font-resources.js +33 -0
  464. package/dist/safe-bash-docx-engine/image-batch-operations.d.ts +4 -0
  465. package/dist/safe-bash-docx-engine/image-batch-operations.js +35 -0
  466. package/dist/safe-bash-docx-engine/image-insertion.js +46 -0
  467. package/dist/safe-bash-docx-engine/image-layout.js +43 -0
  468. package/dist/safe-bash-docx-engine/image-replacement.js +48 -0
  469. package/dist/safe-bash-docx-engine/images.js +49 -0
  470. package/dist/safe-bash-docx-engine/index.d.ts +1 -3
  471. package/dist/safe-bash-docx-engine/index.js +369 -19350
  472. package/dist/safe-bash-docx-engine/inspection.js +49 -0
  473. package/dist/safe-bash-docx-engine/invocation.d.ts +50 -0
  474. package/dist/safe-bash-docx-engine/invocation.js +66 -0
  475. package/dist/safe-bash-docx-engine/io-errors.js +11 -0
  476. package/dist/safe-bash-docx-engine/io.js +29 -0
  477. package/dist/safe-bash-docx-engine/links.js +47 -0
  478. package/dist/safe-bash-docx-engine/lists.js +46 -0
  479. package/dist/safe-bash-docx-engine/location-token.js +27 -0
  480. package/dist/safe-bash-docx-engine/locations.js +39 -0
  481. package/dist/safe-bash-docx-engine/model-context.js +15 -0
  482. package/dist/safe-bash-docx-engine/model-errors.js +13 -0
  483. package/dist/safe-bash-docx-engine/notes.js +48 -0
  484. package/dist/safe-bash-docx-engine/objects.js +49 -0
  485. package/dist/safe-bash-docx-engine/operation-json-schema.js +21 -0
  486. package/dist/safe-bash-docx-engine/operation-schema.js +29 -0
  487. package/dist/safe-bash-docx-engine/pack-uri-batch-operations.d.ts +3 -0
  488. package/dist/safe-bash-docx-engine/pack-uri-batch-operations.js +15 -0
  489. package/dist/safe-bash-docx-engine/pack.js +38 -0
  490. package/dist/safe-bash-docx-engine/package-view-batch-operations.d.ts +4 -0
  491. package/dist/safe-bash-docx-engine/package-view-batch-operations.js +47 -0
  492. package/dist/safe-bash-docx-engine/package-xml.js +25 -0
  493. package/dist/safe-bash-docx-engine/pandoc-adapter.js +55 -6
  494. package/dist/safe-bash-docx-engine/paragraph-edit.js +52 -0
  495. package/dist/safe-bash-docx-engine/part-provider.js +18 -0
  496. package/dist/safe-bash-docx-engine/property-values.js +46 -0
  497. package/dist/safe-bash-docx-engine/publication.js +40 -0
  498. package/dist/safe-bash-docx-engine/removal.js +44 -0
  499. package/dist/safe-bash-docx-engine/revision-decisions.js +46 -0
  500. package/dist/safe-bash-docx-engine/revision-edit.js +43 -0
  501. package/dist/safe-bash-docx-engine/revisions.js +42 -0
  502. package/dist/safe-bash-docx-engine/run-format.js +43 -0
  503. package/dist/safe-bash-docx-engine/sanitize.js +59 -0
  504. package/dist/safe-bash-docx-engine/sections.js +47 -0
  505. package/dist/safe-bash-docx-engine/settings.js +36 -0
  506. package/dist/safe-bash-docx-engine/shape-edit.js +47 -0
  507. package/dist/safe-bash-docx-engine/signatures.js +42 -0
  508. package/dist/safe-bash-docx-engine/simple-selection.d.ts +1 -1
  509. package/dist/safe-bash-docx-engine/stories.js +48 -0
  510. package/dist/safe-bash-docx-engine/structure-model-batch-operations.d.ts +3 -0
  511. package/dist/safe-bash-docx-engine/structure-model-batch-operations.js +64 -0
  512. package/dist/safe-bash-docx-engine/style-model-batch-operations.js +57 -0
  513. package/dist/safe-bash-docx-engine/style-model-result-schema.d.ts +4 -0
  514. package/dist/safe-bash-docx-engine/style-model-result-schema.js +76 -0
  515. package/dist/safe-bash-docx-engine/styles.js +44 -0
  516. package/dist/safe-bash-docx-engine/table-edit.js +52 -0
  517. package/dist/safe-bash-docx-engine/table-read.js +38 -0
  518. package/dist/safe-bash-docx-engine/template.js +45 -0
  519. package/dist/safe-bash-docx-engine/text-replace.js +47 -0
  520. package/dist/safe-bash-docx-engine/text-resource-read.js +42 -0
  521. package/dist/safe-bash-docx-engine/text.js +36 -0
  522. package/dist/safe-bash-docx-engine/validation.js +30 -0
  523. package/dist/safe-bash-docx-engine/xml-parts.js +48 -0
  524. package/dist/safe-bash-markdown-engine/index.js +3 -3
  525. package/dist/safe-bash-network-engine/aggregate.js +3 -3
  526. package/dist/safe-bash-network-engine/args.js +3 -3
  527. package/dist/safe-bash-network-engine/body.js +4 -4
  528. package/dist/safe-bash-network-engine/decode.js +3 -3
  529. package/dist/safe-bash-network-engine/fetch-transport.js +3 -3
  530. package/dist/safe-bash-network-engine/index.js +3 -3
  531. package/dist/safe-bash-network-engine/output.js +3 -3
  532. package/dist/safe-bash-network-engine/platform-portable.js +3 -3
  533. package/dist/safe-bash-network-engine/shared.js +2 -2
  534. package/dist/safe-bash-network-engine/transfer.js +20 -20
  535. package/dist/safe-bash-pptx-engine/bytes.d.ts +1 -4
  536. package/dist/safe-bash-pptx-engine/bytes.js +2 -11
  537. package/dist/safe-bash-pptx-engine/index.d.ts +1 -103
  538. package/dist/safe-bash-pptx-engine/index.js +1 -662
  539. package/dist/safe-bash-presentation-engine/LICENSE +21 -0
  540. package/dist/safe-bash-presentation-engine/accessibility.js +43 -0
  541. package/dist/safe-bash-presentation-engine/animation-editing.js +29 -0
  542. package/dist/safe-bash-presentation-engine/animations.js +23 -0
  543. package/dist/safe-bash-presentation-engine/backgrounds.js +26 -0
  544. package/dist/safe-bash-presentation-engine/bytes.d.ts +4 -0
  545. package/dist/safe-bash-presentation-engine/bytes.js +13 -0
  546. package/dist/safe-bash-presentation-engine/chart-editing.js +60 -0
  547. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/chart-enums.d.ts +2 -2
  548. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/chart-object-operations.d.ts +1 -1
  549. package/dist/safe-bash-presentation-engine/chart-object-operations.js +35 -0
  550. package/dist/safe-bash-presentation-engine/charts.js +41 -0
  551. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/color-enums.d.ts +5 -5
  552. package/dist/safe-bash-presentation-engine/command-placeholder.js +64 -0
  553. package/dist/safe-bash-presentation-engine/comments.js +32 -0
  554. package/dist/safe-bash-presentation-engine/connector-operations.js +50 -0
  555. package/dist/safe-bash-presentation-engine/connectors.js +49 -0
  556. package/dist/safe-bash-presentation-engine/content-types.js +9 -0
  557. package/dist/safe-bash-presentation-engine/contracts.js +0 -0
  558. package/dist/safe-bash-presentation-engine/creation.js +15 -0
  559. package/dist/safe-bash-presentation-engine/diff.js +40 -0
  560. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/drawing-enums.d.ts +20 -20
  561. package/dist/safe-bash-presentation-engine/drawing-format.js +44 -0
  562. package/dist/safe-bash-presentation-engine/drawing-operations.js +41 -0
  563. package/dist/safe-bash-presentation-engine/drawing-schema.d.ts +1549 -0
  564. package/dist/safe-bash-presentation-engine/drawing-schema.js +33 -0
  565. package/dist/safe-bash-presentation-engine/equations.js +30 -0
  566. package/dist/safe-bash-presentation-engine/errors.js +23 -0
  567. package/dist/safe-bash-presentation-engine/fields.js +32 -0
  568. package/dist/safe-bash-presentation-engine/font-metrics.js +12 -0
  569. package/dist/safe-bash-presentation-engine/image-extraction.js +29 -0
  570. package/dist/safe-bash-presentation-engine/image-formatting.js +43 -0
  571. package/dist/safe-bash-presentation-engine/image-insertion.js +26 -0
  572. package/dist/safe-bash-presentation-engine/image-metadata.d.ts +9 -0
  573. package/dist/safe-bash-presentation-engine/image-metadata.js +9 -0
  574. package/dist/safe-bash-presentation-engine/image-replacement.js +30 -0
  575. package/dist/safe-bash-presentation-engine/image-value.js +15 -0
  576. package/dist/safe-bash-presentation-engine/images.js +30 -0
  577. package/dist/safe-bash-presentation-engine/index.d.ts +100 -0
  578. package/dist/safe-bash-presentation-engine/index.js +791 -0
  579. package/dist/safe-bash-presentation-engine/layouts.js +31 -0
  580. package/dist/safe-bash-presentation-engine/length.js +21 -0
  581. package/dist/safe-bash-presentation-engine/links.js +33 -0
  582. package/dist/safe-bash-presentation-engine/masters.js +54 -0
  583. package/dist/safe-bash-presentation-engine/media-editing.js +35 -0
  584. package/dist/safe-bash-presentation-engine/media-extraction.js +24 -0
  585. package/dist/safe-bash-presentation-engine/media.js +23 -0
  586. package/dist/safe-bash-presentation-engine/memberships.js +24 -0
  587. package/dist/safe-bash-presentation-engine/notes.js +27 -0
  588. package/dist/safe-bash-presentation-engine/ole-enum.js +10 -0
  589. package/dist/safe-bash-presentation-engine/ole-insertion.js +29 -0
  590. package/dist/safe-bash-presentation-engine/opaque-objects.js +21 -0
  591. package/dist/safe-bash-presentation-engine/package-reader.js +13 -0
  592. package/dist/safe-bash-presentation-engine/package-tools.js +25 -0
  593. package/dist/safe-bash-presentation-engine/package-uri.d.ts +13 -0
  594. package/dist/safe-bash-presentation-engine/package-uri.js +16 -0
  595. package/dist/safe-bash-presentation-engine/package-writer.js +13 -0
  596. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/presentation-model.d.ts +1 -1
  597. package/dist/safe-bash-presentation-engine/presentation-model.js +63 -0
  598. package/dist/safe-bash-presentation-engine/presentation-settings.js +25 -0
  599. package/dist/safe-bash-presentation-engine/properties.js +37 -0
  600. package/dist/safe-bash-presentation-engine/publication.d.ts +10 -0
  601. package/dist/safe-bash-presentation-engine/publication.js +0 -0
  602. package/dist/safe-bash-presentation-engine/relationships.js +16 -0
  603. package/dist/safe-bash-presentation-engine/resource-limits.js +8 -0
  604. package/dist/safe-bash-presentation-engine/sanitize.js +24 -0
  605. package/dist/safe-bash-presentation-engine/selector-schema.js +7 -0
  606. package/dist/safe-bash-presentation-engine/selectors.js +26 -0
  607. package/dist/safe-bash-presentation-engine/shape-groups.js +47 -0
  608. package/dist/safe-bash-presentation-engine/shape-operations.js +48 -0
  609. package/dist/safe-bash-presentation-engine/shape-path-operations.js +44 -0
  610. package/dist/safe-bash-presentation-engine/shape-paths.js +31 -0
  611. package/dist/safe-bash-presentation-engine/shape-presets.js +11 -0
  612. package/dist/safe-bash-presentation-engine/shape-selection.js +43 -0
  613. package/dist/safe-bash-presentation-engine/shape-transforms.js +28 -0
  614. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/shape-types.d.ts +1 -1
  615. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/shapes.d.ts +1 -1
  616. package/dist/safe-bash-presentation-engine/shapes.js +66 -0
  617. package/dist/safe-bash-presentation-engine/slide-copy.js +24 -0
  618. package/dist/safe-bash-presentation-engine/slide-import.js +27 -0
  619. package/dist/safe-bash-presentation-engine/slide-merge-split.js +33 -0
  620. package/dist/safe-bash-presentation-engine/slide-model.js +74 -0
  621. package/dist/safe-bash-presentation-engine/slide-removal.js +25 -0
  622. package/dist/safe-bash-presentation-engine/slide-transfer-budget.js +17 -0
  623. package/dist/safe-bash-presentation-engine/slides.js +26 -0
  624. package/dist/safe-bash-presentation-engine/table-operations.js +51 -0
  625. package/dist/safe-bash-presentation-engine/table-spans.js +42 -0
  626. package/dist/safe-bash-presentation-engine/tables.js +45 -0
  627. package/dist/safe-bash-presentation-engine/tags.js +25 -0
  628. package/dist/safe-bash-presentation-engine/template-bindings.js +44 -0
  629. package/dist/safe-bash-presentation-engine/template-repeat.js +51 -0
  630. package/dist/safe-bash-presentation-engine/text-fitting.js +39 -0
  631. package/dist/safe-bash-presentation-engine/text-frames.js +52 -0
  632. package/dist/safe-bash-presentation-engine/text-paragraphs.js +58 -0
  633. package/dist/safe-bash-presentation-engine/text-reading.js +23 -0
  634. package/dist/safe-bash-presentation-engine/text-replacement.js +24 -0
  635. package/dist/safe-bash-presentation-engine/text-runs.js +45 -0
  636. package/dist/safe-bash-presentation-engine/themes.js +31 -0
  637. package/dist/safe-bash-presentation-engine/transitions.js +27 -0
  638. package/dist/safe-bash-presentation-engine/validation.js +14 -0
  639. package/dist/safe-bash-presentation-engine/xml-parts.js +25 -0
  640. package/dist/safe-bash-presentation-engine/xml-view.js +8 -0
  641. package/dist/safe-bash-presentation-engine/xml.js +8 -0
  642. package/dist/safe-bash-sqlite-engine/sqlite-edit-snapshot.d.ts +15 -0
  643. package/dist/safe-bash-sqlite-engine/sqlite-finalization.d.ts +7 -0
  644. package/dist/safe-bash-sqlite-engine/sqlite-pages.d.ts +18 -0
  645. package/dist/safe-bash-sqlite-engine/sqlite-record-read.d.ts +8 -0
  646. package/dist/safe-bash-sqlite-engine/sqlite-record-write.d.ts +20 -0
  647. package/dist/safe-bash-sqlite-engine/storage.d.ts +2 -0
  648. package/dist/safe-bash-sqlite-engine/storage.js +236 -55
  649. package/dist/safe-bash-svg-engine/LICENSE +21 -0
  650. package/dist/safe-bash-svg-engine/index.d.ts +8 -0
  651. package/dist/safe-bash-svg-engine/index.js +477 -0
  652. package/dist/safe-bash-zip-engine/index.js +3 -3
  653. package/dist/safe-bash-zip-engine/zip/repair.js +3 -3
  654. package/dist/safe-bash-zip-engine/zip/sfx.js +3 -3
  655. package/dist/safe-bash-zip-engine/zip-format.js +3 -3
  656. package/dist/safe-playwright-cloudflare/browser-provider.generated.js +55 -18
  657. package/dist/safe-playwright-cloudflare/browser-run-code-guest.generated.js +1 -1
  658. package/dist/spreadsheet-engine/datasource.js +4 -1
  659. package/dist/spreadsheet-engine/formulas/functions/math.js +3 -1
  660. package/dist/spreadsheet-engine/rendering/chart/axis.d.ts +26 -0
  661. package/dist/spreadsheet-engine/rendering/chart/axis.js +61 -0
  662. package/dist/spreadsheet-engine/rendering/chart/error-bar.d.ts +39 -0
  663. package/dist/spreadsheet-engine/rendering/chart/error-bar.js +59 -0
  664. package/dist/spreadsheet-engine/rendering/chart/layout.d.ts +24 -0
  665. package/dist/spreadsheet-engine/rendering/chart/layout.js +54 -0
  666. package/dist/spreadsheet-engine/rendering/chart/line.d.ts +23 -0
  667. package/dist/spreadsheet-engine/rendering/chart/line.js +56 -0
  668. package/dist/spreadsheet-engine/rendering/chart/marker.d.ts +35 -0
  669. package/dist/spreadsheet-engine/rendering/chart/marker.js +52 -0
  670. package/dist/spreadsheet-engine/rendering/chart/pie.d.ts +32 -0
  671. package/dist/spreadsheet-engine/rendering/chart/pie.js +47 -0
  672. package/dist/{safe-bash-command-ssconvert → spreadsheet-engine}/rendering/images/codecs.d.ts +0 -1
  673. package/dist/spreadsheet-engine/rendering/images/codecs.js +253 -0
  674. package/dist/spreadsheet-engine/rendering/images/index.d.ts +26 -0
  675. package/dist/spreadsheet-engine/rendering/images/index.js +144 -0
  676. package/dist/spreadsheet-engine/rendering/images/profile-raster.d.ts +4 -0
  677. package/dist/spreadsheet-engine/rendering/images/profile-raster.js +72 -0
  678. package/dist/spreadsheet-engine/rendering/images/scene.d.ts +3 -0
  679. package/dist/spreadsheet-engine/rendering/images/scene.js +34 -0
  680. package/dist/spreadsheet-engine/rendering/print/cell-style.d.ts +10 -0
  681. package/dist/spreadsheet-engine/rendering/print/cell-style.js +52 -0
  682. package/dist/spreadsheet-engine/rendering/print/font-normalization-data.d.ts +43 -0
  683. package/dist/spreadsheet-engine/rendering/print/font-normalization-data.js +1558 -0
  684. package/dist/spreadsheet-engine/rendering/print/font-normalization.d.ts +3 -0
  685. package/dist/spreadsheet-engine/rendering/print/font-normalization.js +113 -0
  686. package/dist/spreadsheet-engine/rendering/print/font-shaping.d.ts +18 -0
  687. package/dist/spreadsheet-engine/rendering/print/font-shaping.js +271 -0
  688. package/dist/spreadsheet-engine/rendering/print/harfbuzz/data.d.ts +1 -0
  689. package/dist/spreadsheet-engine/rendering/print/harfbuzz/data.js +2 -0
  690. package/dist/spreadsheet-engine/rendering/print/header-footer.d.ts +16 -0
  691. package/dist/spreadsheet-engine/rendering/print/header-footer.js +92 -0
  692. package/dist/spreadsheet-engine/rendering/print/layout.d.ts +65 -0
  693. package/dist/spreadsheet-engine/rendering/print/layout.js +75 -0
  694. package/dist/spreadsheet-engine/rendering/print/pagination.d.ts +34 -0
  695. package/dist/spreadsheet-engine/rendering/print/pagination.js +126 -0
  696. package/dist/spreadsheet-engine/rendering/print/settings.d.ts +42 -0
  697. package/dist/spreadsheet-engine/rendering/print/settings.js +159 -0
  698. package/dist/spreadsheet-format-xls/biff-metadata.js +3 -3
  699. package/dist/spreadsheet-format-xls/biff-write-metadata.d.ts +1 -1
  700. package/dist/spreadsheet-format-xls/biff-write-metadata.js +20 -3
  701. package/dist/spreadsheet-format-xls/biff-write.js +1 -1
  702. package/package.json +239 -12
  703. package/third-party/spreadsheet-engine/scripts/harfbuzz/README.md +39 -0
  704. package/third-party/spreadsheet-engine/scripts/harfbuzz/allocator.cc +18 -0
  705. package/third-party/spreadsheet-engine/scripts/harfbuzz/build.mjs +94 -0
  706. package/third-party/spreadsheet-engine/scripts/harfbuzz/completion.patch +98 -0
  707. package/third-party/spreadsheet-engine/scripts/harfbuzz/config-override.h +19 -0
  708. package/third-party/spreadsheet-engine/scripts/harfbuzz/exports.json +29 -0
  709. package/third-party/spreadsheet-engine/scripts/harfbuzz/sources.json +274 -0
  710. package/third-party/spreadsheet-engine/scripts/harfbuzz/verify.d.mts +10 -0
  711. package/third-party/spreadsheet-engine/scripts/harfbuzz/verify.mjs +96 -0
  712. package/third-party/spreadsheet-engine/scripts/harfbuzz/verify.test.mjs +60 -0
  713. package/third-party/spreadsheet-engine/src/rendering/images/NOTICE.md +22 -0
  714. package/third-party/spreadsheet-engine/src/rendering/print/NOTICE.md +30 -0
  715. package/third-party/spreadsheet-engine/src/rendering/print/font-normalization-NOTICE.md +64 -0
  716. package/third-party/spreadsheet-engine/src/rendering/print/font-normalization-data.ts +1558 -0
  717. package/third-party/spreadsheet-engine/src/rendering/print/font-normalization.ts +91 -0
  718. package/third-party/spreadsheet-engine/src/rendering/print/harfbuzz/EMSCRIPTEN-LICENSE.txt +102 -0
  719. package/third-party/spreadsheet-engine/src/rendering/print/harfbuzz/HARFBUZZ-LICENSE.txt +42 -0
  720. package/third-party/spreadsheet-engine/src/rendering/print/harfbuzz/LIBCXX-LICENSE.txt +311 -0
  721. package/third-party/spreadsheet-engine/src/rendering/print/harfbuzz/LIBCXXABI-LICENSE.txt +311 -0
  722. package/third-party/spreadsheet-engine/src/rendering/print/harfbuzz/MUSL-LICENSE.txt +193 -0
  723. package/third-party/spreadsheet-engine/src/rendering/print/harfbuzz/NOTICE.md +41 -0
  724. package/third-party/spreadsheet-engine/src/rendering/print/harfbuzz/data.ts +2 -0
  725. package/dist/safe-bash/command-chunks/chunk-C5TUE2FE.js +0 -169
  726. package/dist/safe-bash/command-chunks/chunk-CVKW2YIC.js +0 -13631
  727. package/dist/safe-bash/command-chunks/chunk-JBGGUHQY.js +0 -17617
  728. package/dist/safe-bash/command-chunks/chunk-S4R2JDPL.js +0 -35
  729. package/dist/safe-bash/command-chunks/chunk-TU5IFVCX.js +0 -33708
  730. package/dist/safe-bash/command-chunks/chunk-TUWGIF22.js +0 -328
  731. package/dist/safe-bash/command-chunks/data-2FJOPYXA-PDKMLCGR.js +0 -8
  732. package/dist/safe-bash/command-chunks/index.browser-2NLML6H4.js +0 -269
  733. package/dist/safe-bash/command-chunks/model-store-EEI3QS4G.js +0 -10
  734. package/dist/safe-bash/command-chunks/pdf-M2GFAR2A-FCJMJCAP.js +0 -683
  735. package/dist/safe-bash-command-ssconvert/rendering/images/formats.d.ts +0 -2
  736. package/dist/safe-bash-docx-engine/command.d.ts +0 -65
  737. package/dist/safe-bash/chunks/{chunk-4T4RQYRI.js → chunk-5HRGBHZH.js} +10 -10
  738. package/dist/safe-bash/chunks/{chunk-QUS6X4MS.js → chunk-EOQMDRTY.js} +0 -0
  739. package/dist/safe-bash/command-chunks/{chunk-2L3JKGUH.js → chunk-4LYZBDZF.js} +4 -4
  740. package/dist/safe-bash/command-chunks/{chunk-EMMSXKEJ.js → chunk-4Q4R3VZU.js} +0 -0
  741. package/dist/safe-bash/command-chunks/{chunk-5RLK2QSY.js → chunk-7JEIWA3A.js} +5 -5
  742. package/dist/safe-bash/command-chunks/{chunk-AV6N7DDA.js → chunk-DDYPQAXN.js} +3 -3
  743. package/dist/safe-bash/command-chunks/{chunk-OOB7YCFQ.js → chunk-FMJKCVSQ.js} +3 -3
  744. package/dist/safe-bash/command-chunks/{chunk-FUL2C4EX.js → chunk-HFKS6AET.js} +3 -3
  745. package/dist/safe-bash/command-chunks/{chunk-2M3WUEDX.js → chunk-J6K5Q53O.js} +10 -10
  746. package/dist/safe-bash/command-chunks/{chunk-ATWMLV75.js → chunk-RJXZYDSN.js} +7 -7
  747. package/dist/safe-bash/command-chunks/{chunk-JD3NSHFT.js → chunk-TVGIJ56E.js} +3 -3
  748. package/dist/safe-bash/command-chunks/{chunk-3I33KPQH.js → chunk-X2HVVMTW.js} +6 -6
  749. package/dist/safe-bash/command-chunks/{odf-UKSXPNOZ-NCL5P7YL.js → odf-UKSXPNOZ-BV2LCKTB.js} +0 -0
  750. package/dist/{safe-bash/command-chunks/chunk-3SVT5VB7.js → safe-bash-docx-engine/operation-types.js} +0 -0
  751. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/accessibility.d.ts +0 -0
  752. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/animation-editing.d.ts +0 -0
  753. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/animations.d.ts +0 -0
  754. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/backgrounds.d.ts +0 -0
  755. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/chart-data-model.d.ts +0 -0
  756. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/chart-editing.d.ts +0 -0
  757. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/chart-font-operations.d.ts +0 -0
  758. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/chart-model-axes.d.ts +0 -0
  759. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/chart-model-core.d.ts +0 -0
  760. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/chart-model-series.d.ts +0 -0
  761. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/chart-model.d.ts +0 -0
  762. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/chart-objects.d.ts +0 -0
  763. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/chart-workbook.d.ts +0 -0
  764. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/charts.d.ts +0 -0
  765. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/command-placeholder.d.ts +0 -0
  766. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/comments.d.ts +0 -0
  767. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/connector-operations.d.ts +0 -0
  768. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/connectors-model.d.ts +0 -0
  769. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/connectors.d.ts +0 -0
  770. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/content-types.d.ts +0 -0
  771. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/contracts.d.ts +0 -0
  772. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/creation.d.ts +0 -0
  773. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/diagram-resources.d.ts +0 -0
  774. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/diff.d.ts +0 -0
  775. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/drawing-format.d.ts +0 -0
  776. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/drawing-operations.d.ts +0 -0
  777. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/equations.d.ts +0 -0
  778. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/errors.d.ts +0 -0
  779. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/fields.d.ts +0 -0
  780. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/font-metrics.d.ts +0 -0
  781. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/freeform-builder.d.ts +0 -0
  782. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/group-model.d.ts +0 -0
  783. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/image-extraction.d.ts +0 -0
  784. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/image-formatting.d.ts +0 -0
  785. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/image-insertion.d.ts +0 -0
  786. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/image-replacement.d.ts +0 -0
  787. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/image-value.d.ts +0 -0
  788. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/images.d.ts +0 -0
  789. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/inventory.d.ts +0 -0
  790. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/language-enum.d.ts +0 -0
  791. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/layouts.d.ts +0 -0
  792. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/length.d.ts +0 -0
  793. package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/links-model.d.ts +4 -4
  794. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/links.d.ts +0 -0
  795. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/masters.d.ts +0 -0
  796. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/media-editing.d.ts +0 -0
  797. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/media-enum.d.ts +0 -0
  798. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/media-extraction.d.ts +0 -0
  799. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/media.d.ts +0 -0
  800. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/memberships.d.ts +0 -0
  801. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/modern-comments.d.ts +0 -0
  802. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/notes.d.ts +0 -0
  803. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/ole-enum.d.ts +0 -0
  804. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/ole-insertion.d.ts +0 -0
  805. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/opaque-objects.d.ts +0 -0
  806. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/package-reader.d.ts +0 -0
  807. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/package-tools.d.ts +0 -0
  808. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/package-view.d.ts +0 -0
  809. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/package-writer.d.ts +0 -0
  810. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/paragraph-alignment.d.ts +0 -0
  811. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/presentation-settings.d.ts +0 -0
  812. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/properties.d.ts +0 -0
  813. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/relationships.d.ts +0 -0
  814. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/resource-limits.d.ts +0 -0
  815. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/sanitize.d.ts +0 -0
  816. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/selector-schema.d.ts +0 -0
  817. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/selectors.d.ts +0 -0
  818. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/shape-adjustments.d.ts +0 -0
  819. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/shape-groups.d.ts +0 -0
  820. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/shape-operations.d.ts +0 -0
  821. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/shape-path-operations.d.ts +0 -0
  822. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/shape-paths.d.ts +0 -0
  823. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/shape-placeholder-types.d.ts +0 -0
  824. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/shape-presets.d.ts +0 -0
  825. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/shape-selection.d.ts +0 -0
  826. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/shape-transforms.d.ts +0 -0
  827. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/slide-copy.d.ts +0 -0
  828. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/slide-import.d.ts +0 -0
  829. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/slide-layout-model.d.ts +0 -0
  830. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/slide-merge-split.d.ts +0 -0
  831. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/slide-model.d.ts +0 -0
  832. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/slide-removal.d.ts +0 -0
  833. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/slide-transfer-budget.d.ts +0 -0
  834. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/slides.d.ts +0 -0
  835. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/table-operations.d.ts +0 -0
  836. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/table-spans.d.ts +0 -0
  837. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/tables-model.d.ts +0 -0
  838. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/tables.d.ts +0 -0
  839. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/tags.d.ts +0 -0
  840. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/template-bindings.d.ts +0 -0
  841. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/template-repeat.d.ts +0 -0
  842. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/text-fitting.d.ts +0 -0
  843. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/text-frame-enums.d.ts +0 -0
  844. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/text-frames.d.ts +0 -0
  845. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/text-paragraphs.d.ts +0 -0
  846. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/text-reading.d.ts +0 -0
  847. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/text-replacement.d.ts +0 -0
  848. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/text-run-color.d.ts +0 -0
  849. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/text-runs.d.ts +0 -0
  850. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/text-style-resolution.d.ts +0 -0
  851. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/themes.d.ts +0 -0
  852. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/transitions.d.ts +0 -0
  853. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/validation.d.ts +0 -0
  854. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/xml-parts.d.ts +0 -0
  855. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/xml-view.d.ts +0 -0
  856. /package/dist/{safe-bash-pptx-engine → safe-bash-presentation-engine}/xml.d.ts +0 -0
@@ -0,0 +1,2849 @@
1
+ // packages/safe-bash-command-docx/src/inspection-command.ts
2
+ import { contextData } from "../../safe-bash-docx-engine/model-context.js";
3
+
4
+ // packages/safe-bash-command-docx/src/discovery.ts
5
+ import { packUriBatchActions } from "../../safe-bash-docx-engine/pack-uri-batch-operations.js";
6
+ import { inspectDocument } from "../../safe-bash-docx-engine/inspection.js";
7
+ import { documentBatchOperations } from "../../safe-bash-docx-engine/batch-operations.js";
8
+ import { documentBatchResultSchema } from "../../safe-bash-docx-engine/batch-result-schema.js";
9
+ import { packageViewBatchActions } from "../../safe-bash-docx-engine/package-view-batch-operations.js";
10
+ import { styleModelBatchOperations as styleOperations } from "../../safe-bash-docx-engine/style-model-batch-operations.js";
11
+ import { structureModelBatchActions } from "../../safe-bash-docx-engine/structure-model-batch-operations.js";
12
+ import { imageBatchActions } from "../../safe-bash-docx-engine/image-batch-operations.js";
13
+ import { styleModelOperationResultSchema } from "../../safe-bash-docx-engine/style-model-result-schema.js";
14
+
15
+ // packages/safe-bash-command-docx/package.json
16
+ var package_default = {
17
+ name: "safe-bash-command-docx",
18
+ version: "0.0.1",
19
+ private: true,
20
+ license: "MIT",
21
+ type: "module",
22
+ main: "dist/index.js",
23
+ types: "dist/index.d.ts",
24
+ exports: {
25
+ ".": {
26
+ types: "./dist/index.d.ts",
27
+ workerd: "./dist/index.js",
28
+ browser: "./dist/index.js",
29
+ import: "./dist/index.js"
30
+ },
31
+ "./io": {
32
+ types: "./dist/io.d.ts",
33
+ workerd: "./dist/io.js",
34
+ browser: "./dist/io.js",
35
+ import: "./dist/io.js"
36
+ },
37
+ "./sdk": {
38
+ types: "./dist/sdk.d.ts",
39
+ import: "./dist/sdk.js"
40
+ }
41
+ },
42
+ files: [
43
+ "dist",
44
+ "LICENSE"
45
+ ],
46
+ scripts: {
47
+ build: "node ../../scripts/guard-package-dist.mjs && tsc",
48
+ typecheck: "tsc --noEmit && tsc -p tsconfig.test.json",
49
+ lint: "eslint src tests && npm run typecheck",
50
+ test: "cd ../.. && vitest run packages/safe-bash-command-docx",
51
+ "test:unit": "cd ../.. && vitest run packages/safe-bash-command-docx"
52
+ },
53
+ dependencies: {},
54
+ devDependencies: {
55
+ "safe-bash-contracts": "*",
56
+ "@poe-code/safe-fs": "*",
57
+ "safe-bash-docx-engine": "*",
58
+ "@poe-code/terminal-text": "*"
59
+ }
60
+ };
61
+
62
+ // packages/terminal-text/src/index.ts
63
+ function escapeTerminalText(text) {
64
+ let result = "";
65
+ for (const character of text) {
66
+ const code = character.codePointAt(0);
67
+ if (code <= 31 || code >= 127 && code <= 159 || code === 1564 || code === 8206 || code === 8207 || code >= 8234 && code <= 8238 || code >= 8294 && code <= 8297) {
68
+ result += `\\u${code.toString(16).padStart(4, "0")}`;
69
+ } else {
70
+ result += character;
71
+ }
72
+ }
73
+ return result;
74
+ }
75
+
76
+ // packages/safe-bash-command-docx/src/discovery.ts
77
+ import { documentValidationProfile } from "../../safe-bash-docx-engine/validation.js";
78
+ import { DocumentBudget as DocumentBudget2 } from "../../safe-bash-docx-engine/budget.js";
79
+
80
+ // packages/safe-bash-command-docx/src/command.ts
81
+ import { path, usage, schemaFor, optionFields, lowerLimits, validateDocxBatch, validateSelections, docxInvocationBudgets, validateInvocation, SourceError } from "../../safe-bash-docx-engine/invocation.js";
82
+ import { BoundsError } from "../../safe-bash-docx-engine/model-errors.js";
83
+ import { DocumentBudget } from "../../safe-bash-docx-engine/budget.js";
84
+ import { ResourceLimitError } from "../../safe-bash-docx-engine/archive.js";
85
+ import { PermissionError, asPermissionError } from "../../safe-bash-docx-engine/io-errors.js";
86
+ import { normalizeDocxPropertyOptions } from "../../safe-bash-docx-engine/command-properties.js";
87
+ import { DocxUsageError, decodeDocxText, parseDocxJson, docxByteLength, copyDocxBytes } from "../../safe-bash-docx-engine/argument-json.js";
88
+ import { docxOperationSchemas, assertDocxFields, validateDocxValue } from "../../safe-bash-docx-engine/operation-schema.js";
89
+ import { SourceError as SourceError2, validateDocxInvocation, validateDocxBatch as validateDocxBatch2, docxInvocationBudgets as docxInvocationBudgets2 } from "../../safe-bash-docx-engine/invocation.js";
90
+ var switches = /* @__PURE__ */ new Set(["json", "inPlace", "force", "dryRun", "allowEmpty", "allowPartialOutput", "first", "all", "raw", "pretty", "unique", "shared", "before", "deleteContent", "trackChanges"]);
91
+ var sourceFields = /* @__PURE__ */ new Set(["file", "fallback", "template", "contentFile", "dataFile", "opsFile"]);
92
+ var errorContexts = /* @__PURE__ */ new WeakMap();
93
+ function direct(id) {
94
+ return Object.hasOwn(docxOperationSchemas, id) && schemaFor(id).transport !== "typed-batch";
95
+ }
96
+ function kebab(key) {
97
+ return [...key].map((c) => c >= "A" && c <= "Z" ? "-" + c.toLowerCase() : c).join("");
98
+ }
99
+ function decimal(value) {
100
+ if (!value || value.trim() !== value) usage("Expected finite decimal notation.");
101
+ let cursor = 0;
102
+ if (value[cursor] === "+" || value[cursor] === "-") cursor++;
103
+ let digits = 0;
104
+ while (value[cursor] !== void 0 && "0123456789".includes(value[cursor])) {
105
+ cursor++;
106
+ digits++;
107
+ }
108
+ if (value[cursor] === ".") {
109
+ cursor++;
110
+ while (value[cursor] !== void 0 && "0123456789".includes(value[cursor])) {
111
+ cursor++;
112
+ digits++;
113
+ }
114
+ }
115
+ if (!digits) usage("Expected finite decimal notation.");
116
+ if (value[cursor] === "e" || value[cursor] === "E") {
117
+ cursor++;
118
+ if (value[cursor] === "+" || value[cursor] === "-") cursor++;
119
+ let exponent = 0;
120
+ while (value[cursor] !== void 0 && "0123456789".includes(value[cursor])) {
121
+ cursor++;
122
+ exponent++;
123
+ }
124
+ if (!exponent) usage("Expected finite decimal notation.");
125
+ }
126
+ const number = Number(value);
127
+ if (cursor !== value.length || !Number.isFinite(number)) usage("Expected finite decimal notation.");
128
+ return number;
129
+ }
130
+ function tryParseCliLength(raw) {
131
+ if (typeof raw !== "string") return raw;
132
+ for (const unit of ["emu", "twip", "dxa", "in", "cm", "mm", "pt"]) {
133
+ if (raw.endsWith(unit)) {
134
+ const numPart = raw.slice(0, -unit.length).trim();
135
+ if (!numPart) return raw;
136
+ const num = Number(numPart);
137
+ if (Number.isFinite(num)) return { value: num, unit: unit === "dxa" ? "twip" : unit };
138
+ }
139
+ }
140
+ return raw;
141
+ }
142
+ var LENGTH_JSON_KEYS = /* @__PURE__ */ new Set(["width", "height", "size", "cellMargin", "rowHeight", "space", "position", "top", "right", "bottom", "left", "header", "footer", "gutter"]);
143
+ function normalizeCliJsonLengths(value, keyHint) {
144
+ if (typeof value === "string") {
145
+ return keyHint && LENGTH_JSON_KEYS.has(keyHint) ? tryParseCliLength(value) : value;
146
+ }
147
+ if (Array.isArray(value)) {
148
+ return value.map((item) => keyHint === "columnWidths" || keyHint === "columnWidthsJson" ? tryParseCliLength(item) : normalizeCliJsonLengths(item));
149
+ }
150
+ if (value !== null && typeof value === "object") {
151
+ const out = {};
152
+ for (const [k, v] of Object.entries(value)) {
153
+ out[k] = normalizeCliJsonLengths(v, k);
154
+ }
155
+ if (keyHint === "cellMargin" && !("value" in out) && !("unit" in out)) {
156
+ const side = out.top ?? out.left ?? out.bottom ?? out.right;
157
+ if (side !== void 0) return side;
158
+ }
159
+ if (out.kind === "table" && out.repeatHeader !== void 0 && out.headerRows !== void 0) {
160
+ if (out.repeatHeader === true && typeof out.headerRows === "number" && out.headerRows >= 1 || out.repeatHeader === false && out.headerRows === 0) {
161
+ delete out.repeatHeader;
162
+ }
163
+ }
164
+ return out;
165
+ }
166
+ return value;
167
+ }
168
+ function cliValue(type, raw, name, budget) {
169
+ if (name.endsWith("Json")) return parseDocxJson(raw, budget);
170
+ const variants = type.split("|").map((s) => s.trim());
171
+ if (raw === "null" && variants.includes("null") && name !== "text") return null;
172
+ if (variants.includes("string") || type === "VfsInput" || type.startsWith("Vfs") || type === "LocationToken") return raw;
173
+ if (variants.includes("boolean") && (raw === "true" || raw === "false")) return raw === "true";
174
+ if (type.includes("Length") && type !== "Length | positive decimal multiple | null") {
175
+ for (const unit of ["emu", "in", "cm", "mm", "pt"]) if (raw.endsWith(unit)) return { value: decimal(raw.slice(0, -unit.length)), unit };
176
+ if (variants.includes("finite number") || variants.includes("number")) return decimal(raw);
177
+ usage("Lengths require explicit units.");
178
+ }
179
+ if (type.includes("integer") || type === "number" || type.startsWith("number ") || type.startsWith("finite ") || type.includes("fraction") || type.includes("decimal multiple")) return decimal(raw);
180
+ if (name === "remove") return raw.split(",");
181
+ if (name === "levels") {
182
+ const ends = raw.split("-");
183
+ if (ends.length !== 2) usage("Expected a level range.");
184
+ return { start: decimal(ends[0]), end: decimal(ends[1]) };
185
+ }
186
+ const enumType = variants.find((value) => value.startsWith("WD_") || value.startsWith("MSO_"));
187
+ if (enumType) return { enum: enumType, name: raw };
188
+ return raw;
189
+ }
190
+ function parseDocxArguments(args, budget = new DocumentBudget()) {
191
+ let operation = "";
192
+ let json = false;
193
+ try {
194
+ if (!Array.isArray(args) || Object.getPrototypeOf(args) !== Array.prototype || !validateDocxValue("ReadonlyArray<Uint8Array>", args)) usage("Expected literal byte arguments.");
195
+ const words = args.map((bytes) => {
196
+ budget.charge("retainedBytes", docxByteLength(bytes));
197
+ const word = decodeDocxText(bytes);
198
+ if (word.includes("\0")) usage("NUL is not permitted in arguments.");
199
+ return word;
200
+ });
201
+ if (words.length === 0) words.push("help");
202
+ if (words[0] === "--help" || words[0] === "-h") words[0] = "help";
203
+ if (words[0] === "--version") words[0] = "version";
204
+ let consumed = 0;
205
+ for (let count = 1; count <= words.length; count++) {
206
+ if (words[count - 1].includes(".")) break;
207
+ const candidate = words.slice(0, count).join(".");
208
+ if (direct(candidate)) {
209
+ operation = candidate;
210
+ consumed = count;
211
+ }
212
+ if (words[count]?.startsWith("-")) break;
213
+ }
214
+ if (words[0] === "text" && consumed === 0) {
215
+ operation = "text.get";
216
+ consumed = 1;
217
+ }
218
+ if (!operation) {
219
+ const valueFlags = new Set(Object.keys(docxOperationSchemas).filter((id) => !id.startsWith("model.")).map((id) => docxOperationSchemas[id]).flatMap((declaration) => Object.keys(optionFields(declaration, true)).filter((name) => !switches.has(name)).map((name) => "--" + kebab(name))));
220
+ valueFlags.add("-o");
221
+ for (let index = 1; index < words.length; index++) {
222
+ const word = words[index];
223
+ if (word === "--") break;
224
+ if (word === "--json") json = true;
225
+ if (valueFlags.has(word)) index++;
226
+ }
227
+ const replacement = (/* @__PURE__ */ new Map([
228
+ ["image", "images"],
229
+ ["table", "tables"],
230
+ ["metadata", "properties"],
231
+ ["replace", "text replace"]
232
+ ])).get(words[0]);
233
+ usage(replacement ? `Unknown document command path. Use docx ${replacement}; see docx help for commands.` : "Unknown document command path. Use docx help to discover commands.");
234
+ }
235
+ const schema = schemaFor(operation);
236
+ const fields = optionFields(schema, true);
237
+ const names = new Map(Object.keys(fields).map((key) => ["--" + kebab(key), key]));
238
+ if (Object.hasOwn(fields, "output")) names.set("-o", "output");
239
+ const options = {};
240
+ const inputs = [];
241
+ let terminated = false;
242
+ let help = false;
243
+ for (let index = consumed; index < words.length; index++) {
244
+ const word = words[index];
245
+ if (word === "--") break;
246
+ const equal = word.indexOf("=");
247
+ const name = names.get(equal < 0 ? word : word.slice(0, equal));
248
+ if (name === "json" && equal < 0) json = true;
249
+ if (name && !switches.has(name) && equal < 0) index++;
250
+ }
251
+ for (let index = consumed; index < words.length; index++) {
252
+ const word = words[index];
253
+ if (!terminated && word === "--") {
254
+ terminated = true;
255
+ continue;
256
+ }
257
+ if (!terminated && (word === "--help" || word === "-h")) {
258
+ if (help || operation === "version") usage("Conflicting discovery options.");
259
+ help = true;
260
+ continue;
261
+ }
262
+ if (terminated || !word.startsWith("-") || word === "-") {
263
+ path(word);
264
+ inputs.push(word);
265
+ continue;
266
+ }
267
+ const equal = word.indexOf("=");
268
+ const flag = equal < 0 ? word : word.slice(0, equal);
269
+ const name = names.get(flag);
270
+ if (!name) usage("Unknown or inapplicable document option.");
271
+ if (name !== "limit" && Object.hasOwn(options, name)) usage("Repeated scalar option.");
272
+ if (switches.has(name)) {
273
+ if (equal >= 0) usage("Presence switches accept no value.");
274
+ options[name] = true;
275
+ if (name === "json") json = true;
276
+ continue;
277
+ }
278
+ const raw = equal >= 0 ? word.slice(equal + 1) : words[++index];
279
+ if (raw === void 0) usage("Missing option value.");
280
+ if (name === "limit") {
281
+ const split = raw.indexOf("=");
282
+ if (split <= 0) usage("Expected a named limit.");
283
+ const key = raw.slice(0, split);
284
+ const limits = options.limit ?? [];
285
+ if (limits.some((item) => item.name === key)) usage("Repeated document limit.");
286
+ limits.push({ name: key, value: decimal(raw.slice(split + 1)) });
287
+ budget = lowerLimits(limits, budget);
288
+ options.limit = limits;
289
+ } else {
290
+ options[name] = name.endsWith("Json") ? raw : cliValue(fields[name].type, raw, name, budget);
291
+ if (!name.endsWith("Json") && !validateDocxValue(fields[name].type, options[name])) usage(`Invalid value for --${kebab(name)}. See docx help ${operation.split(".").join(" ")} for accepted values.`);
292
+ }
293
+ }
294
+ budget = lowerLimits(options.limit, budget);
295
+ for (const name of Object.keys(options)) if (name.endsWith("Json")) options[name] = normalizeCliJsonLengths(parseDocxJson(options[name], budget), name);
296
+ if (operation === "properties.set" && !help) Object.assign(options, normalizeDocxPropertyOptions(options, true));
297
+ if (operation === "help" || operation === "schema") {
298
+ if (inputs.some((word) => word.includes("."))) usage("Unknown discovery path.");
299
+ const target = inputs.join(".");
300
+ if (target && !direct(target) && target !== "text") usage("Unknown discovery path.");
301
+ if (target) {
302
+ const id = target === "text" ? "text.get" : target;
303
+ if (options.operation !== void 0 && id !== "batch" && options.operation !== id) usage("Conflicting discovery path and operation.");
304
+ if (options.operation === void 0) options.operation = id;
305
+ else if (id === "batch" && schemaFor(options.operation).transport === "direct") usage("Operation is not available in batch.");
306
+ }
307
+ if (options.operation !== void 0) schemaFor(options.operation);
308
+ return Object.freeze({ operation, inputs: Object.freeze([]), options: Object.freeze(options) });
309
+ }
310
+ if (help) {
311
+ assertDocxFields(Object.fromEntries(Object.entries(fields).map(([name, field]) => [name, { ...field, required: false }])), options, (type, value) => {
312
+ if (type === "BatchV1") {
313
+ validateDocxBatch(value, budget, { author: options.author, timestamp: options.timestamp });
314
+ return true;
315
+ }
316
+ return void 0;
317
+ });
318
+ if (inputs.length > Number(schema.inputArity === "0|1" ? 1 : schema.inputArity)) usage("Invalid input arity.");
319
+ for (const [file, json2] of [["contentFile", "contentJson"], ["dataFile", "dataJson"], ["opsFile", "opsJson"]]) if (options[file] !== void 0 && options[json2] !== void 0) usage("Conflicting JSON sources.");
320
+ if (options.output !== void 0 && options.inPlace === true) usage("Output and in-place conflict.");
321
+ if (options.raw === true && (options.json === true || options.pretty === true)) usage("Conflicting XML output modes.");
322
+ validateSelections(operation, options);
323
+ const invocation = Object.freeze({ operation: "help", inputs: Object.freeze([]), options: Object.freeze({ operation, ...options.json === true ? { json: true } : {} }) });
324
+ docxInvocationBudgets.set(invocation, budget);
325
+ return invocation;
326
+ }
327
+ for (const name of ["tabStops", "tabStopAdd", "borders", "shading", "columnWidths", "rowOptions", "wrapPolygon"]) {
328
+ if (options[name + "Json"] !== void 0) {
329
+ options[name] = options[name + "Json"];
330
+ delete options[name + "Json"];
331
+ }
332
+ }
333
+ const sources = [];
334
+ for (const [file, json2, semantic, type] of [["contentFile", "contentJson", "content", "OriginalDocumentContentV1"], ["dataFile", "dataJson", "data", "TemplateData"], ["opsFile", "opsJson", "operations", "BatchV1"]]) {
335
+ if (options[file] !== void 0 && options[json2] !== void 0) usage("Conflicting JSON sources.");
336
+ if (options[json2] !== void 0) {
337
+ if (type === "BatchV1") Object.assign(options, validateDocxBatch(options[json2], budget, { author: options.author, timestamp: options.timestamp }));
338
+ else options[semantic] = options[json2];
339
+ delete options[json2];
340
+ }
341
+ if (options[file] !== void 0) {
342
+ const source = options[file];
343
+ path(source);
344
+ sources.push({ argument: semantic, path: source, format: "json", type: type === "BatchV1" ? type : schema.sdkFields[semantic].type });
345
+ delete options[file];
346
+ }
347
+ }
348
+ for (const field of sourceFields) if (options[field] !== void 0) {
349
+ const source = options[field];
350
+ path(source);
351
+ sources.push({ argument: field, path: source, format: "binary", type: "BinaryInput" });
352
+ options[field] = { kind: "vfs", path: source, capability: "command" };
353
+ }
354
+ return validateInvocation({ operation, inputs, options, sources }, budget, true);
355
+ } catch (error) {
356
+ if (error instanceof Error) errorContexts.set(error, { operation: operation || "help", json, budget });
357
+ throw error;
358
+ }
359
+ }
360
+ function createDocxCommandEngine(handler, hostLimits = {}) {
361
+ return {
362
+ async execute(request) {
363
+ if (request.signal.aborted) return { exitCode: 130 };
364
+ let invocation;
365
+ let budget = new DocumentBudget(hostLimits, request.signal);
366
+ let discoveryOutput;
367
+ try {
368
+ invocation = parseDocxArguments(request.args, budget);
369
+ budget = docxInvocationBudgets.get(invocation) ?? lowerLimits(invocation.options.limit, budget);
370
+ const discovery = schemaFor(invocation.operation).discovery ? getDocxDiscovery(invocation, budget) : void 0;
371
+ if (discovery) {
372
+ const output = invocation.options.json === true || invocation.operation === "schema" ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data: discovery.data, warnings: [], errors: [], affected: 0, locations: [] }) + "\n" : discovery.human;
373
+ discoveryOutput = new TextEncoder().encode(output);
374
+ budget.check("serializedOutput", discoveryOutput.byteLength);
375
+ }
376
+ const options = { ...invocation.options };
377
+ const sources = invocation.sources ?? [];
378
+ for (const source of sources) {
379
+ if (source.format !== "json") continue;
380
+ let bytes;
381
+ try {
382
+ if (source.path === "-") {
383
+ const chunks = [];
384
+ let size = 0;
385
+ for await (const chunk of request.stdin) {
386
+ request.signal.throwIfAborted();
387
+ size += docxByteLength(chunk);
388
+ budget.check("xmlPartBytes", size);
389
+ budget.charge("retainedBytes", docxByteLength(chunk));
390
+ chunks.push(copyDocxBytes(chunk));
391
+ }
392
+ budget.charge("retainedBytes", size);
393
+ bytes = new Uint8Array(size);
394
+ let offset = 0;
395
+ for (const chunk of chunks) {
396
+ bytes.set(chunk, offset);
397
+ offset += chunk.byteLength;
398
+ }
399
+ } else {
400
+ if (!handler.readSource) throw new SourceError();
401
+ bytes = await handler.readSource(source, request, budget);
402
+ request.signal.throwIfAborted();
403
+ }
404
+ } catch (error) {
405
+ request.signal.throwIfAborted();
406
+ if (error instanceof ResourceLimitError || error instanceof DocxUsageError) throw error;
407
+ throw asPermissionError(error) ?? new SourceError(error);
408
+ }
409
+ const value = parseDocxJson(bytes, budget);
410
+ if (source.type === "BatchV1") Object.assign(options, validateDocxBatch(value, budget, { author: options.author, timestamp: options.timestamp }));
411
+ else options[source.argument] = value;
412
+ }
413
+ if (invocation.operation === "batch" && sources.filter((source) => source.path === "-").length + invocation.inputs.filter((input) => input === "-").length > 1) usage("Only one stdin consumer is permitted.");
414
+ if (sources.some((source) => source.format === "json")) invocation = validateInvocation({ ...invocation, options, sources: sources.filter((source) => source.format !== "json") }, budget, true);
415
+ } catch (error) {
416
+ if (request.signal.aborted) return { exitCode: 130 };
417
+ if (!(error instanceof DocxUsageError) && !(error instanceof BoundsError) && !(error instanceof ResourceLimitError) && !(error instanceof SourceError) && !(error instanceof PermissionError)) throw error;
418
+ const context = errorContexts.get(error) ?? { operation: invocation?.operation ?? "help", json: invocation?.options.json === true, budget };
419
+ const code = error instanceof BoundsError ? error.code : error instanceof ResourceLimitError ? "limit-exceeded" : error instanceof PermissionError ? "permission" : error instanceof SourceError ? "source-failure" : "usage";
420
+ const diagnostic = commandDiagnostic(error.message, code, context.budget.limits.diagnosticBytes);
421
+ try {
422
+ if (context.json || context.operation === "schema") await request.stdout.write(new TextEncoder().encode(JSON.stringify({ version: 1, operation: context.operation, ok: false, data: null, warnings: [], errors: [{ code, message: diagnostic.message, ..."operationIndex" in error ? { operationIndex: error.operationIndex } : {} }], affected: 0, locations: [] }) + "\n"));
423
+ if (request.signal.aborted) return { exitCode: 130 };
424
+ await request.stderr.write(new TextEncoder().encode(diagnostic.human));
425
+ } catch (transportError) {
426
+ if (request.signal.aborted) return { exitCode: 130 };
427
+ throw transportError;
428
+ }
429
+ if (request.signal.aborted) return { exitCode: 130 };
430
+ return { exitCode: context.operation === "diff" ? 2 : error instanceof BoundsError ? 1 : error instanceof ResourceLimitError ? 4 : error instanceof SourceError || error instanceof PermissionError ? 3 : 2 };
431
+ }
432
+ if (discoveryOutput) {
433
+ if (request.signal.aborted) return { exitCode: 130 };
434
+ try {
435
+ await request.stdout.write(discoveryOutput);
436
+ } catch (error) {
437
+ if (request.signal.aborted) return { exitCode: 130 };
438
+ throw error;
439
+ }
440
+ return { exitCode: request.signal.aborted ? 130 : 0 };
441
+ }
442
+ return handler.execute(invocation, request);
443
+ }
444
+ };
445
+ }
446
+ function commandDiagnostic(source, code, limit) {
447
+ if (code === "stale-selection" && source === "Document operation failed: " + code)
448
+ source += ". Inspect the input again and select a fresh location.";
449
+ if (code === "ambiguous-selection" && source === "Document operation failed: " + code)
450
+ source += ". Inspect the input and choose an unambiguous owner or location.";
451
+ if (code === "conflict" && source === "Document operation failed: " + code)
452
+ source += ". Review the input and destination before retrying. Choose a new output path, or use --in-place only for intentional input replacement.";
453
+ const encoder = new TextEncoder();
454
+ const prefix = limit >= 8 ? "docx: " : "";
455
+ const suffix = limit >= 2 ? "\n" : "";
456
+ const jsonOverhead = encoder.encode(JSON.stringify([{ code, message: "" }])).byteLength;
457
+ const capacity = Math.max(1, limit - Math.max(prefix.length + suffix.length, jsonOverhead));
458
+ const marker = capacity >= 12 ? " [truncated]" : ".";
459
+ const pieces = [];
460
+ let size = 0;
461
+ let truncated = false;
462
+ for (const raw of source) {
463
+ const human = escapeTerminalText(raw);
464
+ const width = Math.max(encoder.encode(human).byteLength, encoder.encode(JSON.stringify(raw)).byteLength - 2);
465
+ if (width > capacity - size) {
466
+ truncated = true;
467
+ break;
468
+ }
469
+ pieces.push({ raw, human, size: width });
470
+ size += width;
471
+ }
472
+ if (truncated) {
473
+ while (pieces.length && size + marker.length > capacity) size -= pieces.pop().size;
474
+ }
475
+ const ending = truncated ? marker : "";
476
+ return {
477
+ message: pieces.map((piece) => piece.raw).join("") + ending,
478
+ human: prefix + pieces.map((piece) => piece.human).join("") + ending + suffix
479
+ };
480
+ }
481
+
482
+ // packages/safe-bash-command-docx/src/discovery.ts
483
+ import { docxCommonOptions, docxOperationSchemas as docxOperationSchemas2 } from "../../safe-bash-docx-engine/operation-schema.js";
484
+ import { getDocxOperationSchema } from "../../safe-bash-docx-engine/operation-json-schema.js";
485
+ import { archivePackingContract, archiveExtractionContract, discoveryFailureSchema, objectOperationContracts, equationOperationContracts, diagramOperationContracts, chartOperationContracts, shapeOperationContracts, imageLayoutOperationContracts, imageOperationContracts, inspectionOperationMetadata, propertyOperationContracts, rasterInsertionOperationContracts, rasterReplacementOperationContracts } from "../../safe-bash-docx-engine/discovery-result-schema.js";
486
+ var styleModelBatchOperations = [...styleOperations, ...structureModelBatchActions.keys()];
487
+ function operationSupport(id, declaration) {
488
+ const supported = imageBatchActions.has(id) || styleModelBatchOperations.includes(id) || id === "batch" || objectOperationContracts[id] || equationOperationContracts[id] || diagramOperationContracts[id] || chartOperationContracts[id] || shapeOperationContracts[id] || inspectionOperationMetadata[id] || imageOperationContracts[id] || rasterInsertionOperationContracts[id] || rasterReplacementOperationContracts[id] || imageLayoutOperationContracts[id] || propertyOperationContracts[id] || declaration.discovery || id === "extract" || id === "pack";
489
+ return supported ? declaration.mutates ? "edit" : "read" : "reject";
490
+ }
491
+ function commandPath(id, declaration) {
492
+ return declaration.transport === "typed-batch" ? ["batch"] : id.split(".");
493
+ }
494
+ function usage2(id, declaration) {
495
+ const path2 = commandPath(id, declaration).join(" ");
496
+ const input = declaration.transport === "typed-batch" ? " INPUT" : declaration.profile === "discovery" && Object.hasOwn(declaration.fields, "operation") ? " [COMMAND PATH]" : declaration.inputArity === "0|1" ? " [INPUT]" : declaration.inputArity === 2 ? " LEFT RIGHT" : declaration.inputArity === 1 ? id === "pack" ? " INVENTORY" : " INPUT" : "";
497
+ return `docx ${path2}${input} [OPTIONS]`;
498
+ }
499
+ function description(declaration) {
500
+ const id = Object.keys(docxOperationSchemas2).find((key) => docxOperationSchemas2[key] === declaration);
501
+ if (id === "batch") return "Execute admitted ordered utility operations against staged document state with one publication; retain the separate style, font, paragraph-format, tab, bounded XML, package/part/resource, immutable Image, immutable package URI and live table/section/review batch subsets. Other model operations remain unsupported.";
502
+ if (packUriBatchActions.has(id)) return "Read a checked immutable package URI value through invocation-local batch handles without document mutation authority.";
503
+ if (imageBatchActions.has(id)) return "Read an immutable Image value through invocation-local batch handles without document mutation authority.";
504
+ if (id.startsWith("model.XmlElementView.")) return "Bounded live XML traversal and structured mutation with shared owner budgets and guarded publication.";
505
+ if (id === "model.parts.numbering.NumberingPart.new.call" || id === "model.parts.document.DocumentPart.numbering_part.get") return "Create and attach an empty numbering part to the admitted document owner, or reuse its valid existing part unchanged. Returns a live NumberingPart handle; all graph changes stage together under shared budgets and publication rules.";
506
+ if (packageViewBatchActions.has(id)) return "Live package, part and resource views with owned values, inert external targets and validated graph edits.";
507
+ if (structureModelBatchActions.has(id)) return "Implemented live table, section and review operation with checked document-owned receivers and typed values.";
508
+ if (styleModelBatchOperations.includes(id)) return "Implemented style model operation with checked document-owned receivers and typed values.";
509
+ return (id === "pack" ? archivePackingContract.description : id === "extract" ? archiveExtractionContract.description : void 0) ?? objectOperationContracts[id]?.description ?? equationOperationContracts[id]?.description ?? diagramOperationContracts[id]?.description ?? chartOperationContracts[id]?.description ?? shapeOperationContracts[id]?.description ?? inspectionOperationMetadata[id]?.description ?? imageOperationContracts[id]?.description ?? rasterInsertionOperationContracts[id]?.description ?? imageLayoutOperationContracts[id]?.description ?? rasterReplacementOperationContracts[id]?.description ?? propertyOperationContracts[id]?.description ?? declaration.discovery?.description ?? "Declared contract; document operation not implemented by this engine.";
510
+ }
511
+ function details(id, declaration) {
512
+ const lines = [
513
+ usage2(id, declaration),
514
+ "",
515
+ description(declaration),
516
+ "",
517
+ `Support for this operation: ${operationSupport(id, declaration)}.`,
518
+ "Support: edit changes only the admitted subset; read returns snapshots; preserve retains unedited bytes; reject provides no execution support.",
519
+ "Limits: resources are unlimited unless explicitly set with --limit NAME=VALUE; duplicate names reject. Capabilities lists effective limits.",
520
+ "Output: reads use stdout; --json emits one version 1 result. Diagnostics use stderr; package --output - is pure binary and conflicts with --json except dry-run.",
521
+ "Mutations require --output or --in-place unless --dry-run. Existing outputs require --force; aliases of input require --in-place. Dry-run publishes nothing.",
522
+ "Exit: 0 success; 1 document/edit/selection failure; 2 usage; 3 I/O/publication; 4 limit; 130 cancellation. Diff uses 0 equal, 1 different, 2 failed, 130 cancellation."
523
+ ];
524
+ if (id === "diff") lines.push("", "Scope defaults to package for --mode parts (default) or xml, and body for text/structure. Explicit story scopes: headers, footers, footnotes, endnotes, comments, text-boxes or all-stories.", "Text compares final logical text. Structure retains stored story XML, collapses plain run/text wrappers, and compares referenced image bytes.", "Results are bounded part-level changes. Exit: 0 equal; 1 different; 2 trouble; 130 cancellation. Only one input may use stdin (-).");
525
+ if (id === "batch") lines.push("", `Admitted ordered utility IDs: ${documentBatchOperations.join(", ")}.`, "Use version 1 and an ordered operations array. Optional stable IDs start with an ASCII letter and contain letters, digits, underscores or hyphens, up to 64 characters; omitted IDs use step1, step2 and so on.", "Whole-array syntax is checked before edits. Later semantic selections use staged state; a later failure discards the unpublished result. Publication and limits belong to the outer batch.", "Utility arrays and typed style/XML/package/resource/Image/package URI/table/section/review subsets use their respective executors; unsupported combinations reject.");
526
+ if (id === "template.apply") lines.push("", "Tags explicitly declare bindings; exact {{tag}} placeholders inside tagged text controls use the same literal fill rules.", "Ordinary brace text outside tagged controls is preserved. No expressions, callbacks or arbitrary code.", "Records have values: [{binding, value}]. Scalars use the control's declared type; native repeat tags require record arrays.", "Top-level arrays require one body repeat and no singleton bindings. Maximum four repeat levels and 1,000 records per region.", "Empty repeats retain one cleared reusable item. All schema, lock, boundary, budget and reference checks precede one publication.", "Only body templates are edited; other stories remain unchanged. Bound controls and affected unsupported structures reject.");
527
+ if (id === "images.set") lines.push(
528
+ "",
529
+ "Edit one existing native inline or anchor picture; --all selects distinct physical drawings atomically.",
530
+ "Size uses the stored unrotated extent ratio; explicit contain/cover/stretch requires both physical dimensions.",
531
+ "Axis frames, offsets, alignments, distances and wrapping require an admitted anchor; inline conversion is unsupported.",
532
+ "Tight/through wrapping requires an explicit native polygon or an admitted retained polygon; no outline is inferred.",
533
+ "Media bytes, relationships and coherent alternate associations remain exact; ambiguous representations reject before publication.",
534
+ "Use schema for the admitted utility batch operations and typed model routes."
535
+ );
536
+ if (id === "images.replace") lines.push(
537
+ "",
538
+ "Select one embedded PNG, JPEG, GIF, BMP or TIFF image occurrence by its location or owner-relative index.",
539
+ "Occurrence replacement clones and rebinds its resource; --shared replaces all physical owners of the resolved resource.",
540
+ "Preserve existing extents and crop unless resizing; explicit fit requires both physical dimensions.",
541
+ "Replacement paths require an explicit stream capability. Linked, alternate and fallback carriers refuse before acquisition.",
542
+ "Supplying fallback is unsupported. Use schema for the admitted utility batch operations and typed model routes."
543
+ );
544
+ if (id === "images.add") lines.push(
545
+ "",
546
+ "Select a whole paragraph, admitted block container, or the unique body.",
547
+ "Header/footer and note containers require an explicit owner.",
548
+ "There is no all, run, caret or range insertion.",
549
+ "Use explicit physical units: emu, in, cm, mm or pt. Pixels are not accepted.",
550
+ "Omitted dimensions use native DPI independently per axis, with 72 DPI fallback.",
551
+ "One dimension preserves native aspect ratio; two dimensions use contain/cover/stretch.",
552
+ "Decorative defaults false; true conflicts with nonempty alt text.",
553
+ "Known PNG/JPEG/GIF/BMP/TIFF source suffixes must match the actual bytes.",
554
+ "Static safe SVG requires a supplied validated PNG, JPEG, GIF, BMP or TIFF fallback; sizes and native DPI come from that fallback.",
555
+ "SVG and fallback paths require an explicit stream capability; only explicit CLI file/fallback dashes consume stdin.",
556
+ "SVG admits bounded static XML with local references only. No scripts, external references, fetching or rasterize step; no rendering parity is claimed.",
557
+ "Both original resources are retained exactly as one inline occurrence. A raster source with supplied fallback rejects.",
558
+ "Floating placement, SVG/fallback replacement and other direct raster insertion remain unsupported."
559
+ );
560
+ if (["images.add", "images.set", "images.replace"].includes(id)) lines.push("Live inline picture sizing and collection lookup are available through declared typed model routes.");
561
+ if (id === "pack") lines.push(
562
+ "",
563
+ "INVENTORY is a version 1 JSON path or stdin (-); no directory scan.",
564
+ "Records require sorted canonical part names, VFS paths, content types, byte lengths and SHA-256 hashes.",
565
+ "File inventories grant their directory; stdin records require explicit absolute VFS paths.",
566
+ "Full extraction manifests are accepted; media-only manifests reject. Update both length and hash after editing.",
567
+ "Symlinks, aliases, unsupported kinds, missing graph targets and output inside the input tree reject.",
568
+ "Retain exact payloads, kind and dialect. Output uses stored sorted entries, fixed 1980 timestamps and no comment.",
569
+ "One shared staged publication; --force never bypasses validation. --dry-run performs no writes.",
570
+ "Live package views are available through the declared typed model routes. Packing requires its own publication and cannot be nested in a batch."
571
+ );
572
+ if (id === "extract") lines.push(
573
+ "",
574
+ "Use --output-dir DIR and --allow-partial-output. The parent directory must already exist.",
575
+ "--selection all (default) retains all files and empty directories; media-only selects word/media/.",
576
+ "Default payload bytes stay exact. --pretty formats XML and relationships while retaining mixed text.",
577
+ "The entire namespace is validated, including excluded members, links and case/Unicode/path aliases.",
578
+ "Requires atomic conditional directory/file publication; read-only or unsupported VFS targets reject.",
579
+ "Preexisting trees always reject, including with --force. No user directory is recursively removed.",
580
+ "I/O or cancellation can leave partial new output; JSON and typed failures retain the publication receipt.",
581
+ "Live package views are available through the declared typed model routes. Extraction is a separate multiple-output operation."
582
+ );
583
+ if (id === "lorem.set") lines.push("", "Provide --seed INTEGER and --paragraph N, a text/owner token, or explicit --all inside --scope (default body).", "Words default to maximal nonempty whitespace-delimited selected logical spans per paragraph; --words overrides the count.", "Seed maps modulo 2^32; amber birch cedar delta elm fern grove heath repeat from (seed + i) modulo 8, restarting per paragraph.", "Generated text uses spaces. Retain tabs, breaks and nontext controls; distribute generated characters into existing text leaves by their original selected lengths, with the remainder in the last leaf.", "A computed zero makes no change. Explicit words can fill an admitted empty whole paragraph. Hidden-format runs follow logical text extraction, without style resolution or rendering.", "This is not anonymization: metadata, images, instructions, inactive markup and unselected text remain unchanged.", "Affected protection, opaque review, grouped shapes and shared stories reject. Generic utility batch execution and live text owners remain pending.");
584
+ if (id.startsWith("signatures.")) lines.push("", "Signatures are package-global; story selectors are inapplicable.", "Inventory does not verify cryptographic validity. Other mutations reject signed input.", "signatures remove is explicit consent to strip the complete signature graph; inspect its exact removal report before any subsequent edit.", "No signature regeneration or generic utility batch execution is supported.");
585
+ if (id === "sanitize") lines.push(
586
+ "",
587
+ "Use --remove properties,comments,revisions,links,objects; choose only needed categories.",
588
+ "Order: properties, comments, revisions, links, objects. No implicit scrub-all.",
589
+ "Revisions require --revision-policy accept|reject; policy without revisions is invalid.",
590
+ "Actions:",
591
+ " properties: remove supported writable scalars; cached or opaque metadata remains.",
592
+ " comments: remove supported bodies and markers; unsafe thread metadata rejects.",
593
+ " revisions: accept/reject supported decisions; nested, move or structural review rejects.",
594
+ " links: unwrap external hyperlinks preserving labels; internal anchors remain.",
595
+ " objects: remove direct inert carriers without previews and unused bindings/leaf targets.",
596
+ "Shared targets, outgoing embedded graphs and other external binding roles remain.",
597
+ "Preflight all actions, edit staged bytes, validate, then publish once.",
598
+ "Inspect actions, record IDs, removed parts/relationships, retained categories and gaps.",
599
+ "No comprehensive privacy or recoverability removal is provided.",
600
+ "Signed/protected inputs reject. Generic utility batches and live models remain pending."
601
+ );
602
+ if (id === "settings.list") lines.push("", "Settings are package-global; story selectors are inapplicable.", "Unknown settings remain opaque; protection credentials are omitted.", "Raw xml set may change only boolean field-update intent in settings.", "No typed settings setter, rights bypass or font installation is supported.");
603
+ if (declaration.transport === "typed-batch") {
604
+ lines.push("", `Batch operation: ${id}`, `Receiver: ${declaration.receiver ?? "none"}`, "Arguments:");
605
+ for (const [key, field] of Object.entries(declaration.batchFields ?? {})) lines.push(` ${key}: ${field.type}${field.required ? " (required)" : ""}`);
606
+ } else {
607
+ lines.push("", "Options:");
608
+ const fields = { ...Object.fromEntries(declaration.commonOptions.map((key) => [key, docxCommonOptions[key]])), ...declaration.fields };
609
+ for (const [key, field] of Object.entries(fields)) {
610
+ if (id.startsWith("tables.") && id !== "tables.add" && (["paragraph", "run", "image", "link", "control", "revision", "shape", "field", "bookmark"].includes(key) || id.split(".").length === 3 && (key === "cell" || key === "all"))) continue;
611
+ if (["lists.add", "lists.set", "tables.add"].includes(id) && (["run", "image", "link", "control", "revision", "shape", "field", "bookmark"].includes(key) || ["lists.add", "tables.add"].includes(id) && key === "all")) continue;
612
+ const flag = [...key].map((c) => c >= "A" && c <= "Z" ? "-" + c.toLowerCase() : c).join("");
613
+ lines.push(` --${flag}${key === "output" ? ", -o" : ""} ${field.type}${field.required ? " (required)" : ""}`);
614
+ }
615
+ lines.push(" --help, -h Show help without acquiring input.");
616
+ if (Object.hasOwn(fields, "occurrence") && Object.hasOwn(fields, "first")) lines.push("", "Choose exactly one: --first | --all | --occurrence NUMBER.");
617
+ if (Object.hasOwn(fields, "output") && Object.hasOwn(fields, "inPlace")) lines.push("", "Publication: --output PATH | --in-place | --dry-run.");
618
+ if (id.startsWith("objects.")) lines.push("", "Without selectors object inventory is package-global; explicit selectors narrow stored physical occurrences.");
619
+ if (id !== "diff" && !id.startsWith("objects.") && Object.hasOwn(fields, "scope")) lines.push("", id.startsWith("notes.") && id !== "notes.add" ? id === "notes.list" ? "Scope defaults to both footnotes and endnotes; --kind or --scope narrows it." : "Selection defaults to footnotes; --kind or --scope selects the note kind." : `Scope defaults to ${id.startsWith("comments.") && id !== "comments.add" ? "comments" : id.startsWith("headers.") ? "headers" : id.startsWith("footers.") ? "footers" : "body"}; positions are one-based within their owner.`);
620
+ if (Object.hasOwn(fields, "select")) lines.push(["section", "paragraph", "run", "table", "cell", "image", "comment", "note", "link", "control", "revision", "shape", "field", "bookmark"].some((key) => Object.hasOwn(fields, key)) ? "Use either --select TOKEN or simple selectors; do not combine them." : "Selection: --select TOKEN.");
621
+ if (Object.hasOwn(fields, "select")) lines.push("Fingerprinted tokens reject when stale; simple selectors resolve against this input. Missing destructive selection rejects; empty mutation matches require --allow-empty.");
622
+ if (Object.hasOwn(fields, "scope")) lines.push("Scopes: body, headers, footers, footnotes, endnotes, comments, text-boxes, all-stories, subject to the operation-specific subset above. Unknown or inapplicable scopes reject; all-selection stays inside the chosen scope.");
623
+ if (["paragraphs.remove", "runs.remove", "tables.remove"].includes(id)) lines.push(
624
+ "",
625
+ "Use explicit whole-resource selectors or scoped --all. Cross-paragraph, story and cell ranges reject.",
626
+ ...id === "tables.remove" ? ["Tables containing section breaks reject."] : [
627
+ "Scalar ranges require fingerprinted endpoints and --markers exclude|include.",
628
+ "Exclude retains proof/rendered markers; include removes them at and between both endpoints.",
629
+ "Whole structures reject --markers. Empty ranges require --allow-empty and do not change content."
630
+ ],
631
+ "Surviving text properties, section breaks and required empty paragraphs remain.",
632
+ "Affected bookmarks, comments, permissions, notes, fields, revisions, graphics and opaque content reject.",
633
+ "All relationships and resources remain retained. Utility batches and live content models remain pending."
634
+ );
635
+ if (id === "text.replace") lines.push("", "--track-changes true requires explicit --author and --timestamp; an empty author is allowed.", "Ordinary replacement rejects author/time. Deleted text retains its formatting; insertion inherits the first match with explicit bold/italic overrides.", "Tracking preserves original/final/all text. Affected existing review, field/control and compound boundaries reject.");
636
+ if (["controls.list", "controls.set"].includes(id)) lines.push("", "Controls are indexed individually, including nested and unsupported kinds; ordinals are one-based inside the selected owner.", "Inspection returns stored IDs/tags/aliases, lock mode, placeholder/binding descriptors, typed values, declared choices and picture relationships.", "No controls get route is declared. Use controls bind for declared binding synchronization. Available in the ordered utility batch with the same fill/refusal profile.");
637
+ if (id === "controls.set") lines.push("", "Choose exactly one: --text STRING | --checked true/false | --choice VALUE | --date YYYY-MM-DD | --file PATH.", "Choose one control ordinal or whole token; use --all explicitly inside the scope. Text-range tokens do not select controls.", "Successful filling, including empty text, clears showingPlcHdr and preserves unrelated properties. Parent replacement erasing nested controls rejects.", "Selected controls and ancestors must be unlocked. Bound filling rejects; it does not detach dataBinding.", "Choices use declared values and render their labels. Checkbox glyph/font mappings must be declared.", "Dates use admitted numeric Gregorian formats and explicit en-US/en-GB or absent language; no host locale is consulted.", "Pictures replace one admitted existing internal DrawingML occurrence with bounded PNG; preserve geometry/crop/alt and shared old resources.", "Validate every all-selected candidate before staging. Kind mismatches and unsupported structures fail atomically.");
638
+ if (["revisions.accept", "revisions.reject"].includes(id)) lines.push("", "Choose one: --revision NUMBER in its scoped owner, a whole --select revision token, or --all inside the selected scope.", "Text-range tokens do not select revisions. No match rejects unless --allow-empty; reruns resolve against the new input.", "Validate every selected revision before mutation. Preserve unselected changes, required owners and faithful annotation/bookmark/field ranges.", "Only admitted inline text and exposed-field run/paragraph property history are editable; unsupported nested, compound, move/table/section and opaque review rejects atomically.", "Reports retain before identities; removed review tokens are not live. Available in the ordered utility batch; use schema for bounded live model routes.");
639
+ if (id === "revisions.add") lines.push("", "--kind insert requires --text; empty insertion requires --allow-empty.", "Insert at a collapsed paragraph/run token or append to selected paragraph/run text. --kind delete forbids --text and requires nonempty selected text.", "Provide explicit --author and UTC --timestamp. Use --all for scoped creation; affected unsafe structures reject before mutation.", "Acceptance/rejection is a separate bounded subset. Available in the ordered utility batch; use schema for bounded live model routes.");
640
+ if (id === "create") lines.push("", "Content: version 1 blocks; optional page, styles and theme settings for new packages.", "Defaults: DOCX, Transitional, US Letter portrait, one-inch margins and Normal style.", "Template blocks append before final section properties; kind/dialect and existing settings are retained.", "No executable templates, field evaluation, font discovery or automatic timestamps.");
641
+ if (id === "inspect") lines.push("", "Theme/font inventory: fontResources contains schemes, table entries, embedding bindings and reference diagnostics.", "Resolved references identify stored package slots; availability and licensing remain unknown.", "Use runs set or styles set/defaults set for typed font/theme references. Embedded font mutation is unsupported.");
642
+ if (id === "tables.add") lines.push(
643
+ "",
644
+ "Rows and cols are required. Default: container width, equal columns, autofit true.",
645
+ "Append to a story or cell; a paragraph anchor inserts after it, or use --before.",
646
+ "A collapsed paragraph token inserts at a Unicode caret and retains the suffix section.",
647
+ "--repeat-header true repeats the first row; --header-rows selects a leading count.",
648
+ "--content-json/--content-file supplies one typed table matching rows and cols.",
649
+ "Formatting may be direct or in that table; duplicate sources reject. Nested blocks retain terminal paragraphs.",
650
+ "Use tables set for cell values/formatting and tables rows/columns add/remove for explicit structural edits. Use tables merge/split for spans. Live table operations are available through declared typed model batches."
651
+ );
652
+ if (["tables.get", "tables.set"].includes(id)) lines.push("", "Coordinates are 1-based: --table 1 --cell B2, or an unambiguous --select TOKEN.");
653
+ if (id === "tables.get") lines.push("Read each physical anchor once, with logical spans, omitted slots and exact text.");
654
+ if (id === "tables.merge") lines.push("", "Select a table and top-left --from A1 / bottom-right --to B2 corners.", "--join paragraphs preserves rich blocks in row order; --join reject accepts only empty cells.", "Partial overlaps, omitted slots and range markers reject before publication.");
655
+ if (id === "tables.split") lines.push("", "Select a logical cell. Rows/cols must divide its existing merged grid slots exactly.", "--distribute anchor retains all blocks in the first cell; paragraphs requires exactly one paragraph per resulting cell.", "Covered coordinates identify the whole owner for this explicit operation.");
656
+ if (id === "tables.set") lines.push(
657
+ "Set changes values or formatting only; growth and deletion require explicit row/column operations.",
658
+ "Text requires a cell. Covered coordinates reject writes unless --covered owner is explicit. Fields, nested tables and opaque content reject destructive replacement."
659
+ );
660
+ if (["tables.rows.add", "tables.rows.remove", "tables.columns.add", "tables.columns.remove"].includes(id)) lines.push(
661
+ "",
662
+ "Select one table using --table or --select. Indexes are 1-based.",
663
+ "Add inserts before the given index; count+1 appends. Omitted add index appends.",
664
+ "Remove requires an existing index and leaves at least one row and column.",
665
+ "Insertion and column removal require an unmerged rectangular grid. Row removal through vertical spans requires --join paragraphs and preserves surviving owner content."
666
+ );
667
+ if (id.startsWith("bookmarks.")) {
668
+ lines.push("", "Inspect paired ranges and structural issues; markers preserve unrelated fields and annotations.");
669
+ if (id === "bookmarks.add") lines.push("Use --select TOKEN for a nonempty paragraph range with half-open Unicode scalar offsets.", "Obtain the range with document.range(paragraphToken, start, end); multi-run and table-cell paragraphs are supported.");
670
+ if (id === "bookmarks.set") lines.push("--references update rewrites supported internal links and REF/PAGEREF fields; reject refuses referenced names.");
671
+ if (id === "bookmarks.remove") lines.push("--references remove unwraps supported references while preserving visible results; reject refuses referenced names.");
672
+ lines.push("Unsupported reference structures and unsafe range boundaries reject before publication.");
673
+ }
674
+ if (["fields", "toc", "captions"].includes(id.split(".")[0])) lines.push("", "Never execute field instructions or recalculate pagination. Results are stored caches.", "Add appends to a selected paragraph. TOC defaults to levels 1-3 and update true; fields default to update false.", "Captions default to a dirty SEQ field; --static true emits label/text only. Existing sequence names require explicit --sequence reuse.", "Set preserves omitted flags and existing contents. --text replaces only the selected TOC/SEQ cache; nested outer cache replacement rejects.", "Typed instruction edits require explicit target for REF/PAGEREF/SEQ. Shared stories and live field models remain unsupported.");
675
+ if (id.startsWith("notes.")) {
676
+ lines.push("", "Note positions are one-based; stored IDs are separate from display numbering.", "Preserve document and section numbering/restart rules; no pagination or displayed-number calculation.");
677
+ if (id === "notes.add") lines.push("--kind is required; text defaults empty. Insert into a selected body paragraph.");
678
+ if (id === "notes.set") lines.push("Replacing a multiply referenced body requires --shared true. Text replacement retains required note markers.");
679
+ if (id === "notes.remove") lines.push("Use --reference N for one shared reference or --references all for every reference.", "Remove a body only when no references remain. Required separators survive.");
680
+ if (id === "notes.add" || id === "notes.remove") lines.push("--renumber preserve is the default; document-order reallocates storage IDs and updates their references.");
681
+ }
682
+ if (id.startsWith("links.")) {
683
+ lines.push("", "Never fetch links. External targets allow absolute https/http/mailto URLs.");
684
+ if (["links.add", "links.set"].includes(id)) lines.push("Use exactly one of --target URL or --bookmark NAME (an internal anchor).", id === "links.add" ? "Append --text to a selected paragraph; existing runs stay unchanged." : "Retarget the selected link; preserve label runs and formatting.");
685
+ if (id === "links.remove") lines.push("Unwrap the visible label by default; --delete-content explicitly deletes it.");
686
+ lines.push("Shared header/footer utility link edits remain pending; live hyperlink traversal is available through typed model batches.");
687
+ }
688
+ if (id === "lists.add") lines.push(
689
+ "",
690
+ "Append to the body or a selected cell; a paragraph anchor inserts after it.",
691
+ "Defaults: level 0, start 1, empty text. Levels are 0-8.",
692
+ "Without --start, a compatible anchor continues its existing list.",
693
+ "An explicit --start creates a separate instance, including when it is 1.",
694
+ "A different kind can extend an unused simple level into a mixed list.",
695
+ "Existing items keep their formats; other definitions create a separate list."
696
+ );
697
+ if (id === "lists.set") lines.push(
698
+ "",
699
+ "Select existing list paragraphs; --all stays inside the chosen scope.",
700
+ "--restart true isolates selected items; --start requires restart true.",
701
+ "An omitted restart start uses the level definition's starting value."
702
+ );
703
+ if (["lists.add", "lists.set"].includes(id)) lines.push(
704
+ "",
705
+ "Picture bullets and unsupported numbering schemes remain unchanged.",
706
+ "Edits requiring their interpretation are rejected. Model batches remain pending."
707
+ );
708
+ if (id === "xml.get") lines.push(
709
+ "",
710
+ "Select one absolute OPC name with --part; no basename or wildcard matching.",
711
+ "--raw is byte-exact, including BOM and encoding. Default JSON uses base64.",
712
+ "--pretty is UTF-8 display serialization, not byte-exact XML; existing text whitespace is retained."
713
+ );
714
+ if (id === "xml.set") lines.push(
715
+ "",
716
+ "--file supplies a complete XML document, never a fragment or expression.",
717
+ "Root expanded name, document kind/dialect and package references must remain valid.",
718
+ "Opaque content must retain its structural position and namespace context; protected/signed inputs reject."
719
+ );
720
+ if (id === "text.get") lines.push(
721
+ "",
722
+ "Alias: docx text INPUT [OPTIONS]. View defaults to final.",
723
+ "Hidden text is included; formatting is direct context, without style resolution.",
724
+ "Field instructions and drawing/equation text are omitted.",
725
+ "Order: body, headers, footers, footnotes, endnotes, comments, text boxes.",
726
+ "Shared parts appear once. Notes/comments: canonical part, then numeric ID.",
727
+ "Paragraph/row: LF; cell/tab: TAB; story: two LFs; page: FF; column: VT.",
728
+ "Cached page breaks add nothing. No extra trailing separator is appended."
729
+ );
730
+ }
731
+ if (documentBatchOperations.includes(id)) {
732
+ for (const [index, line] of lines.entries()) lines[index] = line.replaceAll("Generic utility batches", "Unregistered utility batches").replaceAll("utility batch execution", "unregistered utility batch execution").replaceAll("Utility batch", "Unregistered utility batch").replaceAll("ordered batches remain unsupported", "unregistered ordered batches remain unsupported");
733
+ lines.push("", "This operation supports the admitted ordered utility batch subset; later selections resolve against staged state. Use schema to discover individual typed model routes and their supported subsets.");
734
+ }
735
+ return formatDiscoveryLines(lines);
736
+ }
737
+ function formatDiscoveryLines(lines) {
738
+ const wrapped = [];
739
+ for (const source of lines) {
740
+ let line = escapeTerminalText(source);
741
+ const indent = line.slice(0, line.length - line.trimStart().length);
742
+ while (line.length > 140) {
743
+ const space = line.lastIndexOf(" ", 140);
744
+ const end = space > indent.length ? space : 140;
745
+ wrapped.push(line.slice(0, end));
746
+ line = indent + line.slice(end).trimStart();
747
+ }
748
+ wrapped.push(line);
749
+ }
750
+ return wrapped.join("\n") + "\n";
751
+ }
752
+ function getDocxDiscovery(invocation, budget = new DocumentBudget2()) {
753
+ const parsedBudget = docxInvocationBudgets2.get(invocation);
754
+ if (parsedBudget) budget = budget.lower(Object.fromEntries(Object.entries(budget.limits).map(([name, ceiling]) => [name, Math.min(ceiling, parsedBudget.limits[name])])), parsedBudget.signal);
755
+ invocation = validateDocxInvocation(invocation, budget);
756
+ if (!docxOperationSchemas2[invocation.operation]?.discovery || invocation.inputs.length) return void 0;
757
+ if (invocation.options.limit !== void 0) budget = budget.lower(Object.fromEntries(
758
+ invocation.options.limit.map((item) => [item.name, item.value])
759
+ ));
760
+ const bounded = (discovery) => {
761
+ const wire = invocation.options.json === true || invocation.operation === "schema" ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data: discovery.data, warnings: [], errors: [], affected: 0, locations: [] }) + "\n" : discovery.human;
762
+ const bytes = new TextEncoder().encode(wire).byteLength;
763
+ budget.check("serializedOutput", bytes);
764
+ budget.charge("retainedBytes", bytes);
765
+ return discovery;
766
+ };
767
+ if (invocation.operation === "version") return bounded({
768
+ data: { name: "docx", version: package_default.version, schemaVersion: 1 },
769
+ human: `docx ${escapeTerminalText(package_default.version)}
770
+ `
771
+ });
772
+ if (invocation.operation === "capabilities") {
773
+ const limits = Object.entries(budget.limits).filter(([, ceiling]) => ceiling !== Infinity).map(([name, ceiling]) => ({ name, ceiling }));
774
+ const catalog = [
775
+ { id: "F01", level: "edit", subsets: [{ name: "bounded-opc", level: "edit", reason: "Bounded ZIP/OPC read and validated publication; encrypted and multi-disk packages reject. Full schema validation is not provided." }], detected: null },
776
+ { id: "F02", level: "edit", subsets: [{ name: "original-dialect", level: "edit", reason: "Admit Strict and Transitional dialects and edit only supported structures in the original dialect. No implicit conversion or full schema certification." }], detected: null },
777
+ { id: "F03", level: "edit", subsets: [{ name: "macro-free-kinds", level: "edit", reason: "Read and create original DOCX and DOTX packages with explicit kind. Macro-enabled mutations reject; suffixes do not establish package kind." }], detected: null },
778
+ { id: "F04", level: "preserve", subsets: [{ name: "opaque-xml-retention", level: "preserve", reason: "Namespace-aware bounded edits retain unmodified opaque XML. Recognition does not authorize semantic edits; affected unsupported structures reject." }], detected: null },
779
+ { id: "F05", level: "read", subsets: [{ name: "declared-compatibility-profile", level: "read", reason: "Bounded logical reads use the declared understood-namespace profile. Unselected alternate branches remain preserved; unknown MustUnderstand requirements and affected unsupported branches reject. No blanket extension support." }], detected: null },
780
+ { id: "F50", level: "edit", subsets: [{ name: "explicit-inventory-packing", level: "edit", reason: "Sorted authenticated VFS records, retained kind/dialect and exact opaque bytes; complete graph validation and one deterministic staged publication. No scanning or ambient files." }, { name: "exclusive-archive-extraction", level: "read", reason: "Whole namespace admission, exact all/media-only bytes and optional pretty XML into a new explicit tree; conditional VFS directory/file creation and explicit partial-output consent. No rollback or live-model claim." }], detected: null },
781
+ { id: "F48", level: "read", subsets: [{ name: "bounded-comparison", level: "read", reason: "Explicit package payload/XML or story text/structure scope. Both inputs share cumulative retention, XML, work and change budgets; no rendering, ID renumbering or host I/O." }], detected: null },
782
+ { id: "F47", level: "edit", subsets: [{ name: "record-template-filling", level: "edit", reason: "Exact tagged body control bindings, typed records and native nested rows/sections; four repeat levels, 1,000 items per region and cumulative budgets. Empty arrays retain reusable cleared prototypes. IDs and occurrence-local relationships remap before one publication; no expressions or host access. Template apply is available in the ordered utility batch. Whole model APIs remain pending." }], detected: null },
783
+ { id: "F46", level: "edit", subsets: [{ name: "selective-sanitization", level: "edit", reason: "Fixed-order explicit properties/comments/revisions/links/objects actions with exact effects and retained gaps; unsupported affected review/objects reject before publication. No comprehensive privacy or recoverability promise; utility batches remain unsupported." }], detected: null },
784
+ { id: "F45", level: "edit", subsets: [{ name: "seeded-selected-dummy-text", level: "edit", reason: "Required seed, paragraph-local original vocabulary, explicit count or whitespace-delimited logical span count; retain formatting and nontext data. Not anonymization; no time, randomness, networking or external generator. Generic utility batches and live owners remain pending." }], detected: null },
785
+ { id: "F44", level: "edit", subsets: [{ name: "bounded-content-removal", level: "edit", reason: "Explicit paragraph/run scalar endpoints and marker inclusion; whole paragraphs, runs and tables. Section breaks, required empty paragraphs and all resource graphs survive. Affected annotations, notes, fields, review and graphics reject; no cross-container ranges, resource garbage collection or utility batches." }], detected: null },
786
+ { id: "F43", level: "edit", subsets: [{ name: "signature-structure-inventory", level: "read", reason: "Exact declared OPC origin, relationship and part roles, including external metadata; cryptographic validity is unknown." }, { name: "explicit-signature-removal", level: "edit", reason: "Complete safe signature graph and content-type removal with exact reports. Default mutations reject signed input; no signature regeneration. Explicit signature removal is available in the ordered utility batch before other edits." }], detected: null },
787
+ { id: "F40", level: "preserve", subsets: [{ name: "inert-object-inventory-extraction", level: "read", reason: "OLE/package relationships, shape-bound previews and shared resources; exact bounded VFS payload extraction. No activation, binary decoding or linked fetch. Macro/protection state remains unknown unless declared; external targets are redacted." }], detected: null },
788
+ { id: "F39", level: "edit", subsets: [{ name: "physical-equation-inventory", level: "read", reason: "Package-global physical outer math units with inert stored/global properties and inactive/opaque preservation." }, { name: "bounded-equation-fragments", level: "edit", reason: "Explicit whole-paragraph append or same-root unit replacement using matching-dialect bounded fragments. Full schema, evaluation, conversion, layout, rendering, utility batch execution and live math models remain unsupported." }], detected: null },
789
+ { id: "F38", level: "read", subsets: [{ name: "physical-diagram-inventory", level: "read", reason: "Package-global physical role candidates and native bindings with inert graph closure, including orphan parts. Preserve-only snapshots imply no semantic editing, activation, rendering, external acquisition or live model support." }, { name: "opaque-graphics-preservation", level: "preserve", reason: "Eligible unknown graphics and extensions remain separately qualified opaque observations, including inactive alternatives. Unknown-only evidence does not establish a known diagram; utility batch execution remains unsupported." }], detected: null },
790
+ { id: "F37", level: "read", subsets: [{ name: "physical-chart-part-inventory", level: "read", reason: "Package-wide definitions, including unreferenced parts, with ordered plot groups, indexed string/numeric/multilevel caches and inert formula metadata. Cached freshness unknown; no active occurrence, formula engine, workbook validation or rendering claim." }, { name: "opaque-chart-preservation", level: "preserve", reason: "Extension/wrong-profile definitions remain explicitly opaque. Workbook/style/color descriptors and physical graph references stay inert; utility batch and live models are unsupported." }], detected: null },
791
+ { id: "F36", level: "edit", subsets: [{ name: "native-shape-inventory", level: "read", reason: "Active native, Office and VML shape/group occurrences with hierarchy, stored metadata, text-box story owners and physical section references. No rendering, geometry editing or live drawing models." }, { name: "simple-text-box-assignment", level: "edit", reason: "Whole simple admitted ungrouped box text assignment replaces run formatting and retains paragraph properties/geometry. Preserving scoped text editors reuse carrier authority. Nested/grouped, linked, opaque, multiple-body and shared-header edits reject; no implicit shared edits or utility batch execution." }], detected: null },
792
+ { id: "F32", level: "edit", subsets: [{ name: "inline-png-jpeg-insertion", level: "edit", reason: "Original bounded utility insertion of admitted PNG/JPEG bytes into one whole paragraph or admitted body/cell/explicit header/note block container. Native per-axis DPI with independent 72 fallback, explicit physical units, checked contain/cover/stretch and decorative/alt intent. Known suffixes must match bytes; retained exact media and capability publication. Five-format header metadata characterization does not imply insertion of GIF/BMP/TIFF. Floating authoring, SVG without a supplied fallback, pixel decoding and rendering remain unsupported. Live inline picture sizing and collection lookup are available through declared typed model routes. The separate static SVG/fallback insertion subset is qualified under F35." }, { name: "standalone-image-values", level: "read", reason: "Immutable PNG, JPEG, GIF, BMP and TIFF values with bounded headers, effective DPI, native and scaled lengths, owned bytes and compatibility SHA-1. No image-part, shape or collection authority; insertion support remains separate." }, { name: "raster-occurrence-replacement", level: "edit", reason: "Direct bounded PNG, JPEG, GIF, BMP and TIFF occurrence replacement clones and rebinds one drawing; explicit shared intent rebinds the resolved resource across physical owners. Default geometry and inactive references remain preserved. Linked/alternate/fallback replacement and unregistered utility batch execution remain pending. Declared image-part, drawing and collection model routes are available." }], detected: null },
793
+ { id: "F31", level: "read", subsets: [{ name: "image-inventory-extraction", level: "read", reason: "Bounded selected occurrence/resource inventory and exact original-byte VFS extraction with explicit manifest-inclusive publication intent. Unknown geometry/media stays null or opaque preserve-only; linked resources remain inert. No pixel decoding, DPI/native-size, rendering, live model or full image parity." }], detected: null },
794
+ { id: "F33", level: "edit", subsets: [{ name: "stored-image-layout", level: "read", reason: "Read admitted native extents, crop, rotation, flips, wrap, z-order, separate axis positions and alt/decorative metadata. Unsupported or invalid metadata stays null with warnings; no rendering is inferred." }, { name: "native-picture-layout", level: "edit", reason: "Direct bounded edits of coherent existing native picture extents, crop, transform, aspect locks and metadata; admitted anchors support separate axis frames, offsets or alignments, distances, stacking and explicit wrapping polygons. Exact media, relationships and admitted coherent alternate associations are preserved. Inline conversion and rendering remain unsupported. Live inline picture sizing and collection lookup are available through declared typed model routes." }], detected: null },
795
+ { id: "F34", level: "read", subsets: [{ name: "inert-image-alternatives", level: "read", reason: "Selected core-v1 carrier references and exact admitted internal alternate/fallback bytes; raw selected VML remains preserve-only. Inactive MCE evidence stays preserved; no Choice activation, unsupported decoding or external acquisition." }], detected: null },
796
+ { id: "F35", level: "edit", subsets: [{ name: "shared-image-owners", level: "read", reason: "Occurrence-local geometry and exact selected-owner references remain distinct from shared byte hashes. Unique groups after selection with first selected representative and no null-hash grouping; Live shared-image models remain pending." }, { name: "explicit-shared-raster-replacement", level: "edit", reason: "Explicit direct replacement targets the resolved internal resource across owner-local relationships, preserving geometry and reporting each physical owner. Filename and byte-hash equality never establish shared identity. Utility batch and live model execution remain pending." }, { name: "static-svg-fallback-insertion", level: "edit", reason: "Direct inline insertion of bounded static safe SVG XML with explicitly supplied validated PNG, JPEG, GIF, BMP or TIFF fallback. Fallback pixel dimensions and per-axis DPI supply native geometry; original SVG/fallback bytes, distinct media parts and owner-local relationships form one coherent occurrence. No fetching, rasterization, pixel decoding, MCE activation or rendering parity. Floating insertion and SVG/fallback replacement remain unsupported. Live inline picture sizing and collection lookup are available through declared typed model routes." }], detected: null },
797
+ { id: "F30", level: "edit", subsets: [{ name: "typed-document-properties", level: "edit", reason: "Read and explicitly set/remove admitted core, extended and custom scalar metadata. Exact qualified or unambiguous stored names; UTC whole-second utility strings and retained custom variants/IDs. Missing-part creation is explicit and collision-safe. Cached, opaque, invalid and ambiguous metadata stays read/preserve-only; unrelated timestamps, counts and XML remain unchanged. Live CoreProperties reads and setters also support typed model batches with explicit metadata for part creation. No automatic clocks, recalculation or corpus conformance claim." }], detected: null },
798
+ { id: "F28", level: "edit", subsets: [{ name: "control-values", level: "edit", reason: "Bounded plain/rich scalar text, declared checkbox glyphs, stored choice values, numeric Gregorian dates and existing internal PNG picture replacement. Indexed nested/unsupported controls remain inspected. Locked or bound filling, parent replacement erasing nested controls and unsupported affected structures reject atomically. Declared binding synchronization uses the separate controls bind route. Live model owners and ordered batches remain unsupported." }], detected: null },
799
+ { id: "F29", level: "edit", subsets: [{ name: "native-repetition", level: "edit", reason: "Bounded native block and unmerged grid-row repetition from exact scalar records, including empty reusable placeholders. Remap contained IDs, bookmarks, classic comments and admitted inline PNG drawings while retaining shared media. Affected bindings, locks, review, opaque structures and crossing ownership reject. Template apply, live owners and ordered batches remain pending." }, { name: "binding-synchronization", level: "edit", reason: "Declared tag keys identify one internal custom XML singleton and all complete scoped recipients, including aliases. Root-inclusive namespace-resolved child paths and explicit string/boolean/integer/double types preserve false, zero and empty values. Unresolved same-store recipients, incomplete scope, ambiguity and locks reject before publication. No binding detachment or resource fetch." }], detected: null },
800
+ { id: "F26", level: "edit", subsets: [{ name: "revision-decisions", level: "edit", reason: "Direct acceptance/rejection of ordinary inline text wrappers and supported exposed-field run/paragraph property history. Scoped ordinal, whole revision token or explicit all; validate every selected candidate before edits, preserving unselected review and required owners. Nested/compound/move/table/section/opaque review and affected field/control/range boundaries reject. Available in the ordered utility batch; use schema for bounded live model routes." }, { name: "tracked-text-creation", level: "edit", reason: "Explicit-author/time insertion, deletion and literal replacement on admitted scalar text ranges. Preserve original/final/all views and run properties; affected existing review and compound boundaries reject. Acceptance/rejection is a separate bounded subset; available in the ordered utility batch; use schema for bounded live model routes." }, { name: "revision-read-views", level: "read", reason: "Final/original/all text and run/paragraph property snapshots; IDs, authors and stored timestamps. Ordinary unrelated edits preserve review markup. Tracked creation and acceptance/rejection are separately bounded editing subsets." }], detected: null },
801
+ { id: "F27", level: "read", subsets: [{ name: "complex-revision-inventory", level: "read", reason: "Move wrappers/range markers and opaque table, section and extension revisions; affected complex edits reject." }], detected: null },
802
+ { id: "F25", level: "edit", subsets: [{ name: "classic-comments", level: "edit", reason: "Explicit author/time and run-boundary anchors in admitted body, footnote and endnote stories; utility shared-note occurrences, header/footer and nested-comment anchors reject. List/get/set/remove comments preserve unrelated annotations. Declared live comment owners and typed comment model batches support the bounded rich-content operations listed by schema." }, { name: "comment-extension-synchronization", level: "edit", reason: "Inventories extension parts and IDs; single-paragraph text edits retain thread links and resolution. Removal synchronizes verified IDs and people; surviving replies, opaque affected metadata and unverified structures reject. Thread authoring remains unsupported." }], detected: null },
803
+ { id: "F24", level: "edit", subsets: [{ name: "footnotes-endnotes", level: "edit", reason: "Read, insert, edit and remove notes and references with reserved separator preservation, scoped IDs and explicit shared-reference policies. Document and section numbering/restart rules remain intact; storage renumbering does not calculate pagination or displayed numbers. Live document model remains pending." }], detected: null },
804
+ { id: "F23", level: "edit", subsets: [{ name: "toc-caption-structures", level: "edit", reason: "Bounded TOC levels, inert caption sequences and static labels. Explicit cached text and dirty flags; no layout or sequence evaluation. Existing sequence collisions require explicit reuse." }], detected: null },
805
+ { id: "F22", level: "edit", subsets: [{ name: "cached-fields", level: "edit", reason: "List simple, complex and nested fields; edit supported plain cached results without execution. Preserve instructions, formatting and omitted flags. Create bounded fields and edit typed instructions. Nested-result replacement, shared-story editing and live model remain pending." }], detected: null },
806
+ { id: "F21", level: "edit", subsets: [{ name: "bookmark-ranges", level: "edit", reason: "List, create, rename and remove checked ranges; explicit reference policy for internal links and REF/PAGEREF fields. Multi-run paragraph and table-cell boundaries; stale, missing, duplicate and crossing structures checked. Complex reference removal, shared-story edits and general field/model APIs remain unsupported." }, { name: "hyperlinks", level: "edit", reason: "Create, list, retarget and unwrap direct paragraph hyperlinks; explicit label deletion. Inert HTTP/HTTPS/mailto and internal anchors, owner-scoped relationship cleanup. Shared story edits remain pending. Declared live hyperlink getters expose stored values through typed model routes." }], detected: null },
807
+ { id: "F20", level: "edit", subsets: [{ name: "logical-grid", level: "edit", reason: "Inspect logical owners and spans. Explicit rectangular merges join blocks in row order; split restores existing grid slots with anchor or paragraph distribution. Covered writes require owner intent. Row deletion preserves surviving spans. Omitted/wrapped grids, legacy merges and span insertion/column removal remain unsupported." }], detected: null },
808
+ { id: "F19", level: "edit", subsets: [{ name: "table-construction", level: "edit", reason: "Bounded rectangular grids, nested typed blocks, repeated leading headers, borders/shading, margins and row height/splitting. Selected cell values and table/row/cell formatting, explicit rectangular row/column insertion and deletion. Merged grids support explicit merge/split and row removal; omitted grids remain readable. Span insertion and column removal remain pending. Live table, row and cell owners are available through declared typed model routes." }], detected: null },
809
+ { id: "F18", level: "edit", subsets: [{ name: "multilevel-numbering", level: "edit", reason: "Bounded list add/set, levels 0-8, scoped IDs and start/restart overrides; resolve paragraph and numbering style links. Preserve mixed levels and unrelated opaque schemes/picture resources. Advanced level-definition setters and whole numbering-model coverage remain pending." }, { name: "owned-numbering-part-creation", level: "edit", reason: "Synchronous NumberingPart.new(ownerPackage) and missing-part getter creation return an attached live part with its dialect, content type and internal relationship staged together. Reuse preserves existing definitions; explicit creation validates the graph. Typed batch handles share owner budgets, rollback and one publication." }], detected: null },
810
+ { id: "F17", level: "edit", subsets: [{ name: "header-footer-stories", level: "edit", reason: "Noncreating reads of every variant; explicit shared edits, local clone/rebind and removal. Preserve cached fields and outgoing resources; scoped paragraph/text operations reuse story ownership. Whole-story text rejects fields, tables and opaque blocks. Declared live header/footer owners expose their bounded paragraph and table operations through typed model routes." }], detected: null },
811
+ { id: "F16", level: "edit", subsets: [{ name: "section-page-settings", level: "edit", reason: "Edit owner-local geometry, columns, section starts, page-number and first-page metadata; append sections and inventory inherited header/footer bindings. Even/odd policy is document-wide and requires explicit all-section scope. No pagination claim." }], detected: null },
812
+ { id: "F41", level: "preserve", subsets: [{ name: "package-resource-inventories", level: "read", reason: "Package-global customXML and glossary metadata, whole-part locations, ancillary closure and inert external references. Missing or ambiguous metadata remains preserved with bounded warnings; no content dump, import, schema fetch or semantic editing." }, { name: "opaque-package-retention", level: "preserve", reason: "Retain unedited ancillary payloads and relationship XML across admitted mutations. Bound raw replacements and unsupported same-store recipients reject rather than detach or partially synchronize." }], detected: null },
813
+ { id: "F42", level: "read", subsets: [{ name: "settings-and-protection", level: "read", reason: "Package-global stored settings, compatibility, field-update and font embedding flags; credential-free protection state. Only raw boolean field-update intent is editable. Protected packages and changed locked controls reject; unchanged locked owners survive scoped text replacement. Unknown settings remain preserved; no rights bypass, password verification or font installation." }, { name: "theme-and-font-resources", level: "read", reason: "Inspect theme colors, major/minor/script fonts, font tables, embedding metadata and reference diagnostics. Preserve embedded bytes and language metadata; embedded font mutation is unsupported. No installation, availability, licensing or rasterization inference." }], detected: null },
814
+ { id: "F15", level: "edit", subsets: [{ name: "title-and-heading-creation", level: "edit", reason: "Level 0 creates Title; levels 1-9 create paragraph headings through creation and paragraph insertion. Deterministic style IDs preserve conflicting user definitions and reuse compatible built-ins. Heading creation is also available through the typed Document.add_heading model route." }], detected: null },
815
+ { id: "F14", level: "edit", subsets: [{ name: "style-definitions", level: "edit", reason: "Paragraph, character and table styles; defaults, inheritance, linked styles and heading definitions. Latent defaults and individual visibility, priority, locking and gallery metadata are editable. Live style collections, inherited font/paragraph objects, latent entries and owned typed batches are implemented; use schema for implemented document content model operations and their supported subsets." }], detected: null },
816
+ { id: "F13", level: "edit", subsets: [{ name: "paragraph-editing", level: "edit", reason: "Direct paragraph properties and whole text; block and inline caret insertion with suffix retention. Explicit breaks, sorted tab stops, border sides and shading; style-owned paragraph model handles are implemented." }], detected: null },
817
+ { id: "F12", level: "edit", subsets: [{ name: "bounded-ordered-utility-batch", level: "edit", reason: `F47: Version 1 ordered typed operations with stable IDs, whole-array syntax admission, staged selections, shared budgets, final validation and one publication. Admitted IDs: ${documentBatchOperations.join(", ")}. Use schema to discover individual typed model routes and their supported subsets.` }, { name: "scoped-direct-run-formatting", level: "edit", reason: "Whole-run text assignment retains owning formatting; run or paragraph scalar ranges accept formatting only. Nullable direct properties, explicit font/theme references and half-point sizes. No style resolution, font loading or whole document model execution." }], detected: null },
818
+ { id: "F11", level: "edit", subsets: [{ name: "structured-creation", level: "edit", reason: "DOCX/DOTX, Strict/Transitional; original paragraphs/tables and explicit new-package settings; append-only supplied templates." }], detected: null },
819
+ { id: "F06", level: "read", subsets: [{ name: "inventory", level: "read", reason: "No rendering, linked-resource access or signature verification." }], detected: null },
820
+ { id: "F49", level: "read", subsets: [{ name: "core-v1", level: "read", reason: "Partial core-v1 validation only." }], detected: null },
821
+ { id: "F08", level: "read", subsets: [{ name: "logical-story-text", level: "read", reason: "Explicit story scopes and review views; hidden text included, cached field results only; no drawing/equation text or rendering." }], detected: null },
822
+ { id: "F09", level: "read", subsets: [{ name: "logical-unicode", level: "read", reason: "Unicode order and direct language/RTL/font properties; no shaping or style cascade." }], detected: null },
823
+ { id: "F07", level: "edit", subsets: [{ name: "explicit-xml-part", level: "edit", reason: "Validated whole-part replacement; immutable opaque content, no protection bypass; raw bytes or bounded display serialization." }], detected: null },
824
+ { id: "F10", level: "edit", subsets: [{ name: "literal-paragraph-text", level: "edit", reason: "Nonoverlapping original-text matches, run formatting preservation, explicit cardinality and bold/italic overrides; structural barriers, protected and shared parts guarded." }], detected: null }
825
+ ];
826
+ const data2 = { input: null, features: catalog.map((feature) => ({ ...feature, operationIds: Object.entries(docxOperationSchemas2).filter(([, declaration]) => declaration.featureIds.includes(feature.id)).map(([id]) => id) })), host: { read: false, atomicReplace: false, transactions: false, binaryStdout: true }, limits, validationProfiles: [documentValidationProfile] };
827
+ return bounded({ data: data2, human: capabilitiesHelp(data2) });
828
+ }
829
+ const selected = invocation.options.operation;
830
+ const declarations = selected ? [[selected, docxOperationSchemas2[selected]]] : Object.entries(docxOperationSchemas2);
831
+ if (invocation.operation === "help") {
832
+ const data2 = { name: "docx", paths: declarations.map(([id, declaration]) => ({
833
+ path: commandPath(id, declaration),
834
+ usage: usage2(id, declaration),
835
+ description: description(declaration),
836
+ operationIds: [id]
837
+ })) };
838
+ return bounded({ data: data2, human: selected ? details(selected, declarations[0][1]) : formatDiscoveryLines([
839
+ "docx \u2014 document utility",
840
+ "",
841
+ "Common tasks:",
842
+ " docx create -o empty.docx",
843
+ " docx text INPUT",
844
+ " docx text replace INPUT --find Draft --with Final --all -o final.docx",
845
+ " docx images list INPUT",
846
+ " docx images replace INPUT --image 1 --file emblem.png --in-place",
847
+ " docx tables set INPUT --table 1 --cell B2 --text Harbor --in-place",
848
+ " docx properties set INPUT --name title --value 'Coastal caf\xE9' --in-place",
849
+ "",
850
+ "Use docx help COMMAND PATH for options, selectors and supported subsets; for example docx help images replace.",
851
+ "Mutations require --output or --in-place unless --dry-run. Positions are one-based; --select uses a fresh fingerprinted location.",
852
+ "",
853
+ "Implemented commands and declared unsupported contracts (read/edit/reject):",
854
+ ...declarations.filter(([, declaration]) => declaration.transport !== "typed-batch").map(([id, declaration]) => ` ${usage2(id, declaration)} [${operationSupport(id, declaration)}]`),
855
+ "",
856
+ "Use docx help batch --operation ID for every typed model declaration; schema enumerates all declarations.",
857
+ "Edit/read labels cover only admitted subsets. Reject labels are declared contracts without execution support.",
858
+ "Aliases: --help, -h; --version."
859
+ ]) });
860
+ }
861
+ const data = { schemaVersion: 1, validationProfiles: [documentValidationProfile], operations: declarations.map(([id, declaration]) => ({
862
+ id,
863
+ path: commandPath(id, declaration),
864
+ input: getDocxOperationSchema(id, declaration.transport === "typed-batch" ? "batch" : "sdk"),
865
+ result: id === "pack" ? archivePackingContract.result : id === "extract" ? archiveExtractionContract.result : id === "batch" ? documentBatchResultSchema() : styleModelBatchOperations.includes(id) ? styleModelOperationResultSchema(id) : objectOperationContracts[id]?.result ?? equationOperationContracts[id]?.result ?? diagramOperationContracts[id]?.result ?? chartOperationContracts[id]?.result ?? shapeOperationContracts[id]?.result ?? inspectionOperationMetadata[id]?.result ?? imageOperationContracts[id]?.result ?? rasterInsertionOperationContracts[id]?.result ?? imageLayoutOperationContracts[id]?.result ?? rasterReplacementOperationContracts[id]?.result ?? propertyOperationContracts[id]?.result ?? declaration.discovery?.result ?? { ...discoveryFailureSchema(id), description: "Only failures are specified here; operation not implemented." },
866
+ featureIds: declaration.featureIds,
867
+ support: operationSupport(id, declaration)
868
+ })) };
869
+ return bounded({ data, human: JSON.stringify(data) + "\n" });
870
+ }
871
+ async function inspectDocxCapabilities(bytes, context, host = {}) {
872
+ const budget = context.budget ?? new DocumentBudget2({}, context.signal);
873
+ const base = getDocxDiscovery({ operation: "capabilities", inputs: [], options: {} }, budget).data;
874
+ const inspected = await inspectDocument(bytes, { ...context, budget });
875
+ const detections = new Map(inspected.features.map((feature) => [feature.id, feature.detected]));
876
+ const data = {
877
+ ...base,
878
+ host: { read: host.capabilities?.read !== false && typeof host.readFile === "function", atomicReplace: host.capabilities?.atomicFileStaging === true && typeof host.createStagedFile === "function" && typeof host.publishStagedFile === "function" && typeof host.removeStagedFile === "function", transactions: false, binaryStdout: true },
879
+ features: base.features.map((feature) => ({ ...feature, detected: feature.id === "F01" || feature.id === "F02" || feature.id === "F03" || feature.id === "F04" ? true : detections.get(feature.id) ?? null })),
880
+ input: {
881
+ signed: inspected.signed,
882
+ protected: inspected.protected,
883
+ unsupportedNamespaces: inspected.unsupportedNamespaces,
884
+ unsupportedOperations: Object.entries(docxOperationSchemas2).filter(([id, declaration]) => operationSupport(id, declaration) === "reject" || declaration.mutates && (inspected.signed && id !== "signatures.remove" || inspected.protected)).map(([id]) => id)
885
+ }
886
+ };
887
+ const human = capabilitiesHelp(data);
888
+ const encoder = new TextEncoder();
889
+ budget.check("serializedOutput", Math.max(encoder.encode(JSON.stringify(data)).byteLength, encoder.encode(human).byteLength));
890
+ return { data, human };
891
+ }
892
+ function capabilitiesHelp(data) {
893
+ const human = "docx capabilities\n\n" + data.features.map((feature) => `${feature.id}: ${feature.level}; detected: ${feature.detected ?? "unknown"}
894
+ ${feature.subsets.map((subset) => `${subset.name}: ${subset.level} \u2014 ${subset.reason}`).join("\n ")}`).join("\n") + "\n\nLimits:\n" + data.limits.map((limit) => ` ${limit.name}: ${limit.ceiling}`).join("\n") + (data.input ? "\nUnsupported namespaces: " + (data.input.unsupportedNamespaces.map(escapeTerminalText).join(", ") || "none detected") : "\nNo input inspected; feature presence is unknown.") + "\nRead returns stored data; preserve retains opaque content; edit covers only the listed subsets; reject has no execution support.\nRecognition and absence of a tag do not establish editing support.\n";
895
+ return formatDiscoveryLines(human.trimEnd().split("\n"));
896
+ }
897
+
898
+ // packages/safe-bash-command-docx/src/pack-command.ts
899
+ import { dirname, resolvePath } from "@poe-platform/safe-fs/core";
900
+ import { parseDocxJson as parseDocxJson2 } from "../../safe-bash-docx-engine/argument-json.js";
901
+ import { packDocumentArchive } from "../../safe-bash-docx-engine/pack.js";
902
+ import { asPermissionError as asPermissionError2 } from "../../safe-bash-docx-engine/io-errors.js";
903
+ async function executePackCommand(invocation, request, context, io) {
904
+ const input = invocation.inputs[0], path2 = input === "-" ? void 0 : resolvePath(request.cwd, input);
905
+ let bytes;
906
+ try {
907
+ if (path2 !== void 0) {
908
+ const fs = request.filesystem;
909
+ const segments = path2.split("/").slice(1);
910
+ let current = "";
911
+ for (let i = 0; i < segments.length; i++) {
912
+ current += "/" + segments[i];
913
+ const stat = await fs.lstat(current, { signal: request.signal });
914
+ if (stat.type !== (i === segments.length - 1 ? "file" : "directory") || await fs.realpath(current, { signal: request.signal }) !== current)
915
+ throw new SourceError2();
916
+ }
917
+ }
918
+ bytes = await io.readBytes({ open(signal) {
919
+ if (path2 === void 0) return request.stdin;
920
+ return request.filesystem.readStream ? request.filesystem.readStream(path2, { signal }) : { async *[Symbol.asyncIterator]() {
921
+ yield await request.filesystem.readFile(path2, { signal });
922
+ } };
923
+ } });
924
+ } catch (error) {
925
+ request.signal.throwIfAborted();
926
+ if (error && typeof error === "object" && "code" in error && ["limit-exceeded", "cancelled"].includes(String(error.code))) throw error;
927
+ throw asPermissionError2(error) ?? new SourceError2(error);
928
+ }
929
+ const inventory = parseDocxJson2(bytes, context.budget);
930
+ const options = { ...invocation.options, ...typeof invocation.options.output === "string" && invocation.options.output !== "-" ? { output: resolvePath(request.cwd, invocation.options.output) } : {} };
931
+ const data = await packDocumentArchive(inventory, options, { ...context, filesystem: request.filesystem, stdout: request.stdout, ...path2 === void 0 ? {} : { inventoryDirectory: dirname(path2) } });
932
+ if (options.output === "-" && !data.dryRun) return new Uint8Array();
933
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: "pack", ok: true, data, warnings: [], errors: [], affected: 1, locations: [] }) + "\n" : `docx pack: ${data.dryRun ? "dry-run; " : ""}1 document created
934
+ `);
935
+ }
936
+
937
+ // packages/safe-bash-command-docx/src/inspection-command.ts
938
+ import { extractDocumentArchive, ArchiveExtractionError } from "../../safe-bash-docx-engine/extract.js";
939
+ import { compareDocument } from "../../safe-bash-docx-engine/diff.js";
940
+
941
+ // packages/safe-bash-command-docx/src/removal-command.ts
942
+ import { resolvePath as resolvePath2 } from "@poe-platform/safe-fs/core";
943
+ import { removeDocumentContent } from "../../safe-bash-docx-engine/removal.js";
944
+ import { PublicationError } from "../../safe-bash-docx-engine/publication.js";
945
+ async function executeContentRemovalCommand(invocation, bytes, input, request, context) {
946
+ const options = invocation.options;
947
+ if ((options.inPlace || options.output !== void 0 && options.output !== "-") && invocation.inputs[0] !== "-" && !input)
948
+ throw new PublicationError("unsupported-publication", "File publication requires admitted input identity.");
949
+ const output = options.output === void 0 ? void 0 : options.output === "-" ? "-" : resolvePath2(request.cwd, options.output);
950
+ const data = await removeDocumentContent(
951
+ bytes,
952
+ { operation: invocation.operation, options: { ...options, ...output === void 0 ? {} : { output } }, ...input ? { input } : {} },
953
+ { ...context, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout }
954
+ );
955
+ if (output === "-" && !data.dryRun) return new Uint8Array();
956
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: data.changes.length, locations: data.changes.flatMap((c) => c.after ? [c.after] : []), warnings: [], errors: [] }) + "\n" : `docx ${invocation.operation.split(".").join(" ")}: ${data.dryRun ? "dry-run; " : ""}${data.changes.length} ${data.changes.length === 1 ? "selection" : "selections"} changed
957
+ `);
958
+ }
959
+
960
+ // packages/safe-bash-command-docx/src/objects-command.ts
961
+ import { resolvePath as resolvePath3 } from "@poe-platform/safe-fs/core";
962
+ import { measurePackageResourceSerialization } from "../../safe-bash-docx-engine/ancillary-resources.js";
963
+ import { archiveSettings, CancellationError } from "../../safe-bash-docx-engine/archive.js";
964
+ import { DocxUsageError as DocxUsageError2 } from "../../safe-bash-docx-engine/argument-json.js";
965
+ import {
966
+ inspectDocumentObjects,
967
+ extractDocumentObjects,
968
+ ObjectExtractionPublicationError,
969
+ ObjectExtractionCancellationError
970
+ } from "../../safe-bash-docx-engine/objects.js";
971
+ import { PublicationError as PublicationError2 } from "../../safe-bash-docx-engine/publication.js";
972
+ function utf8Length(text) {
973
+ let bytes = 0;
974
+ for (const character of text) {
975
+ const code = character.codePointAt(0);
976
+ bytes += code <= 127 ? 1 : code <= 2047 ? 2 : code <= 65535 ? 3 : 4;
977
+ }
978
+ return bytes;
979
+ }
980
+ function escapedUtf8Length(text) {
981
+ let bytes = 0;
982
+ for (const character of text) bytes += utf8Length(escapeTerminalText(character));
983
+ return bytes;
984
+ }
985
+ var ObjectCommandPublicationError = class extends ObjectExtractionPublicationError {
986
+ constructor(error, responseBytes, diagnosticBytes) {
987
+ super(error, error.data);
988
+ this.responseBytes = responseBytes;
989
+ this.diagnosticBytes = diagnosticBytes;
990
+ }
991
+ responseBytes;
992
+ diagnosticBytes;
993
+ };
994
+ async function executeObjectsCommand(invocation, bytes, input, request, context, onExtraction) {
995
+ if (!["objects.list", "objects.extract"].includes(invocation.operation))
996
+ throw new DocxUsageError2("Expected an object inspection or extraction operation.");
997
+ const settings = archiveSettings(context), options = invocation.options;
998
+ const budget = settings.budget.lower(
999
+ Object.fromEntries((options.limit ?? []).map((limit) => [limit.name, limit.value]))
1000
+ );
1001
+ const extraction = invocation.operation === "objects.extract";
1002
+ let reserved = false;
1003
+ const admitPublication = (planned) => {
1004
+ const { warnings: warnings2, ...data2 } = planned, locations2 = data2.entries.flatMap((entry) => entry.locations);
1005
+ const diagnosticSize2 = warnings2.reduce(
1006
+ (size, warning) => size + utf8Length(`docx: ${warning.code}: ${warning.message}
1007
+ `),
1008
+ 0
1009
+ );
1010
+ budget.check(
1011
+ "diagnosticBytes",
1012
+ diagnosticSize2 + utf8Length(
1013
+ "docx: unsupported-publication: Document operation failed: unsupported-publication\n"
1014
+ )
1015
+ );
1016
+ let responseSize;
1017
+ if (options.json) {
1018
+ const envelope2 = {
1019
+ version: 1,
1020
+ operation: invocation.operation,
1021
+ ok: true,
1022
+ data: data2,
1023
+ affected: 0,
1024
+ locations: locations2,
1025
+ warnings: warnings2,
1026
+ errors: []
1027
+ };
1028
+ const success = measurePackageResourceSerialization(envelope2, budget) + 1;
1029
+ const failure = measurePackageResourceSerialization(
1030
+ {
1031
+ ...envelope2,
1032
+ ok: false,
1033
+ data: { ...data2, complete: false },
1034
+ errors: [
1035
+ {
1036
+ code: "unsupported-publication",
1037
+ message: "Document operation failed: unsupported-publication"
1038
+ }
1039
+ ]
1040
+ },
1041
+ budget
1042
+ ) + 1;
1043
+ budget.check("serializedOutput", Math.max(success, failure));
1044
+ responseSize = Math.max(success, failure);
1045
+ } else {
1046
+ responseSize = utf8Length(`Objects extracted: ${data2.entries.length}; complete: false
1047
+ `);
1048
+ budget.check("serializedOutput", responseSize);
1049
+ }
1050
+ const diagnostics = diagnosticSize2 + utf8Length(
1051
+ "docx: unsupported-publication: Document operation failed: unsupported-publication\n"
1052
+ );
1053
+ budget.charge(
1054
+ "retainedBytes",
1055
+ responseSize * 12 + diagnostics * 12 + data2.entries.length * 512 + 1024
1056
+ );
1057
+ budget.charge("work", responseSize * 12 + diagnostics * 12 + data2.entries.length * 16 + 1024);
1058
+ reserved = true;
1059
+ return void 0;
1060
+ };
1061
+ const commandError = (error) => {
1062
+ const { warnings: warnings2, ...data2 } = error.data, diagnostic = commandDiagnostic(
1063
+ "Document operation failed: " + error.code,
1064
+ error.code,
1065
+ budget.limits.diagnosticBytes
1066
+ );
1067
+ const envelope2 = {
1068
+ version: 1,
1069
+ operation: invocation.operation,
1070
+ ok: false,
1071
+ data: data2,
1072
+ affected: 0,
1073
+ locations: data2.entries.flatMap((entry) => entry.locations),
1074
+ warnings: warnings2,
1075
+ errors: [{ code: error.code, message: diagnostic.message }]
1076
+ };
1077
+ return new ObjectCommandPublicationError(
1078
+ error,
1079
+ new TextEncoder().encode(options.json ? JSON.stringify(envelope2) + "\n" : ""),
1080
+ new TextEncoder().encode(diagnostic.human)
1081
+ );
1082
+ };
1083
+ let inspected;
1084
+ try {
1085
+ inspected = extraction ? await extractDocumentObjects(
1086
+ bytes,
1087
+ {
1088
+ ...options,
1089
+ outputDir: resolvePath3(request.cwd, options.outputDir),
1090
+ ...input ? { input } : {}
1091
+ },
1092
+ {
1093
+ ...settings,
1094
+ budget,
1095
+ encoding: { order: "input", compression: "store" },
1096
+ filesystem: request.filesystem,
1097
+ admitPublication
1098
+ }
1099
+ ) : await inspectDocumentObjects(
1100
+ bytes,
1101
+ invocation.options,
1102
+ { ...settings, budget }
1103
+ );
1104
+ } catch (error) {
1105
+ if (reserved && error instanceof ObjectExtractionPublicationError) throw commandError(error);
1106
+ throw error;
1107
+ }
1108
+ if ("entries" in inspected && onExtraction) onExtraction(inspected);
1109
+ const { warnings, ...data } = inspected;
1110
+ const records = "items" in data ? data.items : [];
1111
+ const locations = "entries" in data ? data.entries.flatMap((entry) => entry.locations) : records.map((record) => record.location);
1112
+ const envelope = {
1113
+ version: 1,
1114
+ operation: invocation.operation,
1115
+ ok: true,
1116
+ data,
1117
+ affected: 0,
1118
+ locations,
1119
+ warnings,
1120
+ errors: []
1121
+ };
1122
+ let text;
1123
+ if (options.json) {
1124
+ if (!reserved) {
1125
+ const size = measurePackageResourceSerialization(envelope, budget) + 1;
1126
+ budget.check("serializedOutput", size);
1127
+ budget.charge("retainedBytes", size * 6);
1128
+ }
1129
+ text = JSON.stringify(envelope) + "\n";
1130
+ } else if ("entries" in data) {
1131
+ text = `Objects extracted: ${data.entries.filter((entry) => entry.published).length}; complete: ${data.complete}
1132
+ `;
1133
+ } else {
1134
+ let size = utf8Length(`Objects: ${records.length}
1135
+ `);
1136
+ for (const record of records)
1137
+ size += escapedUtf8Length(record.name ?? "Unresolved object") + escapedUtf8Length(record.details.resource?.contentType ?? "unresolved") + utf8Length(`: ; ${record.details.resource?.bytes ?? "unknown"} bytes; ${record.support}
1138
+ `);
1139
+ budget.check("serializedOutput", size);
1140
+ budget.charge("retainedBytes", size * 6);
1141
+ text = `Objects: ${records.length}
1142
+ ` + records.map(
1143
+ (record) => `${escapeTerminalText(record.name ?? "Unresolved object")}: ${escapeTerminalText(record.details.resource?.contentType ?? "unresolved")}; ${record.details.resource?.bytes ?? "unknown"} bytes; ${record.support}
1144
+ `
1145
+ ).join("");
1146
+ }
1147
+ const diagnosticSize = warnings.reduce(
1148
+ (size, warning) => size + utf8Length(`docx: ${warning.code}: ${warning.message}
1149
+ `),
1150
+ 0
1151
+ );
1152
+ if (!reserved) {
1153
+ budget.check("diagnosticBytes", diagnosticSize);
1154
+ budget.charge("retainedBytes", diagnosticSize * 3 + utf8Length(text) * 3);
1155
+ }
1156
+ if (warnings.length) {
1157
+ try {
1158
+ await request.stderr.write(
1159
+ new TextEncoder().encode(
1160
+ warnings.map((warning) => `docx: ${warning.code}: ${warning.message}
1161
+ `).join("")
1162
+ )
1163
+ );
1164
+ settings.signal.throwIfAborted();
1165
+ } catch (cause) {
1166
+ const published = "entries" in data ? [
1167
+ ...data.entries.filter((entry) => entry.published).map((entry) => ({ path: entry.path, bytes: entry.bytes })),
1168
+ ...data.manifest.published ? [{ path: data.manifest.path, bytes: data.manifest.bytes }] : []
1169
+ ] : [];
1170
+ if (settings.signal.aborted) {
1171
+ const error2 = new CancellationError("Object diagnostics cancelled.", { cause });
1172
+ if ("entries" in data)
1173
+ throw new ObjectExtractionCancellationError(
1174
+ error2,
1175
+ { ...data, warnings, complete: false },
1176
+ published
1177
+ );
1178
+ throw error2;
1179
+ }
1180
+ const error = new PublicationError2(
1181
+ "sink-failure",
1182
+ "Object diagnostics could not be written.",
1183
+ published,
1184
+ false,
1185
+ { cause }
1186
+ );
1187
+ if ("entries" in data)
1188
+ throw commandError(
1189
+ new ObjectExtractionPublicationError(error, { ...data, warnings, complete: false })
1190
+ );
1191
+ throw error;
1192
+ }
1193
+ }
1194
+ budget.check("work", 0);
1195
+ return new TextEncoder().encode(text);
1196
+ }
1197
+
1198
+ // packages/safe-bash-command-docx/src/inspection-command.ts
1199
+ import { ObjectExtractionCancellationError as ObjectExtractionCancellationError2 } from "../../safe-bash-docx-engine/objects.js";
1200
+ import { inspectDocumentRevisions } from "../../safe-bash-docx-engine/revisions.js";
1201
+
1202
+ // packages/safe-bash-command-docx/src/revision-edit-command.ts
1203
+ import { resolvePath as resolvePath4 } from "@poe-platform/safe-fs/core";
1204
+ import { PublicationError as PublicationError3 } from "../../safe-bash-docx-engine/publication.js";
1205
+ import { editDocumentRevisions } from "../../safe-bash-docx-engine/revision-edit.js";
1206
+ async function executeRevisionEditCommand(invocation, bytes, input, request, context) {
1207
+ const options = invocation.options;
1208
+ const destination = options.output === void 0 || options.output === "-" ? options.output : resolvePath4(request.cwd, options.output);
1209
+ if ((options.inPlace || destination !== void 0 && destination !== "-") && invocation.inputs[0] !== "-" && !input)
1210
+ throw new PublicationError3("unsupported-publication", "Tracked file publication requires admitted input identity.");
1211
+ const data = await editDocumentRevisions(
1212
+ bytes,
1213
+ { ...options, ...input ? { input } : {}, ...destination === void 0 ? {} : { output: destination } },
1214
+ { ...context, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout }
1215
+ );
1216
+ if (destination === "-" && !data.dryRun) return new Uint8Array();
1217
+ const message = options.json ? JSON.stringify({ version: 1, operation: "revisions.add", ok: true, data, affected: data.changes.length, locations: data.changes.map((change) => change.after), warnings: [], errors: [] }) : `docx revisions add: ${data.dryRun ? "dry-run; " : ""}${data.changes.length} tracked ${options.kind === "insert" ? "insertions" : "deletions"}`;
1218
+ return new TextEncoder().encode(message + "\n");
1219
+ }
1220
+
1221
+ // packages/safe-bash-command-docx/src/revision-decisions-command.ts
1222
+ import { resolvePath as resolvePath5 } from "@poe-platform/safe-fs/core";
1223
+ import { PublicationError as PublicationError4 } from "../../safe-bash-docx-engine/publication.js";
1224
+ import { editDocumentRevisionDecisions } from "../../safe-bash-docx-engine/revision-decisions.js";
1225
+ async function executeRevisionDecisionCommand(invocation, bytes, input, request, context) {
1226
+ const options = invocation.options;
1227
+ const output = options.output === void 0 || options.output === "-" ? options.output : resolvePath5(request.cwd, options.output);
1228
+ if ((options.inPlace || output !== void 0 && output !== "-") && invocation.inputs[0] !== "-" && !input) throw new PublicationError4("unsupported-publication", "Revision decision publication requires admitted input identity.");
1229
+ const data = await editDocumentRevisionDecisions(
1230
+ bytes,
1231
+ { operation: invocation.operation, options: { ...options, ...output === void 0 ? {} : { output } }, ...input ? { input } : {} },
1232
+ { ...context, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout }
1233
+ );
1234
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1235
+ return new TextEncoder().encode((options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: data.changes.length, locations: data.changes.flatMap((change) => change.after ? [change.after] : []), warnings: [], errors: [] }) : `docx ${invocation.operation.split(".").join(" ")}: ${data.dryRun ? "dry-run; " : ""}${data.changes.length} ${data.changes.length === 1 ? "revision" : "revisions"} decided`) + "\n");
1236
+ }
1237
+
1238
+ // packages/safe-bash-command-docx/src/controls-command.ts
1239
+ import { resolvePath as resolvePath6 } from "@poe-platform/safe-fs/core";
1240
+ import { DocumentIo } from "../../safe-bash-docx-engine/io.js";
1241
+ import { PublicationError as PublicationError5 } from "../../safe-bash-docx-engine/publication.js";
1242
+ import { editDocumentControls, inspectDocumentControls } from "../../safe-bash-docx-engine/controls.js";
1243
+ async function executeControlsCommand(invocation, bytes, input, request, context) {
1244
+ if (invocation.operation === "controls.list") {
1245
+ const data2 = await inspectDocumentControls(bytes, invocation.options, context);
1246
+ return new TextEncoder().encode((invocation.options.json ? JSON.stringify({ version: 1, operation: "controls.list", ok: true, data: data2, affected: 0, locations: data2.items.map((item) => item.location), warnings: [], errors: [] }) : data2.items.map((item) => `${item.location.positions.control}: ${item.kind}; ${item.support}; ${escapeTerminalText(item.tag ?? "")}`).join("\n")) + "\n");
1247
+ }
1248
+ const options = invocation.options;
1249
+ const output = options.output === void 0 || options.output === "-" ? options.output : resolvePath6(request.cwd, options.output);
1250
+ if ((options.inPlace || output !== void 0 && output !== "-") && invocation.inputs[0] !== "-" && !input) throw new PublicationError5("unsupported-publication", "Control publication requires admitted input identity.");
1251
+ const data = await editDocumentControls(
1252
+ bytes,
1253
+ { ...options, ...output === void 0 ? {} : { output }, ...input ? { input } : {} },
1254
+ {
1255
+ ...context,
1256
+ encoding: { order: "input", compression: "store" },
1257
+ filesystem: request.filesystem,
1258
+ stdout: request.stdout,
1259
+ binaryResolver: { capability: "command", async *open(path2, { signal, maxBytes }) {
1260
+ const source = { open: (inner) => path2 === "-" ? request.stdin : request.filesystem.readStream ? request.filesystem.readStream(resolvePath6(request.cwd, path2), { signal: inner }) : { async *[Symbol.asyncIterator]() {
1261
+ yield await request.filesystem.readFile(resolvePath6(request.cwd, path2), { signal: inner });
1262
+ } } };
1263
+ const bounded = new DocumentIo({ ...context, signal, limits: { ...context.limits, maxArchiveBytes: maxBytes }, ...request.registerCleanup ? { registerCleanup: request.registerCleanup } : {} });
1264
+ try {
1265
+ signal.throwIfAborted();
1266
+ yield await bounded.readBytes(source);
1267
+ } finally {
1268
+ await bounded.cleanup();
1269
+ }
1270
+ } }
1271
+ }
1272
+ );
1273
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1274
+ return new TextEncoder().encode((options.json ? JSON.stringify({ version: 1, operation: "controls.set", ok: true, data, affected: data.changes.length, locations: data.changes.map((change) => change.after), warnings: [], errors: [] }) : `docx controls set: ${data.dryRun ? "dry-run; " : ""}${data.changes.length} controls filled`) + "\n");
1275
+ }
1276
+
1277
+ // packages/safe-bash-command-docx/src/control-template-command.ts
1278
+ import { resolvePath as resolvePath7 } from "@poe-platform/safe-fs/core";
1279
+ import { applyDocumentTemplate } from "../../safe-bash-docx-engine/template.js";
1280
+ import { editDocumentControlBindings } from "../../safe-bash-docx-engine/control-bindings.js";
1281
+ import { editDocumentControlRepeats } from "../../safe-bash-docx-engine/control-repeat.js";
1282
+ import { PublicationError as PublicationError6 } from "../../safe-bash-docx-engine/publication.js";
1283
+ async function executeControlTemplateCommand(invocation, bytes, input, request, context) {
1284
+ const options = invocation.options;
1285
+ const output = options.output === void 0 || options.output === "-" ? options.output : resolvePath7(request.cwd, options.output);
1286
+ if ((options.inPlace || output !== void 0 && output !== "-") && invocation.inputs[0] !== "-" && !input) throw new PublicationError6("unsupported-publication", "Control template publication requires admitted input identity.");
1287
+ const args = { ...invocation.options, ...output === void 0 ? {} : { output }, ...input ? { input } : {} };
1288
+ const publication = { ...context, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout };
1289
+ const data = invocation.operation === "template.apply" ? await applyDocumentTemplate(bytes, args, publication) : invocation.operation === "controls.repeat" ? await editDocumentControlRepeats(bytes, args, publication) : await editDocumentControlBindings(bytes, args, publication);
1290
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1291
+ return new TextEncoder().encode((options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: data.changes.length, locations: data.changes.map((change) => change.after), warnings: [], errors: [] }) : `docx ${invocation.operation.split(".").join(" ")}: ${data.dryRun ? "dry-run; " : ""}${data.changes.length} control owners changed`) + "\n");
1292
+ }
1293
+
1294
+ // packages/safe-bash-command-docx/src/comments-command.ts
1295
+ import { resolvePath as resolvePath8 } from "@poe-platform/safe-fs/core";
1296
+ import { editDocumentComments, inspectDocumentComments } from "../../safe-bash-docx-engine/comments.js";
1297
+ import { PublicationError as PublicationError7 } from "../../safe-bash-docx-engine/publication.js";
1298
+ async function executeCommentsCommand(invocation, bytes, input, request, context) {
1299
+ const options = invocation.options;
1300
+ if (invocation.operation === "comments.list" || invocation.operation === "comments.get") {
1301
+ const data2 = await inspectDocumentComments(bytes, { operation: invocation.operation, options }, context, "resource");
1302
+ const items = "item" in data2 ? [data2.item] : data2.items;
1303
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data: data2, affected: 0, locations: items.map((note) => note.location), warnings: [], errors: [] }) + "\n" : items.map((note) => `${note.properties.find((property) => property.name === "comment_id").value}: ${(note.text ?? "").split("\n").map((line) => escapeTerminalText(line)).join("\n")}`).join("\n") + "\n");
1304
+ }
1305
+ if ((options.inPlace || options.output !== void 0 && options.output !== "-") && invocation.inputs[0] !== "-" && !input)
1306
+ throw new PublicationError7("unsupported-publication", "File publication requires admitted input identity.");
1307
+ const output = options.output === void 0 ? void 0 : options.output === "-" ? "-" : resolvePath8(request.cwd, options.output);
1308
+ const data = await editDocumentComments(
1309
+ bytes,
1310
+ { operation: invocation.operation, options: { ...options, ...output === void 0 ? {} : { output } }, ...input ? { input } : {} },
1311
+ { ...context, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout }
1312
+ );
1313
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1314
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: data.changes.length, locations: data.changes.flatMap((change) => change.after ? [change.after] : []), warnings: [], errors: [] }) + "\n" : `docx ${invocation.operation.split(".").join(" ")}: ${data.dryRun ? "dry-run; " : ""}${data.changes.length} ${data.changes.length === 1 ? "selection" : "selections"} changed
1315
+ `);
1316
+ }
1317
+
1318
+ // packages/safe-bash-command-docx/src/fields-command.ts
1319
+ import { resolvePath as resolvePath9 } from "@poe-platform/safe-fs/core";
1320
+ import { editDocumentFields } from "../../safe-bash-docx-engine/fields.js";
1321
+ import { PublicationError as PublicationError8 } from "../../safe-bash-docx-engine/publication.js";
1322
+ async function executeFieldsCommand(invocation, bytes, input, request, context) {
1323
+ const options = invocation.options;
1324
+ if ((options.inPlace || options.output !== void 0 && options.output !== "-") && invocation.inputs[0] !== "-" && !input)
1325
+ throw new PublicationError8("unsupported-publication", "File publication requires admitted input identity.");
1326
+ const output = options.output === void 0 ? void 0 : options.output === "-" ? "-" : resolvePath9(request.cwd, options.output);
1327
+ const data = await editDocumentFields(
1328
+ bytes,
1329
+ { operation: invocation.operation, options: { ...options, ...output === void 0 ? {} : { output } }, ...input ? { input } : {} },
1330
+ { ...context, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout }
1331
+ );
1332
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1333
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: data.changes.length, locations: data.changes.map((c) => c.after), warnings: [], errors: [] }) + "\n" : `docx ${invocation.operation.split(".").join(" ")}: ${data.dryRun ? "dry-run; " : ""}${data.changes.length} ${data.changes.length === 1 ? "selection" : "selections"} changed
1334
+ `);
1335
+ }
1336
+
1337
+ // packages/safe-bash-command-docx/src/notes-command.ts
1338
+ import { resolvePath as resolvePath10 } from "@poe-platform/safe-fs/core";
1339
+ import { editDocumentNotes, inspectDocumentNotes } from "../../safe-bash-docx-engine/notes.js";
1340
+ import { PublicationError as PublicationError9 } from "../../safe-bash-docx-engine/publication.js";
1341
+ async function executeNotesCommand(invocation, bytes, input, request, context) {
1342
+ const options = invocation.options;
1343
+ if (invocation.operation === "notes.list" || invocation.operation === "notes.get") {
1344
+ const data2 = await inspectDocumentNotes(bytes, { operation: invocation.operation, options }, context);
1345
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data: data2, affected: 0, locations: data2.items.map((note) => note.location), warnings: [], errors: [] }) + "\n" : data2.items.map((note) => `${note.kind} ${note.id}: ${note.text.split("\n").map((line) => escapeTerminalText(line)).join("\n")}`).join("\n") + "\n");
1346
+ }
1347
+ if ((options.inPlace || options.output !== void 0 && options.output !== "-") && invocation.inputs[0] !== "-" && !input)
1348
+ throw new PublicationError9("unsupported-publication", "File publication requires admitted input identity.");
1349
+ const output = options.output === void 0 ? void 0 : options.output === "-" ? "-" : resolvePath10(request.cwd, options.output);
1350
+ const data = await editDocumentNotes(
1351
+ bytes,
1352
+ { operation: invocation.operation, options: { ...options, ...output === void 0 ? {} : { output } }, ...input ? { input } : {} },
1353
+ { ...context, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout }
1354
+ );
1355
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1356
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: data.changes.length, locations: data.changes.flatMap((change) => change.after ? [change.after] : []), warnings: [], errors: [] }) + "\n" : `docx ${invocation.operation.split(".").join(" ")}: ${data.dryRun ? "dry-run; " : ""}${data.changes.length} ${data.changes.length === 1 ? "selection" : "selections"} changed
1357
+ `);
1358
+ }
1359
+
1360
+ // packages/safe-bash-command-docx/src/inspection-command.ts
1361
+ import { inspectDocumentFields } from "../../safe-bash-docx-engine/fields.js";
1362
+
1363
+ // packages/safe-bash-command-docx/src/bookmarks-command.ts
1364
+ import { resolvePath as resolvePath11 } from "@poe-platform/safe-fs/core";
1365
+ import { editDocumentBookmarks } from "../../safe-bash-docx-engine/bookmarks.js";
1366
+ import { PublicationError as PublicationError10 } from "../../safe-bash-docx-engine/publication.js";
1367
+ async function executeBookmarksCommand(invocation, bytes, input, request, context) {
1368
+ const options = invocation.options;
1369
+ if ((options.inPlace || options.output !== void 0 && options.output !== "-") && invocation.inputs[0] !== "-" && !input)
1370
+ throw new PublicationError10("unsupported-publication", "File publication requires admitted input identity.");
1371
+ const output = options.output === void 0 ? void 0 : options.output === "-" ? "-" : resolvePath11(request.cwd, options.output);
1372
+ const data = await editDocumentBookmarks(
1373
+ bytes,
1374
+ { operation: invocation.operation, options: { ...options, ...output === void 0 ? {} : { output } }, ...input ? { input } : {} },
1375
+ { ...context, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout }
1376
+ );
1377
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1378
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: data.changes.length, locations: data.changes.map((c) => c.after), warnings: [], errors: [] }) + "\n" : `docx ${invocation.operation.split(".").join(" ")}: ${data.dryRun ? "dry-run; " : ""}${data.changes.length} ${data.changes.length === 1 ? "selection" : "selections"} changed
1379
+ `);
1380
+ }
1381
+
1382
+ // packages/safe-bash-command-docx/src/inspection-command.ts
1383
+ import { inspectDocumentBookmarks } from "../../safe-bash-docx-engine/bookmarks.js";
1384
+
1385
+ // packages/safe-bash-command-docx/src/links-command.ts
1386
+ import { resolvePath as resolvePath12 } from "@poe-platform/safe-fs/core";
1387
+ import { editDocumentLinks } from "../../safe-bash-docx-engine/links.js";
1388
+ import { PublicationError as PublicationError11 } from "../../safe-bash-docx-engine/publication.js";
1389
+ async function executeLinksCommand(invocation, bytes, input, request, context) {
1390
+ const options = invocation.options;
1391
+ if ((options.inPlace || options.output !== void 0 && options.output !== "-") && invocation.inputs[0] !== "-" && !input)
1392
+ throw new PublicationError11("unsupported-publication", "File publication requires admitted input identity.");
1393
+ const output = options.output === void 0 ? void 0 : options.output === "-" ? "-" : resolvePath12(request.cwd, options.output);
1394
+ const data = await editDocumentLinks(
1395
+ bytes,
1396
+ { operation: invocation.operation, options: { ...options, ...output === void 0 ? {} : { output } }, ...input ? { input } : {} },
1397
+ { ...context, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout }
1398
+ );
1399
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1400
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: data.changes.length, locations: data.changes.map((c) => c.after), warnings: [], errors: [] }) + "\n" : `docx ${invocation.operation.split(".").join(" ")}: ${data.dryRun ? "dry-run; " : ""}${data.changes.length} ${data.changes.length === 1 ? "selection" : "selections"} changed
1401
+ `);
1402
+ }
1403
+
1404
+ // packages/safe-bash-command-docx/src/inspection-command.ts
1405
+ import { inspectDocumentLinks } from "../../safe-bash-docx-engine/links.js";
1406
+
1407
+ // packages/safe-bash-command-docx/src/table-edit-command.ts
1408
+ import { resolvePath as resolvePath13 } from "@poe-platform/safe-fs/core";
1409
+ import { editDocumentTables } from "../../safe-bash-docx-engine/table-edit.js";
1410
+ import { PublicationError as PublicationError12 } from "../../safe-bash-docx-engine/publication.js";
1411
+ async function executeTableEditCommand(invocation, bytes, input, request, context) {
1412
+ const options = invocation.options;
1413
+ if ((options.inPlace || options.output !== void 0 && options.output !== "-") && invocation.inputs[0] !== "-" && !input)
1414
+ throw new PublicationError12("unsupported-publication", "File publication requires admitted input identity.");
1415
+ const output = options.output === void 0 ? void 0 : options.output === "-" ? "-" : resolvePath13(request.cwd, options.output);
1416
+ const data = await editDocumentTables(
1417
+ bytes,
1418
+ { operation: invocation.operation, options: { ...options, ...output === void 0 ? {} : { output } }, ...input ? { input } : {} },
1419
+ { ...context, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout }
1420
+ );
1421
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1422
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: data.changes.length, locations: data.changes.map((c) => c.after), warnings: [], errors: [] }) + "\n" : `docx ${invocation.operation.split(".").join(" ")}: ${data.dryRun ? "dry-run; " : ""}${data.changes.length} ${data.changes.length === 1 ? "selection" : "selections"} changed
1423
+ `);
1424
+ }
1425
+
1426
+ // packages/safe-bash-command-docx/src/inspection-command.ts
1427
+ import { inspectDocumentTable, inspectDocumentTables } from "../../safe-bash-docx-engine/table-read.js";
1428
+ import { inspectDocumentParagraph, inspectDocumentRun, inspectDocumentParagraphs, inspectDocumentRuns } from "../../safe-bash-docx-engine/text-resource-read.js";
1429
+
1430
+ // packages/safe-bash-command-docx/src/lists-command.ts
1431
+ import { resolvePath as resolvePath14 } from "@poe-platform/safe-fs/core";
1432
+ import { editDocumentLists } from "../../safe-bash-docx-engine/lists.js";
1433
+ import { PublicationError as PublicationError13 } from "../../safe-bash-docx-engine/publication.js";
1434
+ async function executeListsCommand(invocation, bytes, input, request, context) {
1435
+ const options = invocation.options;
1436
+ if ((options.inPlace || options.output !== void 0 && options.output !== "-") && invocation.inputs[0] !== "-" && !input)
1437
+ throw new PublicationError13("unsupported-publication", "File publication requires admitted input identity.");
1438
+ const output = options.output === void 0 ? void 0 : options.output === "-" ? "-" : resolvePath14(request.cwd, options.output);
1439
+ const data = await editDocumentLists(
1440
+ bytes,
1441
+ { operation: invocation.operation, options: { ...options, ...output === void 0 ? {} : { output } }, ...input ? { input } : {} },
1442
+ { ...context, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout }
1443
+ );
1444
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1445
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: data.changes.length, locations: data.changes.map((c) => c.after), warnings: [], errors: [] }) + "\n" : `docx ${invocation.operation.split(".").join(" ")}: ${data.dryRun ? "dry-run; " : ""}${data.changes.length} ${data.changes.length === 1 ? "selection" : "selections"} changed
1446
+ `);
1447
+ }
1448
+
1449
+ // packages/safe-bash-command-docx/src/sections-command.ts
1450
+ import { resolvePath as resolvePath15 } from "@poe-platform/safe-fs/core";
1451
+ import { PublicationError as PublicationError14 } from "../../safe-bash-docx-engine/publication.js";
1452
+ import { editDocumentSections, inspectDocumentSections } from "../../safe-bash-docx-engine/sections.js";
1453
+ async function executeSectionsCommand(invocation, bytes, input, request, context) {
1454
+ const options = invocation.options;
1455
+ if (invocation.operation === "sections.list") {
1456
+ const data2 = await inspectDocumentSections(bytes, options, context);
1457
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data: data2, affected: 0, locations: data2.items.map((s) => s.location), warnings: [], errors: [] }) + "\n" : data2.items.map((s) => escapeTerminalText(`Section ${s.position}: ${s.direct.orientation}, ${s.direct.startType}, ${s.direct.columns} column(s)`)).join("\n") + "\n");
1458
+ }
1459
+ if ((options.inPlace || options.output !== void 0 && options.output !== "-") && invocation.inputs[0] !== "-" && !input) throw new PublicationError14("unsupported-publication", "File publication requires admitted input identity.");
1460
+ const output = options.output === void 0 ? void 0 : options.output === "-" ? "-" : resolvePath15(request.cwd, options.output);
1461
+ const data = await editDocumentSections(
1462
+ bytes,
1463
+ { operation: invocation.operation, options: { ...options, ...output === void 0 ? {} : { output } }, ...input ? { input } : {} },
1464
+ { ...context, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout }
1465
+ );
1466
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1467
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: data.changes.length, locations: data.changes.map((c) => c.after), warnings: [], errors: [] }) + "\n" : `docx ${invocation.operation.split(".").join(" ")}: ${data.dryRun ? "dry-run; " : ""}${data.changes.length} section(s) changed
1468
+ `);
1469
+ }
1470
+
1471
+ // packages/safe-bash-command-docx/src/stories-command.ts
1472
+ import { resolvePath as resolvePath16 } from "@poe-platform/safe-fs/core";
1473
+ import { PublicationError as PublicationError15 } from "../../safe-bash-docx-engine/publication.js";
1474
+ import { editDocumentStories, inspectDocumentStories } from "../../safe-bash-docx-engine/stories.js";
1475
+ async function executeStoriesCommand(invocation, bytes, input, request, context) {
1476
+ const options = invocation.options;
1477
+ if (invocation.operation.endsWith(".list") || invocation.operation.endsWith(".get")) {
1478
+ const data2 = await inspectDocumentStories(bytes, { operation: invocation.operation, options }, context);
1479
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data: data2, affected: 0, locations: data2.items.map((s) => s.location), warnings: [], errors: [] }) + "\n" : data2.items.map((s) => escapeTerminalText(`Section ${s.section}, ${s.variant}: ${s.linked ? "linked" : "local"}, ${s.part ?? "absent"}`) + "\n" + s.text.split("\n").map((line) => escapeTerminalText(line)).join("\n")).join("\n") + "\n");
1480
+ }
1481
+ if ((options.inPlace || options.output !== void 0 && options.output !== "-") && invocation.inputs[0] !== "-" && !input) throw new PublicationError15("unsupported-publication", "File publication requires admitted input identity.");
1482
+ const output = options.output === void 0 ? void 0 : options.output === "-" ? "-" : resolvePath16(request.cwd, options.output);
1483
+ const data = await editDocumentStories(
1484
+ bytes,
1485
+ { operation: invocation.operation, options: { ...options, ...output === void 0 ? {} : { output } }, ...input ? { input } : {} },
1486
+ { ...context, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout }
1487
+ );
1488
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1489
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: data.affectedSections.length, locations: data.changes.map((c) => c.after), warnings: [], errors: [] }) + "\n" : `docx ${invocation.operation.split(".").join(" ")}: ${data.dryRun ? "dry-run; " : ""}${data.affectedSections.length} section(s) affected
1490
+ `);
1491
+ }
1492
+
1493
+ // packages/safe-bash-command-docx/src/inspection-command.ts
1494
+ import { UnsupportedEmbeddedFontMutationError } from "../../safe-bash-docx-engine/font-resources.js";
1495
+ import { inspectDocumentFonts } from "../../safe-bash-docx-engine/font-inventory.js";
1496
+ import { resolvePath as resolvePath34 } from "@poe-platform/safe-fs/core";
1497
+ import { archiveSettings as archiveSettings17, ResourceLimitError as ResourceLimitError4, CancellationError as CancellationError7 } from "../../safe-bash-docx-engine/archive.js";
1498
+ import { DocumentBudget as DocumentBudget3, documentLimitDefaults } from "../../safe-bash-docx-engine/budget.js";
1499
+ import { DocumentIo as DocumentIo5 } from "../../safe-bash-docx-engine/io.js";
1500
+ import { inspectDocument as inspectDocument2, inspectionLocationView, selectInspectionLocations, validateDocument } from "../../safe-bash-docx-engine/inspection.js";
1501
+
1502
+ // packages/safe-bash-command-docx/src/xml-command.ts
1503
+ import { resolvePath as resolvePath17 } from "@poe-platform/safe-fs/core";
1504
+ import { archiveSettings as archiveSettings2, ResourceLimitError as ResourceLimitError2, CancellationError as CancellationError2 } from "../../safe-bash-docx-engine/archive.js";
1505
+ import { getDocumentXml, replaceDocumentXmlPart } from "../../safe-bash-docx-engine/xml-parts.js";
1506
+ import { PublicationError as PublicationError16 } from "../../safe-bash-docx-engine/publication.js";
1507
+ import { asPermissionError as asPermissionError3 } from "../../safe-bash-docx-engine/io-errors.js";
1508
+ async function executeXmlCommand(invocation, bytes, input, request, context, io) {
1509
+ const options = invocation.options;
1510
+ if (invocation.operation === "xml.get") {
1511
+ const data2 = await getDocumentXml(bytes, context, {
1512
+ part: options.part,
1513
+ raw: options.raw === true || options.json !== true && options.pretty !== true,
1514
+ ...options.pretty === void 0 ? {} : { pretty: options.pretty }
1515
+ });
1516
+ if (data2 instanceof Uint8Array) return data2;
1517
+ if (!options.json) return new TextEncoder().encode(data2.content);
1518
+ return new TextEncoder().encode(JSON.stringify({ version: 1, operation: "xml.get", ok: true, data: data2, warnings: [], errors: [], affected: 0, locations: [] }) + "\n");
1519
+ }
1520
+ if ((options.inPlace || options.output !== void 0 && options.output !== "-") && invocation.inputs[0] !== "-" && !input)
1521
+ throw new PublicationError16("unsupported-publication", "File publication requires admitted input identity.");
1522
+ const file = invocation.sources.find((source) => source.argument === "file").path;
1523
+ let replacement;
1524
+ try {
1525
+ replacement = await io.readBytes({ open(signal) {
1526
+ const source = file === "-" ? request.stdin : request.filesystem.readStream ? request.filesystem.readStream(resolvePath17(request.cwd, file), { signal }) : { async *[Symbol.asyncIterator]() {
1527
+ yield await request.filesystem.readFile(resolvePath17(request.cwd, file), { signal });
1528
+ } };
1529
+ return { async *[Symbol.asyncIterator]() {
1530
+ let size = 0;
1531
+ for await (const chunk of source) {
1532
+ size += chunk.length;
1533
+ if (size > Math.min(archiveSettings2(context).limits.maxEntryBytes, context.budget.limits.xmlPartBytes)) throw new ResourceLimitError2("XML input byte limit exceeded.");
1534
+ yield chunk;
1535
+ }
1536
+ } };
1537
+ } });
1538
+ } catch (error) {
1539
+ if (error instanceof ResourceLimitError2 || error instanceof CancellationError2) throw error;
1540
+ request.signal.throwIfAborted();
1541
+ throw asPermissionError3(error) ?? new SourceError2(error);
1542
+ }
1543
+ const output = typeof options.output === "string" ? options.output === "-" ? "-" : resolvePath17(request.cwd, options.output) : void 0;
1544
+ const data = await replaceDocumentXmlPart(bytes, replacement, {
1545
+ part: options.part,
1546
+ ...options.allowEmpty === void 0 ? {} : { allowEmpty: options.allowEmpty },
1547
+ ...input ? { input } : {},
1548
+ ...output === void 0 ? {} : { output },
1549
+ ...options.inPlace === void 0 ? {} : { inPlace: options.inPlace },
1550
+ ...options.force === void 0 ? {} : { force: options.force },
1551
+ ...options.dryRun === void 0 ? {} : { dryRun: options.dryRun },
1552
+ ...options.json === void 0 ? {} : { json: options.json }
1553
+ }, { ...context, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout });
1554
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1555
+ return new TextEncoder().encode(options.json ? JSON.stringify({
1556
+ version: 1,
1557
+ operation: "xml.set",
1558
+ ok: true,
1559
+ data,
1560
+ warnings: [],
1561
+ errors: [],
1562
+ affected: data.changed ? 1 : 0,
1563
+ locations: data.changes.map((change) => change.after)
1564
+ }) + "\n" : `docx xml set: ${data.dryRun ? "dry-run; " : ""}${data.changed ? "1 part replaced" : "unchanged"}
1565
+ `);
1566
+ }
1567
+
1568
+ // packages/safe-bash-command-docx/src/inspection-command.ts
1569
+ import { PublicationError as PublicationError34 } from "../../safe-bash-docx-engine/publication.js";
1570
+ import { asPermissionError as asPermissionError6 } from "../../safe-bash-docx-engine/io-errors.js";
1571
+ import { extractDocumentText } from "../../safe-bash-docx-engine/text.js";
1572
+
1573
+ // packages/safe-bash-command-docx/src/create-command.ts
1574
+ import { resolvePath as resolvePath18 } from "@poe-platform/safe-fs/core";
1575
+ import { createDocument } from "../../safe-bash-docx-engine/create.js";
1576
+ import { PublicationError as PublicationError17 } from "../../safe-bash-docx-engine/publication.js";
1577
+ import { asPermissionError as asPermissionError4 } from "../../safe-bash-docx-engine/io-errors.js";
1578
+ async function executeCreateCommand(invocation, request, context, io) {
1579
+ const options = invocation.options;
1580
+ const file = invocation.sources?.find((source) => source.argument === "template")?.path;
1581
+ let template, input;
1582
+ if (file !== void 0) {
1583
+ if (file !== "-" && options.output !== void 0 && options.output !== "-" && !request.filesystem.lstat)
1584
+ throw new PublicationError17("unsupported-publication", "Template file publication requires admitted source identity.");
1585
+ try {
1586
+ if (file !== "-" && request.filesystem.lstat) {
1587
+ const path2 = resolvePath18(request.cwd, file);
1588
+ input = { path: path2, stat: await request.filesystem.lstat(path2, { signal: request.signal }) };
1589
+ }
1590
+ template = await io.readBytes({ open(signal) {
1591
+ if (file === "-") return request.stdin;
1592
+ const path2 = resolvePath18(request.cwd, file);
1593
+ return request.filesystem.readStream ? request.filesystem.readStream(path2, { signal }) : { async *[Symbol.asyncIterator]() {
1594
+ yield await request.filesystem.readFile(path2, { signal });
1595
+ } };
1596
+ } });
1597
+ } catch (error) {
1598
+ request.signal.throwIfAborted();
1599
+ if (error && typeof error === "object" && "code" in error && ["limit-exceeded", "cancelled"].includes(String(error.code))) throw error;
1600
+ throw asPermissionError4(error) ?? new SourceError2(error);
1601
+ }
1602
+ }
1603
+ const creation = {
1604
+ ...template === void 0 ? {} : { template },
1605
+ ...Object.fromEntries(["kind", "dialect", "content", "timestamp", "author"].filter((key) => options[key] !== void 0).map((key) => [key, options[key]]))
1606
+ };
1607
+ const output = typeof options.output === "string" ? options.output === "-" ? "-" : resolvePath18(request.cwd, options.output) : void 0;
1608
+ const data = await createDocument(creation, {
1609
+ ...input ? { input } : {},
1610
+ ...output === void 0 ? {} : { output },
1611
+ ...options.force === void 0 ? {} : { force: options.force },
1612
+ ...options.dryRun === void 0 ? {} : { dryRun: options.dryRun },
1613
+ ...options.json === void 0 ? {} : { json: options.json }
1614
+ }, { ...context, encoding: { order: "name", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout });
1615
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1616
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: "create", ok: true, data, warnings: [], errors: [], affected: 1, locations: [] }) + "\n" : `docx create: ${data.dryRun ? "dry-run; " : ""}1 document created
1617
+ `);
1618
+ }
1619
+
1620
+ // packages/safe-bash-command-docx/src/text-replace-command.ts
1621
+ import { resolvePath as resolvePath19 } from "@poe-platform/safe-fs/core";
1622
+ import { PublicationError as PublicationError18 } from "../../safe-bash-docx-engine/publication.js";
1623
+ import { setDocumentDummyText, replaceDocumentText } from "../../safe-bash-docx-engine/text-replace.js";
1624
+ async function executeTextReplaceCommand(invocation, bytes, input, request, context) {
1625
+ const options = invocation.options;
1626
+ if ((options.inPlace || options.output !== void 0 && options.output !== "-") && invocation.inputs[0] !== "-" && !input)
1627
+ throw new PublicationError18("unsupported-publication", "File publication requires admitted input identity.");
1628
+ const output = options.output === void 0 ? void 0 : options.output === "-" ? "-" : resolvePath19(request.cwd, options.output);
1629
+ const data = await (invocation.operation === "lorem.set" ? setDocumentDummyText : replaceDocumentText)(
1630
+ bytes,
1631
+ { ...options, ...input ? { input } : {}, ...output === void 0 ? {} : { output } },
1632
+ { ...context, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout }
1633
+ );
1634
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1635
+ return new TextEncoder().encode(options.json ? JSON.stringify({
1636
+ version: 1,
1637
+ operation: invocation.operation,
1638
+ ok: true,
1639
+ data,
1640
+ warnings: [],
1641
+ errors: [],
1642
+ affected: data.changes.length,
1643
+ locations: data.changes.map((change) => change.after)
1644
+ }) + "\n" : `docx ${invocation.operation === "lorem.set" ? "lorem set (not anonymization)" : "text replace"}: ${data.dryRun ? "dry-run; " : ""}${data.changes.length} ${data.changes.length === 1 ? "match" : "matches"} replaced
1645
+ `);
1646
+ }
1647
+
1648
+ // packages/safe-bash-command-docx/src/paragraph-edit-command.ts
1649
+ import { resolvePath as resolvePath20 } from "@poe-platform/safe-fs/core";
1650
+ import { editDocumentParagraphs } from "../../safe-bash-docx-engine/paragraph-edit.js";
1651
+ import { PublicationError as PublicationError19 } from "../../safe-bash-docx-engine/publication.js";
1652
+ async function executeParagraphEditCommand(invocation, bytes, input, request, context) {
1653
+ const options = invocation.options;
1654
+ if ((options.inPlace || options.output !== void 0 && options.output !== "-") && invocation.inputs[0] !== "-" && !input)
1655
+ throw new PublicationError19("unsupported-publication", "File publication requires admitted input identity.");
1656
+ const output = options.output === void 0 ? void 0 : options.output === "-" ? "-" : resolvePath20(request.cwd, options.output);
1657
+ const data = await editDocumentParagraphs(
1658
+ bytes,
1659
+ { operation: invocation.operation, options: { ...options, ...output === void 0 ? {} : { output } }, ...input ? { input } : {} },
1660
+ { ...context, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout }
1661
+ );
1662
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1663
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: data.changes.length, locations: data.changes.map((c) => c.after), warnings: [], errors: [] }) + "\n" : `docx ${invocation.operation.split(".").join(" ")}: ${data.dryRun ? "dry-run; " : ""}${data.changes.length} ${data.changes.length === 1 ? "selection" : "selections"} changed
1664
+ `);
1665
+ }
1666
+
1667
+ // packages/safe-bash-command-docx/src/batch-command.ts
1668
+ import { resolvePath as resolvePath22 } from "@poe-platform/safe-fs/core";
1669
+ import { executeDocumentBatch as executeDocumentBatch2 } from "../../safe-bash-docx-engine/batch.js";
1670
+ import { documentBatchActions } from "../../safe-bash-docx-engine/batch-operations.js";
1671
+ import { PublicationError as PublicationError21 } from "../../safe-bash-docx-engine/publication.js";
1672
+
1673
+ // packages/safe-bash-command-docx/src/style-model-command.ts
1674
+ import { resolvePath as resolvePath21 } from "@poe-platform/safe-fs/core";
1675
+ import { archiveSettings as archiveSettings3 } from "../../safe-bash-docx-engine/archive.js";
1676
+ import { PublicationError as PublicationError20 } from "../../safe-bash-docx-engine/publication.js";
1677
+ import { executeDocumentBatch } from "../../safe-bash-docx-engine/batch.js";
1678
+ import { DocumentIo as DocumentIo2 } from "../../safe-bash-docx-engine/io.js";
1679
+ import { UnsupportedProfileError } from "../../safe-bash-docx-engine/package-xml.js";
1680
+ async function executeStyleModelCommand(invocation, bytes, input, request, context) {
1681
+ const options = invocation.options;
1682
+ const settings = archiveSettings3(context);
1683
+ const operations = options.operations.map((item) => {
1684
+ const descriptor = item.arguments.imageDescriptor;
1685
+ if (item.operation !== "model.image.image.Image.from_file.call" || !descriptor || typeof descriptor !== "object" || !("path" in descriptor) || !("capability" in descriptor) || descriptor.capability !== "command") return item;
1686
+ return { ...item, arguments: { ...item.arguments, imageDescriptor: { ...descriptor, path: resolvePath21(request.cwd, descriptor.path) } } };
1687
+ });
1688
+ const output = options.output === void 0 ? void 0 : options.output === "-" ? "-" : resolvePath21(request.cwd, options.output);
1689
+ if ((options.inPlace || output !== void 0 && output !== "-") && invocation.inputs[0] !== "-" && !input)
1690
+ throw new PublicationError20("unsupported-publication", "File publication requires admitted input identity.");
1691
+ const { version, operations: ignoredOperations, ...intent } = options;
1692
+ const data = await executeDocumentBatch(bytes, { version, operations }, { ...intent, ...input ? { input } : {}, ...output === void 0 ? {} : { output } }, {
1693
+ ...context,
1694
+ encoding: { order: "input", compression: "store" },
1695
+ filesystem: request.filesystem,
1696
+ stdout: request.stdout,
1697
+ ...request.registerCleanup ? { registerCleanup: request.registerCleanup } : {},
1698
+ binaryResolver: { capability: "command", ...request.filesystem.lstat ? { filesystem: request.filesystem } : {}, async *open(path2, { signal, maxBytes }) {
1699
+ const readStream = request.filesystem.readStream;
1700
+ if (!readStream) throw new UnsupportedProfileError("Image paths require an explicit streaming read capability.");
1701
+ const source = { open: (inner) => readStream.call(request.filesystem, path2, { signal: inner }) };
1702
+ const io = new DocumentIo2({ ...settings, signal, limits: { ...settings.limits, maxArchiveBytes: maxBytes }, ...request.registerCleanup ? { registerCleanup: request.registerCleanup } : {} });
1703
+ try {
1704
+ signal.throwIfAborted();
1705
+ yield await io.readBytes(source);
1706
+ } finally {
1707
+ await io.cleanup();
1708
+ }
1709
+ } }
1710
+ });
1711
+ if (data.publication && output === "-" && !options.dryRun) return new Uint8Array();
1712
+ const affected = data.results.reduce((sum, result) => sum + result.affected, 0);
1713
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: "batch", ok: true, data, warnings: [], errors: [], affected, locations: [] }) + "\n" : `docx batch: ${options.dryRun ? "dry-run; " : ""}${data.results.length} operations; ${affected} changes
1714
+ `);
1715
+ }
1716
+
1717
+ // packages/safe-bash-command-docx/src/batch-command.ts
1718
+ async function executeBatchCommand(invocation, bytes, input, request, context) {
1719
+ const options = invocation.options;
1720
+ if (options.operations.length && options.operations.some((item) => !documentBatchActions.has(item.operation) || item.resultHandle) && options.operations.every((item) => !documentBatchActions.has(item.operation) || ["paragraphs.get", "runs.get"].includes(item.operation)))
1721
+ return executeStyleModelCommand(invocation, bytes, input, request, context);
1722
+ if ((options.inPlace || options.output !== void 0 && options.output !== "-") && invocation.inputs[0] !== "-" && !input)
1723
+ throw new PublicationError21("unsupported-publication", "File publication requires admitted input identity.");
1724
+ const output = options.output === void 0 ? void 0 : options.output === "-" ? "-" : resolvePath22(request.cwd, options.output);
1725
+ const { version, operations, ...intent } = options;
1726
+ const data = await executeDocumentBatch2(
1727
+ bytes,
1728
+ { version, operations },
1729
+ { ...intent, ...input ? { input } : {}, ...output === void 0 ? {} : { output } },
1730
+ {
1731
+ ...context,
1732
+ encoding: { order: "input", compression: "store" },
1733
+ filesystem: request.filesystem,
1734
+ stdout: request.stdout,
1735
+ binaryResolver: { capability: "command", filesystem: request.filesystem, open(path2, { signal }) {
1736
+ const absolute = resolvePath22(request.cwd, path2);
1737
+ return request.filesystem.readStream ? request.filesystem.readStream(absolute, { signal }) : { async *[Symbol.asyncIterator]() {
1738
+ yield await request.filesystem.readFile(absolute, { signal });
1739
+ } };
1740
+ } }
1741
+ }
1742
+ );
1743
+ if (output === "-" && data.publication && !options.dryRun) return new Uint8Array();
1744
+ const affected = data.results.reduce((sum, result) => sum + result.affected, 0);
1745
+ return new TextEncoder().encode(options.json ? JSON.stringify({ version: 1, operation: "batch", ok: true, data, warnings: [], errors: [], affected, locations: [] }) + "\n" : `docx batch: ${options.dryRun ? "dry-run; " : ""}${data.results.length} operations; ${affected} changes
1746
+ `);
1747
+ }
1748
+
1749
+ // packages/safe-bash-command-docx/src/styles-command.ts
1750
+ import { resolvePath as resolvePath23 } from "@poe-platform/safe-fs/core";
1751
+ import { PublicationError as PublicationError22 } from "../../safe-bash-docx-engine/publication.js";
1752
+ import { inspectDocumentStyles, editDocumentStyles } from "../../safe-bash-docx-engine/styles.js";
1753
+ async function executeStylesCommand(invocation, bytes, input, request, context) {
1754
+ const options = invocation.options;
1755
+ const humanJson = (value) => JSON.stringify(value, null, 2).split("\n").map((line) => escapeTerminalText(line)).join("\n");
1756
+ const edit = ["styles.add", "styles.set", "styles.remove", "styles.defaults.set", "styles.latent.add", "styles.latent.set", "styles.latent.remove", "styles.latent.defaults.set"].includes(invocation.operation);
1757
+ if (edit && (options.inPlace || options.output !== void 0 && options.output !== "-") && invocation.inputs[0] !== "-" && !input)
1758
+ throw new PublicationError22("unsupported-publication", "File publication requires admitted input identity.");
1759
+ const output = options.output === void 0 ? void 0 : options.output === "-" ? "-" : resolvePath23(request.cwd, options.output);
1760
+ const data = edit ? await editDocumentStyles(
1761
+ bytes,
1762
+ {
1763
+ ...options,
1764
+ operation: invocation.operation,
1765
+ ...input ? { input } : {},
1766
+ ...output === void 0 ? {} : { output }
1767
+ },
1768
+ { ...context, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout }
1769
+ ) : await inspectDocumentStyles(bytes, { ...options, ...invocation.operation.startsWith("styles.latent.") ? { latent: true } : {} }, context);
1770
+ if (edit && output === "-" && "dryRun" in data && !data.dryRun) return new Uint8Array();
1771
+ const affected = "changes" in data ? data.changes.length : 0;
1772
+ const human = invocation.operation.startsWith("styles.latent.") && "latent" in data ? humanJson(invocation.operation === "styles.latent.defaults.get" ? data.latent?.defaults ?? null : data.latent) + "\n" : invocation.operation === "styles.defaults.get" && "defaults" in data ? humanJson(data.defaults) + "\n" : invocation.operation === "styles.get" && "styles" in data ? data.styles.map((style) => [
1773
+ `${escapeTerminalText(style.id)}: ${escapeTerminalText(style.name)} (${escapeTerminalText(style.type)})`,
1774
+ `Base: ${escapeTerminalText(style.base ?? "none")}; next: ${escapeTerminalText(style.next ?? "none")}; linked: ${escapeTerminalText(style.linkedStyle ?? "none")}`,
1775
+ `Direct: ${escapeTerminalText(JSON.stringify(style.direct, (_key, value) => value === null ? void 0 : value))}`,
1776
+ `Inherited result: ${escapeTerminalText(style.effective === null ? "unresolved" : JSON.stringify(style.effective, (_key, value) => value === null ? void 0 : value))}`
1777
+ ].join("\n")).join("\n") + "\n" : "styles" in data ? data.styles.map((style) => `${escapeTerminalText(style.id)}: ${escapeTerminalText(style.name)}`).join("\n") + "\n" : `docx ${invocation.operation.split(".").join(" ")}: ${"dryRun" in data && data.dryRun ? "dry-run; " : ""}${affected} styles changed
1778
+ `;
1779
+ return new TextEncoder().encode(options.json ? JSON.stringify({
1780
+ version: 1,
1781
+ operation: invocation.operation,
1782
+ ok: true,
1783
+ data,
1784
+ warnings: [],
1785
+ errors: [],
1786
+ affected,
1787
+ locations: []
1788
+ }) + "\n" : human);
1789
+ }
1790
+
1791
+ // packages/safe-bash-command-docx/src/run-format-command.ts
1792
+ import { resolvePath as resolvePath24 } from "@poe-platform/safe-fs/core";
1793
+ import { PublicationError as PublicationError23 } from "../../safe-bash-docx-engine/publication.js";
1794
+ import { formatDocumentRuns } from "../../safe-bash-docx-engine/run-format.js";
1795
+ async function executeRunFormatCommand(invocation, bytes, input, request, context) {
1796
+ const options = invocation.options;
1797
+ if ((options.inPlace || options.output !== void 0 && options.output !== "-") && invocation.inputs[0] !== "-" && !input)
1798
+ throw new PublicationError23("unsupported-publication", "File publication requires admitted input identity.");
1799
+ const output = options.output === void 0 ? void 0 : options.output === "-" ? "-" : resolvePath24(request.cwd, options.output);
1800
+ const data = await formatDocumentRuns(
1801
+ bytes,
1802
+ { ...options, ...input ? { input } : {}, ...output === void 0 ? {} : { output } },
1803
+ { ...context, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout }
1804
+ );
1805
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1806
+ return new TextEncoder().encode(options.json ? JSON.stringify({
1807
+ version: 1,
1808
+ operation: "runs.set",
1809
+ ok: true,
1810
+ data,
1811
+ warnings: [],
1812
+ errors: [],
1813
+ affected: data.changes.length,
1814
+ locations: data.changes.map((change) => change.after)
1815
+ }) + "\n" : `docx runs set: ${data.dryRun ? "dry-run; " : ""}${data.changes.length} ${options.text === void 0 ? `${data.changes.length === 1 ? "selection" : "selections"} formatted` : `${data.changes.length === 1 ? "run" : "runs"} updated`}
1816
+ `);
1817
+ }
1818
+
1819
+ // packages/safe-bash-command-docx/src/ancillary-resources-command.ts
1820
+ import { inspectDocumentPackageResources, measurePackageResourceSerialization as measurePackageResourceSerialization2, packageResourceWarnings } from "../../safe-bash-docx-engine/ancillary-resources.js";
1821
+ import { archiveSettings as archiveSettings4, CancellationError as CancellationError3 } from "../../safe-bash-docx-engine/archive.js";
1822
+ import { PublicationError as PublicationError24 } from "../../safe-bash-docx-engine/publication.js";
1823
+ import { DocxUsageError as DocxUsageError3 } from "../../safe-bash-docx-engine/argument-json.js";
1824
+ async function executePackageResourcesCommand(invocation, bytes, request, context) {
1825
+ if (invocation.operation !== "custom-xml.list" && invocation.operation !== "glossary.list") throw new DocxUsageError3("Expected a global package resource inventory.");
1826
+ const settings = archiveSettings4(context), budget = settings.budget.lower(Object.fromEntries((invocation.options.limit ?? []).map((limit) => [limit.name, limit.value]))), data = await inspectDocumentPackageResources(bytes, invocation.operation, invocation.options, context);
1827
+ const warnings = packageResourceWarnings(data);
1828
+ const result = { version: 1, operation: invocation.operation, ok: true, data, warnings, errors: [], affected: 0, locations: data.items.map((item) => item.location) };
1829
+ const human = `${invocation.operation === "custom-xml.list" ? "Custom XML" : "Glossary"} resources: ${data.items.length}
1830
+ ` + data.items.map((item) => `${escapeTerminalText(item.name)}: preserve; ${item.details.parts.length} parts; ${item.references.length} references`).join("\n") + (data.items.length ? "\n" : "");
1831
+ const length = invocation.options.json ? measurePackageResourceSerialization2(result, budget) + 1 : new TextEncoder().encode(human).length;
1832
+ budget.check("serializedOutput", length);
1833
+ budget.charge("retainedBytes", length * 3);
1834
+ const text = invocation.options.json ? JSON.stringify(result) + "\n" : human, output = new TextEncoder().encode(text);
1835
+ const diagnosticLength = warnings.reduce((length2, warning) => length2 + "docx: ".length + warning.code.length + ": ".length + warning.message.length + 1, 0);
1836
+ budget.check("diagnosticBytes", diagnosticLength);
1837
+ budget.charge("retainedBytes", diagnosticLength * 3);
1838
+ if (warnings.length) {
1839
+ const diagnostic = new TextEncoder().encode(warnings.map((warning) => `docx: ${warning.code}: ${warning.message}
1840
+ `).join(""));
1841
+ try {
1842
+ await request.stderr.write(diagnostic);
1843
+ } catch (cause) {
1844
+ if (context.signal.aborted) throw new CancellationError3("Resource inventory diagnostics cancelled.", { cause });
1845
+ throw new PublicationError24("sink-failure", "Resource inventory diagnostics could not be written.", [], false, { cause });
1846
+ }
1847
+ }
1848
+ budget.check("work", 0);
1849
+ budget.check("serializedOutput", output.length);
1850
+ return output;
1851
+ }
1852
+
1853
+ // packages/safe-bash-command-docx/src/signatures-command.ts
1854
+ import { resolvePath as resolvePath25 } from "@poe-platform/safe-fs/core";
1855
+ import { archiveSettings as archiveSettings5 } from "../../safe-bash-docx-engine/archive.js";
1856
+ import { measurePackageResourceSerialization as measurePackageResourceSerialization3 } from "../../safe-bash-docx-engine/ancillary-resources.js";
1857
+ import { PublicationError as PublicationError25 } from "../../safe-bash-docx-engine/publication.js";
1858
+ import { inspectDocumentSignatures, stripDocumentSignatures } from "../../safe-bash-docx-engine/signatures.js";
1859
+ async function executeSignaturesCommand(invocation, bytes, input, request, context) {
1860
+ const settings = archiveSettings5(context), encoder = new TextEncoder();
1861
+ const budget = settings.budget.lower(Object.fromEntries((invocation.options.limit ?? []).map((item) => [item.name, item.value])));
1862
+ if (invocation.operation === "signatures.list") {
1863
+ const data2 = await inspectDocumentSignatures(bytes, invocation.options, { ...settings, budget });
1864
+ const envelope2 = { version: 1, operation: invocation.operation, ok: true, data: data2, warnings: [], errors: [], affected: 0, locations: data2.items.map((item) => item.location) };
1865
+ measurePackageResourceSerialization3(envelope2, budget);
1866
+ const text = invocation.options.json ? JSON.stringify(envelope2) + "\n" : `Signature parts: ${data2.items.length}; relationships: ${data2.relationships.length}
1867
+ Cryptographic validity: unknown (not verified)
1868
+ ` + data2.items.flatMap((item) => item.details.parts.map((part) => `${escapeTerminalText(part.name)}: ${escapeTerminalText(part.contentType)}; ${part.bytes} bytes; SHA-256 ${part.sha256}
1869
+ `)).join("") + data2.relationships.map((edge) => ` Relationship: ${escapeTerminalText(edge.owner)} ${escapeTerminalText(edge.id)} ${escapeTerminalText(edge.type)} -> ${escapeTerminalText(edge.target ?? "redacted external target")} (${edge.external ? "external" : "internal"})
1870
+ `).join("");
1871
+ const output2 = encoder.encode(text);
1872
+ budget.check("serializedOutput", output2.length);
1873
+ budget.charge("retainedBytes", output2.length * 8);
1874
+ budget.charge("work", output2.length * 8);
1875
+ settings.signal.throwIfAborted();
1876
+ return output2;
1877
+ }
1878
+ const options = invocation.options;
1879
+ const output = options.output === void 0 || options.output === "-" ? options.output : resolvePath25(request.cwd, options.output);
1880
+ if ((options.inPlace || output !== void 0 && output !== "-") && invocation.inputs[0] !== "-" && !input)
1881
+ throw new PublicationError25("unsupported-publication", "Signature publication requires admitted input identity.");
1882
+ const envelope = (data2) => ({ version: 1, operation: "signatures.remove", ok: true, data: data2, warnings: [], errors: [], affected: data2.removedParts.length, locations: [] });
1883
+ const human = (data2) => `docx signatures remove: ${data2.dryRun ? "dry-run; " : ""}${data2.removedParts.length} parts, ${data2.removedRelationships.length} relationships, ${data2.removedContentTypes.length} content-type entries removed
1884
+ ` + data2.removedParts.map((name) => ` Part: ${escapeTerminalText(name)}
1885
+ `).join("") + data2.removedRelationships.map((edge) => ` Relationship: ${escapeTerminalText(edge.owner)} ${escapeTerminalText(edge.id)} ${escapeTerminalText(edge.type)} -> ${escapeTerminalText(edge.target ?? "redacted external target")} (${edge.external ? "external" : "internal"})
1886
+ `).join("") + data2.removedContentTypes.map((entry) => ` Content type: ${entry.kind} ${escapeTerminalText(entry.name)} ${escapeTerminalText(entry.contentType)}
1887
+ `).join("");
1888
+ const data = await stripDocumentSignatures(bytes, { ...options, ...input ? { input } : {}, ...output === void 0 ? {} : { output } }, {
1889
+ ...settings,
1890
+ budget,
1891
+ encoding: { order: "input", compression: "store" },
1892
+ filesystem: request.filesystem,
1893
+ stdout: request.stdout,
1894
+ admitPublication(planned) {
1895
+ const size = output === "-" && !planned.dryRun ? 0 : options.json ? measurePackageResourceSerialization3(envelope(planned), budget) + 1 : encoder.encode(human(planned)).length;
1896
+ budget.check("serializedOutput", size);
1897
+ budget.charge("retainedBytes", size * 8);
1898
+ budget.charge("work", size * 8);
1899
+ return void 0;
1900
+ }
1901
+ });
1902
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1903
+ return encoder.encode(options.json ? JSON.stringify(envelope(data)) + "\n" : human(data));
1904
+ }
1905
+
1906
+ // packages/safe-bash-command-docx/src/sanitize-command.ts
1907
+ import { resolvePath as resolvePath26 } from "@poe-platform/safe-fs/core";
1908
+ import { archiveSettings as archiveSettings6 } from "../../safe-bash-docx-engine/archive.js";
1909
+ import { PublicationError as PublicationError26 } from "../../safe-bash-docx-engine/publication.js";
1910
+ import { sanitizeDocument } from "../../safe-bash-docx-engine/sanitize.js";
1911
+ import { measurePackageResourceSerialization as measurePackageResourceSerialization4 } from "../../safe-bash-docx-engine/ancillary-resources.js";
1912
+ async function executeSanitizeCommand(invocation, bytes, input, request, context) {
1913
+ const options = invocation.options;
1914
+ const output = options.output === void 0 || options.output === "-" ? options.output : resolvePath26(request.cwd, options.output);
1915
+ if ((options.inPlace || output !== void 0 && output !== "-") && invocation.inputs[0] !== "-" && !input) throw new PublicationError26("unsupported-publication", "Sanitization publication requires admitted input identity.");
1916
+ const settings = archiveSettings6(context), budget = settings.budget.lower(Object.fromEntries((options.limit ?? []).map((item) => [item.name, item.value])));
1917
+ const envelope = (data2) => ({ version: 1, operation: "sanitize", ok: true, data: data2, affected: data2.actions.reduce((sum, action) => sum + action.affected, 0), locations: [], warnings: [], errors: [] });
1918
+ const human = (data2) => {
1919
+ const affected = data2.actions.reduce((sum, action) => sum + action.affected, 0);
1920
+ return `docx sanitize: ${data2.dryRun ? "dry-run; " : ""}${affected} ${affected === 1 ? "record" : "records"} affected
1921
+ ` + data2.actions.map((action) => ` ${action.category}: ${action.action}; ${action.affected}
1922
+ `).join("") + `Retained categories: ${data2.retained.join(", ") || "none selected for retention"}
1923
+ ` + data2.gaps.map((gap) => ` ${gap}
1924
+ `).join("");
1925
+ };
1926
+ const data = await sanitizeDocument(bytes, { ...options, ...input ? { input } : {}, ...output === void 0 ? {} : { output } }, { ...settings, budget, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout, admitSanitization(planned) {
1927
+ const size = output === "-" && !planned.dryRun ? 0 : options.json ? measurePackageResourceSerialization4(envelope(planned), budget) + 1 : new TextEncoder().encode(human(planned)).length;
1928
+ budget.check("serializedOutput", size);
1929
+ budget.charge("retainedBytes", size * 8);
1930
+ budget.charge("work", size * 8);
1931
+ } });
1932
+ if (output === "-" && !data.dryRun) return new Uint8Array();
1933
+ return new TextEncoder().encode(options.json ? JSON.stringify(envelope(data)) + "\n" : human(data));
1934
+ }
1935
+
1936
+ // packages/safe-bash-command-docx/src/settings-command.ts
1937
+ import { inspectDocumentSettings } from "../../safe-bash-docx-engine/settings.js";
1938
+ import { archiveSettings as archiveSettings7 } from "../../safe-bash-docx-engine/archive.js";
1939
+ import { measurePackageResourceSerialization as measurePackageResourceSerialization5 } from "../../safe-bash-docx-engine/ancillary-resources.js";
1940
+ async function executeSettingsCommand(invocation, bytes, context) {
1941
+ const settings = archiveSettings7(context), budget = settings.budget.lower(Object.fromEntries((invocation.options.limit ?? []).map((limit) => [limit.name, limit.value])));
1942
+ const data = await inspectDocumentSettings(bytes, invocation.options, { ...settings, budget }, "resource");
1943
+ const result = { version: 1, operation: "settings.list", ok: true, data, warnings: [], errors: [], affected: 0, locations: data.items.map((item) => item.location) };
1944
+ measurePackageResourceSerialization5(result, budget);
1945
+ const text = invocation.options.json ? JSON.stringify(result) + "\n" : `Settings parts: ${data.items.length}
1946
+ ` + data.items.map((item) => {
1947
+ const field = (name) => item.properties.find((property) => property.name === name)?.value;
1948
+ return `${escapeTerminalText(item.name)}: ${item.support}; ${field("entryCount")} entries; ${field("opaqueCount")} opaque
1949
+ Field updates: ${field("updateFields") ?? "absent or unsupported"}
1950
+ ` + ["embedTrueTypeFonts", "embedSystemFonts", "saveSubsetFonts"].map((name) => ` ${name}: ${field(name) ?? "absent or unsupported"}
1951
+ `).join("") + item.properties.filter((property) => property.name.startsWith("protection[") && property.name.endsWith(".kind")).map((property) => {
1952
+ const prefix = property.name.slice(0, -5);
1953
+ return ` ${escapeTerminalText(String(property.value))}: enforced ${field(prefix + ".enforced") ?? "unknown"}; edit ${escapeTerminalText(String(field(prefix + ".edit") ?? "unspecified"))}
1954
+ `;
1955
+ }).join("");
1956
+ }).join("");
1957
+ const output = new TextEncoder().encode(text);
1958
+ budget.check("serializedOutput", output.length);
1959
+ budget.charge("retainedBytes", output.length * 3);
1960
+ return output;
1961
+ }
1962
+
1963
+ // packages/safe-bash-command-docx/src/properties-command.ts
1964
+ import { resolvePath as resolvePath27 } from "@poe-platform/safe-fs/core";
1965
+ import { inspectDocumentProperties, editDocumentProperties } from "../../safe-bash-docx-engine/document-properties.js";
1966
+ import { normalizeDocxPropertyOptions as normalizeDocxPropertyOptions2 } from "../../safe-bash-docx-engine/command-properties.js";
1967
+ import { propertyDeclaration } from "../../safe-bash-docx-engine/property-values.js";
1968
+ import { readDocumentArchive } from "../../safe-bash-docx-engine/admission.js";
1969
+ import { archiveSettings as archiveSettings8, CancellationError as CancellationError4 } from "../../safe-bash-docx-engine/archive.js";
1970
+ import { SelectionError } from "../../safe-bash-docx-engine/location-token.js";
1971
+ import { PublicationError as PublicationError27 } from "../../safe-bash-docx-engine/publication.js";
1972
+ import { DocxUsageError as DocxUsageError4 } from "../../safe-bash-docx-engine/argument-json.js";
1973
+ import { measurePackageResourceSerialization as measurePackageResourceSerialization6 } from "../../safe-bash-docx-engine/ancillary-resources.js";
1974
+ function utf8Length2(text) {
1975
+ let length = 0;
1976
+ for (const character of text) {
1977
+ const code = character.codePointAt(0);
1978
+ length += code <= 127 ? 1 : code <= 2047 ? 2 : code <= 65535 ? 3 : 4;
1979
+ }
1980
+ return length;
1981
+ }
1982
+ function escapedUtf8Length2(text) {
1983
+ let length = 0;
1984
+ for (const character of text) length += utf8Length2(escapeTerminalText(character));
1985
+ return length;
1986
+ }
1987
+ async function executePropertiesCommand(invocation, bytes, input, request, context) {
1988
+ if (!["properties.list", "properties.get", "properties.set", "properties.remove"].includes(invocation.operation)) throw new DocxUsageError4("Expected a document property operation.");
1989
+ const settings = archiveSettings8(context), options = { ...invocation.options }, edit = invocation.operation === "properties.set" || invocation.operation === "properties.remove";
1990
+ const budget = settings.budget.lower(Object.fromEntries((options.limit ?? []).map((v) => [v.name, v.value])));
1991
+ if (edit && (options.inPlace || options.output !== void 0 && options.output !== "-") && invocation.inputs[0] !== "-" && !input) throw new PublicationError27("unsupported-publication", "File publication requires admitted input identity.");
1992
+ if (invocation.operation === "properties.set") {
1993
+ let type = options.type, qualified = options.name;
1994
+ if (type === void 0 || !qualified.includes(":")) {
1995
+ try {
1996
+ const snapshot = await inspectDocumentProperties(bytes, { name: qualified }, { ...context, budget }), item = snapshot.items[0];
1997
+ qualified = item.name ?? qualified;
1998
+ type ??= item.properties[0]?.type;
1999
+ } catch (error) {
2000
+ if (!(error instanceof SelectionError) || error.code !== "missing-selection") throw error;
2001
+ const archive = await readDocumentArchive(bytes, { ...context, budget });
2002
+ if (!qualified.includes(":")) {
2003
+ const group = propertyDeclaration("core", qualified, archive.dialect) ? "core" : propertyDeclaration("extended", qualified, archive.dialect) ? "extended" : "custom";
2004
+ qualified = `${group}:${qualified}`;
2005
+ }
2006
+ }
2007
+ }
2008
+ const normalized = normalizeDocxPropertyOptions2({ name: qualified, value: options.value, ...type === void 0 ? {} : { type } }, typeof options.value === "string");
2009
+ options.value = normalized.value;
2010
+ }
2011
+ const output = options.output === void 0 ? void 0 : options.output === "-" ? "-" : resolvePath27(request.cwd, options.output);
2012
+ let data;
2013
+ if (edit) data = await editDocumentProperties(bytes, { ...options, operation: invocation.operation, ...input ? { input } : {}, ...output === void 0 ? {} : { output } }, { ...context, budget, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, stdout: request.stdout });
2014
+ else data = await inspectDocumentProperties(bytes, options, { ...context, budget });
2015
+ if (edit && output === "-" && "dryRun" in data && !data.dryRun) return new Uint8Array();
2016
+ const warnings = "warnings" in data ? data.warnings : [], affected = "changes" in data ? data.changes.length : 0;
2017
+ const resultData = "items" in data ? invocation.operation === "properties.get" ? { item: data.items[0] } : { items: data.items } : data;
2018
+ const locations = "items" in data ? data.items.map((item) => item.location) : data.changes.flatMap((change) => change.after ? [change.after] : change.before ? [change.before] : []);
2019
+ const envelope = { version: 1, operation: invocation.operation, ok: true, data: resultData, warnings, errors: [], affected, locations };
2020
+ if (options.json) {
2021
+ const measured = measurePackageResourceSerialization6(envelope, budget);
2022
+ budget.check("serializedOutput", measured + 1);
2023
+ budget.charge("retainedBytes", (measured + 1) * 6);
2024
+ } else {
2025
+ const retained = "items" in data ? data.items.reduce((size, item) => size + (item.name?.length ?? 16) + (item.properties.length ? String(item.properties[0].value).length : 32) + 4, 16) : 128;
2026
+ budget.charge("retainedBytes", retained * 12);
2027
+ budget.charge("work", retained * 12);
2028
+ }
2029
+ let text;
2030
+ if (options.json) text = JSON.stringify(envelope) + "\n";
2031
+ else if ("items" in data && data.items.length) {
2032
+ const fields = data.items.map((item) => [item.name ?? "Unnamed property", item.properties.length ? String(item.properties[0].value) : "preserved unsupported value"]);
2033
+ const minimum = fields.reduce((size, [name, value]) => size + utf8Length2(name) + utf8Length2(value) + 3, 0);
2034
+ budget.check("serializedOutput", minimum);
2035
+ const exact = fields.reduce((size, [name, value]) => size + escapedUtf8Length2(name) + escapedUtf8Length2(value) + 3, 0);
2036
+ budget.check("serializedOutput", exact);
2037
+ text = fields.map(([name, value]) => `${escapeTerminalText(name)}: ${escapeTerminalText(value)}`).join("\n") + "\n";
2038
+ } else {
2039
+ text = "items" in data ? "Properties: 0\n" : `docx ${invocation.operation.split(".").join(" ")}: ${data.dryRun ? "dry-run; " : ""}${affected} properties changed
2040
+ `;
2041
+ budget.check("serializedOutput", utf8Length2(text));
2042
+ }
2043
+ const length = utf8Length2(text);
2044
+ budget.check("serializedOutput", length);
2045
+ budget.charge("retainedBytes", length * 3);
2046
+ budget.charge("work", warnings.reduce((size, warning) => size + 9 + warning.code.length + warning.message.length, 0));
2047
+ const diagnosticLength = warnings.reduce((size, warning) => size + 9 + utf8Length2(warning.code) + utf8Length2(warning.message), 0);
2048
+ budget.check("diagnosticBytes", diagnosticLength);
2049
+ budget.charge("retainedBytes", diagnosticLength * 3);
2050
+ const diagnosticText = warnings.map((warning) => `docx: ${warning.code}: ${warning.message}
2051
+ `).join("");
2052
+ if (diagnosticLength) {
2053
+ try {
2054
+ await request.stderr.write(new TextEncoder().encode(diagnosticText));
2055
+ } catch (cause) {
2056
+ if (settings.signal.aborted) throw new CancellationError4("Property diagnostics cancelled.", { cause });
2057
+ throw new PublicationError27("sink-failure", "Property diagnostics could not be written.", [], false, { cause });
2058
+ }
2059
+ }
2060
+ budget.check("work", 0);
2061
+ return new TextEncoder().encode(text);
2062
+ }
2063
+
2064
+ // packages/safe-bash-command-docx/src/images-command.ts
2065
+ import { resolvePath as resolvePath28 } from "@poe-platform/safe-fs/core";
2066
+ import { measurePackageResourceSerialization as measurePackageResourceSerialization7 } from "../../safe-bash-docx-engine/ancillary-resources.js";
2067
+ import { archiveSettings as archiveSettings9, CancellationError as CancellationError5 } from "../../safe-bash-docx-engine/archive.js";
2068
+ import { DocxUsageError as DocxUsageError5 } from "../../safe-bash-docx-engine/argument-json.js";
2069
+ import { inspectDocumentImages, extractDocumentImages, ImageExtractionPublicationError, ImageExtractionCancellationError } from "../../safe-bash-docx-engine/images.js";
2070
+ import { PublicationError as PublicationError28 } from "../../safe-bash-docx-engine/publication.js";
2071
+ function utf8Length3(text) {
2072
+ let bytes = 0;
2073
+ for (const character of text) {
2074
+ const code = character.codePointAt(0);
2075
+ bytes += code <= 127 ? 1 : code <= 2047 ? 2 : code <= 65535 ? 3 : 4;
2076
+ }
2077
+ return bytes;
2078
+ }
2079
+ function escapedUtf8Length3(text) {
2080
+ let bytes = 0;
2081
+ for (const character of text) bytes += utf8Length3(escapeTerminalText(character));
2082
+ return bytes;
2083
+ }
2084
+ var ImageCommandPublicationError = class extends ImageExtractionPublicationError {
2085
+ constructor(error, responseBytes, diagnosticBytes) {
2086
+ super(error, error.data);
2087
+ this.responseBytes = responseBytes;
2088
+ this.diagnosticBytes = diagnosticBytes;
2089
+ }
2090
+ responseBytes;
2091
+ diagnosticBytes;
2092
+ };
2093
+ async function executeImagesCommand(invocation, bytes, input, request, context, onExtraction) {
2094
+ if (!["images.list", "images.get", "images.extract"].includes(invocation.operation)) throw new DocxUsageError5("Expected an image inspection or extraction operation.");
2095
+ const settings = archiveSettings9(context), options = invocation.options;
2096
+ const budget = settings.budget.lower(Object.fromEntries((options.limit ?? []).map((limit) => [limit.name, limit.value])));
2097
+ const extraction = invocation.operation === "images.extract";
2098
+ let reserved = false;
2099
+ const admitPublication = (planned) => {
2100
+ const { warnings: warnings2, ...data2 } = planned, locations2 = data2.entries.flatMap((entry) => entry.locations);
2101
+ const diagnosticSize2 = warnings2.reduce((size, warning) => size + utf8Length3(`docx: ${warning.code}: ${warning.message}
2102
+ `), 0);
2103
+ budget.check("diagnosticBytes", diagnosticSize2 + utf8Length3("docx: unsupported-publication: Document operation failed: unsupported-publication\n"));
2104
+ let responseSize;
2105
+ if (options.json) {
2106
+ const envelope2 = { version: 1, operation: invocation.operation, ok: true, data: data2, affected: 0, locations: locations2, warnings: warnings2, errors: [] };
2107
+ const success = measurePackageResourceSerialization7(envelope2, budget) + 1;
2108
+ const failure = measurePackageResourceSerialization7({ ...envelope2, ok: false, data: { ...data2, complete: false }, errors: [{ code: "unsupported-publication", message: "Document operation failed: unsupported-publication" }] }, budget) + 1;
2109
+ budget.check("serializedOutput", Math.max(success, failure));
2110
+ responseSize = Math.max(success, failure);
2111
+ } else {
2112
+ responseSize = utf8Length3(`Images extracted: ${data2.entries.length}; complete: false
2113
+ `);
2114
+ budget.check("serializedOutput", responseSize);
2115
+ }
2116
+ const diagnostics = diagnosticSize2 + utf8Length3("docx: unsupported-publication: Document operation failed: unsupported-publication\n");
2117
+ budget.charge("retainedBytes", responseSize * 12 + diagnostics * 12 + data2.entries.length * 512 + 1024);
2118
+ budget.charge("work", responseSize * 12 + diagnostics * 12 + data2.entries.length * 16 + 1024);
2119
+ reserved = true;
2120
+ return void 0;
2121
+ };
2122
+ const commandError = (error) => {
2123
+ const { warnings: warnings2, ...data2 } = error.data, diagnostic = commandDiagnostic("Document operation failed: " + error.code, error.code, budget.limits.diagnosticBytes);
2124
+ const reportPublication = options.allowPartialOutput === true || error.published.length > 0;
2125
+ const envelope2 = { version: 1, operation: invocation.operation, ok: false, data: reportPublication ? data2 : null, affected: 0, locations: reportPublication ? data2.entries.flatMap((entry) => entry.locations) : [], warnings: warnings2, errors: [{ code: error.code, message: diagnostic.message }] };
2126
+ return new ImageCommandPublicationError(error, new TextEncoder().encode(options.json ? JSON.stringify(envelope2) + "\n" : ""), new TextEncoder().encode(diagnostic.human));
2127
+ };
2128
+ let inspected;
2129
+ try {
2130
+ inspected = extraction ? await extractDocumentImages(bytes, { ...options, outputDir: resolvePath28(request.cwd, options.outputDir), ...input ? { input } : {} }, { ...settings, budget, encoding: { order: "input", compression: "store" }, filesystem: request.filesystem, admitPublication }) : await inspectDocumentImages(bytes, { ...invocation.options, operation: invocation.operation }, { ...settings, budget });
2131
+ } catch (error) {
2132
+ if (reserved && error instanceof ImageExtractionPublicationError) throw commandError(error);
2133
+ throw error;
2134
+ }
2135
+ if ("entries" in inspected && onExtraction) onExtraction(inspected);
2136
+ const { warnings, ...data } = inspected;
2137
+ const records = "items" in data ? data.items ?? [] : "item" in data && data.item ? [data.item] : [];
2138
+ const locations = "entries" in data ? data.entries.flatMap((entry) => entry.locations) : records.map((record) => record.location);
2139
+ const envelope = { version: 1, operation: invocation.operation, ok: true, data, affected: 0, locations, warnings, errors: [] };
2140
+ let text;
2141
+ if (options.json) {
2142
+ if (!reserved) {
2143
+ const size = measurePackageResourceSerialization7(envelope, budget) + 1;
2144
+ budget.check("serializedOutput", size);
2145
+ budget.charge("retainedBytes", size * 6);
2146
+ }
2147
+ text = JSON.stringify(envelope) + "\n";
2148
+ } else if ("entries" in data) {
2149
+ text = `Images extracted: ${data.entries.filter((entry) => entry.published).length}; complete: ${data.complete}
2150
+ `;
2151
+ } else {
2152
+ let size = utf8Length3(`Images: ${records.length}
2153
+ `);
2154
+ for (const record of records) size += escapedUtf8Length3(record.name ?? "Unresolved image") + utf8Length3(`: ${record.details.mime ?? "unresolved"}; ${record.details.bytes ?? "unknown"} bytes; ${record.support}
2155
+ `);
2156
+ budget.check("serializedOutput", size);
2157
+ budget.charge("retainedBytes", size * 6);
2158
+ text = `Images: ${records.length}
2159
+ ` + records.map((record) => `${escapeTerminalText(record.name ?? "Unresolved image")}: ${record.details.mime ?? "unresolved"}; ${record.details.bytes ?? "unknown"} bytes; ${record.support}
2160
+ `).join("");
2161
+ }
2162
+ const diagnosticSize = warnings.reduce((size, warning) => size + utf8Length3(`docx: ${warning.code}: ${warning.message}
2163
+ `), 0);
2164
+ if (!reserved) {
2165
+ budget.check("diagnosticBytes", diagnosticSize);
2166
+ budget.charge("retainedBytes", diagnosticSize * 3 + utf8Length3(text) * 3);
2167
+ }
2168
+ if (warnings.length) {
2169
+ try {
2170
+ await request.stderr.write(new TextEncoder().encode(warnings.map((warning) => `docx: ${warning.code}: ${warning.message}
2171
+ `).join("")));
2172
+ settings.signal.throwIfAborted();
2173
+ } catch (cause) {
2174
+ const published = "entries" in data ? [...data.entries.filter((entry) => entry.published).map((entry) => ({ path: entry.path, bytes: entry.bytes })), ...data.manifest.published ? [{ path: data.manifest.path, bytes: data.manifest.bytes }] : []] : [];
2175
+ if (settings.signal.aborted) {
2176
+ const error2 = new CancellationError5("Image diagnostics cancelled.", { cause });
2177
+ if ("entries" in data) throw new ImageExtractionCancellationError(error2, { ...data, warnings, complete: false }, published);
2178
+ throw error2;
2179
+ }
2180
+ const error = new PublicationError28("sink-failure", "Image diagnostics could not be written.", published, false, { cause });
2181
+ if ("entries" in data) throw commandError(new ImageExtractionPublicationError(error, { ...data, warnings, complete: false }));
2182
+ throw error;
2183
+ }
2184
+ }
2185
+ budget.check("work", 0);
2186
+ return new TextEncoder().encode(text);
2187
+ }
2188
+
2189
+ // packages/safe-bash-command-docx/src/inspection-command.ts
2190
+ import { ImageExtractionCancellationError as ImageExtractionCancellationError2 } from "../../safe-bash-docx-engine/images.js";
2191
+
2192
+ // packages/safe-bash-command-docx/src/image-insertion-command.ts
2193
+ import { resolvePath as resolvePath29 } from "@poe-platform/safe-fs/core";
2194
+ import { archiveSettings as archiveSettings10 } from "../../safe-bash-docx-engine/archive.js";
2195
+ import { DocxUsageError as DocxUsageError6 } from "../../safe-bash-docx-engine/argument-json.js";
2196
+ import { measurePackageResourceSerialization as measurePackageResourceSerialization8 } from "../../safe-bash-docx-engine/ancillary-resources.js";
2197
+ import { insertDocumentImage } from "../../safe-bash-docx-engine/image-insertion.js";
2198
+ import { DocumentIo as DocumentIo3 } from "../../safe-bash-docx-engine/io.js";
2199
+ import { UnsupportedProfileError as UnsupportedProfileError2 } from "../../safe-bash-docx-engine/package-xml.js";
2200
+ import { PublicationError as PublicationError29 } from "../../safe-bash-docx-engine/publication.js";
2201
+ async function executeImageInsertionCommand(invocation, bytes, input, request, context) {
2202
+ if (invocation.operation !== "images.add") throw new DocxUsageError6("Expected image insertion.");
2203
+ const settings = archiveSettings10(context), options = invocation.options;
2204
+ const budget = settings.budget.lower(Object.fromEntries((options.limit ?? []).map((item) => [item.name, item.value])));
2205
+ const output = options.output === void 0 || options.output === "-" ? options.output : resolvePath29(request.cwd, options.output);
2206
+ const normalizeSource = (source, argument) => {
2207
+ if (source?.kind !== "vfs" || source.capability !== "command") return source;
2208
+ const reserved = source.path === "-" && invocation.sources?.some((item) => item.argument === argument && item.format === "binary" && item.path === "-");
2209
+ return { ...source, path: reserved ? "-" : resolvePath29(request.cwd, source.path) };
2210
+ };
2211
+ const file = normalizeSource(options.file, "file"), fallback = normalizeSource(options.fallback, "fallback");
2212
+ if ((options.inPlace || output !== void 0 && output !== "-") && invocation.inputs[0] !== "-" && !input) throw new PublicationError29("unsupported-publication", "Image publication requires admitted input identity.");
2213
+ const envelope = (data2) => ({ version: 1, operation: invocation.operation, ok: true, data: data2, affected: data2.changes.length, locations: data2.changes.map((c) => c.after), warnings: [], errors: [] });
2214
+ const human = (data2) => `docx images add: ${data2.dryRun ? "dry-run; " : ""}${data2.changes.length} ${data2.changes.length === 1 ? "selection" : "selections"} changed
2215
+ `;
2216
+ const data = await insertDocumentImage(bytes, { operation: "images.add", options: { ...options, file, ...fallback === void 0 ? {} : { fallback }, ...output === void 0 ? {} : { output } }, ...input ? { input } : {} }, {
2217
+ ...settings,
2218
+ budget,
2219
+ encoding: { order: "input", compression: "store" },
2220
+ filesystem: request.filesystem,
2221
+ stdout: request.stdout,
2222
+ admitPublication(planned) {
2223
+ const size = output === "-" && !planned.dryRun ? 0 : options.json ? measurePackageResourceSerialization8(envelope(planned), budget) + 1 : new TextEncoder().encode(human(planned)).length;
2224
+ const diagnosticSize = new TextEncoder().encode("docx: unsupported-publication: Document operation failed: unsupported-publication\n").length;
2225
+ budget.check("serializedOutput", size);
2226
+ budget.check("diagnosticBytes", diagnosticSize);
2227
+ budget.charge("retainedBytes", size * 8 + diagnosticSize * 8);
2228
+ budget.charge("work", size * 8 + diagnosticSize * 8);
2229
+ return void 0;
2230
+ },
2231
+ binaryResolver: { capability: "command", async *open(path2, { signal, maxBytes }) {
2232
+ const readStream = request.filesystem.readStream;
2233
+ if (path2 !== "-" && !readStream) throw new UnsupportedProfileError2("Image paths require an explicit streaming read capability.");
2234
+ const source = { open: (inner) => path2 === "-" ? request.stdin : readStream.call(request.filesystem, resolvePath29(request.cwd, path2), { signal: inner }) };
2235
+ const io = new DocumentIo3({ ...settings, budget, signal, limits: { ...settings.limits, maxArchiveBytes: maxBytes }, ...request.registerCleanup ? { registerCleanup: request.registerCleanup } : {} });
2236
+ try {
2237
+ signal.throwIfAborted();
2238
+ yield await io.readBytes(source);
2239
+ } finally {
2240
+ await io.cleanup();
2241
+ }
2242
+ } }
2243
+ });
2244
+ if (output === "-" && !data.dryRun) return new Uint8Array();
2245
+ return new TextEncoder().encode(options.json ? JSON.stringify(envelope(data)) + "\n" : human(data));
2246
+ }
2247
+
2248
+ // packages/safe-bash-command-docx/src/image-replacement-command.ts
2249
+ import { resolvePath as resolvePath30 } from "@poe-platform/safe-fs/core";
2250
+ import { archiveSettings as archiveSettings11 } from "../../safe-bash-docx-engine/archive.js";
2251
+ import { DocxUsageError as DocxUsageError7 } from "../../safe-bash-docx-engine/argument-json.js";
2252
+ import { replaceDocumentImage } from "../../safe-bash-docx-engine/image-replacement.js";
2253
+ import { measurePackageResourceSerialization as measurePackageResourceSerialization9 } from "../../safe-bash-docx-engine/ancillary-resources.js";
2254
+ import { DocumentIo as DocumentIo4 } from "../../safe-bash-docx-engine/io.js";
2255
+ import { UnsupportedProfileError as UnsupportedProfileError3 } from "../../safe-bash-docx-engine/package-xml.js";
2256
+ import { PublicationError as PublicationError30 } from "../../safe-bash-docx-engine/publication.js";
2257
+ async function executeImageReplacementCommand(invocation, bytes, input, request, context) {
2258
+ if (invocation.operation !== "images.replace") throw new DocxUsageError7("Expected image replacement.");
2259
+ const settings = archiveSettings11(context), options = invocation.options;
2260
+ const budget = settings.budget.lower(Object.fromEntries((options.limit ?? []).map((limit) => [limit.name, limit.value])));
2261
+ const output = options.output === void 0 || options.output === "-" ? options.output : resolvePath30(request.cwd, options.output);
2262
+ const file = options.file.kind === "vfs" && options.file.capability === "command" ? { ...options.file, path: resolvePath30(request.cwd, options.file.path) } : options.file;
2263
+ if ((options.inPlace || output !== void 0 && output !== "-") && invocation.inputs[0] !== "-" && !input) throw new PublicationError30("unsupported-publication", "Image publication requires admitted input identity.");
2264
+ const envelope = (data2) => ({ version: 1, operation: "images.replace", ok: true, data: data2, affected: data2.changes.length, locations: data2.changes.map((change) => change.after), warnings: [], errors: [] });
2265
+ const human = (data2) => `docx images replace: ${data2.dryRun ? "dry-run; " : ""}${data2.changes.length} ${data2.changes.length === 1 ? "occurrence" : "occurrences"} changed
2266
+ `;
2267
+ const data = await replaceDocumentImage(bytes, { operation: "images.replace", options: { ...options, file, ...output === void 0 ? {} : { output } }, ...input ? { input } : {} }, {
2268
+ ...settings,
2269
+ budget,
2270
+ encoding: { order: "input", compression: "store" },
2271
+ filesystem: request.filesystem,
2272
+ stdout: request.stdout,
2273
+ ...request.registerCleanup ? { registerCleanup: request.registerCleanup } : {},
2274
+ admitPublication(planned) {
2275
+ const size = output === "-" && !planned.dryRun ? 0 : options.json ? measurePackageResourceSerialization9(envelope(planned), budget) + 1 : new TextEncoder().encode(human(planned)).length;
2276
+ const diagnostics = new TextEncoder().encode("docx: unsupported-publication: Document operation failed: unsupported-publication\n").length;
2277
+ budget.check("serializedOutput", size);
2278
+ budget.check("diagnosticBytes", diagnostics);
2279
+ budget.charge("retainedBytes", size * 8 + diagnostics * 8);
2280
+ budget.charge("work", size * 8 + diagnostics * 8);
2281
+ return void 0;
2282
+ },
2283
+ binaryResolver: { capability: "command", async *open(path2, { signal, maxBytes }) {
2284
+ const readStream = request.filesystem.readStream;
2285
+ if (!readStream) throw new UnsupportedProfileError3("Image paths require an explicit streaming read capability.");
2286
+ const source = { open: (inner) => readStream.call(request.filesystem, resolvePath30(request.cwd, path2), { signal: inner }) };
2287
+ const io = new DocumentIo4({ ...settings, budget, signal, limits: { ...settings.limits, maxArchiveBytes: maxBytes }, ...request.registerCleanup ? { registerCleanup: request.registerCleanup } : {} });
2288
+ try {
2289
+ signal.throwIfAborted();
2290
+ yield await io.readBytes(source);
2291
+ } finally {
2292
+ await io.cleanup();
2293
+ }
2294
+ } }
2295
+ });
2296
+ if (output === "-" && !data.dryRun) return new Uint8Array();
2297
+ return new TextEncoder().encode(options.json ? JSON.stringify(envelope(data)) + "\n" : human(data));
2298
+ }
2299
+
2300
+ // packages/safe-bash-command-docx/src/image-layout-command.ts
2301
+ import { resolvePath as resolvePath31 } from "@poe-platform/safe-fs/core";
2302
+ import { archiveSettings as archiveSettings12 } from "../../safe-bash-docx-engine/archive.js";
2303
+ import { DocxUsageError as DocxUsageError8 } from "../../safe-bash-docx-engine/argument-json.js";
2304
+ import { setDocumentImageLayout } from "../../safe-bash-docx-engine/image-layout.js";
2305
+ import { measurePackageResourceSerialization as measurePackageResourceSerialization10 } from "../../safe-bash-docx-engine/ancillary-resources.js";
2306
+ import { PublicationError as PublicationError31 } from "../../safe-bash-docx-engine/publication.js";
2307
+ async function executeImageLayoutCommand(invocation, bytes, input, request, context) {
2308
+ if (invocation.operation !== "images.set") throw new DocxUsageError8("Expected image layout.");
2309
+ const settings = archiveSettings12(context), options = invocation.options;
2310
+ const budget = settings.budget.lower(Object.fromEntries((options.limit ?? []).map((limit) => [limit.name, limit.value])));
2311
+ const output = options.output === void 0 || options.output === "-" ? options.output : resolvePath31(request.cwd, options.output);
2312
+ if ((options.inPlace || output !== void 0 && output !== "-") && invocation.inputs[0] !== "-" && !input) throw new PublicationError31("unsupported-publication", "Image publication requires admitted input identity.");
2313
+ const envelope = (data2) => ({ version: 1, operation: "images.set", ok: true, data: data2, affected: data2.changes.length, locations: data2.changes.map((change) => change.after), warnings: [], errors: [] });
2314
+ const human = (data2) => `docx images set: ${data2.dryRun ? "dry-run; " : ""}${data2.changes.length} ${data2.changes.length === 1 ? "occurrence" : "occurrences"} changed
2315
+ `;
2316
+ const data = await setDocumentImageLayout(bytes, { operation: "images.set", options: { ...options, ...output === void 0 ? {} : { output } }, ...input ? { input } : {} }, {
2317
+ ...settings,
2318
+ budget,
2319
+ encoding: { order: "input", compression: "store" },
2320
+ filesystem: request.filesystem,
2321
+ stdout: request.stdout,
2322
+ ...request.registerCleanup ? { registerCleanup: request.registerCleanup } : {},
2323
+ admitPublication(planned) {
2324
+ const size = output === "-" && !planned.dryRun ? 0 : options.json ? measurePackageResourceSerialization10(envelope(planned), budget) + 1 : new TextEncoder().encode(human(planned)).length;
2325
+ const diagnostics = new TextEncoder().encode("docx: unsupported-publication: Document operation failed: unsupported-publication\n").length;
2326
+ budget.check("serializedOutput", size);
2327
+ budget.check("diagnosticBytes", diagnostics);
2328
+ budget.charge("retainedBytes", size * 8 + diagnostics * 8);
2329
+ budget.charge("work", size * 8 + diagnostics * 8);
2330
+ return void 0;
2331
+ }
2332
+ });
2333
+ if (output === "-" && !data.dryRun) return new Uint8Array();
2334
+ return new TextEncoder().encode(options.json ? JSON.stringify(envelope(data)) + "\n" : human(data));
2335
+ }
2336
+
2337
+ // packages/safe-bash-command-docx/src/shapes-command.ts
2338
+ import { resolvePath as resolvePath32 } from "@poe-platform/safe-fs/core";
2339
+ import { archiveSettings as archiveSettings13 } from "../../safe-bash-docx-engine/archive.js";
2340
+ import { DocxUsageError as DocxUsageError9 } from "../../safe-bash-docx-engine/argument-json.js";
2341
+ import { measurePackageResourceSerialization as measurePackageResourceSerialization11 } from "../../safe-bash-docx-engine/ancillary-resources.js";
2342
+ import { PublicationError as PublicationError32 } from "../../safe-bash-docx-engine/publication.js";
2343
+ import { inspectDocumentShapes, editDocumentShapes } from "../../safe-bash-docx-engine/shape-edit.js";
2344
+ async function executeShapesCommand(invocation, bytes, input, request, context) {
2345
+ if (invocation.operation !== "shapes.list" && invocation.operation !== "shapes.set") throw new DocxUsageError9("Expected a shape inventory or text assignment operation.");
2346
+ const settings = archiveSettings13(context), shapeOptions = invocation.options;
2347
+ const budget = settings.budget.lower(Object.fromEntries((shapeOptions.limit ?? []).map((limit) => [limit.name, limit.value])));
2348
+ if (invocation.operation === "shapes.list") {
2349
+ const inspected = await inspectDocumentShapes(bytes, invocation.options, { ...settings, budget });
2350
+ const { warnings, ...data2 } = inspected;
2351
+ const envelope2 = { version: 1, operation: "shapes.list", ok: true, data: data2, affected: 0, locations: data2.items.map((item) => item.location), warnings, errors: [] };
2352
+ const retainedSize = measurePackageResourceSerialization11(envelope2, budget);
2353
+ budget.charge("retainedBytes", retainedSize * 12);
2354
+ budget.charge("work", retainedSize * 12);
2355
+ const human2 = `Shapes: ${data2.items.length}
2356
+ ` + data2.items.map((item) => `${escapeTerminalText(item.name ?? "Unnamed shape")}: ${item.details.representation}; ${item.details.kind}; ${item.support}
2357
+ `).join("");
2358
+ const size = invocation.options.json ? measurePackageResourceSerialization11(envelope2, budget) + 1 : new TextEncoder().encode(human2).length;
2359
+ const diagnostic = warnings.map((warning) => `docx: ${escapeTerminalText(warning.code)}: ${escapeTerminalText(warning.message)}
2360
+ `).join("");
2361
+ budget.check("serializedOutput", size);
2362
+ budget.check("diagnosticBytes", new TextEncoder().encode(diagnostic).length);
2363
+ budget.charge("retainedBytes", size * 8 + diagnostic.length * 8);
2364
+ budget.charge("work", size * 8 + diagnostic.length * 8);
2365
+ if (diagnostic) await request.stderr.write(new TextEncoder().encode(diagnostic));
2366
+ settings.signal.throwIfAborted();
2367
+ return new TextEncoder().encode(invocation.options.json ? JSON.stringify(envelope2) + "\n" : human2);
2368
+ }
2369
+ const options = invocation.options;
2370
+ const output = options.output === void 0 || options.output === "-" ? options.output : resolvePath32(request.cwd, options.output);
2371
+ if ((options.inPlace || output !== void 0 && output !== "-") && invocation.inputs[0] !== "-" && !input) throw new PublicationError32("unsupported-publication", "Shape publication requires admitted input identity.");
2372
+ const envelope = (data2) => ({ version: 1, operation: "shapes.set", ok: true, data: data2, affected: data2.changes.length, locations: data2.changes.map((change) => change.after), warnings: [], errors: [] });
2373
+ const human = (data2) => `docx shapes set: ${data2.dryRun ? "dry-run; " : ""}${data2.changes.length} ${data2.changes.length === 1 ? "shape" : "shapes"} changed
2374
+ `;
2375
+ const data = await editDocumentShapes(bytes, { operation: "shapes.set", options: { ...options, ...output === void 0 ? {} : { output } }, ...input ? { input } : {} }, {
2376
+ ...settings,
2377
+ budget,
2378
+ encoding: { order: "input", compression: "store" },
2379
+ filesystem: request.filesystem,
2380
+ stdout: request.stdout,
2381
+ ...request.registerCleanup ? { registerCleanup: request.registerCleanup } : {},
2382
+ admitPublication(planned) {
2383
+ const size = output === "-" && !planned.dryRun ? 0 : options.json ? measurePackageResourceSerialization11(envelope(planned), budget) + 1 : new TextEncoder().encode(human(planned)).length;
2384
+ const diagnostics = new TextEncoder().encode("docx: unsupported-publication: Document operation failed: unsupported-publication\n").length;
2385
+ budget.check("serializedOutput", size);
2386
+ budget.check("diagnosticBytes", diagnostics);
2387
+ budget.charge("retainedBytes", size * 8 + diagnostics * 8);
2388
+ budget.charge("work", size * 8 + diagnostics * 8);
2389
+ return void 0;
2390
+ }
2391
+ });
2392
+ if (output === "-" && !data.dryRun) return new Uint8Array();
2393
+ return new TextEncoder().encode(options.json ? JSON.stringify(envelope(data)) + "\n" : human(data));
2394
+ }
2395
+
2396
+ // packages/safe-bash-command-docx/src/charts-command.ts
2397
+ import { archiveSettings as archiveSettings14 } from "../../safe-bash-docx-engine/archive.js";
2398
+ import { DocxUsageError as DocxUsageError10 } from "../../safe-bash-docx-engine/argument-json.js";
2399
+ import { measurePackageResourceSerialization as measurePackageResourceSerialization12 } from "../../safe-bash-docx-engine/ancillary-resources.js";
2400
+ import { inspectDocumentCharts } from "../../safe-bash-docx-engine/charts.js";
2401
+ async function executeChartsCommand(invocation, bytes, request, context) {
2402
+ if (invocation.operation !== "charts.list") throw new DocxUsageError10("Expected physical chart inventory.");
2403
+ const options = invocation.options, settings = archiveSettings14(context);
2404
+ const budget = settings.budget.lower(Object.fromEntries((options.limit ?? []).map((limit) => [limit.name, limit.value])));
2405
+ const inspected = await inspectDocumentCharts(bytes, options, { ...settings, budget });
2406
+ const { warnings, ...data } = inspected;
2407
+ const envelope = { version: 1, operation: "charts.list", ok: true, data, affected: 0, locations: data.items.map((item) => item.location), warnings, errors: [] };
2408
+ const retainedSize = measurePackageResourceSerialization12(envelope, budget);
2409
+ budget.charge("retainedBytes", retainedSize * 12);
2410
+ budget.charge("work", retainedSize * 12);
2411
+ const human = `Chart parts: ${data.items.length}
2412
+ ` + data.items.map((item) => `${escapeTerminalText(item.name ?? item.location.value.part)}: ${escapeTerminalText(item.details.chartTypes.join(", ") || "opaque or no plot groups")}; ${item.support}
2413
+ `).join("");
2414
+ const diagnostic = warnings.map((warning) => `docx: ${escapeTerminalText(warning.code)}: ${escapeTerminalText(warning.message)}
2415
+ `).join("");
2416
+ const size = options.json ? retainedSize + 1 : new TextEncoder().encode(human).length;
2417
+ budget.check("serializedOutput", size);
2418
+ budget.check("diagnosticBytes", new TextEncoder().encode(diagnostic).length);
2419
+ budget.charge("retainedBytes", size * 8 + diagnostic.length * 8);
2420
+ budget.charge("work", size * 8 + diagnostic.length * 8);
2421
+ if (diagnostic) await request.stderr.write(new TextEncoder().encode(diagnostic));
2422
+ settings.signal.throwIfAborted();
2423
+ return new TextEncoder().encode(options.json ? JSON.stringify(envelope) + "\n" : human);
2424
+ }
2425
+
2426
+ // packages/safe-bash-command-docx/src/diagrams-command.ts
2427
+ import { archiveSettings as archiveSettings15 } from "../../safe-bash-docx-engine/archive.js";
2428
+ import { DocxUsageError as DocxUsageError11 } from "../../safe-bash-docx-engine/argument-json.js";
2429
+ import { measurePackageResourceSerialization as measurePackageResourceSerialization13 } from "../../safe-bash-docx-engine/ancillary-resources.js";
2430
+ import { inspectDocumentDiagrams } from "../../safe-bash-docx-engine/diagrams.js";
2431
+ function serializeDiagramMutationFailure(operation, error, code, message, budget) {
2432
+ const diagnostic = { code, message, location: error.location.token };
2433
+ const diagnosticSize = measurePackageResourceSerialization13(diagnostic, budget);
2434
+ budget.check("diagnosticBytes", diagnosticSize);
2435
+ const envelope = { version: 1, operation, ok: false, data: null, affected: 0, locations: error.locations, warnings: [], errors: [diagnostic] };
2436
+ const size = measurePackageResourceSerialization13(envelope, budget) + 1;
2437
+ budget.check("serializedOutput", size);
2438
+ budget.charge("retainedBytes", size * 12);
2439
+ budget.charge("work", size * 12);
2440
+ return new TextEncoder().encode(JSON.stringify(envelope) + "\n");
2441
+ }
2442
+ async function executeDiagramsCommand(invocation, bytes, request, context) {
2443
+ if (invocation.operation !== "diagrams.list") throw new DocxUsageError11("Expected physical diagram inventory.");
2444
+ const options = invocation.options, settings = archiveSettings15(context);
2445
+ const budget = settings.budget.lower(Object.fromEntries((options.limit ?? []).map((limit) => [limit.name, limit.value])));
2446
+ const { warnings, ...data } = await inspectDocumentDiagrams(bytes, options, { ...settings, budget });
2447
+ const envelope = { version: 1, operation: "diagrams.list", ok: true, data, affected: 0, locations: data.items.map((item) => item.location), warnings, errors: [] };
2448
+ const retainedSize = measurePackageResourceSerialization13(envelope, budget);
2449
+ budget.charge("retainedBytes", retainedSize * 12);
2450
+ budget.charge("work", retainedSize * 12);
2451
+ const human = `Diagram records: ${data.items.length}
2452
+ ` + data.items.map((item) => `${escapeTerminalText(item.name)}: ${escapeTerminalText(item.details.roles.map((role) => role.role).join(", ") || "opaque graphics")}; preserve
2453
+ `).join("");
2454
+ const diagnostic = warnings.map((warning) => `docx: ${escapeTerminalText(warning.code)}: ${escapeTerminalText(warning.message)}
2455
+ `).join("");
2456
+ const encoder = new TextEncoder(), diagnosticBytes = encoder.encode(diagnostic), size = options.json ? retainedSize + 1 : encoder.encode(human).length;
2457
+ budget.check("serializedOutput", size);
2458
+ budget.check("diagnosticBytes", diagnosticBytes.length);
2459
+ budget.charge("retainedBytes", size * 8 + diagnosticBytes.length * 8);
2460
+ budget.charge("work", size * 8 + diagnosticBytes.length * 8);
2461
+ if (diagnosticBytes.length) await request.stderr.write(diagnosticBytes);
2462
+ settings.signal.throwIfAborted();
2463
+ return encoder.encode(options.json ? JSON.stringify(envelope) + "\n" : human);
2464
+ }
2465
+
2466
+ // packages/safe-bash-command-docx/src/inspection-command.ts
2467
+ import { UnsupportedDiagramMutationError } from "../../safe-bash-docx-engine/diagrams.js";
2468
+
2469
+ // packages/safe-bash-command-docx/src/equations-command.ts
2470
+ import { resolvePath as resolvePath33 } from "@poe-platform/safe-fs/core";
2471
+ import { archiveSettings as archiveSettings16, CancellationError as CancellationError6, ResourceLimitError as ResourceLimitError3 } from "../../safe-bash-docx-engine/archive.js";
2472
+ import { DocxUsageError as DocxUsageError12 } from "../../safe-bash-docx-engine/argument-json.js";
2473
+ import { measurePackageResourceSerialization as measurePackageResourceSerialization14 } from "../../safe-bash-docx-engine/ancillary-resources.js";
2474
+ import { asPermissionError as asPermissionError5 } from "../../safe-bash-docx-engine/io-errors.js";
2475
+ import { inspectDocumentEquations, addDocumentEquation, replaceDocumentEquation } from "../../safe-bash-docx-engine/equations.js";
2476
+ import { UnsupportedProfileError as UnsupportedProfileError4 } from "../../safe-bash-docx-engine/package-xml.js";
2477
+ import { PublicationError as PublicationError33 } from "../../safe-bash-docx-engine/publication.js";
2478
+ async function executeEquationsCommand(invocation, bytes, input, request, context, io) {
2479
+ if (!["equations.list", "equations.add", "equations.replace"].includes(invocation.operation)) throw new DocxUsageError12("Expected equation inventory or fragment mutation.");
2480
+ const settings = archiveSettings16(context), encoder = new TextEncoder();
2481
+ const budget = settings.budget.lower(Object.fromEntries((invocation.options.limit ?? []).map((item) => [item.name, item.value])));
2482
+ if (invocation.operation === "equations.list") {
2483
+ const options2 = invocation.options;
2484
+ const { warnings, ...data2 } = await inspectDocumentEquations(bytes, options2, { ...settings, budget });
2485
+ const envelope2 = { version: 1, operation: invocation.operation, ok: true, data: data2, affected: 0, locations: data2.items.map((item) => item.location), warnings, errors: [] };
2486
+ const retainedSize = measurePackageResourceSerialization14(envelope2, budget);
2487
+ budget.charge("retainedBytes", retainedSize * 12);
2488
+ budget.charge("work", retainedSize * 12);
2489
+ const human2 = `Equation units: ${data2.items.length}
2490
+ ` + data2.items.map((item) => `${escapeTerminalText(item.name)}: ${item.details.mode}; ${item.support}
2491
+ `).join("");
2492
+ const diagnostic = warnings.map((warning) => `docx: ${escapeTerminalText(warning.code)}: ${escapeTerminalText(warning.message)}
2493
+ `).join("");
2494
+ const diagnosticBytes = encoder.encode(diagnostic), size = options2.json ? retainedSize + 1 : encoder.encode(human2).length;
2495
+ budget.check("serializedOutput", size);
2496
+ budget.check("diagnosticBytes", diagnosticBytes.length);
2497
+ budget.charge("retainedBytes", size * 8 + diagnosticBytes.length * 8);
2498
+ budget.charge("work", size * 8 + diagnosticBytes.length * 8);
2499
+ settings.signal.throwIfAborted();
2500
+ if (diagnosticBytes.length) await request.stderr.write(diagnosticBytes);
2501
+ return encoder.encode(options2.json ? JSON.stringify(envelope2) + "\n" : human2);
2502
+ }
2503
+ const operation = invocation.operation, options = invocation.options;
2504
+ const output = options.output === void 0 || options.output === "-" ? options.output : resolvePath33(request.cwd, options.output);
2505
+ const file = options.file.kind === "vfs" && options.file.capability === "command" ? { ...options.file, path: options.file.path === "-" && invocation.sources?.some((source) => source.argument === "file" && source.path === "-") ? "-" : resolvePath33(request.cwd, options.file.path) } : options.file;
2506
+ if ((options.inPlace || output !== void 0 && output !== "-") && invocation.inputs[0] !== "-" && !input)
2507
+ throw new PublicationError33("unsupported-publication", "Equation publication requires admitted input identity.");
2508
+ const envelope = (data2) => ({ version: 1, operation, ok: true, data: data2, affected: data2.changes.length, locations: data2.changes.map((change) => change.after), warnings: [], errors: [] });
2509
+ const human = (data2) => `docx ${operation.replace(".", " ")}: ${data2.dryRun ? "dry-run; " : ""}${data2.changes.length} selection changed
2510
+ `;
2511
+ const mutationContext = {
2512
+ ...settings,
2513
+ budget,
2514
+ encoding: { order: "input", compression: "store" },
2515
+ filesystem: request.filesystem,
2516
+ stdout: request.stdout,
2517
+ admitPublication(planned) {
2518
+ const size = output === "-" && !planned.dryRun ? 0 : options.json ? measurePackageResourceSerialization14(envelope(planned), budget) + 1 : encoder.encode(human(planned)).length;
2519
+ budget.check("serializedOutput", size);
2520
+ budget.charge("retainedBytes", size * 8);
2521
+ budget.charge("work", size * 8);
2522
+ return void 0;
2523
+ },
2524
+ binaryResolver: { capability: "command", async *open(path2, { signal, maxBytes }) {
2525
+ try {
2526
+ if (path2 !== "-" && !request.filesystem.readStream) throw new UnsupportedProfileError4("Equation fragment paths require an explicit streaming read capability.");
2527
+ const source = { open(inner) {
2528
+ const stream = path2 === "-" ? request.stdin : request.filesystem.readStream(resolvePath33(request.cwd, path2), { signal: inner });
2529
+ return { async *[Symbol.asyncIterator]() {
2530
+ let size = 0;
2531
+ for await (const chunk of stream) {
2532
+ size += chunk.length;
2533
+ if (size > Math.min(maxBytes, settings.limits.maxEntryBytes, budget.limits.xmlPartBytes)) throw new ResourceLimitError3("Equation fragment byte limit exceeded.");
2534
+ yield chunk;
2535
+ }
2536
+ } };
2537
+ } };
2538
+ signal.throwIfAborted();
2539
+ yield await io.readBytes(source);
2540
+ } catch (error) {
2541
+ if (error instanceof ResourceLimitError3 || error instanceof CancellationError6 || error instanceof UnsupportedProfileError4) throw error;
2542
+ if (signal.aborted) throw new CancellationError6("Equation fragment acquisition cancelled.", { cause: signal.reason });
2543
+ throw asPermissionError5(error) ?? new SourceError2(error);
2544
+ }
2545
+ } }
2546
+ };
2547
+ const mutationOptions = { ...options, file, ...output === void 0 ? {} : { output } };
2548
+ const data = operation === "equations.add" ? await addDocumentEquation(bytes, { operation, options: mutationOptions, ...input ? { input } : {} }, mutationContext) : await replaceDocumentEquation(bytes, { operation, options: mutationOptions, ...input ? { input } : {} }, mutationContext);
2549
+ if (output === "-" && !data.dryRun) return new Uint8Array();
2550
+ return encoder.encode(options.json ? JSON.stringify(envelope(data)) + "\n" : human(data));
2551
+ }
2552
+
2553
+ // packages/safe-bash-command-docx/src/inspection-command.ts
2554
+ import { UnsupportedEquationMutationError } from "../../safe-bash-docx-engine/equations.js";
2555
+ function createDocxInspectionCommandEngine(options = {}) {
2556
+ contextData(options);
2557
+ const limits = Object.freeze(archiveSettings17({ limits: options.limits ?? {}, signal: new AbortController().signal }).limits);
2558
+ let fontResolver;
2559
+ if (options.fontResolver !== void 0) {
2560
+ contextData(options.fontResolver, ["capability", "fonts"]);
2561
+ contextData(options.fontResolver.fonts, ["measure"]);
2562
+ if (typeof options.fontResolver.capability !== "string" || !options.fontResolver.capability || typeof options.fontResolver.fonts.measure !== "function") throw new TypeError("Expected an explicit font capability adapter.");
2563
+ fontResolver = Object.freeze({ capability: options.fontResolver.capability, fonts: Object.freeze({ measure: options.fontResolver.fonts.measure.bind(options.fontResolver.fonts) }) });
2564
+ }
2565
+ return createDocxCommandEngine({
2566
+ async readSource(source, request, budget) {
2567
+ const io = new DocumentIo5({ limits, signal: request.signal, budget, ...request.registerCleanup ? { registerCleanup: request.registerCleanup } : {} });
2568
+ try {
2569
+ return await io.readBytes({ open(signal) {
2570
+ const path2 = resolvePath34(request.cwd, source.path);
2571
+ return request.filesystem.readStream ? request.filesystem.readStream(path2, { signal }) : { async *[Symbol.asyncIterator]() {
2572
+ yield await request.filesystem.readFile(path2, { signal });
2573
+ } };
2574
+ } });
2575
+ } finally {
2576
+ await io.cleanup();
2577
+ }
2578
+ },
2579
+ async execute(invocation, request) {
2580
+ const budget = docxInvocationBudgets2.get(invocation) ?? new DocumentBudget3({}, request.signal);
2581
+ const context = { limits, signal: request.signal, budget, ...fontResolver ? { fontResolver } : {} };
2582
+ const io = new DocumentIo5({ ...context, ...request.registerCleanup ? { registerCleanup: request.registerCleanup } : {} });
2583
+ let acquiring = false;
2584
+ let writingDiagnostics = false;
2585
+ let output;
2586
+ let exitCode = 0;
2587
+ let archiveReceipt;
2588
+ let imageReceipt;
2589
+ const sinkFailure = (cause) => {
2590
+ if (archiveReceipt) {
2591
+ const extraction2 = { ...archiveReceipt, complete: false, possiblePartialOutput: archiveReceipt.complete || archiveReceipt.possiblePartialOutput };
2592
+ if (request.signal.aborted || cause instanceof CancellationError7) throw new ArchiveExtractionError(cause, extraction2, true);
2593
+ return { exitCode: 3, extraction: extraction2 };
2594
+ }
2595
+ if (!imageReceipt) return { exitCode: request.signal.aborted || cause instanceof CancellationError7 ? 130 : invocation.operation === "diff" ? 2 : 3 };
2596
+ const extraction = { ...imageReceipt, complete: false };
2597
+ if (request.signal.aborted || cause instanceof CancellationError7) {
2598
+ const published = [...extraction.entries.filter((entry) => entry.published).map((entry) => ({ path: entry.path, bytes: entry.bytes })), ...extraction.manifest.published ? [{ path: extraction.manifest.path, bytes: extraction.manifest.bytes }] : []];
2599
+ const ErrorType = invocation.operation === "objects.extract" ? ObjectExtractionCancellationError2 : ImageExtractionCancellationError2;
2600
+ throw new ErrorType(cause instanceof CancellationError7 ? cause : new CancellationError7("Resource output cancelled.", { cause }), extraction, published);
2601
+ }
2602
+ return { exitCode: 3, extraction };
2603
+ };
2604
+ const controlTemplateOperation = ["controls.repeat", "controls.bind", "template.apply"].includes(invocation.operation);
2605
+ const controlOperation = controlTemplateOperation || ["controls.list", "controls.set"].includes(invocation.operation);
2606
+ const fieldOperation = ["fields.add", "fields.set", "toc.add", "toc.set", "captions.add", "captions.set"].includes(invocation.operation);
2607
+ const commentOperation = ["comments.list", "comments.get", "comments.add", "comments.set", "comments.remove"].includes(invocation.operation);
2608
+ const revisionEditOperation = ["revisions.add", "revisions.accept", "revisions.reject"].includes(invocation.operation);
2609
+ const noteOperation = ["notes.list", "notes.get", "notes.add", "notes.set", "notes.remove"].includes(invocation.operation);
2610
+ const bookmarkOperation = ["bookmarks.add", "bookmarks.set", "bookmarks.remove"].includes(invocation.operation);
2611
+ const linkOperation = ["links.add", "links.set", "links.remove"].includes(invocation.operation);
2612
+ const tableOperation = ["tables.set", "tables.rows.add", "tables.rows.remove", "tables.columns.add", "tables.columns.remove", "tables.merge", "tables.split"].includes(invocation.operation);
2613
+ const listOperation = ["lists.add", "lists.set"].includes(invocation.operation);
2614
+ const storyOperation = ["headers.list", "headers.get", "headers.set", "headers.remove", "footers.list", "footers.get", "footers.set", "footers.remove"].includes(invocation.operation);
2615
+ const propertyOperation = ["properties.list", "properties.get", "properties.set", "properties.remove"].includes(invocation.operation);
2616
+ const objectOperation = ["objects.list", "objects.extract"].includes(invocation.operation);
2617
+ const imageOperation = ["images.list", "images.get", "images.extract"].includes(invocation.operation);
2618
+ const imageInsertionOperation = invocation.operation === "images.add";
2619
+ const imageReplacementOperation = invocation.operation === "images.replace";
2620
+ const imageLayoutOperation = invocation.operation === "images.set";
2621
+ const shapeOperation = ["shapes.list", "shapes.set"].includes(invocation.operation);
2622
+ const chartOperation = invocation.operation === "charts.list";
2623
+ const diagramOperation = invocation.operation === "diagrams.list";
2624
+ const equationOperation = ["equations.list", "equations.add", "equations.replace"].includes(invocation.operation);
2625
+ const equationEditOperation = equationOperation && invocation.operation !== "equations.list";
2626
+ const signatureOperation = ["signatures.list", "signatures.remove"].includes(invocation.operation);
2627
+ const fontOperation = invocation.operation === "fonts.list";
2628
+ const packageResourceOperation = fontOperation || signatureOperation || invocation.operation === "settings.list" || objectOperation || equationOperation || diagramOperation || chartOperation || imageLayoutOperation || imageReplacementOperation || imageInsertionOperation || imageOperation || propertyOperation || ["custom-xml.list", "glossary.list"].includes(invocation.operation);
2629
+ try {
2630
+ if (invocation.operation === "diff") {
2631
+ acquiring = true;
2632
+ const inputs = [];
2633
+ for (const input of invocation.inputs) {
2634
+ inputs.push(await io.readBytes({ open(signal) {
2635
+ if (input === "-") return request.stdin;
2636
+ const path2 = resolvePath34(request.cwd, input);
2637
+ return request.filesystem.readStream ? request.filesystem.readStream(path2, { signal }) : { async *[Symbol.asyncIterator]() {
2638
+ yield await request.filesystem.readFile(path2, { signal });
2639
+ } };
2640
+ } }));
2641
+ }
2642
+ acquiring = false;
2643
+ const data = await compareDocument(inputs[0], inputs[1], context, invocation.options);
2644
+ exitCode = data.equal ? 0 : 1;
2645
+ output = new TextEncoder().encode(invocation.options.json ? JSON.stringify({ version: 1, operation: "diff", ok: true, data, warnings: [], errors: [], affected: 0, locations: [] }) + "\n" : `docx diff: ${data.equal ? "equal" : "different"} (${data.mode}); ${data.differences.length} changed parts
2646
+ `);
2647
+ budget.check("serializedOutput", output.length);
2648
+ } else if (invocation.operation === "pack") {
2649
+ output = await executePackCommand(invocation, request, context, io);
2650
+ budget.check("serializedOutput", output.length);
2651
+ } else if (invocation.operation === "create") {
2652
+ output = await executeCreateCommand(invocation, request, context, io);
2653
+ budget.check("serializedOutput", output.length);
2654
+ } else {
2655
+ if (invocation.operation !== "extract" && !shapeOperation && !packageResourceOperation && invocation.operation !== "revisions.list" && !controlOperation && !revisionEditOperation && !commentOperation && !noteOperation && !fieldOperation && invocation.operation !== "fields.list" && !bookmarkOperation && invocation.operation !== "bookmarks.list" && !linkOperation && invocation.operation !== "links.list" && !tableOperation && !["tables.get", "tables.list", "paragraphs.get", "runs.get", "paragraphs.list", "runs.list"].includes(invocation.operation) && !listOperation && !storyOperation && invocation.operation !== "batch" && invocation.operation !== "capabilities" && invocation.operation !== "inspect" && invocation.operation !== "validate" && invocation.operation !== "text.get" && !["sanitize", "text.replace", "lorem.set"].includes(invocation.operation) && invocation.operation !== "runs.set" && !["paragraphs.remove", "runs.remove", "tables.remove", "paragraphs.set", "paragraphs.add", "runs.add", "tables.add"].includes(invocation.operation) && !["sections.list", "sections.set", "sections.add", "batch", "styles.list", "styles.get", "styles.add", "styles.set", "styles.remove", "styles.defaults.get", "styles.defaults.set", "styles.latent.list", "styles.latent.get", "styles.latent.add", "styles.latent.set", "styles.latent.remove", "styles.latent.defaults.get", "styles.latent.defaults.set"].includes(invocation.operation) && invocation.operation !== "xml.get" && invocation.operation !== "xml.set") {
2656
+ throw Object.assign(new Error("This document operation is not implemented."), { code: "unsupported-profile" });
2657
+ }
2658
+ if (!fontOperation && invocation.operation !== "inspect" && invocation.operation !== "revisions.list" && !controlOperation && !revisionEditOperation && !fieldOperation && invocation.operation !== "fields.list" && !bookmarkOperation && invocation.operation !== "bookmarks.list" && !linkOperation && invocation.operation !== "links.list" && ["link", "control", "revision", "shape", "field", "bookmark"].some((key) => invocation.options[key] !== void 0 && !(key === "shape" && (shapeOperation || ["text.get", "text.replace"].includes(invocation.operation))))) {
2659
+ throw Object.assign(new Error("This inspection selector is not implemented."), { code: "unsupported-profile" });
2660
+ }
2661
+ const input = invocation.inputs[0];
2662
+ acquiring = true;
2663
+ let inputIdentity;
2664
+ if ((equationEditOperation || ["images.extract", "objects.extract"].includes(invocation.operation) || imageInsertionOperation || imageReplacementOperation || imageLayoutOperation) && input !== "-" && request.filesystem.lstat) {
2665
+ const path2 = resolvePath34(request.cwd, input);
2666
+ inputIdentity = { path: path2, stat: await request.filesystem.lstat(path2, { signal: request.signal }) };
2667
+ }
2668
+ if ((controlTemplateOperation || invocation.operation === "controls.set" || commentOperation && !["comments.list", "comments.get"].includes(invocation.operation) || noteOperation && !["notes.list", "notes.get"].includes(invocation.operation) || revisionEditOperation || fieldOperation || bookmarkOperation || linkOperation || tableOperation || ["sanitize", "signatures.remove", "shapes.set", "properties.set", "properties.remove", "lists.add", "lists.set", "headers.set", "headers.remove", "footers.set", "footers.remove", "sections.set", "sections.add", "batch", "styles.add", "styles.set", "styles.remove", "styles.defaults.set", "styles.latent.add", "styles.latent.set", "styles.latent.remove", "styles.latent.defaults.set", "xml.set", "text.replace", "lorem.set", "runs.set", "paragraphs.remove", "runs.remove", "tables.remove", "paragraphs.set", "paragraphs.add", "runs.add", "tables.add"].includes(invocation.operation)) && input !== "-" && request.filesystem.lstat && (invocation.operation !== "batch" || invocation.options.inPlace === true || typeof invocation.options.output === "string" && invocation.options.output !== "-")) {
2669
+ const path2 = resolvePath34(request.cwd, input);
2670
+ inputIdentity = { path: path2, stat: await request.filesystem.lstat(path2, { signal: request.signal }) };
2671
+ }
2672
+ const bytes = await io.readBytes({ open(signal) {
2673
+ if (input === "-") return request.stdin;
2674
+ const path2 = resolvePath34(request.cwd, input);
2675
+ if (request.filesystem.readStream) return request.filesystem.readStream(path2, { signal });
2676
+ return { async *[Symbol.asyncIterator]() {
2677
+ yield await request.filesystem.readFile(path2, { signal });
2678
+ } };
2679
+ } });
2680
+ acquiring = false;
2681
+ if (invocation.operation === "extract") {
2682
+ const extraction = await extractDocumentArchive(bytes, { ...invocation.options, outputDir: resolvePath34(request.cwd, invocation.options.outputDir) }, { ...context, filesystem: request.filesystem });
2683
+ archiveReceipt = extraction;
2684
+ const envelope = { version: 1, operation: "extract", ok: true, data: extraction, affected: 0, locations: [], warnings: [], errors: [] };
2685
+ output = new TextEncoder().encode(invocation.options.json ? JSON.stringify(envelope) + "\n" : `Extracted: ${extraction.entries.length}; complete: true
2686
+ `);
2687
+ budget.check("serializedOutput", output.length);
2688
+ } else if (fontOperation) {
2689
+ const data = await inspectDocumentFonts(bytes, invocation.options, context);
2690
+ const human = `Font resources: ${data.items.length}
2691
+ ` + data.items.map((item) => `${escapeTerminalText(item.name)}: ${item.support}; ${item.details.parts.length} parts; ${item.references.length} references
2692
+ `).join("");
2693
+ output = new TextEncoder().encode(invocation.options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: 0, locations: data.items.map((item) => item.location), warnings: [], errors: [] }) + "\n" : human);
2694
+ budget.check("serializedOutput", output.length);
2695
+ } else if (shapeOperation || packageResourceOperation || controlOperation || revisionEditOperation || commentOperation || noteOperation || fieldOperation || bookmarkOperation || linkOperation || tableOperation || listOperation || storyOperation || ["sanitize", "sections.list", "sections.set", "sections.add", "batch", "styles.list", "styles.get", "styles.add", "styles.set", "styles.remove", "styles.defaults.get", "styles.defaults.set", "styles.latent.list", "styles.latent.get", "styles.latent.add", "styles.latent.set", "styles.latent.remove", "styles.latent.defaults.get", "styles.latent.defaults.set", "xml.get", "xml.set", "text.replace", "lorem.set", "runs.set", "paragraphs.remove", "runs.remove", "tables.remove", "paragraphs.set", "paragraphs.add", "runs.add", "tables.add"].includes(invocation.operation)) {
2696
+ output = invocation.operation === "sanitize" ? await executeSanitizeCommand(invocation, bytes, inputIdentity, request, context) : signatureOperation ? await executeSignaturesCommand(invocation, bytes, inputIdentity, request, context) : invocation.operation === "settings.list" ? await executeSettingsCommand(invocation, bytes, context) : objectOperation ? await executeObjectsCommand(invocation, bytes, inputIdentity, request, context, (data) => {
2697
+ imageReceipt = data;
2698
+ return void 0;
2699
+ }) : equationOperation ? await executeEquationsCommand(invocation, bytes, inputIdentity, request, context, io) : diagramOperation ? await executeDiagramsCommand(invocation, bytes, request, context) : chartOperation ? await executeChartsCommand(invocation, bytes, request, context) : shapeOperation ? await executeShapesCommand(invocation, bytes, inputIdentity, request, context) : imageLayoutOperation ? await executeImageLayoutCommand(invocation, bytes, inputIdentity, request, context) : imageReplacementOperation ? await executeImageReplacementCommand(invocation, bytes, inputIdentity, request, context) : imageInsertionOperation ? await executeImageInsertionCommand(invocation, bytes, inputIdentity, request, context) : imageOperation ? await executeImagesCommand(invocation, bytes, inputIdentity, request, context, (data) => {
2700
+ imageReceipt = data;
2701
+ return void 0;
2702
+ }) : packageResourceOperation ? propertyOperation ? await executePropertiesCommand(invocation, bytes, inputIdentity, request, context) : await executePackageResourcesCommand(invocation, bytes, request, context) : controlOperation ? controlTemplateOperation ? await executeControlTemplateCommand(invocation, bytes, inputIdentity, request, context) : await executeControlsCommand(invocation, bytes, inputIdentity, request, context) : revisionEditOperation ? invocation.operation === "revisions.add" ? await executeRevisionEditCommand(invocation, bytes, inputIdentity, request, context) : await executeRevisionDecisionCommand(invocation, bytes, inputIdentity, request, context) : commentOperation ? await executeCommentsCommand(invocation, bytes, inputIdentity, request, context) : noteOperation ? await executeNotesCommand(invocation, bytes, inputIdentity, request, context) : fieldOperation ? await executeFieldsCommand(invocation, bytes, inputIdentity, request, context) : bookmarkOperation ? await executeBookmarksCommand(invocation, bytes, inputIdentity, request, context) : linkOperation ? await executeLinksCommand(invocation, bytes, inputIdentity, request, context) : tableOperation ? await executeTableEditCommand(invocation, bytes, inputIdentity, request, context) : listOperation ? await executeListsCommand(invocation, bytes, inputIdentity, request, context) : storyOperation ? await executeStoriesCommand(invocation, bytes, inputIdentity, request, context) : invocation.operation.startsWith("sections.") ? await executeSectionsCommand(invocation, bytes, inputIdentity, request, context) : invocation.operation === "batch" ? await executeBatchCommand(invocation, bytes, inputIdentity, request, context) : invocation.operation.startsWith("styles.") ? await executeStylesCommand(invocation, bytes, inputIdentity, request, context) : ["paragraphs.remove", "runs.remove", "tables.remove"].includes(invocation.operation) ? await executeContentRemovalCommand(invocation, bytes, inputIdentity, request, context) : ["paragraphs.set", "paragraphs.add", "runs.add", "tables.add"].includes(invocation.operation) ? await executeParagraphEditCommand(invocation, bytes, inputIdentity, request, context) : invocation.operation === "runs.set" ? await executeRunFormatCommand(invocation, bytes, inputIdentity, request, context) : ["sanitize", "text.replace", "lorem.set"].includes(invocation.operation) ? await executeTextReplaceCommand(invocation, bytes, inputIdentity, request, context) : await executeXmlCommand(invocation, bytes, inputIdentity, request, context, io);
2703
+ budget.check("serializedOutput", output.length);
2704
+ } else if (invocation.operation === "revisions.list") {
2705
+ const data = await inspectDocumentRevisions(bytes, invocation.options, context, "resource");
2706
+ const human = data.items.map((item, i) => {
2707
+ const field = (name) => escapeTerminalText(String(item.properties.find((property) => property.name === name)?.value ?? "unknown"));
2708
+ return `${i + 1}. ${field("markup")} (ID ${field("id")}): ${field("support")}; ${field("author")}; ${field("stored_timestamp")}`;
2709
+ }).join("\n") + (data.items.length ? "\n" : "");
2710
+ output = new TextEncoder().encode(invocation.options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: 0, locations: data.items.map((i) => i.location), warnings: [], errors: [] }) + "\n" : human);
2711
+ budget.check("serializedOutput", output.length);
2712
+ } else if (invocation.operation === "fields.list") {
2713
+ const data = await inspectDocumentFields(bytes, invocation.options, context);
2714
+ output = new TextEncoder().encode(invocation.options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: 0, locations: data.items.map((i) => i.location), warnings: [], errors: [] }) + "\n" : data.items.map((item, i) => `${i + 1}. ${escapeTerminalText(item.kind)}: ${escapeTerminalText(item.instruction)} \u2192 ${escapeTerminalText(item.result)}`).join("\n") + (data.items.length ? "\n" : ""));
2715
+ budget.check("serializedOutput", output.length);
2716
+ } else if (invocation.operation === "bookmarks.list") {
2717
+ const data = await inspectDocumentBookmarks(bytes, invocation.options, context);
2718
+ const human = [...data.items.map((item, i) => `${i + 1}. ${escapeTerminalText(item.name)} (ID ${escapeTerminalText(item.id)})`), ...data.issues.map((issue) => `Issue: ${escapeTerminalText(issue)}`)].join("\n") + (data.items.length || data.issues.length ? "\n" : "");
2719
+ output = new TextEncoder().encode(invocation.options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: 0, locations: data.items.map((i) => i.location), warnings: [], errors: [] }) + "\n" : human);
2720
+ budget.check("serializedOutput", output.length);
2721
+ } else if (invocation.operation === "links.list") {
2722
+ const data = await inspectDocumentLinks(bytes, invocation.options, context);
2723
+ output = new TextEncoder().encode(invocation.options.json ? JSON.stringify({ version: 1, operation: "links.list", ok: true, data, affected: 0, locations: data.items.map((i) => i.location), warnings: [], errors: [] }) + "\n" : data.items.map((item, i) => `${i + 1}. ${escapeTerminalText(item.text)} \u2192 ${escapeTerminalText(item.address || "#" + item.fragment)}`).join("\n") + (data.items.length ? "\n" : ""));
2724
+ budget.check("serializedOutput", output.length);
2725
+ } else if (invocation.operation === "paragraphs.list" || invocation.operation === "runs.list") {
2726
+ const read = invocation.operation === "paragraphs.list" ? inspectDocumentParagraphs : inspectDocumentRuns;
2727
+ const data = await read(bytes, invocation.options, context);
2728
+ output = new TextEncoder().encode(invocation.options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: 0, locations: data.items.map((item) => item.location), warnings: [], errors: [] }) + "\n" : data.items.map((item, index) => `${index + 1}. ${escapeTerminalText(item.text)}
2729
+ `).join(""));
2730
+ budget.check("serializedOutput", output.length);
2731
+ } else if (invocation.operation === "paragraphs.get" || invocation.operation === "runs.get") {
2732
+ const read = invocation.operation === "paragraphs.get" ? inspectDocumentParagraph : inspectDocumentRun;
2733
+ const data = await read(bytes, invocation.options, context);
2734
+ output = new TextEncoder().encode(invocation.options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: 0, locations: [data.item.location], warnings: [], errors: [] }) + "\n" : escapeTerminalText(data.item.text) + "\n");
2735
+ budget.check("serializedOutput", output.length);
2736
+ } else if (invocation.operation === "tables.list") {
2737
+ const data = await inspectDocumentTables(bytes, invocation.options, context);
2738
+ const human = data.items.map((item) => `Table ${item.location.positions.table}: ${item.details.rows} rows; ${item.details.columns} columns
2739
+ `).join("");
2740
+ output = new TextEncoder().encode(invocation.options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: 0, locations: data.items.map((item) => item.location), warnings: [], errors: [] }) + "\n" : human);
2741
+ budget.check("serializedOutput", output.length);
2742
+ } else if (invocation.operation === "tables.get") {
2743
+ const data = await inspectDocumentTable(bytes, invocation.options, context);
2744
+ const details2 = data.item.details;
2745
+ const human = `docx tables get: ${details2.rows} rows; ${details2.columns} columns
2746
+ ` + details2.cells.map((cell) => `Row ${cell.row}, column ${cell.column} (${cell.rowSpan}x${cell.columnSpan}): ${escapeTerminalText(cell.text)}
2747
+ `).join("");
2748
+ output = new TextEncoder().encode(invocation.options.json ? JSON.stringify({ version: 1, operation: invocation.operation, ok: true, data, affected: 0, locations: [data.item.location, ...details2.cells.map((cell) => cell.location)], warnings: [], errors: [] }) + "\n" : human);
2749
+ budget.check("serializedOutput", output.length);
2750
+ } else if (invocation.operation === "capabilities") {
2751
+ const discovery = await inspectDocxCapabilities(bytes, context, request.filesystem);
2752
+ output = new TextEncoder().encode(invocation.options.json ? JSON.stringify({ version: 1, operation: "capabilities", ok: true, data: discovery.data, warnings: [], errors: [], affected: 0, locations: [] }) + "\n" : discovery.human);
2753
+ budget.check("serializedOutput", output.length);
2754
+ } else {
2755
+ const inspectionView = {};
2756
+ const readContext = { ...context, [inspectionLocationView]: inspectionView };
2757
+ const data = invocation.operation === "text.get" ? await extractDocumentText(bytes, context, invocation.options) : invocation.operation === "inspect" ? await inspectDocument2(bytes, readContext) : await validateDocument(bytes, context, invocation.options.profile === void 0 ? {} : { profile: invocation.options.profile });
2758
+ const locations = [];
2759
+ if ("segments" in data) locations.push(...new Map(data.segments.map((segment) => [segment.location.token, segment.location])).values());
2760
+ if (invocation.operation === "inspect")
2761
+ locations.push(...selectInspectionLocations(inspectionView.document, inspectionView.roots, invocation.options));
2762
+ const valid = !("valid" in data) || data.valid;
2763
+ exitCode = valid ? 0 : 1;
2764
+ const warnings = "warnings" in data ? data.warnings.map((warning) => typeof warning === "string" ? { code: "partial-validation", message: warning } : warning) : [];
2765
+ const errors = "diagnostics" in data ? data.diagnostics.map((item) => ({ code: "invalid-package", message: item.message, part: item.part, location: item.location })) : [];
2766
+ const human = "text" in data ? data.text : "valid" in data ? `docx validate: ${data.valid ? "valid within" : "invalid within"} ${data.profile}
2767
+ ${data.checks.map((check) => `${check.id}: ${check.status}`).join("\n")}
2768
+ ` : `docx inspect: ${data.kind}, ${data.dialect}
2769
+ Parts: ${data.parts.length}; paragraphs: ${data.counts.paragraphs}; tables: ${data.counts.tables}; images: ${data.counts.images}
2770
+ Cached pages: ${data.counts.cachedPages ?? "unknown"}; rendered pages: not calculated
2771
+ Themes: ${data.fontResources.themes.length}; font tables: ${data.fontResources.fontTables.length}; unresolved font/theme references: ${data.fontResources.diagnostics.length}
2772
+ Font references do not establish installed fonts or licensing.
2773
+ Signatures present: ${data.signed}; signatures verified: not performed
2774
+ Protected: ${data.protected}
2775
+ `;
2776
+ const diagnostic = warnings.map((warning) => `docx: ${escapeTerminalText(warning.code)}: ${escapeTerminalText(warning.message)}
2777
+ `).join("") + errors.map((error) => `docx: ${escapeTerminalText(error.code)}: ${escapeTerminalText(error.message)}
2778
+ `).join("");
2779
+ budget.check("diagnosticBytes", new TextEncoder().encode(diagnostic).length);
2780
+ output = new TextEncoder().encode(invocation.options.json === true ? JSON.stringify({ version: 1, operation: invocation.operation, ok: valid, data: valid ? data : null, warnings, errors, affected: 0, locations }) + "\n" : human);
2781
+ budget.check("serializedOutput", output.length);
2782
+ if (diagnostic) {
2783
+ writingDiagnostics = true;
2784
+ await request.stderr.write(new TextEncoder().encode(diagnostic));
2785
+ request.signal.throwIfAborted();
2786
+ writingDiagnostics = false;
2787
+ }
2788
+ }
2789
+ }
2790
+ } catch (error) {
2791
+ if (error instanceof ArchiveExtractionError) {
2792
+ archiveReceipt = error.data;
2793
+ const diagnostic2 = commandDiagnostic(error.message, error.code, budget.limits.diagnosticBytes);
2794
+ const envelope = { version: 1, operation: "extract", ok: false, data: error.data, affected: 0, locations: [], warnings: [], errors: [{ code: error.code, message: error.message }] };
2795
+ try {
2796
+ if (invocation.options.json) await request.stdout.write(new TextEncoder().encode(JSON.stringify(envelope) + "\n"));
2797
+ await request.stderr.write(new TextEncoder().encode(diagnostic2.human));
2798
+ } catch (cause) {
2799
+ return sinkFailure(cause);
2800
+ }
2801
+ if (error.code === "cancelled") throw error;
2802
+ return { exitCode: error.code === "limit-exceeded" ? 4 : error.code === "conflict" ? 1 : 3, extraction: error.data };
2803
+ }
2804
+ if (["images.extract", "objects.extract"].includes(invocation.operation) && (error instanceof ImageExtractionCancellationError2 || error instanceof ObjectExtractionCancellationError2)) throw error;
2805
+ const cancelled = request.signal.aborted || error instanceof CancellationError7;
2806
+ if (writingDiagnostics) return { exitCode: cancelled ? 130 : invocation.operation === "diff" ? 2 : 3 };
2807
+ const code = cancelled ? "cancelled" : error instanceof ResourceLimitError4 ? "limit-exceeded" : asPermissionError6(error) ? "permission" : acquiring ? "source-failure" : error && typeof error === "object" && "code" in error ? String(error.code) : "invalid-package";
2808
+ exitCode = error instanceof ResourceLimitError4 ? 4 : code === "conflict" ? 1 : acquiring || error instanceof PublicationError34 || code === "permission" || code === "source-failure" || code === "sink-failure" ? 3 : code === "usage" ? 2 : 1;
2809
+ if (cancelled) exitCode = 130;
2810
+ else if (invocation.operation === "diff") exitCode = 2;
2811
+ const failureMessage = acquiring ? "Unable to read the declared document input." : error instanceof PublicationError34 && error.stdoutMayBePartial ? "Binary stdout may contain partial output." : error instanceof UnsupportedEmbeddedFontMutationError ? error.message : "Document operation failed: " + code;
2812
+ const detail = code === "usage" && error instanceof Error && error.message ? ` (${error.message})` : "";
2813
+ const recoveryMessage = code === "usage" ? `${failureMessage}${detail}. See docx help ${invocation.operation.split(".").join(" ")} for accepted arguments and data schemas.` : code === "missing-selection" && invocation.operation === "text.replace" ? `${failureMessage}. Review --find, --scope and selection; see docx help text replace. Use --allow-empty only when a no-match result is intended.` : failureMessage;
2814
+ const diagnostic = commandDiagnostic(recoveryMessage, code, budget.limits.diagnosticBytes);
2815
+ const message = diagnostic.message;
2816
+ const batchFailure = invocation.operation === "batch" && error instanceof Error && "operationIndex" in error ? { operationIndex: error.operationIndex, ..."operationId" in error ? { operationId: error.operationId } : {} } : {};
2817
+ const imageFailure = ["images.extract", "objects.extract"].includes(invocation.operation) && (error instanceof ImageCommandPublicationError || error instanceof ObjectCommandPublicationError) ? error : void 0;
2818
+ const locatedFailure = error instanceof UnsupportedDiagramMutationError || error instanceof UnsupportedEquationMutationError ? error : void 0;
2819
+ if (imageFailure) imageReceipt = imageFailure.data;
2820
+ output = imageFailure ? imageFailure.responseBytes : locatedFailure && invocation.options.json === true ? serializeDiagramMutationFailure(invocation.operation, locatedFailure, code, message, budget) : new TextEncoder().encode(invocation.options.json === true ? JSON.stringify({ version: 1, operation: invocation.operation, ok: false, data: null, warnings: [], errors: [{ code, message, ...batchFailure }], affected: 0, locations: [] }) + "\n" : "");
2821
+ try {
2822
+ await request.stderr.write(imageFailure ? imageFailure.diagnosticBytes : new TextEncoder().encode(diagnostic.human));
2823
+ } catch (cause) {
2824
+ return sinkFailure(cause);
2825
+ }
2826
+ } finally {
2827
+ await io.cleanup();
2828
+ }
2829
+ try {
2830
+ if (output.length) await request.stdout.write(output);
2831
+ } catch (cause) {
2832
+ return sinkFailure(cause);
2833
+ }
2834
+ if (request.signal.aborted) return sinkFailure(request.signal.reason);
2835
+ return { exitCode, ...archiveReceipt ? { extraction: archiveReceipt } : {} };
2836
+ }
2837
+ }, { compressedInput: limits.maxArchiveBytes, expandedPackage: limits.maxTotalBytes, zipEntries: limits.maxMembers, retainedBytes: limits.maxRetainedBytes, xmlPartBytes: Math.min(limits.maxEntryBytes, documentLimitDefaults.xmlPartBytes), ...options.documentLimits });
2838
+ }
2839
+
2840
+ export {
2841
+ parseDocxArguments,
2842
+ createDocxCommandEngine,
2843
+ SourceError2 as SourceError,
2844
+ validateDocxInvocation,
2845
+ validateDocxBatch2 as validateDocxBatch,
2846
+ getDocxDiscovery,
2847
+ inspectDocxCapabilities,
2848
+ createDocxInspectionCommandEngine
2849
+ };