@poe-platform/safe-bash 0.1.814 → 0.1.816

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 (602) hide show
  1. package/dist/image-ast/index.js +1 -1
  2. package/dist/mp4-ast/codecs.d.ts +3 -0
  3. package/dist/mp4-ast/esds-source.d.ts +7 -0
  4. package/dist/mp4-ast/index.d.ts +6 -1
  5. package/dist/mp4-ast/mp4-codec-metadata.d.ts +48 -0
  6. package/dist/mp4-ast/mp4-codec-source.d.ts +8 -0
  7. package/dist/mp4-ast/mp4-fragment-source.d.ts +35 -0
  8. package/dist/mp4-ast/mp4-packets-source.d.ts +11 -0
  9. package/dist/mp4-ast/mp4-sample-source.d.ts +5 -2
  10. package/dist/mp4-ast/types.d.ts +11 -0
  11. package/dist/pdf-ast/ast.d.ts +6 -0
  12. package/dist/pdf-ast/content/evaluator.d.ts +4 -1
  13. package/dist/pdf-ast/content/stored-dictionary.d.ts +15 -1
  14. package/dist/pdf-ast/content/stored-record.d.ts +6 -0
  15. package/dist/pdf-ast/cos/object-reader.d.ts +3 -2
  16. package/dist/pdf-ast/cos/retained-writer.d.ts +1 -0
  17. package/dist/pdf-ast/cos/value-parser.d.ts +5 -0
  18. package/dist/pdf-ast/edit/forms.d.ts +1 -0
  19. package/dist/pdf-ast/edit/retained-form-data.d.ts +9 -0
  20. package/dist/pdf-ast/edit/retained-graph.d.ts +1 -0
  21. package/dist/pdf-ast/edit/retained-page-copy.d.ts +10 -0
  22. package/dist/pdf-ast/extract/images.d.ts +2 -1
  23. package/dist/pdf-ast/fonts/resolve.d.ts +1 -0
  24. package/dist/pdf-ast/index.d.ts +3 -0
  25. package/dist/pdf-ast/index.js +1563 -373
  26. package/dist/pdf-ast/render/raster.d.ts +14 -0
  27. package/dist/pdf-ast/render/svg-image-stream.d.ts +6 -0
  28. package/dist/pdf-ast/render/svg-path-stream.d.ts +15 -0
  29. package/dist/pdf-ast/retained-document.d.ts +1 -1
  30. package/dist/safe-bash/chunks/{chunk-I6ECNJMR.js → chunk-AXGI5JVL.js} +1 -1
  31. package/dist/safe-bash/chunks/{chunk-TPG55BAQ.js → chunk-FQRI5AS5.js} +1 -1
  32. package/dist/safe-bash/chunks/{chunk-TWWGAW4M.js → chunk-HD6DWOAC.js} +1 -1
  33. package/dist/safe-bash/chunks/{chunk-5JCZEXEM.js → chunk-SXSEF5E2.js} +12 -7
  34. package/dist/safe-bash/command-chunks/biff-UBP2BZLK-JPODPKS3.js +5448 -0
  35. package/dist/safe-bash/command-chunks/{chunk-S7HIOT7Z.js → chunk-26JE5JEB.js} +4 -4
  36. package/dist/safe-bash/command-chunks/{chunk-AG2SNMP5.js → chunk-2ALHVXEM.js} +2 -2
  37. package/dist/safe-bash/command-chunks/{chunk-4YLACJHE.js → chunk-2IMIKROX.js} +6 -6
  38. package/dist/safe-bash/command-chunks/{chunk-MYZ46FQL.js → chunk-2QZUAZTH.js} +1 -1
  39. package/dist/safe-bash/command-chunks/{chunk-YAD7EV4N.js → chunk-2TWXRJPB.js} +11 -11
  40. package/dist/safe-bash/command-chunks/{chunk-NYFYTL5G.js → chunk-345YBIHP.js} +27 -27
  41. package/dist/safe-bash/command-chunks/{chunk-3MG5EAMX.js → chunk-35DU6I2M.js} +5 -5
  42. package/dist/safe-bash/command-chunks/{chunk-FSVJ67G5.js → chunk-3DWFXESW.js} +2 -2
  43. package/dist/safe-bash/command-chunks/{chunk-TKCUGMRZ.js → chunk-3K5CVXUV.js} +18 -18
  44. package/dist/safe-bash/command-chunks/{chunk-6LPSKLLD.js → chunk-3MUFXGA2.js} +3 -3
  45. package/dist/safe-bash/command-chunks/{chunk-AVGXFWEB.js → chunk-3PM46VWH.js} +191 -70
  46. package/dist/safe-bash/command-chunks/{chunk-6QYSF7I2.js → chunk-3ZWFE4CK.js} +7 -7
  47. package/dist/safe-bash/command-chunks/{chunk-LAPOMHGY.js → chunk-45DKGZYO.js} +857 -424
  48. package/dist/safe-bash/command-chunks/{chunk-SW37YCBW.js → chunk-4772DJKS.js} +54 -36
  49. package/dist/safe-bash/command-chunks/{chunk-FOONI6BD.js → chunk-4ABR3KGK.js} +7 -7
  50. package/dist/safe-bash/command-chunks/{chunk-7KZ5LWV2.js → chunk-4IDV763L.js} +1 -1
  51. package/dist/safe-bash/command-chunks/{chunk-FGGHYUWR.js → chunk-4QEJPP3K.js} +102 -7
  52. package/dist/safe-bash/command-chunks/{chunk-RV5AGXOV.js → chunk-4X2MPZXW.js} +2 -2
  53. package/dist/safe-bash/command-chunks/{chunk-LNTEV56A.js → chunk-4YFTJS5U.js} +2 -2
  54. package/dist/safe-bash/command-chunks/{chunk-6XES7Z4G.js → chunk-57PK2QFX.js} +12 -12
  55. package/dist/safe-bash/command-chunks/{chunk-42MEXZBJ.js → chunk-5GDF5FAS.js} +1 -1
  56. package/dist/safe-bash/command-chunks/{chunk-BS3ZEQGT.js → chunk-5KZMR6AJ.js} +18 -16
  57. package/dist/safe-bash/command-chunks/{chunk-ZU2KJMXO.js → chunk-5MNQTHED.js} +10 -10
  58. package/dist/safe-bash/command-chunks/{chunk-W25EIKDJ.js → chunk-5NC2IQMQ.js} +1 -1
  59. package/dist/safe-bash/command-chunks/{chunk-KY4LCHUF.js → chunk-5O45KGW5.js} +1 -1
  60. package/dist/safe-bash/command-chunks/{chunk-GYM5ICK4.js → chunk-5V7WIQ2D.js} +7 -7
  61. package/dist/safe-bash/command-chunks/{chunk-3JM7E42I.js → chunk-5XUWGUGN.js} +114 -35
  62. package/dist/safe-bash/command-chunks/{chunk-SUTHGUD3.js → chunk-5YL453ZF.js} +34 -34
  63. package/dist/safe-bash/command-chunks/{chunk-IHXZMAMY.js → chunk-62RG3GHF.js} +6 -6
  64. package/dist/safe-bash/command-chunks/{chunk-P2LT6TGR.js → chunk-6EZWG56T.js} +9 -9
  65. package/dist/safe-bash/command-chunks/{chunk-CCMAHM3I.js → chunk-6JGICYHP.js} +2 -2
  66. package/dist/safe-bash/command-chunks/{chunk-AWPI4DZR.js → chunk-6KJDTKE4.js} +3 -3
  67. package/dist/safe-bash/command-chunks/{chunk-FUQMEUAT.js → chunk-6M3JTPKE.js} +8 -8
  68. package/dist/safe-bash/command-chunks/{chunk-H33D4R26.js → chunk-6RLWPB44.js} +4 -4
  69. package/dist/safe-bash/command-chunks/{chunk-3GRMU7TM.js → chunk-6W4RMBFH.js} +6 -6
  70. package/dist/safe-bash/command-chunks/{chunk-RIVKF77R.js → chunk-6YF2QADH.js} +6 -6
  71. package/dist/safe-bash/command-chunks/{chunk-LEO4VRIN.js → chunk-77ROD2TR.js} +5 -5
  72. package/dist/safe-bash/command-chunks/{chunk-XNGM3W5R.js → chunk-7B2MHKIW.js} +1 -1
  73. package/dist/safe-bash/command-chunks/{chunk-RFMHNTTF.js → chunk-7OCTMVYJ.js} +1 -1
  74. package/dist/safe-bash/command-chunks/{chunk-DBLQUZGN.js → chunk-7PYDVQPB.js} +2 -2
  75. package/dist/safe-bash/command-chunks/{chunk-AM5LANIE.js → chunk-A2L3U7DW.js} +7 -7
  76. package/dist/safe-bash/command-chunks/{chunk-UYGQEQIP.js → chunk-A4P37F3P.js} +5 -5
  77. package/dist/safe-bash/command-chunks/{chunk-ADHFF2IM.js → chunk-A5SPMSKD.js} +9 -9
  78. package/dist/safe-bash/command-chunks/{chunk-ENEIE44W.js → chunk-A6OTPNNI.js} +3 -3
  79. package/dist/safe-bash/command-chunks/chunk-AF2IO57Q.js +733 -0
  80. package/dist/safe-bash/command-chunks/{chunk-AFPXADZG.js → chunk-AHD3CGAY.js} +4 -4
  81. package/dist/safe-bash/command-chunks/{chunk-VT7UBPAE.js → chunk-ALD53QFL.js} +89 -30
  82. package/dist/safe-bash/command-chunks/{chunk-4B2ZUGLT.js → chunk-ARE267HR.js} +5 -5
  83. package/dist/safe-bash/command-chunks/{chunk-OTF2AJ5M.js → chunk-AYQPJQJR.js} +6 -6
  84. package/dist/safe-bash/command-chunks/{chunk-2VVJRVYM.js → chunk-B6XTAKKQ.js} +1 -1
  85. package/dist/safe-bash/command-chunks/{chunk-GCHB7VNX.js → chunk-BIJW6QWB.js} +17 -17
  86. package/dist/safe-bash/command-chunks/{chunk-OVEPYULA.js → chunk-BKK4MS3V.js} +1 -1
  87. package/dist/safe-bash/command-chunks/{chunk-3EB2FSAN.js → chunk-BOVDUJ3A.js} +7 -7
  88. package/dist/safe-bash/command-chunks/{chunk-SEPUP6TZ.js → chunk-BSTABZIK.js} +1 -1
  89. package/dist/safe-bash/command-chunks/{chunk-ATHHWPSE.js → chunk-BZRWZ6GO.js} +1 -1
  90. package/dist/safe-bash/command-chunks/{chunk-5BIQWWLB.js → chunk-CFMJXJS5.js} +1 -1
  91. package/dist/safe-bash/command-chunks/{chunk-BZMNC7Q5.js → chunk-CGJ7GMHO.js} +7 -7
  92. package/dist/safe-bash/command-chunks/{chunk-RGDOYWOD.js → chunk-CHZE6FNT.js} +2 -2
  93. package/dist/safe-bash/command-chunks/{chunk-V7E3PZOK.js → chunk-CKA7ZROU.js} +7 -7
  94. package/dist/safe-bash/command-chunks/{chunk-MEM2ZPMI.js → chunk-CKIXC7AO.js} +3 -3
  95. package/dist/safe-bash/command-chunks/{chunk-Y54L4P4J.js → chunk-CORUUCS2.js} +5 -5
  96. package/dist/safe-bash/command-chunks/{chunk-FF7UGJWS.js → chunk-DBZCTL7C.js} +150 -35
  97. package/dist/safe-bash/command-chunks/{chunk-6ZGCKUAM.js → chunk-DIRK47GT.js} +1 -1
  98. package/dist/safe-bash/command-chunks/{chunk-WYZG3DRR.js → chunk-DM5WURQL.js} +2 -2
  99. package/dist/safe-bash/command-chunks/{chunk-EBHOZIBS.js → chunk-DOVWHVHI.js} +6 -6
  100. package/dist/safe-bash/command-chunks/{chunk-GQGMQMIM.js → chunk-DXOXUKQB.js} +248 -6
  101. package/dist/safe-bash/command-chunks/{chunk-JR3Q6QNL.js → chunk-DZOKH5BL.js} +7 -7
  102. package/dist/safe-bash/command-chunks/{chunk-K4XNUJVJ.js → chunk-E22EAYJN.js} +197 -171
  103. package/dist/safe-bash/command-chunks/{chunk-3EASXF5D.js → chunk-E4TF5W6O.js} +2 -2
  104. package/dist/safe-bash/command-chunks/{chunk-MLOYUXUV.js → chunk-EJ4UP7DA.js} +31 -9
  105. package/dist/safe-bash/command-chunks/{chunk-USGZN2KE.js → chunk-ENMJHB2C.js} +5 -5
  106. package/dist/safe-bash/command-chunks/{chunk-ZSQZHFWS.js → chunk-ERWIJYCS.js} +7 -7
  107. package/dist/safe-bash/command-chunks/{chunk-S2QNBAN6.js → chunk-ET6LMDEX.js} +12 -12
  108. package/dist/safe-bash/command-chunks/{chunk-6XGDWFNQ.js → chunk-EWC56JNI.js} +5 -5
  109. package/dist/safe-bash/command-chunks/{chunk-EQWFKNHJ.js → chunk-EZDWPTYB.js} +19 -19
  110. package/dist/safe-bash/command-chunks/{chunk-CQBACD2V.js → chunk-F2NF6FHV.js} +2 -2
  111. package/dist/safe-bash/command-chunks/{chunk-NFII726L.js → chunk-FAU2KL6I.js} +2 -2
  112. package/dist/safe-bash/command-chunks/{chunk-4EHY6J2Z.js → chunk-FB2WPI3M.js} +5 -5
  113. package/dist/safe-bash/command-chunks/{chunk-2PKBXGXD.js → chunk-FEBTT5NH.js} +5 -5
  114. package/dist/safe-bash/command-chunks/chunk-FGARVKAX.js +704 -0
  115. package/dist/safe-bash/command-chunks/{chunk-N4MUBJCT.js → chunk-FGHSE3RZ.js} +1 -1
  116. package/dist/safe-bash/command-chunks/{chunk-WBKB7HBZ.js → chunk-FHQOFEQK.js} +8 -8
  117. package/dist/safe-bash/command-chunks/{chunk-3ZRCL756.js → chunk-FJLSYX5P.js} +7 -7
  118. package/dist/safe-bash/command-chunks/{chunk-PMWW7KSB.js → chunk-FJSD43VF.js} +1 -1
  119. package/dist/safe-bash/command-chunks/{chunk-XKAUKLF7.js → chunk-FLSXHLJG.js} +9 -9
  120. package/dist/safe-bash/command-chunks/{chunk-3EW7GYHM.js → chunk-FR63MJSO.js} +7 -7
  121. package/dist/safe-bash/command-chunks/{chunk-NRFTYZ2R.js → chunk-FUYZUETI.js} +6 -6
  122. package/dist/safe-bash/command-chunks/{chunk-JUHOL5KB.js → chunk-G3FK5VVG.js} +1 -1
  123. package/dist/safe-bash/command-chunks/{chunk-4UPKVQWH.js → chunk-G3LUT475.js} +6 -6
  124. package/dist/safe-bash/command-chunks/{chunk-Q7UZTMF4.js → chunk-GAROGIVU.js} +1 -1
  125. package/dist/safe-bash/command-chunks/{chunk-4RRYWHED.js → chunk-GMBUOYTN.js} +4 -4
  126. package/dist/safe-bash/command-chunks/{chunk-FYYFV6PW.js → chunk-GR4ONCQ5.js} +6 -6
  127. package/dist/safe-bash/command-chunks/{chunk-XTEIT5CI.js → chunk-GTOMW4VV.js} +1 -1
  128. package/dist/safe-bash/command-chunks/{chunk-OVQP6KH5.js → chunk-H56BSMFQ.js} +6 -6
  129. package/dist/safe-bash/command-chunks/{chunk-RQYPFLZJ.js → chunk-HOJ7WDTS.js} +6 -6
  130. package/dist/safe-bash/command-chunks/{chunk-BLIFGBIO.js → chunk-HOKPYTHQ.js} +2 -2
  131. package/dist/safe-bash/command-chunks/chunk-HQEYSSZV.js +152 -0
  132. package/dist/safe-bash/command-chunks/{chunk-NEMUPUUB.js → chunk-ICJH6A73.js} +7 -7
  133. package/dist/safe-bash/command-chunks/{chunk-CSE4VQKG.js → chunk-IJE65P52.js} +3 -3
  134. package/dist/safe-bash/command-chunks/{chunk-MKOIPOXX.js → chunk-IOXMGD2H.js} +3 -3
  135. package/dist/safe-bash/command-chunks/{chunk-LDW3RF7Y.js → chunk-ISFGPCED.js} +12 -12
  136. package/dist/safe-bash/command-chunks/{chunk-S43QRKDC.js → chunk-IVKAFEPO.js} +7 -7
  137. package/dist/safe-bash/command-chunks/{chunk-A347DLRB.js → chunk-IWVANZWH.js} +3 -3
  138. package/dist/safe-bash/command-chunks/{chunk-ZXELXF2H.js → chunk-IZ3SD5S2.js} +4 -4
  139. package/dist/safe-bash/command-chunks/{chunk-HGIMFVI2.js → chunk-J6FNSVHT.js} +5 -5
  140. package/dist/safe-bash/command-chunks/{chunk-GLAF45M7.js → chunk-JA36YOZI.js} +1 -1
  141. package/dist/safe-bash/command-chunks/{chunk-WHNYT34N.js → chunk-K2R7H3KO.js} +1 -1
  142. package/dist/safe-bash/command-chunks/{chunk-2ETEJOYX.js → chunk-K7VDCBXW.js} +21 -21
  143. package/dist/safe-bash/command-chunks/{chunk-CK2WFJZN.js → chunk-KASXIRKD.js} +12 -14
  144. package/dist/safe-bash/command-chunks/{chunk-CKEMZUE3.js → chunk-KDBU5Q2N.js} +6 -6
  145. package/dist/safe-bash/command-chunks/{chunk-6VBDJC6V.js → chunk-KDDXLHN7.js} +6 -6
  146. package/dist/safe-bash/command-chunks/chunk-KHUT7BB5.js +65 -0
  147. package/dist/safe-bash/command-chunks/{chunk-NEVQWOU6.js → chunk-KLAC2MIZ.js} +10 -10
  148. package/dist/safe-bash/command-chunks/{chunk-QGD64UHJ.js → chunk-KLCHCSIV.js} +1 -1
  149. package/dist/safe-bash/command-chunks/{chunk-CXME4YHU.js → chunk-KM2SMMXZ.js} +59 -201
  150. package/dist/safe-bash/command-chunks/{chunk-RHU44OMN.js → chunk-KXM3HTAF.js} +1 -1
  151. package/dist/safe-bash/command-chunks/{chunk-AVOGFREX.js → chunk-KYIGYYEY.js} +3 -3
  152. package/dist/safe-bash/command-chunks/{chunk-5OM3UIK3.js → chunk-L2VLASZ4.js} +3 -3
  153. package/dist/safe-bash/command-chunks/{chunk-Z7QOSXQC.js → chunk-LECGQSQW.js} +7 -7
  154. package/dist/safe-bash/command-chunks/{chunk-RXQ2G2YK.js → chunk-LFSWLJPR.js} +9 -9
  155. package/dist/safe-bash/command-chunks/{chunk-OSYY6E23.js → chunk-LJ3UYESS.js} +1 -1
  156. package/dist/safe-bash/command-chunks/{chunk-MVLVIMJ6.js → chunk-LMLBQSAM.js} +6 -6
  157. package/dist/safe-bash/command-chunks/{chunk-MGMTRGKM.js → chunk-LNAZ3E4Q.js} +4 -4
  158. package/dist/safe-bash/command-chunks/{chunk-WJ2ERUCQ.js → chunk-LNKZVU5V.js} +1 -1
  159. package/dist/safe-bash/command-chunks/{chunk-WWHMI4S3.js → chunk-LQDANF2B.js} +8 -8
  160. package/dist/safe-bash/command-chunks/{chunk-CIRDVCAZ.js → chunk-LQX7RAF7.js} +7 -7
  161. package/dist/safe-bash/command-chunks/{chunk-SWAKALDJ.js → chunk-LT2YCGC5.js} +10 -10
  162. package/dist/safe-bash/command-chunks/{chunk-Y7AXMCFV.js → chunk-LZY46GYY.js} +8 -8
  163. package/dist/safe-bash/command-chunks/{chunk-VT2PHQ63.js → chunk-MDFNUNK5.js} +15 -15
  164. package/dist/safe-bash/command-chunks/{chunk-YP3WWV5N.js → chunk-MN3BB4WW.js} +4 -4
  165. package/dist/safe-bash/command-chunks/{chunk-WTVJLHMG.js → chunk-MOUCMZZP.js} +1 -1
  166. package/dist/safe-bash/command-chunks/{chunk-IB5QP4LF.js → chunk-MQE77MEQ.js} +3 -3
  167. package/dist/safe-bash/command-chunks/{chunk-FSYMSWJU.js → chunk-MUTARE5I.js} +6 -6
  168. package/dist/safe-bash/command-chunks/{chunk-F762XDNG.js → chunk-MZYQKH26.js} +3 -3
  169. package/dist/safe-bash/command-chunks/{chunk-N6G3345Q.js → chunk-N32AP43V.js} +7 -7
  170. package/dist/safe-bash/command-chunks/{chunk-XU6S3XUZ.js → chunk-N35IJXBK.js} +9 -9
  171. package/dist/safe-bash/command-chunks/{chunk-EVYKV3QI.js → chunk-N3ZH4YYH.js} +3 -3
  172. package/dist/safe-bash/command-chunks/{chunk-VUWXLH3E.js → chunk-N4HWOLGZ.js} +2 -2
  173. package/dist/safe-bash/command-chunks/{chunk-G3TAX3CV.js → chunk-N5J3IZZK.js} +8124 -7200
  174. package/dist/safe-bash/command-chunks/{chunk-W3ZSWK76.js → chunk-NCNHJRIY.js} +8 -8
  175. package/dist/safe-bash/command-chunks/{chunk-FXCSPPYE.js → chunk-NDALIHKK.js} +20 -20
  176. package/dist/safe-bash/command-chunks/{chunk-BS5JEUEW.js → chunk-NKK76B4V.js} +8 -8
  177. package/dist/safe-bash/command-chunks/{chunk-4EZJV4FZ.js → chunk-NLCUQD7Y.js} +1 -1
  178. package/dist/safe-bash/command-chunks/{chunk-RHDERFMR.js → chunk-O2HNOQQG.js} +5 -5
  179. package/dist/safe-bash/command-chunks/{chunk-G2COZLXX.js → chunk-OBIXFO25.js} +10 -10
  180. package/dist/safe-bash/command-chunks/{chunk-47IAU25U.js → chunk-OCV5ZU35.js} +3 -3
  181. package/dist/safe-bash/command-chunks/{chunk-3YEQI5B7.js → chunk-OFDJJRAD.js} +9 -9
  182. package/dist/safe-bash/command-chunks/{chunk-VDTFVRYX.js → chunk-OFONWWEZ.js} +2 -2
  183. package/dist/safe-bash/command-chunks/{chunk-F4YFTO2K.js → chunk-OHEZQ4QA.js} +9 -9
  184. package/dist/safe-bash/command-chunks/{chunk-JW6WVNTM.js → chunk-OIHQXURE.js} +1 -1
  185. package/dist/safe-bash/command-chunks/{chunk-ZTMZO4IT.js → chunk-ONQP4FNV.js} +1 -1
  186. package/dist/safe-bash/command-chunks/{chunk-K2WOMJOQ.js → chunk-OVUY46QF.js} +1 -1
  187. package/dist/safe-bash/command-chunks/{chunk-DGBQ7QDE.js → chunk-OWCBX5M2.js} +1 -1
  188. package/dist/safe-bash/command-chunks/{chunk-LKGTH2Q7.js → chunk-P462JTNT.js} +5 -5
  189. package/dist/safe-bash/command-chunks/{chunk-5LFGXN3D.js → chunk-P4OWVKMD.js} +6 -6
  190. package/dist/safe-bash/command-chunks/{chunk-46AMTJPE.js → chunk-POGVOCOB.js} +8 -8
  191. package/dist/safe-bash/command-chunks/{chunk-PLMF35XK.js → chunk-PPN53PX3.js} +4 -4
  192. package/dist/safe-bash/command-chunks/{chunk-V5XC43BX.js → chunk-PRO7JOIH.js} +8 -8
  193. package/dist/safe-bash/command-chunks/{chunk-UJERQEJB.js → chunk-PU5DMQGG.js} +1 -1
  194. package/dist/safe-bash/command-chunks/{chunk-IWHNRYER.js → chunk-Q65GWGQR.js} +3 -3
  195. package/dist/safe-bash/command-chunks/{chunk-BLGGAHQW.js → chunk-QCIAX6HZ.js} +1 -1
  196. package/dist/safe-bash/command-chunks/{chunk-ET5SFGRH.js → chunk-QDV2NIFR.js} +1 -1
  197. package/dist/safe-bash/command-chunks/{chunk-Y42KSX63.js → chunk-QMBMZSJF.js} +6 -6
  198. package/dist/safe-bash/command-chunks/{chunk-KUOCGGEU.js → chunk-QNETPOMH.js} +6 -5
  199. package/dist/safe-bash/command-chunks/{chunk-QB72X7FF.js → chunk-QNX5LZBK.js} +7 -7
  200. package/dist/safe-bash/command-chunks/{chunk-LZ2JFMKT.js → chunk-QOKFSYD5.js} +9 -9
  201. package/dist/safe-bash/command-chunks/{chunk-7DOLY7IV.js → chunk-R7LF4XQV.js} +2 -2
  202. package/dist/safe-bash/command-chunks/{chunk-PIVH35EQ.js → chunk-RINR7XPR.js} +37 -10
  203. package/dist/safe-bash/command-chunks/{chunk-MPXMRTMY.js → chunk-ROQ3VNVX.js} +8 -8
  204. package/dist/safe-bash/command-chunks/{chunk-6WNVGCXD.js → chunk-RRAQII52.js} +5 -5
  205. package/dist/safe-bash/command-chunks/{chunk-2BNGPR6Z.js → chunk-RTHYAGKI.js} +2 -2
  206. package/dist/safe-bash/command-chunks/chunk-RTKDZBJS.js +816 -0
  207. package/dist/safe-bash/command-chunks/{chunk-JVKE7YZN.js → chunk-RVWIEXR7.js} +4 -4
  208. package/dist/safe-bash/command-chunks/{chunk-XM5QJCPD.js → chunk-S5ER73EA.js} +8 -8
  209. package/dist/safe-bash/command-chunks/{chunk-YRPXBGRX.js → chunk-SBXS4S6Y.js} +3 -3
  210. package/dist/safe-bash/command-chunks/{chunk-HI6ZYH3W.js → chunk-SHLT5R64.js} +9 -9
  211. package/dist/safe-bash/command-chunks/{chunk-Q5PWYPQV.js → chunk-SICTBSLW.js} +7 -7
  212. package/dist/safe-bash/command-chunks/{chunk-AXXZNB7U.js → chunk-SL4LD25A.js} +9 -9
  213. package/dist/safe-bash/command-chunks/{chunk-JGKSWDGP.js → chunk-SNA2LVBX.js} +1 -1
  214. package/dist/safe-bash/command-chunks/{chunk-TXPDKEGY.js → chunk-SWIF6BBY.js} +8 -8
  215. package/dist/safe-bash/command-chunks/{chunk-PS5GDFIP.js → chunk-T2FRXSQT.js} +2 -2
  216. package/dist/safe-bash/command-chunks/{chunk-HELAVGZH.js → chunk-T4SEQU66.js} +3 -3
  217. package/dist/safe-bash/command-chunks/{chunk-3SPLP2DB.js → chunk-T5OQ53XS.js} +1 -1
  218. package/dist/safe-bash/command-chunks/{chunk-KBAQHE5Y.js → chunk-TG2RVQLP.js} +2 -2
  219. package/dist/safe-bash/command-chunks/{chunk-CZ5K2YPU.js → chunk-TXU7MMHN.js} +24 -24
  220. package/dist/safe-bash/command-chunks/{chunk-TYPS5MOU.js → chunk-TXWDR2P4.js} +1 -1
  221. package/dist/safe-bash/command-chunks/{chunk-ETXPMVR6.js → chunk-TY7JXEWI.js} +11 -11
  222. package/dist/safe-bash/command-chunks/{chunk-X6OHFKBL.js → chunk-U42WHQRH.js} +8 -8
  223. package/dist/safe-bash/command-chunks/{chunk-Z2WNYEPD.js → chunk-UFLMOU3B.js} +4 -4
  224. package/dist/safe-bash/command-chunks/{chunk-2BLTUQNK.js → chunk-UJYXSLM6.js} +2 -2
  225. package/dist/safe-bash/command-chunks/{chunk-Q7TVCBU2.js → chunk-UKAGRRLZ.js} +1 -1
  226. package/dist/safe-bash/command-chunks/{chunk-4GQKCUS5.js → chunk-UPWLHHZ2.js} +13 -13
  227. package/dist/safe-bash/command-chunks/{chunk-5L4YGRQU.js → chunk-URQSUMMJ.js} +4 -4
  228. package/dist/safe-bash/command-chunks/{chunk-KPHLESD4.js → chunk-UT5X6QRU.js} +5 -5
  229. package/dist/safe-bash/command-chunks/{chunk-T5S4SJGO.js → chunk-V6JPIZUW.js} +7 -7
  230. package/dist/safe-bash/command-chunks/{chunk-MKK6FM5H.js → chunk-VMZIAFVJ.js} +11 -11
  231. package/dist/safe-bash/command-chunks/{chunk-HK6MSB7Z.js → chunk-VNNNVT4C.js} +5 -5
  232. package/dist/safe-bash/command-chunks/{chunk-ROL5AEX6.js → chunk-VVV45NLY.js} +1 -1
  233. package/dist/safe-bash/command-chunks/chunk-VVWHFNHD.js +502 -0
  234. package/dist/safe-bash/command-chunks/{chunk-KCLJGRU7.js → chunk-VZTVR3JI.js} +12 -12
  235. package/dist/safe-bash/command-chunks/{chunk-PLR5IULU.js → chunk-WDVPHDBH.js} +5 -5
  236. package/dist/safe-bash/command-chunks/{chunk-MNK3DDH6.js → chunk-WH624PKJ.js} +2 -2
  237. package/dist/safe-bash/command-chunks/{chunk-TJLXSENN.js → chunk-WHZ6XK7Y.js} +1 -1
  238. package/dist/safe-bash/command-chunks/{chunk-DN6MSXY7.js → chunk-WIW3KDBS.js} +2 -2
  239. package/dist/safe-bash/command-chunks/{chunk-GXMPXMDP.js → chunk-WMBELKPP.js} +11 -11
  240. package/dist/safe-bash/command-chunks/{chunk-NHNZYWPW.js → chunk-WMV5224N.js} +3 -3
  241. package/dist/safe-bash/command-chunks/{chunk-RTNI47C5.js → chunk-WOL3LBXE.js} +4 -4
  242. package/dist/safe-bash/command-chunks/{chunk-7SOE7XIS.js → chunk-WVD5WZXD.js} +5 -5
  243. package/dist/safe-bash/command-chunks/{chunk-XMTR7QGL.js → chunk-X42MJT2J.js} +4 -4
  244. package/dist/safe-bash/command-chunks/{chunk-XUJAQA3S.js → chunk-XBWD6SI3.js} +33 -33
  245. package/dist/safe-bash/command-chunks/{chunk-ZQM37BGE.js → chunk-XFIDOCYH.js} +2 -2
  246. package/dist/safe-bash/command-chunks/{chunk-IBYMPAUW.js → chunk-XPQUUFQD.js} +2 -2
  247. package/dist/safe-bash/command-chunks/{chunk-NQINS4XY.js → chunk-XVEI4HZL.js} +1 -1
  248. package/dist/safe-bash/command-chunks/{chunk-KSBNZTAZ.js → chunk-YKODRSGT.js} +6 -6
  249. package/dist/safe-bash/command-chunks/{chunk-WZRFS5OY.js → chunk-YXR4JE4U.js} +4 -4
  250. package/dist/safe-bash/command-chunks/{chunk-DCMSPMMD.js → chunk-Z7UIOPHJ.js} +1 -1
  251. package/dist/safe-bash/command-chunks/{chunk-AY3KQ4EN.js → chunk-ZAYTFXUX.js} +7 -7
  252. package/dist/safe-bash/command-chunks/{chunk-DZH54L3F.js → chunk-ZM7HMBAJ.js} +10 -10
  253. package/dist/safe-bash/command-chunks/{chunk-NFGCBQN3.js → chunk-ZNCPIZCN.js} +2 -2
  254. package/dist/safe-bash/command-chunks/{chunk-HKGNBH7Z.js → chunk-ZRHKXN6W.js} +4 -4
  255. package/dist/safe-bash/command-chunks/{chunk-A45UG4KT.js → chunk-ZZERSKAR.js} +5 -5
  256. package/dist/safe-bash/command-chunks/{clipboard-BBDK33GP-QZ4ERNQX.js → clipboard-BBDK33GP-VB22F7GI.js} +2 -2
  257. package/dist/safe-bash/command-chunks/{command-engine-7V6PZR7G.js → command-engine-GHE6QUHU.js} +63 -23
  258. package/dist/safe-bash/command-chunks/{engine-UYJENSWK-VSCGKSQV.js → engine-RG6HQCCB-FXYZS264.js} +1 -1
  259. package/dist/safe-bash/command-chunks/{gnumeric-UJPXWBVR-7VOHQAPM.js → gnumeric-UJPXWBVR-YPXTNEDZ.js} +2 -2
  260. package/dist/safe-bash/command-chunks/model-store-I7YAWL5V.js +54 -0
  261. package/dist/safe-bash/command-chunks/{xlsx-RE54MFCS-DI3F765V.js → xlsx-RE54MFCS-IQ6OXXKK.js} +1 -1
  262. package/dist/safe-bash/commands/bc/index.browser.js +1 -1
  263. package/dist/safe-bash/full-core.browser.js +4 -4
  264. package/dist/safe-bash/plugins/index.browser.js +3 -3
  265. package/dist/safe-bash/registry-entry.browser.js +2 -2
  266. package/dist/safe-bash/search.browser.js +1 -1
  267. package/dist/safe-bash/shell/runtime.d.ts +1 -0
  268. package/dist/safe-bash/shell/runtime.js +12 -3
  269. package/dist/safe-bash/shell/sync-extra-evaluators.js +7 -4
  270. package/dist/safe-bash/shell-entry.browser.js +2 -2
  271. package/dist/safe-bash-command-awk/awk-runtime.js +3 -3
  272. package/dist/safe-bash-command-awk/awk.js +4 -4
  273. package/dist/safe-bash-command-awk/index.js +4 -4
  274. package/dist/safe-bash-command-cp/index.js +3 -3
  275. package/dist/safe-bash-command-csvkit/index.js +1 -1
  276. package/dist/safe-bash-command-diff/diff.js +2 -2
  277. package/dist/safe-bash-command-diff/index.js +3 -3
  278. package/dist/safe-bash-command-diff/sync.js +2 -2
  279. package/dist/safe-bash-command-factor/command.js +2 -2
  280. package/dist/safe-bash-command-factor/index.js +2 -2
  281. package/dist/safe-bash-command-ffmpeg/index.js +1 -1
  282. package/dist/safe-bash-command-ffprobe/index.js +2 -2
  283. package/dist/safe-bash-command-ffprobe/media.d.ts +12 -2
  284. package/dist/safe-bash-command-ffprobe/media.js +4 -2
  285. package/dist/safe-bash-command-getopt/command.js +2 -2
  286. package/dist/safe-bash-command-getopt/index.js +2 -2
  287. package/dist/safe-bash-command-html-to-markdown/index.js +51 -813
  288. package/dist/safe-bash-command-html-to-markdown/stored-destination.d.ts +8 -0
  289. package/dist/safe-bash-command-html-to-markdown/stored-destination.js +10 -0
  290. package/dist/safe-bash-command-html-to-markdown/stored-text.d.ts +4 -1
  291. package/dist/safe-bash-command-html-to-markdown/stored-text.js +1 -1
  292. package/dist/safe-bash-command-htmlq/index.js +1280 -419
  293. package/dist/safe-bash-command-iconv/command.js +2 -2
  294. package/dist/safe-bash-command-iconv/index.js +2 -2
  295. package/dist/safe-bash-command-llm/index.js +2 -2
  296. package/dist/safe-bash-command-llm/openai.js +2 -2
  297. package/dist/safe-bash-command-llm/providers/index.js +2 -2
  298. package/dist/safe-bash-command-llm/providers/openai.js +2 -2
  299. package/dist/safe-bash-command-node/commands/node/browser.js +4 -4
  300. package/dist/safe-bash-command-node/commands/node/default-runtime.js +4 -4
  301. package/dist/safe-bash-command-node/commands/node/safejs.js +4 -4
  302. package/dist/safe-bash-command-pandoc/command.js +10 -9
  303. package/dist/safe-bash-command-pandoc/index.js +60 -59
  304. package/dist/safe-bash-command-patch/index.js +8 -7
  305. package/dist/safe-bash-command-patch/patch-formats.d.ts +6 -5
  306. package/dist/safe-bash-command-patch/patch-formats.js +3 -2
  307. package/dist/safe-bash-command-patch/patch-gnu-paths.d.ts +7 -7
  308. package/dist/safe-bash-command-patch/patch-gnu-reject.d.ts +1 -1
  309. package/dist/safe-bash-command-patch/patch-gnu-reject.js +3 -2
  310. package/dist/safe-bash-command-patch/patch-publication.js +3 -2
  311. package/dist/safe-bash-command-patch/patch-text.d.ts +13 -0
  312. package/dist/safe-bash-command-patch/patch.js +7 -6
  313. package/dist/safe-bash-command-patch/stored-patch.d.ts +32 -6
  314. package/dist/safe-bash-command-patch/stored-target.d.ts +2 -1
  315. package/dist/safe-bash-command-patch/unified.d.ts +22 -8
  316. package/dist/safe-bash-command-patch/unified.js +2 -1
  317. package/dist/safe-bash-command-pdftk/index.js +45 -122
  318. package/dist/safe-bash-command-pdftoppm/index.js +131 -27
  319. package/dist/safe-bash-command-playwright-cli/index.js +12 -12
  320. package/dist/safe-bash-command-playwright-cli/playwright/abilities.js +1 -1
  321. package/dist/safe-bash-command-playwright-cli/playwright/capability-events.js +1 -1
  322. package/dist/safe-bash-command-playwright-cli/playwright/capability-result.js +1 -1
  323. package/dist/safe-bash-command-playwright-cli/playwright/controller.js +7 -7
  324. package/dist/safe-bash-command-playwright-cli/playwright/download-capabilities.js +1 -1
  325. package/dist/safe-bash-command-playwright-cli/playwright/drop-capability.js +1 -1
  326. package/dist/safe-bash-command-playwright-cli/playwright/index.js +12 -12
  327. package/dist/safe-bash-command-playwright-cli/playwright/modal-capabilities.js +1 -1
  328. package/dist/safe-bash-command-playwright-cli/playwright/native-evaluation.js +1 -1
  329. package/dist/safe-bash-command-playwright-cli/playwright/native-json-snapshot.js +1 -1
  330. package/dist/safe-bash-command-playwright-cli/playwright/native-snapshot.js +1 -1
  331. package/dist/safe-bash-command-playwright-cli/playwright/open-options.js +2 -2
  332. package/dist/safe-bash-command-playwright-cli/playwright/profile.js +3 -3
  333. package/dist/safe-bash-command-playwright-cli/playwright/recording-capabilities.js +1 -1
  334. package/dist/safe-bash-command-playwright-cli/playwright/route-capabilities.js +1 -1
  335. package/dist/safe-bash-command-playwright-cli/playwright/snapshot.js +3 -3
  336. package/dist/safe-bash-command-playwright-cli/playwright/standard-capabilities.js +1 -1
  337. package/dist/safe-bash-command-playwright-cli/playwright/storage-capabilities.js +1 -1
  338. package/dist/safe-bash-command-playwright-cli/playwright/tracing-capabilities.js +1 -1
  339. package/dist/safe-bash-command-playwright-cli/playwright/webmcp-capabilities.js +1 -1
  340. package/dist/safe-bash-command-pptx/engine.js +1 -1
  341. package/dist/safe-bash-command-python/executor.js +11 -11
  342. package/dist/safe-bash-command-python/index.js +11 -11
  343. package/dist/safe-bash-command-python/jspi.js +2 -2
  344. package/dist/safe-bash-command-rg/index.js +3 -3
  345. package/dist/safe-bash-command-rg/rg-command.js +3 -3
  346. package/dist/safe-bash-command-safejs/index.js +4 -4
  347. package/dist/safe-bash-command-safejs/io.js +3 -3
  348. package/dist/safe-bash-command-safejs/render.js +2 -2
  349. package/dist/safe-bash-command-safejs/runtime.js +4 -4
  350. package/dist/safe-bash-command-soffice/index.js +5 -4
  351. package/dist/safe-bash-command-sort/index.js +3 -3
  352. package/dist/safe-bash-command-ssconvert/index.js +13 -13
  353. package/dist/safe-bash-command-tar/create.js +3 -3
  354. package/dist/safe-bash-command-tar/extract.js +3 -3
  355. package/dist/safe-bash-command-tar/index.js +7 -7
  356. package/dist/safe-bash-command-tar/modes.js +5 -5
  357. package/dist/safe-bash-command-unzip/index.js +2 -2
  358. package/dist/safe-bash-command-unzip/unzip.js +2 -2
  359. package/dist/safe-bash-command-xmllint/index.js +1 -1
  360. package/dist/safe-bash-command-xz/index.js +5 -5
  361. package/dist/safe-bash-compression-engine/files.js +5 -5
  362. package/dist/safe-bash-compression-engine/index.js +3 -3
  363. package/dist/safe-bash-compression-engine/operand.js +6 -6
  364. package/dist/safe-bash-compression-engine/stream.js +3 -3
  365. package/dist/safe-bash-compression-engine/zstd-decode.js +2 -2
  366. package/dist/safe-bash-contracts/escaping.js +3 -3
  367. package/dist/safe-bash-contracts/filesystem-output.js +3 -3
  368. package/dist/safe-bash-contracts/index.js +10 -10
  369. package/dist/safe-bash-docx-engine/ancillary-resources.js +9 -9
  370. package/dist/safe-bash-docx-engine/batch-operations.js +66 -66
  371. package/dist/safe-bash-docx-engine/batch-result-schema.js +78 -78
  372. package/dist/safe-bash-docx-engine/batch.js +77 -77
  373. package/dist/safe-bash-docx-engine/bookmarks.js +17 -17
  374. package/dist/safe-bash-docx-engine/charts.js +10 -10
  375. package/dist/safe-bash-docx-engine/command-option-rules.js +5 -5
  376. package/dist/safe-bash-docx-engine/command-properties.js +3 -3
  377. package/dist/safe-bash-docx-engine/comments.js +25 -25
  378. package/dist/safe-bash-docx-engine/control-bindings.js +20 -20
  379. package/dist/safe-bash-docx-engine/control-repeat.js +20 -20
  380. package/dist/safe-bash-docx-engine/controls.js +18 -18
  381. package/dist/safe-bash-docx-engine/create.js +10 -10
  382. package/dist/safe-bash-docx-engine/diagrams.js +10 -10
  383. package/dist/safe-bash-docx-engine/diff.js +12 -12
  384. package/dist/safe-bash-docx-engine/document-properties.js +15 -15
  385. package/dist/safe-bash-docx-engine/equations.js +16 -16
  386. package/dist/safe-bash-docx-engine/extract.js +13 -13
  387. package/dist/safe-bash-docx-engine/fields.js +22 -22
  388. package/dist/safe-bash-docx-engine/font-inventory.js +17 -17
  389. package/dist/safe-bash-docx-engine/font-resources.js +5 -5
  390. package/dist/safe-bash-docx-engine/image-batch-operations.js +13 -13
  391. package/dist/safe-bash-docx-engine/image-insertion.js +20 -20
  392. package/dist/safe-bash-docx-engine/image-layout.js +18 -18
  393. package/dist/safe-bash-docx-engine/image-replacement.js +21 -21
  394. package/dist/safe-bash-docx-engine/images.js +18 -18
  395. package/dist/safe-bash-docx-engine/index.js +113 -113
  396. package/dist/safe-bash-docx-engine/inspection.js +19 -19
  397. package/dist/safe-bash-docx-engine/invocation.js +8 -8
  398. package/dist/safe-bash-docx-engine/io.js +8 -8
  399. package/dist/safe-bash-docx-engine/links.js +20 -20
  400. package/dist/safe-bash-docx-engine/lists.js +19 -19
  401. package/dist/safe-bash-docx-engine/locations.js +14 -14
  402. package/dist/safe-bash-docx-engine/notes.js +21 -21
  403. package/dist/safe-bash-docx-engine/objects.js +18 -18
  404. package/dist/safe-bash-docx-engine/operation-json-schema.js +3 -3
  405. package/dist/safe-bash-docx-engine/operation-schema.js +2 -2
  406. package/dist/safe-bash-docx-engine/pack.js +13 -13
  407. package/dist/safe-bash-docx-engine/package-view-batch-operations.js +21 -21
  408. package/dist/safe-bash-docx-engine/pandoc-adapter.js +28 -28
  409. package/dist/safe-bash-docx-engine/paragraph-edit.js +24 -24
  410. package/dist/safe-bash-docx-engine/part-provider.js +3 -3
  411. package/dist/safe-bash-docx-engine/property-values.js +3 -3
  412. package/dist/safe-bash-docx-engine/publication.js +8 -8
  413. package/dist/safe-bash-docx-engine/removal.js +20 -20
  414. package/dist/safe-bash-docx-engine/revision-decisions.js +21 -21
  415. package/dist/safe-bash-docx-engine/revision-edit.js +19 -19
  416. package/dist/safe-bash-docx-engine/revisions.js +17 -17
  417. package/dist/safe-bash-docx-engine/run-format.js +19 -19
  418. package/dist/safe-bash-docx-engine/sanitize.js +33 -33
  419. package/dist/safe-bash-docx-engine/sections.js +18 -18
  420. package/dist/safe-bash-docx-engine/settings.js +10 -10
  421. package/dist/safe-bash-docx-engine/shape-edit.js +20 -20
  422. package/dist/safe-bash-docx-engine/signatures.js +14 -14
  423. package/dist/safe-bash-docx-engine/stories.js +21 -21
  424. package/dist/safe-bash-docx-engine/structure-model-batch-operations.js +37 -37
  425. package/dist/safe-bash-docx-engine/style-model-batch-operations.js +26 -26
  426. package/dist/safe-bash-docx-engine/style-model-result-schema.js +43 -43
  427. package/dist/safe-bash-docx-engine/styles.js +17 -17
  428. package/dist/safe-bash-docx-engine/table-edit.js +26 -26
  429. package/dist/safe-bash-docx-engine/table-read.js +15 -15
  430. package/dist/safe-bash-docx-engine/template.js +21 -21
  431. package/dist/safe-bash-docx-engine/text-replace.js +19 -19
  432. package/dist/safe-bash-docx-engine/text-resource-read.js +15 -15
  433. package/dist/safe-bash-docx-engine/text.js +15 -15
  434. package/dist/safe-bash-docx-engine/validation.js +6 -6
  435. package/dist/safe-bash-docx-engine/xml-parts.js +21 -21
  436. package/dist/safe-bash-line-ending-engine/command.js +4 -4
  437. package/dist/safe-bash-line-ending-engine/index.js +7 -7
  438. package/dist/safe-bash-markdown-engine/commonmark-blocks.js +3 -3
  439. package/dist/safe-bash-markdown-engine/commonmark-inlines.js +3 -3
  440. package/dist/safe-bash-markdown-engine/gfm-syntax.js +2 -2
  441. package/dist/safe-bash-markdown-engine/index.js +4 -4
  442. package/dist/safe-bash-network-engine/aggregate.js +3 -3
  443. package/dist/safe-bash-network-engine/args.js +3 -3
  444. package/dist/safe-bash-network-engine/body.js +4 -4
  445. package/dist/safe-bash-network-engine/decode.js +3 -3
  446. package/dist/safe-bash-network-engine/fetch-transport.js +3 -3
  447. package/dist/safe-bash-network-engine/index.js +3 -3
  448. package/dist/safe-bash-network-engine/output.js +3 -3
  449. package/dist/safe-bash-network-engine/platform-portable.js +3 -3
  450. package/dist/safe-bash-network-engine/shared.js +2 -2
  451. package/dist/safe-bash-network-engine/transfer.js +9 -9
  452. package/dist/safe-bash-presentation-engine/accessibility.js +31 -30
  453. package/dist/safe-bash-presentation-engine/animation-editing.js +16 -15
  454. package/dist/safe-bash-presentation-engine/animations.js +16 -15
  455. package/dist/safe-bash-presentation-engine/backgrounds.js +17 -16
  456. package/dist/safe-bash-presentation-engine/bytes.js +4 -3
  457. package/dist/safe-bash-presentation-engine/chart-editing.js +34 -33
  458. package/dist/safe-bash-presentation-engine/chart-object-operations.js +25 -24
  459. package/dist/safe-bash-presentation-engine/charts.js +31 -30
  460. package/dist/safe-bash-presentation-engine/command-placeholder.js +60 -58
  461. package/dist/safe-bash-presentation-engine/comments.js +17 -16
  462. package/dist/safe-bash-presentation-engine/connector-operations.js +32 -31
  463. package/dist/safe-bash-presentation-engine/connectors.js +29 -28
  464. package/dist/safe-bash-presentation-engine/content-types.js +5 -4
  465. package/dist/safe-bash-presentation-engine/creation.js +7 -6
  466. package/dist/safe-bash-presentation-engine/diff.d.ts +1 -0
  467. package/dist/safe-bash-presentation-engine/diff.js +44 -33
  468. package/dist/safe-bash-presentation-engine/drawing-format.js +20 -19
  469. package/dist/safe-bash-presentation-engine/drawing-operations.js +31 -30
  470. package/dist/safe-bash-presentation-engine/drawing-schema.js +21 -20
  471. package/dist/safe-bash-presentation-engine/equations.js +17 -16
  472. package/dist/safe-bash-presentation-engine/errors.js +3 -2
  473. package/dist/safe-bash-presentation-engine/fields.js +17 -16
  474. package/dist/safe-bash-presentation-engine/font-metrics.js +4 -3
  475. package/dist/safe-bash-presentation-engine/image-extraction.js +20 -19
  476. package/dist/safe-bash-presentation-engine/image-formatting.js +32 -31
  477. package/dist/safe-bash-presentation-engine/image-insertion.js +18 -17
  478. package/dist/safe-bash-presentation-engine/image-replacement.js +21 -20
  479. package/dist/safe-bash-presentation-engine/image-value.js +5 -4
  480. package/dist/safe-bash-presentation-engine/images.js +19 -18
  481. package/dist/safe-bash-presentation-engine/index.js +135 -132
  482. package/dist/safe-bash-presentation-engine/layouts.js +16 -15
  483. package/dist/safe-bash-presentation-engine/length.js +4 -3
  484. package/dist/safe-bash-presentation-engine/links.js +16 -15
  485. package/dist/safe-bash-presentation-engine/masters.js +15 -14
  486. package/dist/safe-bash-presentation-engine/media-editing.js +24 -23
  487. package/dist/safe-bash-presentation-engine/media-extraction.js +17 -16
  488. package/dist/safe-bash-presentation-engine/media.js +16 -15
  489. package/dist/safe-bash-presentation-engine/memberships.js +15 -14
  490. package/dist/safe-bash-presentation-engine/notes.d.ts +1 -0
  491. package/dist/safe-bash-presentation-engine/notes.js +22 -15
  492. package/dist/safe-bash-presentation-engine/ole-enum.js +5 -4
  493. package/dist/safe-bash-presentation-engine/ole-insertion.js +20 -19
  494. package/dist/safe-bash-presentation-engine/opaque-objects.js +10 -9
  495. package/dist/safe-bash-presentation-engine/package-reader.js +6 -5
  496. package/dist/safe-bash-presentation-engine/package-tools.js +19 -18
  497. package/dist/safe-bash-presentation-engine/package-uri.js +4 -3
  498. package/dist/safe-bash-presentation-engine/package-writer.js +5 -4
  499. package/dist/safe-bash-presentation-engine/presentation-model.js +59 -57
  500. package/dist/safe-bash-presentation-engine/presentation-settings.js +14 -13
  501. package/dist/safe-bash-presentation-engine/properties.d.ts +2 -1
  502. package/dist/safe-bash-presentation-engine/properties.js +25 -15
  503. package/dist/safe-bash-presentation-engine/relationships.js +5 -4
  504. package/dist/safe-bash-presentation-engine/resource-limits.js +2 -1
  505. package/dist/safe-bash-presentation-engine/retained-diff.d.ts +56 -0
  506. package/dist/safe-bash-presentation-engine/retained-inspection.js +14 -13
  507. package/dist/safe-bash-presentation-engine/retained-notes.d.ts +27 -0
  508. package/dist/safe-bash-presentation-engine/retained-package.js +6 -5
  509. package/dist/safe-bash-presentation-engine/retained-properties.d.ts +26 -0
  510. package/dist/safe-bash-presentation-engine/retained-text.js +33 -517
  511. package/dist/safe-bash-presentation-engine/sanitize.js +20 -16
  512. package/dist/safe-bash-presentation-engine/selectors.js +11 -10
  513. package/dist/safe-bash-presentation-engine/shape-groups.js +31 -30
  514. package/dist/safe-bash-presentation-engine/shape-operations.js +30 -29
  515. package/dist/safe-bash-presentation-engine/shape-path-operations.js +32 -31
  516. package/dist/safe-bash-presentation-engine/shape-paths.js +16 -15
  517. package/dist/safe-bash-presentation-engine/shape-presets.js +4 -3
  518. package/dist/safe-bash-presentation-engine/shape-selection.js +31 -30
  519. package/dist/safe-bash-presentation-engine/shape-transforms.js +18 -17
  520. package/dist/safe-bash-presentation-engine/shapes.js +27 -26
  521. package/dist/safe-bash-presentation-engine/slide-copy.js +17 -16
  522. package/dist/safe-bash-presentation-engine/slide-import.js +18 -17
  523. package/dist/safe-bash-presentation-engine/slide-merge-split.js +20 -19
  524. package/dist/safe-bash-presentation-engine/slide-model.js +43 -42
  525. package/dist/safe-bash-presentation-engine/slide-removal.js +18 -17
  526. package/dist/safe-bash-presentation-engine/slide-transfer-budget.js +10 -9
  527. package/dist/safe-bash-presentation-engine/slides.js +19 -18
  528. package/dist/safe-bash-presentation-engine/table-operations.js +33 -32
  529. package/dist/safe-bash-presentation-engine/table-spans.js +32 -31
  530. package/dist/safe-bash-presentation-engine/tables.js +31 -30
  531. package/dist/safe-bash-presentation-engine/tags.js +16 -15
  532. package/dist/safe-bash-presentation-engine/template-bindings.js +33 -32
  533. package/dist/safe-bash-presentation-engine/template-repeat.js +40 -39
  534. package/dist/safe-bash-presentation-engine/text-fitting.js +27 -26
  535. package/dist/safe-bash-presentation-engine/text-frames.js +27 -26
  536. package/dist/safe-bash-presentation-engine/text-paragraphs.js +27 -26
  537. package/dist/safe-bash-presentation-engine/text-reading.js +12 -11
  538. package/dist/safe-bash-presentation-engine/text-replacement.js +17 -16
  539. package/dist/safe-bash-presentation-engine/text-runs.js +20 -19
  540. package/dist/safe-bash-presentation-engine/themes.js +16 -15
  541. package/dist/safe-bash-presentation-engine/transitions.js +16 -15
  542. package/dist/safe-bash-presentation-engine/validation.js +10 -9
  543. package/dist/safe-bash-presentation-engine/xml-parts.js +19 -18
  544. package/dist/safe-bash-presentation-engine/xml-view.js +4 -3
  545. package/dist/safe-bash-presentation-engine/xml.js +4 -3
  546. package/dist/safe-bash-query-engine/index.js +3 -3
  547. package/dist/safe-bash-query-engine/interpreter.js +2 -2
  548. package/dist/safe-bash-query-engine/query-core.js +3 -3
  549. package/dist/safe-bash-regex-engine/ere/matcher.js +3 -3
  550. package/dist/safe-bash-xml-engine/document.js +3 -3
  551. package/dist/safe-bash-xml-engine/evaluate.js +1 -1
  552. package/dist/safe-bash-xml-engine/index.js +4 -4
  553. package/dist/safe-bash-xml-engine/json.js +14 -10
  554. package/dist/safe-bash-xml-engine/query.js +2 -2
  555. package/dist/safe-bash-xml-engine/stored-document.d.ts +4 -0
  556. package/dist/safe-bash-xml-engine/stored-document.js +1 -1
  557. package/dist/safe-bash-xml-engine/stored-evaluate.js +3 -3
  558. package/dist/safe-bash-zip-engine/index.js +2 -2
  559. package/dist/safe-bash-zip-engine/zip/repair.js +2 -2
  560. package/dist/safe-bash-zip-engine/zip/sfx.js +2 -2
  561. package/dist/safe-bash-zip-engine/zip-format.js +2 -2
  562. package/dist/spreadsheet-format-xls/biff-properties-merge.js +88 -73
  563. package/dist/spreadsheet-format-xls/biff-properties.js +3 -3
  564. package/dist/spreadsheet-format-xls/biff-property-transcode.d.ts +6 -1
  565. package/dist/spreadsheet-format-xls/biff-property-transcode.js +15 -4
  566. package/dist/spreadsheet-format-xls/biff-property-values.d.ts +36 -0
  567. package/dist/spreadsheet-format-xls/biff-property-values.js +227 -0
  568. package/dist/xlsx-ast/comment-geometry.d.ts +12 -0
  569. package/dist/xlsx-ast/comment-geometry.js +71 -0
  570. package/dist/xlsx-ast/xlsx-metadata.d.ts +1 -1
  571. package/dist/xlsx-ast/xlsx-metadata.js +27 -2
  572. package/dist/xlsx-ast/xlsx-write-metadata.js +9 -1
  573. package/dist/xlsx-ast/xlsx.js +9 -4
  574. package/package.json +6 -3
  575. package/dist/safe-bash/command-chunks/biff-KRHJ63K3-VQPJCVIL.js +0 -5309
  576. package/dist/safe-bash/command-chunks/chunk-DBNJEXHK.js +0 -387
  577. package/dist/safe-bash/command-chunks/chunk-EV5G535P.js +0 -240
  578. package/dist/safe-bash/command-chunks/model-store-UB5DWMAP.js +0 -54
  579. package/dist/safe-bash/command-chunks/{chunk-NGSO645G.js → chunk-3ZVK2OAY.js} +6 -6
  580. package/dist/safe-bash/command-chunks/{chunk-W2FKFEVY.js → chunk-4YSBUQPV.js} +3 -3
  581. package/dist/safe-bash/command-chunks/{chunk-UJSLBBQ7.js → chunk-5MFRN3CB.js} +4 -4
  582. package/dist/safe-bash/command-chunks/{chunk-AW4Q3GZW.js → chunk-5QXRIZSS.js} +3 -3
  583. package/dist/safe-bash/command-chunks/{chunk-KUGV3SSL.js → chunk-CZXYWGVO.js} +3 -3
  584. package/dist/safe-bash/command-chunks/{chunk-JWORWL72.js → chunk-DX7KU6YU.js} +3 -3
  585. package/dist/safe-bash/command-chunks/{chunk-Z37OM247.js → chunk-E3BL7W5C.js} +3 -3
  586. package/dist/safe-bash/command-chunks/{chunk-RIKNMBLZ.js → chunk-FEKECRJP.js} +3 -3
  587. package/dist/safe-bash/command-chunks/{chunk-D3HW7R2N.js → chunk-FTZFCMVI.js} +9 -9
  588. package/dist/safe-bash/command-chunks/{chunk-KRRG4MGH.js → chunk-GEDO5V32.js} +3 -3
  589. package/dist/safe-bash/command-chunks/{chunk-NBRXQUK7.js → chunk-M3OXQXCU.js} +3 -3
  590. package/dist/safe-bash/command-chunks/{chunk-JRSZ5IGD.js → chunk-OAM2SUUI.js} +6 -6
  591. package/dist/safe-bash/command-chunks/{chunk-HFKS6AET.js → chunk-OCOJMKDP.js} +4 -4
  592. package/dist/safe-bash/command-chunks/{chunk-FMJKCVSQ.js → chunk-OOB7YCFQ.js} +3 -3
  593. package/dist/safe-bash/command-chunks/{chunk-GGH376XQ.js → chunk-OU4VE5CR.js} +6 -6
  594. package/dist/safe-bash/command-chunks/{chunk-DYERIXPU.js → chunk-QGTQJCKW.js} +3 -3
  595. package/dist/safe-bash/command-chunks/{chunk-ZSQCROFE.js → chunk-RXXNLH7A.js} +3 -3
  596. package/dist/safe-bash/command-chunks/{chunk-TI52LKLL.js → chunk-UVM6QG2H.js} +3 -3
  597. package/dist/safe-bash/command-chunks/{chunk-BJXADHRT.js → chunk-WKU65Z3Q.js} +6 -6
  598. package/dist/safe-bash/command-chunks/{chunk-KGKF5NM2.js → chunk-WOXLPDO6.js} +3 -3
  599. package/dist/safe-bash/command-chunks/{chunk-Y5ADXWBQ.js → chunk-WXW665TV.js} +4 -4
  600. package/dist/safe-bash/command-chunks/{chunk-FWCUEZ3K.js → chunk-WYBCSJFG.js} +3 -3
  601. package/dist/safe-bash/command-chunks/{chunk-BXU5Y7I5.js → chunk-XI2LETBJ.js} +3 -3
  602. package/dist/safe-bash/command-chunks/{chunk-LNLACEAN.js → chunk-Y3ZRIZL7.js} +3 -3
@@ -336,6 +336,157 @@ var PdfStagingStorage = class {
336
336
  }
337
337
  };
338
338
 
339
+ // packages/pdf-ast/src/content/stored-path.ts
340
+ var BLOCK_BYTES = 4096;
341
+ var RECORD_BYTES = 56;
342
+ var RECORDS = Math.floor((BLOCK_BYTES - 8) / RECORD_BYTES);
343
+ var kinds = ["close", "move", "line", "cubic", "rect"];
344
+ var StoredPathWriter = class {
345
+ constructor(storage, signal) {
346
+ this.storage = storage;
347
+ this.signal = signal;
348
+ }
349
+ storage;
350
+ signal;
351
+ bytes = new Uint8Array(BLOCK_BYTES);
352
+ view = new DataView(this.bytes.buffer);
353
+ first = -1;
354
+ position = -1;
355
+ used = 0;
356
+ count = 0;
357
+ finished = false;
358
+ bounds = [Infinity, Infinity, -Infinity, -Infinity];
359
+ allocate() {
360
+ const at = this.storage.allocate(BLOCK_BYTES);
361
+ if (!Number.isSafeInteger(at) || at < 0 || !Number.isSafeInteger(at + BLOCK_BYTES)) throw new RangeError("Invalid PDF path allocation");
362
+ return at;
363
+ }
364
+ async append(segment) {
365
+ this.signal?.throwIfAborted();
366
+ if (this.finished) throw new Error("PDF path is already finished");
367
+ if (this.position === -1) this.first = this.position = this.allocate();
368
+ if (this.used === RECORDS) {
369
+ const next = this.allocate();
370
+ this.view.setFloat64(0, next, true);
371
+ await this.storage.write(this.position, this.bytes, this.signal ? { signal: this.signal } : void 0);
372
+ this.position = next;
373
+ this.used = 0;
374
+ }
375
+ const at = 8 + this.used++ * RECORD_BYTES;
376
+ this.view.setFloat64(at, kinds.indexOf(segment.kind), true);
377
+ const values = segment.kind === "close" ? [] : segment.kind === "cubic" ? [segment.x, segment.y, segment.x1, segment.y1, segment.x2, segment.y2] : segment.kind === "rect" ? [segment.x, segment.y, segment.width, segment.height] : [segment.x, segment.y];
378
+ for (let i = 0; i < values.length; i++) this.view.setFloat64(at + 8 + i * 8, values[i], true);
379
+ const include = (x, y) => {
380
+ this.bounds[0] = Math.min(this.bounds[0], x);
381
+ this.bounds[1] = Math.min(this.bounds[1], y);
382
+ this.bounds[2] = Math.max(this.bounds[2], x);
383
+ this.bounds[3] = Math.max(this.bounds[3], y);
384
+ };
385
+ if (segment.kind !== "close") include(segment.x, segment.y);
386
+ if (segment.kind === "cubic") {
387
+ include(segment.x1, segment.y1);
388
+ include(segment.x2, segment.y2);
389
+ }
390
+ if (segment.kind === "rect") include(segment.x + segment.width, segment.y + segment.height);
391
+ this.count++;
392
+ }
393
+ async finish() {
394
+ this.signal?.throwIfAborted();
395
+ if (this.finished) throw new Error("PDF path is already finished");
396
+ this.finished = true;
397
+ if (this.position !== -1) {
398
+ this.view.setFloat64(0, -1, true);
399
+ await this.storage.write(this.position, this.bytes.subarray(0, 8 + this.used * RECORD_BYTES), this.signal ? { signal: this.signal } : void 0);
400
+ }
401
+ return { kind: "stored-path", storage: this.storage, position: this.first, count: this.count, bounds: this.bounds };
402
+ }
403
+ };
404
+ async function* readStoredPath(path, signal) {
405
+ let position = path.position, remaining = path.count;
406
+ while (remaining > 0) {
407
+ signal?.throwIfAborted();
408
+ if (!Number.isSafeInteger(position) || position < 0) throw new Error("Invalid PDF path block");
409
+ const count = Math.min(RECORDS, remaining), length = 8 + count * RECORD_BYTES;
410
+ const bytes = (await path.storage.read(position, length, signal ? { signal } : void 0)).slice();
411
+ if (bytes.length !== length) throw new Error("Incomplete PDF path block");
412
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
413
+ position = view.getFloat64(0, true);
414
+ for (let i = 0; i < count; i++) {
415
+ signal?.throwIfAborted();
416
+ const at = 8 + i * RECORD_BYTES, kind = kinds[view.getFloat64(at, true)];
417
+ const value = (n) => view.getFloat64(at + 8 + n * 8, true);
418
+ if (kind === "close") yield { kind };
419
+ else if (kind === "move" || kind === "line") yield { kind, x: value(0), y: value(1) };
420
+ else if (kind === "rect") yield { kind, x: value(0), y: value(1), width: value(2), height: value(3) };
421
+ else if (kind === "cubic") yield { kind, x: value(0), y: value(1), x1: value(2), y1: value(3), x2: value(4), y2: value(5) };
422
+ else throw new Error("Invalid PDF path record");
423
+ }
424
+ remaining -= count;
425
+ }
426
+ }
427
+
428
+ // packages/pdf-ast/src/render/svg-path-stream.ts
429
+ function svgPathSegment(segment, height, matrix2) {
430
+ const point = (x, y) => matrix2 ? `${matrix2[0] * x + matrix2[2] * y + matrix2[4]} ${height - matrix2[1] * x - matrix2[3] * y - matrix2[5]}` : `${x} ${height - y}`;
431
+ switch (segment.kind) {
432
+ case "move":
433
+ return `M ${point(segment.x, segment.y)}`;
434
+ case "line":
435
+ return `L ${point(segment.x, segment.y)}`;
436
+ case "cubic":
437
+ return `C ${point(segment.x1, segment.y1)} ${point(segment.x2, segment.y2)} ${point(segment.x, segment.y)}`;
438
+ case "rect":
439
+ return matrix2 ? `M ${point(segment.x, segment.y)} L ${point(segment.x + segment.width, segment.y)} L ${point(segment.x + segment.width, segment.y + segment.height)} L ${point(segment.x, segment.y + segment.height)} Z` : `M ${segment.x} ${height - segment.y} h ${segment.width} v ${-segment.height} h ${-segment.width} Z`;
440
+ case "close":
441
+ return "Z";
442
+ }
443
+ }
444
+ function limit(value) {
445
+ if (value === void 0 || value === Infinity) return Infinity;
446
+ if (!Number.isSafeInteger(value) || value < 0) throw new RangeError("Invalid SVG path limit");
447
+ return value;
448
+ }
449
+ async function* encodeSvgPathDataChunks(input, height, options = {}) {
450
+ const { signal } = options;
451
+ signal?.throwIfAborted();
452
+ const chunkBytes = options.chunkBytes ?? 16384, maxSegments = limit(options.maxSegments), maximum10 = limit(options.maxOutputBytes);
453
+ if (!Number.isSafeInteger(chunkBytes) || chunkBytes < 1) throw new RangeError("Invalid SVG path chunk size");
454
+ const stored = "kind" in input && input.kind === "stored-path" ? input : void 0;
455
+ if (stored && (!Number.isSafeInteger(stored.count) || stored.count < 0)) throw new RangeError("Invalid stored SVG path count");
456
+ if (stored && stored.count > maxSegments) throw new PdfError("E_LIMIT", "SVG path segment limit exceeded");
457
+ const source = stored ? readStoredPath(stored, signal) : input;
458
+ const buffer = new Uint8Array(Math.min(16384, chunkBytes)), encoder = new TextEncoder();
459
+ let used = 0, count = 0, total = 0, first = true;
460
+ for await (const segment of source) {
461
+ signal?.throwIfAborted();
462
+ if (count >= maxSegments) throw new PdfError("E_LIMIT", "SVG path segment limit exceeded");
463
+ if (++count % 64 === 0) {
464
+ await new Promise((resolve2) => setTimeout(resolve2, 0));
465
+ signal?.throwIfAborted();
466
+ }
467
+ const part = svgPathSegment(segment, height, options.matrix);
468
+ if (part === void 0) continue;
469
+ const text = (first ? "" : " ") + part;
470
+ first = false;
471
+ if (text.length > maximum10 - total || !Number.isSafeInteger(total + text.length)) throw new PdfError("E_LIMIT", "SVG path output byte limit exceeded");
472
+ total += text.length;
473
+ const bytes = encoder.encode(text);
474
+ for (let at = 0; at < bytes.length; ) {
475
+ signal?.throwIfAborted();
476
+ const take = Math.min(buffer.length - used, bytes.length - at);
477
+ buffer.set(bytes.subarray(at, at + take), used);
478
+ used += take;
479
+ at += take;
480
+ if (used === buffer.length) {
481
+ yield buffer.slice();
482
+ used = 0;
483
+ }
484
+ }
485
+ }
486
+ signal?.throwIfAborted();
487
+ if (used) yield buffer.slice(0, used);
488
+ }
489
+
339
490
  // packages/pdf-ast/src/content/stored-record.ts
340
491
  function* encodeParts(value, storage, key, ancestors) {
341
492
  if (key === "storage") {
@@ -522,6 +673,87 @@ var RecordReader = class {
522
673
  }
523
674
  return result;
524
675
  }
676
+ async size(tag) {
677
+ const bytes = await this.take(8);
678
+ const size = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength).getFloat64(0, true);
679
+ if (!Number.isSafeInteger(size) || size < 0 || size > this.remaining || tag === 4 /* String */ && size * 2 > this.remaining) throw new Error("Invalid capture field length");
680
+ return size;
681
+ }
682
+ async discard(length) {
683
+ while (length) {
684
+ const count = Math.min(length, 4096);
685
+ await this.take(count);
686
+ length -= count;
687
+ }
688
+ }
689
+ async stringEquals(expected) {
690
+ const length = await this.size(4 /* String */);
691
+ let equal2 = length === expected.length;
692
+ for (let at = 0; at < length; at += 2048) {
693
+ const bytes = await this.take(Math.min(2048, length - at) * 2);
694
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
695
+ if (equal2) for (let i = 0; i < bytes.length / 2; i++) {
696
+ if (view.getUint16(i * 2, true) !== expected.charCodeAt(at + i)) {
697
+ equal2 = false;
698
+ break;
699
+ }
700
+ }
701
+ }
702
+ return equal2;
703
+ }
704
+ /** Skip without constructing arrays, strings or byte payloads. Only 32
705
+ * container counters stay resident; deeper counters use caller backing. */
706
+ async skip(tag) {
707
+ const frames = [];
708
+ const spilled = new StoredMetadataStack(this.storage, this.signal);
709
+ let remaining = 1;
710
+ for (; ; ) {
711
+ if (remaining === 0) {
712
+ const parent = frames.pop() ?? await spilled.pop();
713
+ if (parent === void 0) return;
714
+ remaining = parent;
715
+ continue;
716
+ }
717
+ if (remaining === -1) {
718
+ const field2 = (await this.take(1))[0];
719
+ if (field2 === 9 /* End */) {
720
+ remaining = 0;
721
+ continue;
722
+ }
723
+ if (field2 !== 4 /* String */) throw new Error("Invalid capture key");
724
+ await this.discard(await this.size(4 /* String */) * 2);
725
+ } else remaining--;
726
+ const current = tag ?? (await this.take(1))[0];
727
+ tag = void 0;
728
+ if (current === 8 /* Object */ || current === 7 /* Array */) {
729
+ const children = current === 8 /* Object */ ? -1 : await this.size(7 /* Array */);
730
+ if (frames.length === 32) await spilled.push(frames.shift());
731
+ frames.push(remaining);
732
+ remaining = children;
733
+ } else if (current === 4 /* String */ || current === 5 /* Bytes */) {
734
+ await this.discard(await this.size(current) * (current === 4 /* String */ ? 2 : 1));
735
+ } else if (current === 3 /* Number */) await this.take(8);
736
+ else if (current !== 0 /* Null */ && current !== 1 /* False */ && current !== 2 /* True */ && current !== 6 /* Storage */) {
737
+ throw new Error("Invalid capture tag");
738
+ }
739
+ }
740
+ }
741
+ async matches(path, expected, depth = 0) {
742
+ const tag = (await this.take(1))[0];
743
+ if (depth === path.length && tag === 4 /* String */) return this.stringEquals(expected);
744
+ if (depth === path.length || tag !== 8 /* Object */) {
745
+ await this.skip(tag);
746
+ return false;
747
+ }
748
+ let matched = false;
749
+ for (; ; ) {
750
+ const field2 = (await this.take(1))[0];
751
+ if (field2 === 9 /* End */) return matched;
752
+ if (field2 !== 4 /* String */) throw new Error("Invalid capture key");
753
+ if (await this.stringEquals(path[depth])) matched = await this.matches(path, expected, depth + 1);
754
+ else await this.skip();
755
+ }
756
+ }
525
757
  async value(tag) {
526
758
  tag ??= (await this.take(1))[0];
527
759
  if (tag === 0 /* Null */) return null;
@@ -571,7 +803,7 @@ var RecordReader = class {
571
803
  return value;
572
804
  }
573
805
  };
574
- async function readStoredRecord(storage, position, signal) {
806
+ async function openStoredRecord(storage, position, signal) {
575
807
  signal?.throwIfAborted();
576
808
  if (!Number.isSafeInteger(position) || position < 0)
577
809
  throw new RangeError("Invalid capture position");
@@ -581,11 +813,22 @@ async function readStoredRecord(storage, position, signal) {
581
813
  const view = new DataView(header2.buffer, header2.byteOffset, header2.byteLength), next = view.getFloat64(0, true), length = view.getFloat64(8, true);
582
814
  if (!Number.isSafeInteger(length) || length < 1 || !Number.isSafeInteger(position + 16 + length))
583
815
  throw new RangeError("Invalid capture length");
584
- const reader = new RecordReader(storage, position + 16, length, signal), value = await reader.value();
816
+ return { reader: new RecordReader(storage, position + 16, length, signal), next };
817
+ }
818
+ async function readStoredRecord(storage, position, signal) {
819
+ const { reader, next } = await openStoredRecord(storage, position, signal);
820
+ const value = await reader.value();
585
821
  if (reader.remaining) throw new Error("Trailing capture bytes");
586
822
  signal?.throwIfAborted();
587
823
  return { value, next };
588
824
  }
825
+ async function storedRecordMatches(storage, position, path, expected, signal) {
826
+ const { reader, next } = await openStoredRecord(storage, position, signal);
827
+ const matched = await reader.matches(path, expected);
828
+ if (reader.remaining) throw new Error("Trailing capture bytes");
829
+ signal?.throwIfAborted();
830
+ return { matched, next };
831
+ }
589
832
  var StoredMetadataStack = class {
590
833
  constructor(storage, signal) {
591
834
  this.storage = storage;
@@ -699,95 +942,6 @@ async function* readStoredOperations(source, signal) {
699
942
  }
700
943
  }
701
944
 
702
- // packages/pdf-ast/src/content/stored-path.ts
703
- var BLOCK_BYTES = 4096;
704
- var RECORD_BYTES = 56;
705
- var RECORDS = Math.floor((BLOCK_BYTES - 8) / RECORD_BYTES);
706
- var kinds = ["close", "move", "line", "cubic", "rect"];
707
- var StoredPathWriter = class {
708
- constructor(storage, signal) {
709
- this.storage = storage;
710
- this.signal = signal;
711
- }
712
- storage;
713
- signal;
714
- bytes = new Uint8Array(BLOCK_BYTES);
715
- view = new DataView(this.bytes.buffer);
716
- first = -1;
717
- position = -1;
718
- used = 0;
719
- count = 0;
720
- finished = false;
721
- bounds = [Infinity, Infinity, -Infinity, -Infinity];
722
- allocate() {
723
- const at = this.storage.allocate(BLOCK_BYTES);
724
- if (!Number.isSafeInteger(at) || at < 0 || !Number.isSafeInteger(at + BLOCK_BYTES)) throw new RangeError("Invalid PDF path allocation");
725
- return at;
726
- }
727
- async append(segment) {
728
- this.signal?.throwIfAborted();
729
- if (this.finished) throw new Error("PDF path is already finished");
730
- if (this.position === -1) this.first = this.position = this.allocate();
731
- if (this.used === RECORDS) {
732
- const next = this.allocate();
733
- this.view.setFloat64(0, next, true);
734
- await this.storage.write(this.position, this.bytes, this.signal ? { signal: this.signal } : void 0);
735
- this.position = next;
736
- this.used = 0;
737
- }
738
- const at = 8 + this.used++ * RECORD_BYTES;
739
- this.view.setFloat64(at, kinds.indexOf(segment.kind), true);
740
- const values = segment.kind === "close" ? [] : segment.kind === "cubic" ? [segment.x, segment.y, segment.x1, segment.y1, segment.x2, segment.y2] : segment.kind === "rect" ? [segment.x, segment.y, segment.width, segment.height] : [segment.x, segment.y];
741
- for (let i = 0; i < values.length; i++) this.view.setFloat64(at + 8 + i * 8, values[i], true);
742
- const include = (x, y) => {
743
- this.bounds[0] = Math.min(this.bounds[0], x);
744
- this.bounds[1] = Math.min(this.bounds[1], y);
745
- this.bounds[2] = Math.max(this.bounds[2], x);
746
- this.bounds[3] = Math.max(this.bounds[3], y);
747
- };
748
- if (segment.kind !== "close") include(segment.x, segment.y);
749
- if (segment.kind === "cubic") {
750
- include(segment.x1, segment.y1);
751
- include(segment.x2, segment.y2);
752
- }
753
- if (segment.kind === "rect") include(segment.x + segment.width, segment.y + segment.height);
754
- this.count++;
755
- }
756
- async finish() {
757
- this.signal?.throwIfAborted();
758
- if (this.finished) throw new Error("PDF path is already finished");
759
- this.finished = true;
760
- if (this.position !== -1) {
761
- this.view.setFloat64(0, -1, true);
762
- await this.storage.write(this.position, this.bytes.subarray(0, 8 + this.used * RECORD_BYTES), this.signal ? { signal: this.signal } : void 0);
763
- }
764
- return { kind: "stored-path", storage: this.storage, position: this.first, count: this.count, bounds: this.bounds };
765
- }
766
- };
767
- async function* readStoredPath(path, signal) {
768
- let position = path.position, remaining = path.count;
769
- while (remaining > 0) {
770
- signal?.throwIfAborted();
771
- if (!Number.isSafeInteger(position) || position < 0) throw new Error("Invalid PDF path block");
772
- const count = Math.min(RECORDS, remaining), length = 8 + count * RECORD_BYTES;
773
- const bytes = (await path.storage.read(position, length, signal ? { signal } : void 0)).slice();
774
- if (bytes.length !== length) throw new Error("Incomplete PDF path block");
775
- const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
776
- position = view.getFloat64(0, true);
777
- for (let i = 0; i < count; i++) {
778
- signal?.throwIfAborted();
779
- const at = 8 + i * RECORD_BYTES, kind = kinds[view.getFloat64(at, true)];
780
- const value = (n) => view.getFloat64(at + 8 + n * 8, true);
781
- if (kind === "close") yield { kind };
782
- else if (kind === "move" || kind === "line") yield { kind, x: value(0), y: value(1) };
783
- else if (kind === "rect") yield { kind, x: value(0), y: value(1), width: value(2), height: value(3) };
784
- else if (kind === "cubic") yield { kind, x: value(0), y: value(1), x1: value(2), y1: value(3), x2: value(4), y2: value(5) };
785
- else throw new Error("Invalid PDF path record");
786
- }
787
- remaining -= count;
788
- }
789
- }
790
-
791
945
  // packages/pdf-ast/src/content/stored-clips.ts
792
946
  var PAGE_BYTES = 4096;
793
947
  var RECORD_BYTES2 = 64;
@@ -18715,14 +18869,14 @@ var FlateStream = class extends DecodeStream {
18715
18869
  throw new FormatError("Unknown block type in flate stream");
18716
18870
  }
18717
18871
  buffer = this.buffer;
18718
- let limit10 = buffer ? buffer.length : 0;
18872
+ let limit11 = buffer ? buffer.length : 0;
18719
18873
  let pos = this.bufferLength;
18720
18874
  while (true) {
18721
18875
  let code1 = this.getCode(litCodeTable);
18722
18876
  if (code1 < 256) {
18723
- if (pos + 1 >= limit10) {
18877
+ if (pos + 1 >= limit11) {
18724
18878
  buffer = this.ensureBuffer(pos + 1);
18725
- limit10 = buffer.length;
18879
+ limit11 = buffer.length;
18726
18880
  }
18727
18881
  buffer[pos++] = code1;
18728
18882
  continue;
@@ -18745,9 +18899,9 @@ var FlateStream = class extends DecodeStream {
18745
18899
  code2 = this.getBits(code2);
18746
18900
  }
18747
18901
  const dist = (code1 & 65535) + code2;
18748
- if (pos + len >= limit10) {
18902
+ if (pos + len >= limit11) {
18749
18903
  buffer = this.ensureBuffer(pos + len);
18750
- limit10 = buffer.length;
18904
+ limit11 = buffer.length;
18751
18905
  }
18752
18906
  for (let k = 0; k < len; ++k, ++pos) {
18753
18907
  buffer[pos] = buffer[pos - dist];
@@ -28224,6 +28378,7 @@ function* repairCandidateSteps(size) {
28224
28378
  // packages/pdf-ast/src/cos/value-parser.ts
28225
28379
  function* parseValueSteps(lexer, maxDepth, repair = false, maxNodes = Infinity, options = {}) {
28226
28380
  yield;
28381
+ if (options.deferDictionaryValues && (!options.dictionaryStorage || options.arrayStorage !== options.dictionaryStorage || options.stringStorage !== options.dictionaryStorage || options.containerStorage !== options.dictionaryStorage)) throw new TypeError("Deferred resource values require shared caller backing");
28227
28382
  let work = 0;
28228
28383
  let nodes = 0;
28229
28384
  const charge = () => {
@@ -28233,14 +28388,15 @@ function* parseValueSteps(lexer, maxDepth, repair = false, maxNodes = Infinity,
28233
28388
  const residentDepth = 32;
28234
28389
  const stack = [];
28235
28390
  let current, depth = 0;
28236
- const pathLength = (options.storedArrayPaths ?? []).reduce((length, path) => Math.max(length, path.length - 1), 0);
28237
- function matchesStoredPath(parent) {
28238
- return options.storedArrayPaths?.some((path) => {
28239
- const length = parent.path.length + 1;
28391
+ const pathLength = [...options.storedArrayPaths ?? [], ...options.storedDictionaryPaths ?? []].reduce((length, path) => Math.max(length, path.length - 1), 0);
28392
+ function matchesStoredPath(parent, paths) {
28393
+ const currentPath = parent ? [...parent.path, parent.kind === "dict" ? parent.key?.decoded : null] : options.arrayPathPrefix ?? [];
28394
+ return paths?.some((path) => {
28395
+ const length = currentPath.length;
28240
28396
  if (!path.length || path.length > length) return false;
28241
28397
  for (let i = 0; i < path.length; i++) {
28242
28398
  const at = length - path.length + i;
28243
- const key = at === parent.path.length ? parent.kind === "dict" ? parent.key?.decoded : void 0 : parent.path[at];
28399
+ const key = currentPath[at];
28244
28400
  if (key == null || path[i] !== "*" && path[i] !== key) return false;
28245
28401
  }
28246
28402
  return true;
@@ -28265,7 +28421,9 @@ function* parseValueSteps(lexer, maxDepth, repair = false, maxNodes = Infinity,
28265
28421
  while (true) {
28266
28422
  if (++work % 16 === 0) yield;
28267
28423
  const parent = current;
28268
- lexer.setStringStorage?.(options.stringStorage && (parent?.kind === "dict" && parent.key && options.storedStringKeys?.includes(parent.key.decoded) || !parent && options.storeRootString) ? options.stringStorage : void 0);
28424
+ const deferred = options.deferDictionaryValues && (parent?.deferred || parent?.kind === "dict" && parent.storedEntries);
28425
+ const selectedString = parent?.kind === "dict" && parent.key && options.storedStringKeys?.includes(parent.key.decoded) || !parent && options.storeRootString;
28426
+ lexer.setStringStorage?.(options.stringStorage && (selectedString || deferred) ? options.stringStorage : void 0);
28269
28427
  const tok = yield "token";
28270
28428
  if (!tok) {
28271
28429
  if (!parent) return void 0;
@@ -28278,11 +28436,11 @@ function* parseValueSteps(lexer, maxDepth, repair = false, maxNodes = Infinity,
28278
28436
  let node;
28279
28437
  if (parent?.kind === "array" && tok.kind === "array-end") {
28280
28438
  yield* pop();
28281
- node = { kind: "array", items: parent.items, ...parent.storedItems ? { storedItems: parent.storedItems } : {}, span: { start: parent.start, end: tok.span.end } };
28439
+ node = { kind: "array", items: parent.items, ...parent.deferred ? { deferred: true } : {}, ...parent.storedItems ? { storedItems: parent.storedItems } : {}, span: { start: parent.start, end: tok.span.end } };
28282
28440
  } else if (parent?.kind === "dict" && !parent.key) {
28283
28441
  if (tok.kind === "dict-end") {
28284
28442
  yield* pop();
28285
- node = yield { kind: "dict", entries: parent.entries, ...parent.storedEntries ? { storedEntries: parent.storedEntries } : {}, span: { start: parent.start, end: tok.span.end } };
28443
+ node = yield { kind: "dict", entries: parent.entries, ...parent.deferred ? { deferred: true } : {}, ...parent.storedEntries ? { storedEntries: parent.storedEntries } : {}, span: { start: parent.start, end: tok.span.end } };
28286
28444
  } else if (tok.kind === "name") {
28287
28445
  charge();
28288
28446
  parent.key = { kind: "name", rawBytes: tok.rawBytes, decoded: tok.decoded, span: tok.span };
@@ -28298,30 +28456,33 @@ function* parseValueSteps(lexer, maxDepth, repair = false, maxNodes = Infinity,
28298
28456
  charge();
28299
28457
  if (depth > maxDepth) throw new PdfError("E_LIMIT", "PDF syntax nesting limit exceeded");
28300
28458
  if (tok.kind === "array-start") {
28301
- const backed = options.arrayStorage && (parent?.kind === "array" && parent.storedItems || parent?.kind === "dict" && (options.storedArrayKeys?.includes(parent.key.decoded) || matchesStoredPath(parent)) || !parent && options.storeRootArray);
28459
+ const backed = options.arrayStorage && (parent?.kind === "array" && parent.storedItems && !parent.deferred || parent?.kind === "dict" && (options.storedArrayKeys?.includes(parent.key.decoded) || matchesStoredPath(parent, options.storedArrayPaths)) || !parent && options.storeRootArray);
28302
28460
  yield* push({
28303
28461
  kind: "array",
28304
28462
  path: ancestorPath(parent),
28305
28463
  start: tok.span.start,
28306
28464
  items: [],
28307
28465
  tail: -1,
28308
- ...backed ? { storedItems: { storage: options.arrayStorage, position: -1, length: 0 } } : {}
28466
+ ...deferred && !backed ? { deferred: true } : {},
28467
+ ...backed || deferred ? { storedItems: { storage: options.arrayStorage, position: -1, length: 0 } } : {}
28309
28468
  });
28310
28469
  continue;
28311
28470
  }
28312
28471
  if (tok.kind === "dict-start") {
28313
- const backed = options.dictionaryStorage && (parent?.kind === "dict" && !parent.storedEntries && options.storedDictionaryKeys?.includes(parent.key.decoded) || !parent && options.storeRootDictionary);
28472
+ const backed = options.dictionaryStorage && (parent?.kind === "dict" && (!parent.storedEntries || parent.deferred) && (options.storedDictionaryKeys?.includes(parent.key.decoded) || matchesStoredPath(parent, options.storedDictionaryPaths)) || !parent && (options.storeRootDictionary || matchesStoredPath(void 0, options.storedDictionaryPaths)));
28314
28473
  yield* push({
28315
28474
  kind: "dict",
28316
28475
  path: ancestorPath(parent),
28317
28476
  start: tok.span.start,
28318
28477
  entries: [],
28319
28478
  tail: -1,
28320
- ...backed ? { storedEntries: { storage: options.dictionaryStorage, position: -1, length: 0 } } : {}
28479
+ ...deferred && !backed ? { deferred: true } : {},
28480
+ ...backed || deferred ? { storedEntries: { storage: options.dictionaryStorage, position: -1, length: 0 } } : {}
28321
28481
  });
28322
28482
  continue;
28323
28483
  }
28324
28484
  node = yield* parseLeafFromToken(tok, lexer);
28485
+ if (deferred && !selectedString && node.kind === "string") node = { ...node, deferred: true };
28325
28486
  }
28326
28487
  const container = current;
28327
28488
  if (!container) return node;
@@ -28680,8 +28841,8 @@ var PdfNameIndex = class {
28680
28841
  this.storage = storage;
28681
28842
  this.maximum = maximum10;
28682
28843
  this.signal = signal;
28683
- const limit10 = typeof maximum10 === "function" ? maximum10() : maximum10;
28684
- if (limit10 !== Infinity && (!Number.isSafeInteger(limit10) || limit10 < 0)) throw new RangeError("Invalid name staging limit");
28844
+ const limit11 = typeof maximum10 === "function" ? maximum10() : maximum10;
28845
+ if (limit11 !== Infinity && (!Number.isSafeInteger(limit11) || limit11 < 0)) throw new RangeError("Invalid name staging limit");
28685
28846
  }
28686
28847
  storage;
28687
28848
  maximum;
@@ -28720,8 +28881,8 @@ var PdfNameIndex = class {
28720
28881
  for (const [objectNumber, offset] of tail) yield { objectNumber, offset, type: "uncompressed" };
28721
28882
  for (const index2 of inputs) yield* index2.entries(signal);
28722
28883
  }
28723
- const limit10 = typeof this.maximum === "function" ? this.maximum() : this.maximum;
28724
- const remaining = Math.min(limit10, Number.MAX_SAFE_INTEGER) - this.stagedBytes;
28884
+ const limit11 = typeof this.maximum === "function" ? this.maximum() : this.maximum;
28885
+ const remaining = Math.min(limit11, Number.MAX_SAFE_INTEGER) - this.stagedBytes;
28725
28886
  if (remaining < 0) throw new PdfError("E_LIMIT", "PDF name staging byte limit exceeded");
28726
28887
  const combined = await PdfObjectIndex.build(rows(), this.storage, {
28727
28888
  runEntries: 64,
@@ -28791,7 +28952,7 @@ var PdfNameIndex = class {
28791
28952
  };
28792
28953
 
28793
28954
  // packages/pdf-ast/src/content/stored-dictionary.ts
28794
- async function* readPdfDictionaryEntries(dict, signal) {
28955
+ async function* readRawPdfDictionaryEntries(dict, signal) {
28795
28956
  signal?.throwIfAborted();
28796
28957
  if (dict.storedEntries) yield* readStoredItems(dict.storedEntries, signal);
28797
28958
  else for (const entry of dict.entries) {
@@ -28799,10 +28960,59 @@ async function* readPdfDictionaryEntries(dict, signal) {
28799
28960
  yield entry;
28800
28961
  }
28801
28962
  }
28802
- async function readPdfDictionaryValue(dict, key, signal) {
28963
+ async function materializeResourceValue(node, signal) {
28964
+ signal?.throwIfAborted();
28965
+ if (node.kind === "dict" && node.deferred && node.storedEntries) {
28966
+ const { deferred: ignoredDeferred, storedEntries: ignoredEntries, ...ordinary } = node;
28967
+ const entries = [];
28968
+ for await (const entry of readRawPdfDictionaryEntries(node, signal)) entries.push({ ...entry, value: await materializeResourceValue(entry.value, signal) });
28969
+ return { ...ordinary, entries };
28970
+ }
28971
+ if (node.kind === "array" && node.deferred && node.storedItems) {
28972
+ const { deferred: ignoredDeferred, storedItems: ignoredItems, ...ordinary } = node;
28973
+ const items = [];
28974
+ for await (const item of readStoredItems(node.storedItems, signal)) items.push(await materializeResourceValue(item, signal));
28975
+ return { ...ordinary, items };
28976
+ }
28977
+ if (node.kind === "string" && node.deferred && node.storedBytes) {
28978
+ const { deferred: ignoredDeferred, storedBytes, ...ordinary } = node;
28979
+ if (!Number.isSafeInteger(storedBytes.byteLength) || storedBytes.byteLength < 0) throw new RangeError("Invalid deferred resource string length");
28980
+ const bytes = new Uint8Array(storedBytes.byteLength);
28981
+ for (let at = 0; at < bytes.length; at += 4096) {
28982
+ if (at && at % 65536 === 0) await new Promise((resolve2) => setTimeout(resolve2, 0));
28983
+ const length = Math.min(4096, bytes.length - at);
28984
+ const chunk = await storedBytes.storage.read(storedBytes.position + at, length, signal ? { signal } : void 0);
28985
+ signal?.throwIfAborted();
28986
+ if (chunk.length !== length) throw new Error("Incomplete deferred resource string");
28987
+ bytes.set(chunk, at);
28988
+ }
28989
+ return { ...ordinary, bytes };
28990
+ }
28991
+ return node;
28992
+ }
28993
+ async function* readPdfDictionaryEntries(dict, signal) {
28994
+ for await (const entry of readRawPdfDictionaryEntries(dict, signal)) yield { ...entry, value: await materializeResourceValue(entry.value, signal) };
28995
+ }
28996
+ async function readPdfDictionaryValue(dict, key, signal, options = {}) {
28997
+ if (dict.storedEntries) {
28998
+ const { storage, length } = dict.storedEntries;
28999
+ if (!Number.isSafeInteger(length) || length < 0) throw new RangeError("Invalid stored array length");
29000
+ let position = dict.storedEntries.position, selected = -1;
29001
+ for (let i = 0; i < length; i++) {
29002
+ if (i && i % 256 === 0) await new Promise((resolve2) => setTimeout(resolve2, 0));
29003
+ const record = await storedRecordMatches(storage, position, ["key", "decoded"], key, signal);
29004
+ if (record.matched) selected = position;
29005
+ position = record.next;
29006
+ }
29007
+ if (position !== -1) throw new Error("Invalid stored array terminator");
29008
+ signal?.throwIfAborted();
29009
+ if (selected === -1) return void 0;
29010
+ const value2 = (await readStoredRecord(storage, selected, signal)).value.value;
29011
+ return options.preserveDeferred ? value2 : materializeResourceValue(value2, signal);
29012
+ }
28803
29013
  let value;
28804
- for await (const entry of readPdfDictionaryEntries(dict, signal)) if (entry.key.decoded === key) value = entry.value;
28805
- return value;
29014
+ for await (const entry of readRawPdfDictionaryEntries(dict, signal)) if (entry.key.decoded === key) value = entry.value;
29015
+ return value && !options.preserveDeferred ? materializeResourceValue(value, signal) : value;
28806
29016
  }
28807
29017
  async function mergePdfResourceDictionaries(destination, source, indexStorage, signal) {
28808
29018
  const storage = destination.storedEntries?.storage ?? source?.storedEntries?.storage;
@@ -28812,7 +29022,7 @@ async function mergePdfResourceDictionaries(destination, source, indexStorage, s
28812
29022
  async function* rows() {
28813
29023
  for (const [dict, replace] of [[destination, true], [source, false]]) {
28814
29024
  if (!dict) continue;
28815
- for await (const entry of readPdfDictionaryEntries(dict, signal)) {
29025
+ for await (const entry of readRawPdfDictionaryEntries(dict, signal)) {
28816
29026
  const name = await names.intern(entry.key.decoded);
28817
29027
  if (!replace && !name.added) continue;
28818
29028
  const position = await writeStoredRecord(storage, entry, -1, signal);
@@ -30901,13 +31111,13 @@ async function decryptPdfObjectStrings(state, objectNumber, generationNumber, va
30901
31111
  let signatureDict = node;
30902
31112
  if (node.storedEntries) {
30903
31113
  signatureDict = { kind: "dict", entries: [] };
30904
- for await (const entry of readPdfDictionaryEntries(node, options.signal)) {
31114
+ for await (const entry of readRawPdfDictionaryEntries(node, options.signal)) {
30905
31115
  if (["Type", "FT", "ByteRange", "Filter"].includes(entry.key.decoded)) dictSet(signatureDict, entry.key.decoded, entry.value);
30906
31116
  }
30907
31117
  }
30908
31118
  const signature = isSignatureDictionary(signatureDict);
30909
31119
  let position = -1, tail = -1;
30910
- for await (const entry of readPdfDictionaryEntries(node, options.signal)) {
31120
+ for await (const entry of readRawPdfDictionaryEntries(node, options.signal)) {
30911
31121
  const transformed = { key: entry.key, value: signature && entry.key.decoded === "Contents" ? entry.value : await transform(entry.value) };
30912
31122
  if (node.storedEntries) {
30913
31123
  tail = await appendStoredRecord(node.storedEntries.storage, transformed, tail, options.signal);
@@ -33259,13 +33469,13 @@ function embedTrueTypeFontInCos(doc, font, usedGlyphs) {
33259
33469
  }
33260
33470
 
33261
33471
  // packages/pdf-ast/src/fonts/resolve.ts
33262
- function* resolve(node, storeRootArray = false, storeRootDictionary = false) {
33263
- const value = yield { kind: "resolve", node, storeRootArray, storeRootDictionary };
33472
+ function* resolve(node, storeRootArray = false, storeRootDictionary = false, arrayPathPrefix) {
33473
+ const value = yield { kind: "resolve", node, storeRootArray, storeRootDictionary, ...arrayPathPrefix ? { arrayPathPrefix } : {} };
33264
33474
  if (value && !("kind" in value)) throw new TypeError("Font lookup returned stream bytes instead of a COS value");
33265
33475
  return value;
33266
33476
  }
33267
- function* resolveDict2(node, backed = false) {
33268
- const value = yield* resolve(node, false, backed);
33477
+ function* resolveDict2(node, backed = false, path) {
33478
+ const value = yield* resolve(node, false, backed, path);
33269
33479
  return value?.kind === "dict" ? value : value?.kind === "stream" ? value.dict : void 0;
33270
33480
  }
33271
33481
  function* resolveArray2(node, backed = false) {
@@ -33381,7 +33591,7 @@ function* resolvePageFontsSteps(rootRef, resourcesDict, selectedName, options =
33381
33591
  fontMatrix = [1e-3, 0, 0, 1e-3, 0, 0];
33382
33592
  }
33383
33593
  charProcs = yield* resolveDict2(dictGet(fObj, "CharProcs"));
33384
- fontResources = yield* resolveDict2(dictGet(fObj, "Resources"));
33594
+ fontResources = yield* resolveDict2(dictGet(fObj, "Resources"), false, ["Resources"]);
33385
33595
  }
33386
33596
  const type3Scale1000 = subtype === "Type3" && fontMatrix ? Math.hypot(fontMatrix[0], fontMatrix[1]) * 1e3 : 1;
33387
33597
  if (subtype === "Type0") {
@@ -34479,8 +34689,8 @@ var CCITTFaxDecoder = class {
34479
34689
  }
34480
34690
  this.codingPos = codingPos;
34481
34691
  }
34482
- *_findTableCode(start, end, table, limit10) {
34483
- const limitValue = limit10 || 0;
34692
+ *_findTableCode(start, end, table, limit11) {
34693
+ const limitValue = limit11 || 0;
34484
34694
  for (let i = start; i <= end; ++i) {
34485
34695
  let code = yield* this._lookBits(i);
34486
34696
  if (code === ccittEOF) {
@@ -40622,8 +40832,8 @@ function* looksLikePostEiContentStream(size, posAfterEi) {
40622
40832
  let p = posAfterEi;
40623
40833
  while (p < size && isPdfWhitespace(yield* byte2(p))) p++;
40624
40834
  if (p >= size) return true;
40625
- const limit10 = Math.min(size, p + 16);
40626
- for (let i = p; i < limit10; i++) {
40835
+ const limit11 = Math.min(size, p + 16);
40836
+ for (let i = p; i < limit11; i++) {
40627
40837
  const b = yield* byte2(i);
40628
40838
  if (b === 40 || b === 60 || b === 37) break;
40629
40839
  if (!isPdfWhitespace(b) && (b < 32 || b > 126)) {
@@ -41188,6 +41398,11 @@ function* resolveColorSpaceInfoSteps(doc, node, resources) {
41188
41398
  case "resolve":
41189
41399
  result = doc.resolve(request.node);
41190
41400
  break;
41401
+ case "resource": {
41402
+ const map = doc.resolveDict(dictGet(request.resources, request.category));
41403
+ result = map ? dictGet(map, request.name) : void 0;
41404
+ break;
41405
+ }
41191
41406
  case "palette":
41192
41407
  result = request.node.kind === "stream" ? doc.decodeStream(request.node) : request.node.bytes;
41193
41408
  break;
@@ -41228,9 +41443,7 @@ function* imageColorSpaceProgram(csNode, resourcesDict, maxDepth = Infinity, dep
41228
41443
  if (name === "DeviceRGB" || name === "RGB" || name === "CalRGB") {
41229
41444
  return { colorSpace: "rgb", colorSpaceLabel: name === "CalRGB" ? "cal-rgb" : "rgb", components: 3 };
41230
41445
  }
41231
- const csResources = resourcesDict ? yield { kind: "resolve", node: dictGet(resourcesDict, "ColorSpace") } : void 0;
41232
- const csResDict = csResources?.kind === "dict" ? csResources : void 0;
41233
- const mapped = csResDict ? dictGet(csResDict, name) : void 0;
41446
+ const mapped = resourcesDict ? yield { kind: "resource", resources: resourcesDict, category: "ColorSpace", name } : void 0;
41234
41447
  if (mapped) {
41235
41448
  return yield* imageColorSpaceProgram(mapped, resourcesDict, maxDepth, depth + 1);
41236
41449
  }
@@ -42556,7 +42769,10 @@ function* runColorProgramSteps(doc, work, sources) {
42556
42769
  while (!step.done) {
42557
42770
  const request = step.value;
42558
42771
  if (request.kind === "resolve") step = work.next(doc?.resolve(request.node));
42559
- else {
42772
+ else if (request.kind === "resource") {
42773
+ const map = doc?.resolveDict(dictGet(request.resources, request.category));
42774
+ step = work.next(map ? dictGet(map, request.name) : void 0);
42775
+ } else {
42560
42776
  if (!doc) throw new PdfError("E_CAPABILITY", "PDF resource color requires a source driver");
42561
42777
  if (request.kind === "decode") {
42562
42778
  const bytes = doc.decodeStream(request.stream);
@@ -42581,8 +42797,7 @@ function* colorComponentCountSteps(hasDocument, csNode, activeResources, depth =
42581
42797
  if (name === "DeviceCMYK" || name === "CMYK") return 4;
42582
42798
  if (name === "DeviceRGB" || name === "RGB" || name === "CalRGB" || name === "Lab") return 3;
42583
42799
  if (hasDocument && activeResources) {
42584
- const csDict = yield* resolveColorNode(dictGet(activeResources, "ColorSpace"), "dict");
42585
- const mapped = csDict ? dictGet(csDict, name) : void 0;
42800
+ const mapped = yield { kind: "resource", resources: activeResources, category: "ColorSpace", name };
42586
42801
  if (mapped) return yield* colorComponentCountSteps(hasDocument, mapped, activeResources, depth + 1);
42587
42802
  }
42588
42803
  return 3;
@@ -42613,8 +42828,7 @@ function* convertContentColorSteps(hasDocument, csNode, csNameFallback, comps, a
42613
42828
  if ((!resolved || resolved.kind === "name") && hasDocument && activeResources) {
42614
42829
  const lookupName = resolved?.kind === "name" ? resolved.decoded : csNameFallback;
42615
42830
  if (lookupName && lookupName !== "DeviceRGB" && lookupName !== "RGB" && lookupName !== "DeviceGray" && lookupName !== "G" && lookupName !== "DeviceCMYK" && lookupName !== "CMYK") {
42616
- const csDict = yield* resolveColorNode(dictGet(activeResources, "ColorSpace"), "dict");
42617
- const mapped = csDict ? dictGet(csDict, lookupName) : void 0;
42831
+ const mapped = yield { kind: "resource", resources: activeResources, category: "ColorSpace", name: lookupName };
42618
42832
  if (mapped) {
42619
42833
  resolved = yield* resolveColorNode(mapped);
42620
42834
  }
@@ -42996,20 +43210,20 @@ function isOptionalContentVisible(doc, ocNode) {
42996
43210
  }
42997
43211
  return step.value;
42998
43212
  }
42999
- function* resolveEvaluationNode(node, storeRootArray = false, arrayPathPrefix) {
43213
+ function* resolveEvaluationNode(node, storeRootArray = false, arrayPathPrefix, storeRootDictionary = false) {
43000
43214
  if (!node) return void 0;
43001
- const result = yield { kind: "resolve", node, ...storeRootArray ? { storeRootArray } : {}, ...arrayPathPrefix ? { arrayPathPrefix } : {} };
43215
+ const result = yield { kind: "resolve", node, ...storeRootDictionary ? { storeRootDictionary } : {}, ...storeRootArray ? { storeRootArray } : {}, ...arrayPathPrefix ? { arrayPathPrefix } : {} };
43002
43216
  if (!result || !("kind" in result) || result.kind !== "resolved") throw new TypeError("Expected a resolved PDF object");
43003
43217
  return result.node;
43004
43218
  }
43005
- function* resolveEvaluationDict(node, arrayPathPrefix) {
43006
- const resolved = yield* resolveEvaluationNode(node, false, arrayPathPrefix);
43219
+ function* resolveEvaluationDict(node, arrayPathPrefix, storeRootDictionary = false) {
43220
+ const resolved = yield* resolveEvaluationNode(node, false, arrayPathPrefix, storeRootDictionary);
43007
43221
  return resolved?.kind === "dict" ? resolved : resolved?.kind === "stream" ? resolved.dict : void 0;
43008
43222
  }
43009
- function* lookupEvaluationDictionary(dict, key) {
43223
+ function* lookupEvaluationDictionary(dict, key, preserveDeferred = false) {
43010
43224
  if (!dict) return void 0;
43011
43225
  if (!dict.storedEntries) return dictGet(dict, key);
43012
- const result = yield { kind: "dictionary-value", dict, key };
43226
+ const result = yield { kind: "dictionary-value", dict, key, ...preserveDeferred ? { preserveDeferred } : {} };
43013
43227
  if (!result || !("kind" in result) || result.kind !== "resolved") throw new TypeError("Expected a PDF dictionary value");
43014
43228
  return result.node;
43015
43229
  }
@@ -43017,6 +43231,23 @@ function* resolveEvaluationArray(node, storeRootArray = false, arrayPathPrefix)
43017
43231
  const resolved = yield* resolveEvaluationNode(node, storeRootArray, arrayPathPrefix);
43018
43232
  return resolved?.kind === "array" ? resolved : void 0;
43019
43233
  }
43234
+ function* evaluationArrayPrefix(array, count) {
43235
+ if (!array.storedItems) return array.items.slice(0, count);
43236
+ const items = array.storedItems;
43237
+ if (!Number.isSafeInteger(items.length) || items.length < 0) throw new RangeError("Invalid stored array length");
43238
+ const prefix = [];
43239
+ let position = items.position;
43240
+ for (let i = 0; i < Math.min(count, items.length); i++) {
43241
+ const reply = yield { kind: "array-item", items, position };
43242
+ if (!reply || !("kind" in reply) || reply.kind !== "resolved" || reply.node?.kind !== "array") throw new TypeError("Expected stored array item");
43243
+ const [next, value] = reply.node.items;
43244
+ if (next?.kind !== "number" || !value) throw new TypeError("Expected stored array record");
43245
+ position = next.value;
43246
+ prefix.push(value);
43247
+ }
43248
+ if (items.length <= count && position !== -1) throw new PdfError("E_PARSE", "Invalid stored array terminator");
43249
+ return prefix;
43250
+ }
43020
43251
  function* visitEvaluationArray(array, visit) {
43021
43252
  if (!array.storedItems) {
43022
43253
  for (const item of array.items) yield* visit(item);
@@ -43461,8 +43692,8 @@ function* evaluateContentSteps(params) {
43461
43692
  st.dashPhase = void 0;
43462
43693
  }
43463
43694
  } else if (operator === "sh" && activeResources && ops[0]?.kind === "name") {
43464
- const shMap = yield* resolveEvaluationDict(dictGet(activeResources, "Shading"));
43465
- const shNode = shMap ? yield* resolveEvaluationNode(dictGet(shMap, ops[0].decoded)) : void 0;
43695
+ const shMap = yield* resolveEvaluationDict(dictGet(activeResources, "Shading"), ["Resources", "Shading"]);
43696
+ const shNode = shMap ? yield* resolveEvaluationNode(yield* lookupEvaluationDictionary(shMap, ops[0].decoded)) : void 0;
43466
43697
  const shDict = shNode?.kind === "dict" ? shNode : shNode?.kind === "stream" ? shNode.dict : void 0;
43467
43698
  const shStream = shNode?.kind === "stream" ? shNode : void 0;
43468
43699
  if (shDict) {
@@ -43513,10 +43744,10 @@ function* evaluateContentSteps(params) {
43513
43744
  } else if (operator === "K") {
43514
43745
  st.strokeColor = yield* resolveScColorOperands("DeviceCMYK", ops, activeResources);
43515
43746
  } else if (operator === "gs" && activeResources && ops[0]?.kind === "name") {
43516
- const extDict = yield* resolveEvaluationDict(dictGet(activeResources, "ExtGState"), ["ExtGState"]);
43517
- const gsDict = extDict ? yield* resolveEvaluationDict(dictGet(extDict, ops[0].decoded), ["ExtGState", ops[0].decoded]) : void 0;
43747
+ const extDict = yield* resolveEvaluationDict(dictGet(activeResources, "ExtGState"), ["Resources", "ExtGState"]);
43748
+ const gsDict = extDict ? yield* resolveEvaluationDict(yield* lookupEvaluationDictionary(extDict, ops[0].decoded, true), ["Resources", "ExtGState", ops[0].decoded], true) : void 0;
43518
43749
  if (gsDict) {
43519
- const mask = yield* resolveEvaluationNode(dictGet(gsDict, "SMask"));
43750
+ const mask = yield* resolveEvaluationNode(yield* lookupEvaluationDictionary(gsDict, "SMask"));
43520
43751
  if (mask?.kind === "name" && mask.decoded === "None") {
43521
43752
  st.softMask = void 0;
43522
43753
  } else if (mask?.kind === "dict") {
@@ -43549,48 +43780,36 @@ function* evaluateContentSteps(params) {
43549
43780
  st.softMask = { subtype: subtype.decoded, operations: captured instanceof StoredOperationsWriter ? [] : captured, ...captured instanceof StoredOperationsWriter ? { storedOperations: captured.snapshot() } : {}, ...parameters.value };
43550
43781
  }
43551
43782
  }
43552
- const bmNode = yield* resolveEvaluationNode(dictGet(gsDict, "BM"));
43783
+ const bmNode = yield* resolveEvaluationNode(yield* lookupEvaluationDictionary(gsDict, "BM", true), true);
43553
43784
  if (bmNode?.kind === "name") {
43554
43785
  st.blendMode = bmNode.decoded === "Compatible" ? "Normal" : bmNode.decoded;
43555
- } else if (bmNode?.kind === "array" && bmNode.items.length > 0) {
43556
- const firstBm = yield* resolveEvaluationNode(bmNode.items[0]);
43786
+ } else if (bmNode?.kind === "array" && (bmNode.storedItems?.length ?? bmNode.items.length) > 0) {
43787
+ const firstBm = yield* resolveEvaluationNode((yield* evaluationArrayPrefix(bmNode, 1))[0]);
43557
43788
  if (firstBm?.kind === "name") {
43558
43789
  st.blendMode = firstBm.decoded === "Compatible" ? "Normal" : firstBm.decoded;
43559
43790
  }
43560
43791
  }
43561
- const caNode = yield* resolveEvaluationNode(dictGet(gsDict, "ca"));
43792
+ const caNode = yield* resolveEvaluationNode(yield* lookupEvaluationDictionary(gsDict, "ca", true), true);
43562
43793
  if (caNode?.kind === "number") st.fillAlpha = Math.max(0, Math.min(1, caNode.value));
43563
- const CANode = yield* resolveEvaluationNode(dictGet(gsDict, "CA"));
43794
+ const CANode = yield* resolveEvaluationNode(yield* lookupEvaluationDictionary(gsDict, "CA", true), true);
43564
43795
  if (CANode?.kind === "number") st.strokeAlpha = Math.max(0, Math.min(1, CANode.value));
43565
- const lwNode = yield* resolveEvaluationNode(dictGet(gsDict, "LW"));
43796
+ const lwNode = yield* resolveEvaluationNode(yield* lookupEvaluationDictionary(gsDict, "LW", true), true);
43566
43797
  if (lwNode?.kind === "number") st.strokeWidth = Math.max(0, lwNode.value);
43567
- const lcNode = yield* resolveEvaluationNode(dictGet(gsDict, "LC"));
43798
+ const lcNode = yield* resolveEvaluationNode(yield* lookupEvaluationDictionary(gsDict, "LC", true), true);
43568
43799
  if (lcNode?.kind === "number" && (lcNode.value === 0 || lcNode.value === 1 || lcNode.value === 2)) {
43569
43800
  st.lineCap = lcNode.value;
43570
43801
  }
43571
- const ljNode = yield* resolveEvaluationNode(dictGet(gsDict, "LJ"));
43802
+ const ljNode = yield* resolveEvaluationNode(yield* lookupEvaluationDictionary(gsDict, "LJ", true), true);
43572
43803
  if (ljNode?.kind === "number" && (ljNode.value === 0 || ljNode.value === 1 || ljNode.value === 2)) {
43573
43804
  st.lineJoin = ljNode.value;
43574
43805
  }
43575
- const mlNode = yield* resolveEvaluationNode(dictGet(gsDict, "ML"));
43806
+ const mlNode = yield* resolveEvaluationNode(yield* lookupEvaluationDictionary(gsDict, "ML", true), true);
43576
43807
  if (mlNode?.kind === "number" && mlNode.value > 0) {
43577
43808
  st.miterLimit = mlNode.value;
43578
43809
  }
43579
- const dArr = yield* resolveEvaluationArray(dictGet(gsDict, "D"), true);
43810
+ const dArr = yield* resolveEvaluationArray(yield* lookupEvaluationDictionary(gsDict, "D", true), true);
43580
43811
  if (dArr && (dArr.storedItems?.length ?? dArr.items.length) >= 2) {
43581
- let pair = dArr.items;
43582
- if (dArr.storedItems) {
43583
- pair = [];
43584
- let position = dArr.storedItems.position;
43585
- for (let i = 0; i < 2; i++) {
43586
- const reply = yield { kind: "array-item", items: dArr.storedItems, position };
43587
- if (!reply || !("kind" in reply) || reply.kind !== "resolved" || reply.node?.kind !== "array") throw new TypeError("Expected dash state record");
43588
- const [next, value] = reply.node.items;
43589
- if (next?.kind !== "number" || !value) throw new TypeError("Expected dash state value");
43590
- position = next.value;
43591
- pair.push(value);
43592
- }
43593
- }
43812
+ const pair = yield* evaluationArrayPrefix(dArr, 2);
43594
43813
  const patArr = yield* resolveEvaluationArray(pair[0], true);
43595
43814
  const phaseNode = yield* resolveEvaluationNode(pair[1]);
43596
43815
  if (patArr && params.geometryStorage) {
@@ -43611,9 +43830,10 @@ function* evaluateContentSteps(params) {
43611
43830
  st.dashPhase = phaseNode?.kind === "number" ? phaseNode.value : 0;
43612
43831
  }
43613
43832
  }
43614
- const fontArr = yield* resolveEvaluationArray(dictGet(gsDict, "Font"));
43615
- if (fontArr && fontArr.items.length >= 2) {
43616
- const fSizeNode = yield* resolveEvaluationNode(fontArr.items[1]);
43833
+ const fontArr = yield* resolveEvaluationArray(yield* lookupEvaluationDictionary(gsDict, "Font", true), true);
43834
+ if (fontArr && (fontArr.storedItems?.length ?? fontArr.items.length) >= 2) {
43835
+ const pair = yield* evaluationArrayPrefix(fontArr, 2);
43836
+ const fSizeNode = yield* resolveEvaluationNode(pair[1]);
43617
43837
  if (fSizeNode?.kind === "number") st.fontSize = fSizeNode.value;
43618
43838
  const gsFontKey = `__ExtGS_Font_${ops[0].decoded}`;
43619
43839
  const gsFontResources = {
@@ -43626,7 +43846,7 @@ function* evaluateContentSteps(params) {
43626
43846
  entries: [
43627
43847
  {
43628
43848
  key: { kind: "name", decoded: gsFontKey, rawBytes: new Uint8Array(0) },
43629
- value: fontArr.items[0]
43849
+ value: pair[0]
43630
43850
  }
43631
43851
  ]
43632
43852
  }
@@ -43665,8 +43885,8 @@ function* evaluateContentSteps(params) {
43665
43885
  const st = curState();
43666
43886
  if (!st.fillPatternName || !resources) return false;
43667
43887
  if (depth >= 8) throw new PdfError("E_LIMIT", "Pattern nesting exceeds the form depth limit");
43668
- const patterns = yield* resolveEvaluationDict(dictGet(resources, "Pattern"));
43669
- const pattern = patterns && (yield* resolveEvaluationNode(dictGet(patterns, st.fillPatternName)));
43888
+ const patterns = yield* resolveEvaluationDict(dictGet(resources, "Pattern"), ["Resources", "Pattern"]);
43889
+ const pattern = patterns && (yield* resolveEvaluationNode(yield* lookupEvaluationDictionary(patterns, st.fillPatternName)));
43670
43890
  const dict = pattern?.kind === "stream" ? pattern.dict : pattern?.kind === "dict" ? pattern : void 0;
43671
43891
  if (!dict) return false;
43672
43892
  const nums = function* (key, fallback) {
@@ -43749,7 +43969,7 @@ function* evaluateContentSteps(params) {
43749
43969
  const iy1 = Math.ceil((Math.max(...corners.map((p) => p[1])) - box[1]) / yStep) - 1;
43750
43970
  if ((ix1 - ix0 + 1) * (iy1 - iy0 + 1) > 2e4) throw new PdfError("E_LIMIT", "Pattern tile count exceeds 20000");
43751
43971
  const nodes = { stream: pattern };
43752
- const patternResources = (yield* resolveEvaluationDict(dictGet(dict, "Resources"))) ?? resources;
43972
+ const patternResources = (yield* resolveEvaluationDict(dictGet(dict, "Resources"), ["Resources"])) ?? resources;
43753
43973
  const patternFonts = [patternResources, ...activeFonts];
43754
43974
  for (let iy = iy0; iy <= iy1; iy++) {
43755
43975
  for (let ix = ix0; ix <= ix1; ix++) {
@@ -43783,7 +44003,7 @@ function* evaluateContentSteps(params) {
43783
44003
  const isolated = isolation?.kind === "boolean" && isolation.value;
43784
44004
  const compositeGroup = !maskGroup && groupType?.kind === "name" && groupType.decoded === "Transparency" && (isolated || st.fillAlpha !== 1 || !!st.softMask || !!st.blendMode && st.blendMode !== "Normal" && st.blendMode !== "Compatible");
43785
44005
  const formNodes = { stream: form };
43786
- const formResDict = (yield* resolveEvaluationDict(dictGet(form.dict, "Resources"))) ?? activeResources;
44006
+ const formResDict = (yield* resolveEvaluationDict(dictGet(form.dict, "Resources"), ["Resources"])) ?? activeResources;
43787
44007
  const formFonts = [formResDict, ...activeFonts];
43788
44008
  let nextCtm = [...st.ctm];
43789
44009
  const matArr = yield* resolveEvaluationArray(dictGet(form.dict, "Matrix"));
@@ -43860,7 +44080,7 @@ function* evaluateContentSteps(params) {
43860
44080
  let resolvedMcid = node.mcid;
43861
44081
  let resolvedActualText = node.actualText ?? node.storedActualText;
43862
44082
  if (typeof node.properties === "string" && activeResources) {
43863
- const propsMap = yield* resolveEvaluationDict(dictGet(activeResources, "Properties"), ["Properties"]);
44083
+ const propsMap = yield* resolveEvaluationDict(dictGet(activeResources, "Properties"), ["Resources", "Properties"]);
43864
44084
  const propRefOrNode = yield* lookupEvaluationDictionary(propsMap, node.properties);
43865
44085
  if (propRefOrNode) {
43866
44086
  const propDict = yield* resolveEvaluationDict(propRefOrNode);
@@ -44044,7 +44264,7 @@ function* evaluateContentSteps(params) {
44044
44264
  case "xobject": {
44045
44265
  const st = curState();
44046
44266
  if (activeResources) {
44047
- const xobjDict = yield* resolveEvaluationDict(dictGet(activeResources, "XObject"), ["XObject"]);
44267
+ const xobjDict = yield* resolveEvaluationDict(dictGet(activeResources, "XObject"), ["Resources", "XObject"]);
44048
44268
  const xobjNode = xobjDict ? yield* resolveEvaluationNode(yield* lookupEvaluationDictionary(xobjDict, node.name)) : void 0;
44049
44269
  if (xobjNode?.kind === "stream") {
44050
44270
  if (!(yield* optionalContentVisibilitySteps(dictGet(xobjNode.dict, "OC")))) {
@@ -44635,10 +44855,10 @@ function* visible(node) {
44635
44855
  function* preparePageAppearanceSteps(pageDict, pageRes, evalResourcesDict, hideAnnotations = false, onAllocation) {
44636
44856
  onAllocation?.(64 * pageRes.entries.length);
44637
44857
  for (const entry of pageRes.entries) {
44638
- const sub = yield* resolveDict3(entry.value, [entry.key.decoded]);
44858
+ const sub = yield* resolveDict3(entry.value, ["Resources", entry.key.decoded]);
44639
44859
  if (sub) {
44640
44860
  onAllocation?.(64 + sub.entries.length * 64);
44641
- const shareBacking = entry.key.decoded === "XObject" || entry.key.decoded === "Properties";
44861
+ const shareBacking = entry.key.decoded !== "Font";
44642
44862
  const clonedSub = sub.storedEntries ? shareBacking ? { ...sub, entries: [] } : yield { kind: "dictionary-merge", destination: sub } : cosDict({});
44643
44863
  if (!sub.storedEntries) for (const se of sub.entries) dictSet(clonedSub, se.key.decoded, se.value);
44644
44864
  dictSet(evalResourcesDict, entry.key.decoded, clonedSub);
@@ -44682,12 +44902,12 @@ function* preparePageAppearanceSteps(pageDict, pageRes, evalResourcesDict, hideA
44682
44902
  if (hasContent === true) {
44683
44903
  onAllocation?.(2048);
44684
44904
  renderedApStream = true;
44685
- const apRes = yield* resolveDict3(dictGet(apN.dict, "Resources"));
44905
+ const apRes = yield* resolveDict3(dictGet(apN.dict, "Resources"), ["Resources"]);
44686
44906
  if (apRes) {
44687
44907
  for (const subKey of ["Font", "XObject", "ExtGState", "ColorSpace", "Pattern", "Shading"]) {
44688
- const srcSub = yield* resolveDict3(dictGet(apRes, subKey), [subKey]);
44908
+ const srcSub = yield* resolveDict3(dictGet(apRes, subKey), ["Resources", subKey]);
44689
44909
  if (!srcSub) continue;
44690
- let dstSub = yield* resolveDict3(dictGet(evalResourcesDict, subKey), [subKey]);
44910
+ let dstSub = yield* resolveDict3(dictGet(evalResourcesDict, subKey), ["Resources", subKey]);
44691
44911
  if (!dstSub) {
44692
44912
  onAllocation?.(64);
44693
44913
  dstSub = cosDict({});
@@ -48314,24 +48534,13 @@ function* svgImageSteps(image, pageHeight) {
48314
48534
  }
48315
48535
  function* svgPathDataSteps(segments, height, matrix2) {
48316
48536
  let work = 0;
48317
- const dParts = [];
48318
- const point = (x, y) => matrix2 ? `${matrix2[0] * x + matrix2[2] * y + matrix2[4]} ${height - matrix2[1] * x - matrix2[3] * y - matrix2[5]}` : `${x} ${height - y}`;
48319
- for (const seg of segments) {
48537
+ const parts = [];
48538
+ for (const segment of segments) {
48320
48539
  if (++work % 16384 === 0) yield;
48321
- if (seg.kind === "move") {
48322
- dParts.push(`M ${point(seg.x, seg.y)}`);
48323
- } else if (seg.kind === "line") {
48324
- dParts.push(`L ${point(seg.x, seg.y)}`);
48325
- } else if (seg.kind === "cubic") {
48326
- dParts.push(`C ${point(seg.x1, seg.y1)} ${point(seg.x2, seg.y2)} ${point(seg.x, seg.y)}`);
48327
- } else if (seg.kind === "rect") {
48328
- if (matrix2) dParts.push(`M ${point(seg.x, seg.y)} L ${point(seg.x + seg.width, seg.y)} L ${point(seg.x + seg.width, seg.y + seg.height)} L ${point(seg.x, seg.y + seg.height)} Z`);
48329
- else dParts.push(`M ${seg.x} ${height - seg.y} h ${seg.width} v ${-seg.height} h ${-seg.width} Z`);
48330
- } else if (seg.kind === "close") {
48331
- dParts.push("Z");
48332
- }
48540
+ const part = svgPathSegment(segment, height, matrix2);
48541
+ if (part !== void 0) parts.push(part);
48333
48542
  }
48334
- return dParts.join(" ");
48543
+ return parts.join(" ");
48335
48544
  }
48336
48545
  function* renderDisplayListToSvgSteps(displayList, options = {}) {
48337
48546
  const baseScale = options.scale ?? (options.dpi ? options.dpi / 72 : 1);
@@ -48641,6 +48850,139 @@ function renderPdfPageToPng(pdfBytes, pageIndex = 0, options) {
48641
48850
  while (!next.done) next = steps.next();
48642
48851
  return next.value;
48643
48852
  }
48853
+ async function* encodeSvgPathPaintChunks(original, pageHeight, options = {}) {
48854
+ const { signal } = options;
48855
+ signal?.throwIfAborted();
48856
+ const chunkBytes = options.chunkBytes ?? 16384, maximum10 = options.maxOutputBytes ?? Infinity, scale = options.scale ?? 1;
48857
+ if (!Number.isSafeInteger(chunkBytes) || chunkBytes < 1) throw new RangeError("Invalid SVG paint chunk size");
48858
+ for (const value of [maximum10, options.maxSegments ?? Infinity, options.maxDashEntries ?? Infinity]) if (value !== Infinity && (!Number.isSafeInteger(value) || value < 0)) throw new RangeError("Invalid SVG paint limit");
48859
+ if (!Number.isFinite(scale) || scale <= 0) throw new RangeError("Invalid SVG paint scale");
48860
+ if (original.kind === "glyph" && (original.value.renderMode === 3 || !original.value.outline && !original.value.unicode.trim())) return;
48861
+ const p = original.kind === "glyph" ? glyphPaint(original.value) : original.value;
48862
+ const segmentCount = p.storedSegments?.count ?? p.segments.length, dashCount = p.storedDash?.length ?? p.dashArray?.length ?? 0;
48863
+ if (!Number.isSafeInteger(segmentCount) || segmentCount < 0 || !Number.isSafeInteger(dashCount) || dashCount < 0) throw new RangeError("Invalid SVG paint record count");
48864
+ if (segmentCount > (options.maxSegments ?? Infinity) || dashCount > (options.maxDashEntries ?? Infinity)) throw new PdfError("E_LIMIT", "SVG paint record limit exceeded");
48865
+ if (!segmentCount) return;
48866
+ let emitted = 0, work = 0;
48867
+ const encoder = new TextEncoder();
48868
+ function* bytes(bytes2) {
48869
+ if (bytes2.length > maximum10 - emitted || !Number.isSafeInteger(emitted + bytes2.length)) throw new PdfError("E_LIMIT", "SVG paint output byte limit exceeded");
48870
+ emitted += bytes2.length;
48871
+ for (let at = 0; at < bytes2.length; at += chunkBytes) {
48872
+ signal?.throwIfAborted();
48873
+ yield bytes2.slice(at, at + chunkBytes);
48874
+ }
48875
+ }
48876
+ function* text(value) {
48877
+ for (let at = 0; at < value.length; ) {
48878
+ let end = Math.min(at + 2048, value.length);
48879
+ if (end < value.length && value.charCodeAt(end - 1) >= 55296 && value.charCodeAt(end - 1) <= 56319) end--;
48880
+ yield* bytes(encoder.encode(value.slice(at, end)));
48881
+ at = end;
48882
+ }
48883
+ }
48884
+ async function checkpoint() {
48885
+ signal?.throwIfAborted();
48886
+ if (++work % 64 === 0) {
48887
+ await new Promise((resolve2) => setTimeout(resolve2, 0));
48888
+ signal?.throwIfAborted();
48889
+ }
48890
+ }
48891
+ async function* dashes(factor) {
48892
+ if (!p.storedDash) {
48893
+ for (const value of p.dashArray ?? []) {
48894
+ await checkpoint();
48895
+ yield value * factor;
48896
+ }
48897
+ return;
48898
+ }
48899
+ const source = p.storedDash;
48900
+ if (!Number.isSafeInteger(source.position) || source.position < 0 || !Number.isSafeInteger(source.position + dashCount * 8)) throw new RangeError("Invalid SVG dash position");
48901
+ for (let at = 0; at < dashCount; at += 512) {
48902
+ await checkpoint();
48903
+ const length = Math.min(512, dashCount - at) * 8, data = (await source.storage.read(source.position + at * 8, length, signal ? { signal } : void 0)).slice();
48904
+ if (data.length !== length) throw new Error("Incomplete SVG dash pattern");
48905
+ const view = new DataView(data.buffer, data.byteOffset, data.length);
48906
+ for (let i = 0; i < length; i += 8) {
48907
+ await checkpoint();
48908
+ yield view.getFloat64(i, true) * factor;
48909
+ }
48910
+ }
48911
+ }
48912
+ const prepared = p.strokeColor ? prepareStroke(p, scale) : void 0;
48913
+ let outlineStroke = false;
48914
+ if (prepared) for await (const value of dashes(1)) {
48915
+ if (value === 0) {
48916
+ outlineStroke = true;
48917
+ break;
48918
+ }
48919
+ }
48920
+ const matrix2 = prepared && (prepared.matrix[0] !== 1 || prepared.matrix[1] !== 0 || prepared.matrix[2] !== 0 || prepared.matrix[3] !== 1) ? prepared.matrix : void 0, inverse = matrix2 ? inverseStrokeMatrix(matrix2) : void 0;
48921
+ const transform = inverse && matrix2 ? ` transform="matrix(${matrix2[0]} ${-matrix2[1]} ${-matrix2[2]} ${matrix2[3]} ${matrix2[4]} ${pageHeight - matrix2[5]})"` : "";
48922
+ const fill = p.fillColor ? `rgb(${Math.round(p.fillColor.r * 255)},${Math.round(p.fillColor.g * 255)},${Math.round(p.fillColor.b * 255)})` : "none", stroke = p.strokeColor && prepared ? `rgb(${Math.round(p.strokeColor.r * 255)},${Math.round(p.strokeColor.g * 255)},${Math.round(p.strokeColor.b * 255)})` : "none";
48923
+ const label = original.kind === "glyph" ? ` aria-label="${escapeXmlText(original.value.unicode)}"` : "";
48924
+ let painted = false;
48925
+ if (!outlineStroke || p.fillColor) {
48926
+ painted = true;
48927
+ yield* text(` <path${label}${transform} d="`);
48928
+ for await (const chunk of encodeSvgPathDataChunks(p.storedSegments ?? p.segments, inverse ? 0 : pageHeight, { ...options, ...inverse ? { matrix: inverse } : {} })) yield* bytes(chunk);
48929
+ yield* text(`" fill="${fill}"${p.fillRule === "evenodd" ? ' fill-rule="evenodd"' : ""}${p.fillAlpha !== void 0 && p.fillAlpha < 1 ? ` fill-opacity="${p.fillAlpha}"` : ""} stroke="${outlineStroke ? "none" : stroke}"${p.strokeAlpha !== void 0 && p.strokeAlpha < 1 ? ` stroke-opacity="${p.strokeAlpha}"` : ""}`);
48930
+ yield* text(p.strokeWidth <= 0 && !matrix2 && !dashCount ? ' stroke-width="1" vector-effect="non-scaling-stroke"' : ` stroke-width="${prepared?.width ?? p.strokeWidth}"`);
48931
+ yield* text(`${p.lineCap === 1 ? ' stroke-linecap="round"' : p.lineCap === 2 ? ' stroke-linecap="square"' : ""}${p.lineJoin === 1 ? ' stroke-linejoin="round"' : p.lineJoin === 2 ? ' stroke-linejoin="bevel"' : ""}${p.miterLimit !== void 0 && p.miterLimit !== 10 ? ` stroke-miterlimit="${p.miterLimit}"` : ""}`);
48932
+ if (!outlineStroke && prepared && dashCount) {
48933
+ yield* text(' stroke-dasharray="');
48934
+ let first = true;
48935
+ const factor = p.storedDash ? prepared.storedDashScale : 1;
48936
+ if (p.storedDash) {
48937
+ for await (const value of dashes(factor)) {
48938
+ yield* text(`${first ? "" : " "}${value}`);
48939
+ first = false;
48940
+ }
48941
+ } else for (const value of prepared.dashArray ?? []) {
48942
+ await checkpoint();
48943
+ yield* text(`${first ? "" : " "}${value}`);
48944
+ first = false;
48945
+ }
48946
+ yield* text('"');
48947
+ }
48948
+ if (!outlineStroke && prepared?.dashPhase) yield* text(` stroke-dashoffset="${prepared.dashPhase}"`);
48949
+ yield* text("/>");
48950
+ }
48951
+ if (outlineStroke) {
48952
+ const io = { signal }, iterator = strokeContourPoints(p, pageHeight, scale, 0, 0, 0, 0, io)[Symbol.iterator]();
48953
+ let firstPoint = true, started = false, contours = 0;
48954
+ try {
48955
+ for (; ; ) {
48956
+ await checkpoint();
48957
+ const next = iterator.next();
48958
+ if (next.done) break;
48959
+ if (io.pathRequest) {
48960
+ const request = io.pathRequest;
48961
+ io.pathRequest = void 0;
48962
+ await request();
48963
+ }
48964
+ const point = next.value;
48965
+ if (point === null) continue;
48966
+ if (!started) {
48967
+ yield* text(`${painted ? "\n" : ""} <path${label} d="`);
48968
+ started = true;
48969
+ }
48970
+ if (firstPoint && contours) yield* text(" ");
48971
+ if (point) {
48972
+ yield* text(`${firstPoint ? "M" : " L"} ${point[0] / scale} ${point[1] / scale}`);
48973
+ firstPoint = false;
48974
+ } else {
48975
+ yield* text(" Z");
48976
+ firstPoint = true;
48977
+ contours++;
48978
+ }
48979
+ }
48980
+ } finally {
48981
+ iterator.return?.();
48982
+ }
48983
+ if (started) yield* text(`" fill="${stroke}" fill-opacity="${p.strokeAlpha ?? 1}"/>`);
48984
+ }
48985
+ }
48644
48986
 
48645
48987
  // packages/pdf-ast/src/render/retained-page-pixels.ts
48646
48988
  async function renderRetainedPagePixels(page2, storage, options = {}) {
@@ -48728,7 +49070,7 @@ async function renderRetainedPagePixels(page2, storage, options = {}) {
48728
49070
 
48729
49071
  // packages/pdf-ast/src/cos/range-parser.ts
48730
49072
  import { listenForAbort as listenForAbort2 } from "@poe-platform/safe-fs/contracts";
48731
- function limit(value, name) {
49073
+ function limit2(value, name) {
48732
49074
  const result = value ?? Infinity;
48733
49075
  if (result !== Infinity && (!Number.isSafeInteger(result) || result < 0)) throw new RangeError(`Invalid ${name}`);
48734
49076
  return result;
@@ -48832,16 +49174,16 @@ async function readValue(lexer, depth, nodes, options) {
48832
49174
  return value;
48833
49175
  }
48834
49176
  async function parseCosRangeValue(source, offset, options = {}) {
48835
- const depth = limit(options.maxRecursionDepth, "maxRecursionDepth");
48836
- const nodes = limit(options.maxNodes, "maxNodes");
48837
- const maxTokenBytes = limit(options.maxTokenBytes, "maxTokenBytes");
49177
+ const depth = limit2(options.maxRecursionDepth, "maxRecursionDepth");
49178
+ const nodes = limit2(options.maxNodes, "maxNodes");
49179
+ const maxTokenBytes = limit2(options.maxTokenBytes, "maxTokenBytes");
48838
49180
  const lexer = new CosRangeLexer(source, { compactNumbers: options.compactNumbers ?? false, compactKeywords: options.compactKeywords ?? false, ...options.onBackingError ? { onBackingError: options.onBackingError } : {}, start: offset, ...options.end === void 0 ? {} : { end: options.end }, maxTokenBytes, ...options.signal ? { signal: options.signal } : {} });
48839
49181
  return { value: await readValue(lexer, depth, nodes, options), offset: lexer.offset };
48840
49182
  }
48841
49183
  async function parseCosRangeObject(source, offset, options = {}) {
48842
- const depth = limit(options.maxRecursionDepth, "maxRecursionDepth");
48843
- const nodes = limit(options.maxNodes, "maxNodes");
48844
- const tokenBytes = limit(options.maxTokenBytes, "maxTokenBytes");
49184
+ const depth = limit2(options.maxRecursionDepth, "maxRecursionDepth");
49185
+ const nodes = limit2(options.maxNodes, "maxNodes");
49186
+ const tokenBytes = limit2(options.maxTokenBytes, "maxTokenBytes");
48845
49187
  const { signal } = options;
48846
49188
  signal?.throwIfAborted();
48847
49189
  const lexer = new CosRangeLexer(source, { compactNumbers: options.compactNumbers ?? false, compactKeywords: options.compactKeywords ?? false, ...options.onBackingError ? { onBackingError: options.onBackingError } : {}, start: offset, maxTokenBytes: tokenBytes, ...signal ? { signal } : {} });
@@ -48863,7 +49205,13 @@ async function parseCosRangeObject(source, offset, options = {}) {
48863
49205
  const first = await byteAt(source, start, signal);
48864
49206
  if (first === 13) start += await byteAt(source, start + 1, signal) === 10 ? 2 : 1;
48865
49207
  else if (first === 10) start++;
48866
- const entry = dictGet(value, "Length");
49208
+ let entry;
49209
+ try {
49210
+ entry = value.storedEntries ? await readPdfDictionaryValue(value, "Length", signal, { preserveDeferred: true }) : dictGet(value, "Length");
49211
+ } catch (error) {
49212
+ options.onBackingError?.(error);
49213
+ throw error;
49214
+ }
48867
49215
  const length = await resolveStreamLength(entry, options);
48868
49216
  signal?.throwIfAborted();
48869
49217
  if (length !== void 0 && Number.isSafeInteger(length) && length >= 0 && length <= source.size - start) {
@@ -49365,45 +49713,73 @@ var PdfReferenceSet = class {
49365
49713
  // packages/pdf-ast/src/cos/filter-dictionary.ts
49366
49714
  async function resolvePdfStreamDictionary(dict, lookup, active, options) {
49367
49715
  let remaining = options.maxNodes ?? 65536;
49368
- const resolve2 = async (node, depth) => {
49369
- if (--remaining < 0 || depth >= (options.maxRecursionDepth ?? 100)) throw new PdfError("E_LIMIT", "PDF filter resolution limit exceeded");
49370
- if (node.kind === "ref") {
49371
- if (active.has(node.objectNumber)) throw new PdfError("E_PARSE", "PDF filter reference cycle");
49372
- const object = await lookup(node);
49373
- if (!object) throw new PdfError("E_PARSE", "Missing PDF filter reference");
49374
- active.add(node.objectNumber);
49375
- try {
49376
- return await resolve2(object.value, depth + 1);
49377
- } finally {
49378
- active.delete(node.objectNumber);
49716
+ const resolve2 = async (node, depth, parent = options.referencePath) => {
49717
+ let path = parent, owned, failed = false;
49718
+ try {
49719
+ for (; ; ) {
49720
+ options.signal?.throwIfAborted();
49721
+ if (--remaining < 0 || depth >= (options.maxRecursionDepth ?? 100)) throw new PdfError("E_LIMIT", "PDF filter resolution limit exceeded");
49722
+ if (node.kind !== "ref") break;
49723
+ if (active.has(node.objectNumber)) throw new PdfError("E_PARSE", "PDF filter reference cycle");
49724
+ for (let ancestor = path; ancestor; ancestor = ancestor.parent) {
49725
+ const seen = await ancestor.seen.has(node.objectNumber).catch((error) => {
49726
+ options.onBackingError?.(error);
49727
+ throw error;
49728
+ });
49729
+ if (seen) throw new PdfError("E_PARSE", "PDF filter reference cycle");
49730
+ }
49731
+ owned ??= { seen: new PdfReferenceSet(options.referenceStorage, options.maxTraversalStagingBytes, options.signal), parent, depth: 0 };
49732
+ path = owned;
49733
+ const object = await lookup(node, path);
49734
+ if (!object) throw new PdfError("E_PARSE", "Missing PDF filter reference");
49735
+ await path.seen.add(node.objectNumber).catch((error) => {
49736
+ options.onBackingError?.(error);
49737
+ throw error;
49738
+ });
49739
+ path.depth++;
49740
+ depth++;
49741
+ node = object.value;
49742
+ if (path.depth % 256 === 0) await new Promise((resolve3) => setTimeout(resolve3, 0));
49379
49743
  }
49380
- }
49381
- if (node.kind === "array") {
49382
- const items = [];
49383
- const { storedItems, ...ordinary } = node;
49384
- if (storedItems) {
49385
- const reader = readStoredItems(storedItems, options.signal);
49386
- try {
49387
- for (; ; ) {
49388
- const item = await reader.next().catch((error) => {
49389
- options.onBackingError?.(error);
49390
- throw error;
49391
- });
49392
- if (item.done) break;
49393
- items.push(await resolve2(item.value, depth + 1));
49744
+ if (node.kind === "array") {
49745
+ const items = [];
49746
+ const { storedItems, ...ordinary } = node;
49747
+ if (storedItems) {
49748
+ const reader = readStoredItems(storedItems, options.signal);
49749
+ try {
49750
+ for (; ; ) {
49751
+ const item = await reader.next().catch((error) => {
49752
+ options.onBackingError?.(error);
49753
+ throw error;
49754
+ });
49755
+ if (item.done) break;
49756
+ items.push(await resolve2(item.value, depth + 1, path));
49757
+ }
49758
+ } finally {
49759
+ await reader.return();
49394
49760
  }
49395
- } finally {
49396
- await reader.return();
49761
+ } else for (const item of node.items) items.push(await resolve2(item, depth + 1, path));
49762
+ return { ...ordinary, items };
49763
+ }
49764
+ if (node.kind === "dict") {
49765
+ const entries2 = [];
49766
+ for (const entry of node.entries) entries2.push({ ...entry, value: await resolve2(entry.value, depth + 1, path) });
49767
+ return { ...node, entries: entries2 };
49768
+ }
49769
+ return node;
49770
+ } catch (error) {
49771
+ failed = true;
49772
+ throw error;
49773
+ } finally {
49774
+ try {
49775
+ await owned?.seen.close();
49776
+ } catch (error) {
49777
+ if (!failed) {
49778
+ options.onBackingError?.(error);
49779
+ await Promise.reject(error);
49397
49780
  }
49398
- } else for (const item of node.items) items.push(await resolve2(item, depth + 1));
49399
- return { ...ordinary, items };
49400
- }
49401
- if (node.kind === "dict") {
49402
- const entries2 = [];
49403
- for (const entry of node.entries) entries2.push({ ...entry, value: await resolve2(entry.value, depth + 1) });
49404
- return { ...node, entries: entries2 };
49781
+ }
49405
49782
  }
49406
- return node;
49407
49783
  };
49408
49784
  const entries = [];
49409
49785
  for (const entry of dict.entries) entries.push(["Filter", "F", "DecodeParms", "DP", "Type"].includes(entry.key.decoded) ? { ...entry, value: await resolve2(entry.value, 0) } : entry);
@@ -49556,7 +49932,7 @@ var PdfObjectReader = class {
49556
49932
  // Recursive length/object-stream lookups share one failure identity so an
49557
49933
  // outer recovery pass cannot mistake a caller-storage error for PDF syntax.
49558
49934
  backingFailures = /* @__PURE__ */ new WeakMap();
49559
- lengthPaths = /* @__PURE__ */ new WeakMap();
49935
+ referencePaths = /* @__PURE__ */ new WeakMap();
49560
49936
  repairedOffsets = /* @__PURE__ */ new Map();
49561
49937
  options;
49562
49938
  capacity;
@@ -49586,10 +49962,7 @@ var PdfObjectReader = class {
49586
49962
  const object2 = await this.load(objectNumber, generationNumber, /* @__PURE__ */ new Set());
49587
49963
  if (object2?.value.kind !== "dict" || !object2.stream) throw new PdfError("E_PARSE", "Expected an indexed PDF stream");
49588
49964
  const active = /* @__PURE__ */ new Set([objectNumber]);
49589
- return { object: object2, dict: await resolvePdfStreamDictionary(object2.value, (ref) => this.load(ref.objectNumber, ref.generationNumber, active), active, { ...this.options, onBackingError: (error) => {
49590
- this.backingFailures.set(active, { error });
49591
- this.options.onBackingError?.(error);
49592
- } }) };
49965
+ return { object: object2, dict: await this.resolveStreamDictionary(object2.value, active) };
49593
49966
  });
49594
49967
  const span = object.stream;
49595
49968
  const input = () => this.source.stream(span.start, span.end - span.start, this.options.signal);
@@ -49597,16 +49970,36 @@ var PdfObjectReader = class {
49597
49970
  const decodeOptions = { ...this.options, stopBeforeImageCodec: options.stopBeforeImageCodec ?? false, raw: options.raw ?? false };
49598
49971
  yield* security ? decodePdfEncryptedStreamChunks(security, objectNumber, generationNumber, dict, input, decodeOptions) : decodePdfStreamChunks(dict, input, decodeOptions);
49599
49972
  }
49973
+ resolveStreamDictionary(dict, active) {
49974
+ return resolvePdfStreamDictionary(dict, async (ref, path) => {
49975
+ const parent = this.referencePaths.get(active);
49976
+ this.referencePaths.set(active, path);
49977
+ try {
49978
+ return await this.load(ref.objectNumber, ref.generationNumber, active);
49979
+ } finally {
49980
+ if (parent) this.referencePaths.set(active, parent);
49981
+ else this.referencePaths.delete(active);
49982
+ }
49983
+ }, active, {
49984
+ ...this.options,
49985
+ referenceStorage: this.storage,
49986
+ referencePath: this.referencePaths.get(active),
49987
+ onBackingError: (error) => {
49988
+ this.backingFailures.set(active, { error });
49989
+ this.options.onBackingError?.(error);
49990
+ }
49991
+ });
49992
+ }
49600
49993
  /** A stream-valued /Length is invalid as a length, but its references still
49601
49994
  * need cycle, admission and backing-error validation. Walk those discarded
49602
49995
  * values in source order instead of retaining one parser and AST per link. */
49603
49996
  async resolveLength(reference, active) {
49604
49997
  const path = {
49605
49998
  seen: new PdfReferenceSet(this.storage, this.options.maxTraversalStagingBytes, this.options.signal),
49606
- parent: this.lengthPaths.get(active),
49999
+ parent: this.referencePaths.get(active),
49607
50000
  depth: 0
49608
50001
  };
49609
- this.lengthPaths.set(active, path);
50002
+ this.referencePaths.set(active, path);
49610
50003
  let next = reference, result, failed = false;
49611
50004
  try {
49612
50005
  while (next) {
@@ -49637,8 +50030,8 @@ var PdfObjectReader = class {
49637
50030
  failed = true;
49638
50031
  throw error;
49639
50032
  } finally {
49640
- if (path.parent) this.lengthPaths.set(active, path.parent);
49641
- else this.lengthPaths.delete(active);
50033
+ if (path.parent) this.referencePaths.set(active, path.parent);
50034
+ else this.referencePaths.delete(active);
49642
50035
  try {
49643
50036
  await path.seen.close();
49644
50037
  } catch (error) {
@@ -49654,7 +50047,7 @@ var PdfObjectReader = class {
49654
50047
  this.options.signal?.throwIfAborted();
49655
50048
  if (active.has(objectNumber)) throw new PdfError("E_PARSE", "PDF indirect object cycle");
49656
50049
  let depth = active.size;
49657
- for (let path = this.lengthPaths.get(active); path; path = path.parent) {
50050
+ for (let path = this.referencePaths.get(active); path; path = path.parent) {
49658
50051
  let seen;
49659
50052
  try {
49660
50053
  seen = await path.seen.has(objectNumber);
@@ -49717,7 +50110,15 @@ var PdfObjectReader = class {
49717
50110
  this.repairedOffsets.set(objectNumber, object.span.start);
49718
50111
  }
49719
50112
  if (this.options.encryption && objectNumber !== this.options.encryptionObjectNumber) {
49720
- let type = object.stream && object.value.kind === "dict" ? dictGet(object.value, "Type") : void 0;
50113
+ let type;
50114
+ if (object.stream && object.value.kind === "dict") {
50115
+ try {
50116
+ type = object.value.storedEntries ? await readPdfDictionaryValue(object.value, "Type", this.options.signal, { preserveDeferred: true }) : dictGet(object.value, "Type");
50117
+ } catch (error) {
50118
+ onBackingError(error);
50119
+ throw error;
50120
+ }
50121
+ }
49721
50122
  if (type?.kind === "ref") type = (await this.load(type.objectNumber, type.generationNumber, active))?.value;
49722
50123
  const value = await decryptPdfObjectStrings(
49723
50124
  this.options.encryption,
@@ -49774,10 +50175,7 @@ var PdfObjectReader = class {
49774
50175
  active.add(number);
49775
50176
  let dict;
49776
50177
  try {
49777
- dict = await resolvePdfStreamDictionary(object.value, (ref) => this.load(ref.objectNumber, ref.generationNumber, active), active, { ...this.options, onBackingError: (error) => {
49778
- this.backingFailures.set(active, { error });
49779
- this.options.onBackingError?.(error);
49780
- } });
50178
+ dict = await this.resolveStreamDictionary(object.value, active);
49781
50179
  } finally {
49782
50180
  active.delete(number);
49783
50181
  }
@@ -50774,16 +51172,16 @@ async function renderRetainedMesh(context, dict, type, input, settings, storage,
50774
51172
 
50775
51173
  // packages/pdf-ast/src/extract/retained-color.ts
50776
51174
  import { readBytes as readBytes14 } from "@poe-platform/safe-fs/contracts";
50777
- function limit2(value, fallback, name) {
51175
+ function limit3(value, fallback, name) {
50778
51176
  const result = value ?? fallback;
50779
51177
  if (result !== Infinity && (!Number.isSafeInteger(result) || result < 0)) throw new RangeError(`Invalid ${name}`);
50780
51178
  return Math.min(result, Number.MAX_SAFE_INTEGER);
50781
51179
  }
50782
51180
  function createRetainedColorAccess(document2, storage, options, storedFunctions = false) {
50783
- const maximum10 = limit2(options.maxWorkingBytes, Infinity, "maxWorkingBytes");
50784
- const maxStaging = limit2(options.maxStagingBytes, Infinity, "maxStagingBytes");
50785
- const maxNodes = limit2(options.maxNodes, 65536, "maxNodes");
50786
- const maxDepth = limit2(options.maxDepth, document2.depthLimit, "maxDepth");
51181
+ const maximum10 = limit3(options.maxWorkingBytes, Infinity, "maxWorkingBytes");
51182
+ const maxStaging = limit3(options.maxStagingBytes, Infinity, "maxStagingBytes");
51183
+ const maxNodes = limit3(options.maxNodes, 65536, "maxNodes");
51184
+ const maxDepth = limit3(options.maxDepth, document2.depthLimit, "maxDepth");
50787
51185
  const chunkBytes = options.chunkBytes ?? 4096;
50788
51186
  if (!Number.isSafeInteger(chunkBytes) || chunkBytes <= 0) throw new RangeError("Invalid chunkBytes");
50789
51187
  let used = 0;
@@ -50833,11 +51231,11 @@ function createRetainedColorAccess(document2, storage, options, storedFunctions
50833
51231
  options.onAllocation?.(bytes);
50834
51232
  used += bytes;
50835
51233
  }
50836
- async function resolve2(value) {
51234
+ async function resolve2(value, path) {
50837
51235
  options.signal?.throwIfAborted();
50838
51236
  if (++nodes > maxNodes) throw new PdfError("E_LIMIT", "PDF color node limit exceeded");
50839
51237
  charge(64);
50840
- const resolved = await document2.lookup(value);
51238
+ const resolved = await document2.lookup(value, void 0, path);
50841
51239
  options.signal?.throwIfAborted();
50842
51240
  if (!resolved) return void 0;
50843
51241
  if (resolved.stream && resolved.reference && resolved.value.kind === "dict") {
@@ -50848,6 +51246,11 @@ function createRetainedColorAccess(document2, storage, options, storedFunctions
50848
51246
  if (resolved.value.kind === "name") charge(resolved.value.decoded.length * 2);
50849
51247
  return resolved.value;
50850
51248
  }
51249
+ async function resource(request) {
51250
+ const map = await resolve2(dictGet(request.resources, request.category), ["Resources", request.category]);
51251
+ const dictionary = map?.kind === "stream" ? map.dict : map;
51252
+ return dictionary?.kind === "dict" ? readPdfDictionaryValue(dictionary, request.name, options.signal) : void 0;
51253
+ }
50851
51254
  function contents(stream) {
50852
51255
  const reference = streams.get(stream);
50853
51256
  return reference ? document2.objects.decodeStream(reference.objectNumber, reference.generationNumber) : decodePdfStreamChunks(stream.dict, async function* () {
@@ -51033,7 +51436,7 @@ function createRetainedColorAccess(document2, storage, options, storedFunctions
51033
51436
  maxRecursionDepth: maxDepth
51034
51437
  });
51035
51438
  options.signal?.throwIfAborted();
51036
- return { resolve: resolve2, decode: decode2, contents, snapshot, snapshotColor, snapshotFunction, charge, context, maxDepth, functionSources, storedFunctions, async close() {
51439
+ return { resolve: resolve2, resource, decode: decode2, contents, snapshot, snapshotColor, snapshotFunction, charge, context, maxDepth, functionSources, storedFunctions, async close() {
51037
51440
  await functionBacking?.close();
51038
51441
  } };
51039
51442
  }
@@ -51052,7 +51455,7 @@ async function openRetainedImageColor(document2, node, resources, storage, optio
51052
51455
  }
51053
51456
  }
51054
51457
  async function resolveImageColor(access, node, resources, options) {
51055
- const { resolve: resolve2, decode: decode2, snapshot, snapshotFunction, charge, context, maxDepth, functionSources } = access;
51458
+ const { resolve: resolve2, resource, decode: decode2, snapshot, snapshotFunction, charge, context, maxDepth, functionSources } = access;
51056
51459
  const work = imageColorSpaceProgram(node, resources, maxDepth);
51057
51460
  try {
51058
51461
  let step = work.next();
@@ -51064,6 +51467,9 @@ async function resolveImageColor(access, node, resources, options) {
51064
51467
  case "resolve":
51065
51468
  result = await resolve2(request.node);
51066
51469
  break;
51470
+ case "resource":
51471
+ result = await resource(request);
51472
+ break;
51067
51473
  case "palette": {
51068
51474
  if (!Number.isSafeInteger(request.maxBytes) || request.maxBytes < 0) throw new PdfError("E_LIMIT", "PDF palette size limit exceeded");
51069
51475
  if (request.node.kind === "stream") result = await decode2(request.node, request.maxBytes);
@@ -51122,7 +51528,7 @@ async function runFunctionSteps(work, signal) {
51122
51528
  }
51123
51529
  }
51124
51530
  async function runRetainedColorProgram(document2, storage, options, work) {
51125
- const { resolve: resolve2, decode: decode2, snapshot, snapshotFunction, context, charge, functionSources, close } = createRetainedColorAccess(document2, storage, options, true);
51531
+ const { resolve: resolve2, resource, decode: decode2, snapshot, snapshotFunction, context, charge, functionSources, close } = createRetainedColorAccess(document2, storage, options, true);
51126
51532
  let failed = false;
51127
51533
  try {
51128
51534
  let step = work.next();
@@ -51131,6 +51537,7 @@ async function runRetainedColorProgram(document2, storage, options, work) {
51131
51537
  const request = step.value;
51132
51538
  let result;
51133
51539
  if (request.kind === "resolve") result = await resolve2(request.node);
51540
+ else if (request.kind === "resource") result = await resource(request);
51134
51541
  else if (request.kind === "decode") result = await decode2(request.stream, request.length, request.start);
51135
51542
  else if (request.kind === "calibrated") result = createCalibratedColorSpace(context, request.family, await snapshot(request.parameters));
51136
51543
  else if (request.kind === "transfer") {
@@ -51205,7 +51612,7 @@ async function renderRetainedShading(document2, node, settings, storage, options
51205
51612
  import { PagedStorage as PagedStorage3 } from "@poe-platform/safe-fs/storage";
51206
51613
 
51207
51614
  // packages/pdf-ast/src/extract/retained-jpeg.ts
51208
- function limit3(value, name) {
51615
+ function limit4(value, name) {
51209
51616
  if (value === void 0 || value === Infinity) return Number.MAX_SAFE_INTEGER;
51210
51617
  if (!Number.isSafeInteger(value) || value < 0) throw new RangeError(`Invalid ${name}`);
51211
51618
  return value;
@@ -51230,8 +51637,8 @@ var PdfRetainedJpeg = class _PdfRetainedJpeg {
51230
51637
  static async open(source, options = {}) {
51231
51638
  const controller = new AbortController();
51232
51639
  options = { ...options, signal: options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal };
51233
- const maximum10 = limit3(options.maxWorkingBytes, "maxWorkingBytes");
51234
- const outputMaximum = limit3(options.maxOutputBytes, "maxOutputBytes");
51640
+ const maximum10 = limit4(options.maxWorkingBytes, "maxWorkingBytes");
51641
+ const outputMaximum = limit4(options.maxOutputBytes, "maxOutputBytes");
51235
51642
  let allocated = 0;
51236
51643
  let parsing = true;
51237
51644
  function charge(bytes) {
@@ -51421,7 +51828,7 @@ async function* tileDescriptors(tiles, storage, signal) {
51421
51828
  }
51422
51829
  }
51423
51830
  }
51424
- function limit4(value, name) {
51831
+ function limit5(value, name) {
51425
51832
  if (value === void 0 || value === Infinity) return Number.MAX_SAFE_INTEGER;
51426
51833
  if (!Number.isSafeInteger(value) || value < 0) throw new RangeError(`Invalid ${name}`);
51427
51834
  return value;
@@ -51455,8 +51862,8 @@ var PdfRetainedJpx = class _PdfRetainedJpx {
51455
51862
  ...options,
51456
51863
  signal: options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal
51457
51864
  };
51458
- const maximum10 = limit4(options.maxWorkingBytes, "maxWorkingBytes");
51459
- const outputMaximum = limit4(options.maxOutputBytes, "maxOutputBytes");
51865
+ const maximum10 = limit5(options.maxWorkingBytes, "maxWorkingBytes");
51866
+ const outputMaximum = limit5(options.maxOutputBytes, "maxOutputBytes");
51460
51867
  let allocated = 0;
51461
51868
  let allocationFailure;
51462
51869
  function charge(bytes) {
@@ -51683,7 +52090,7 @@ var PdfRetainedJpx = class _PdfRetainedJpx {
51683
52090
  };
51684
52091
 
51685
52092
  // packages/pdf-ast/src/extract/retained-jbig2.ts
51686
- function limit5(value, name) {
52093
+ function limit6(value, name) {
51687
52094
  if (value === void 0 || value === Infinity) return Number.MAX_SAFE_INTEGER;
51688
52095
  if (!Number.isSafeInteger(value) || value < 0) throw new RangeError(`Invalid ${name}`);
51689
52096
  return value;
@@ -51710,8 +52117,8 @@ var PdfRetainedJbig2 = class _PdfRetainedJbig2 {
51710
52117
  static async open(source, fallbackWidth, fallbackHeight, options = {}) {
51711
52118
  const controller = new AbortController();
51712
52119
  options = { ...options, signal: options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal };
51713
- const maximum10 = limit5(options.maxWorkingBytes, "maxWorkingBytes");
51714
- const outputMaximum = limit5(options.maxOutputBytes, "maxOutputBytes");
52120
+ const maximum10 = limit6(options.maxWorkingBytes, "maxWorkingBytes");
52121
+ const outputMaximum = limit6(options.maxOutputBytes, "maxOutputBytes");
51715
52122
  let allocated = 0;
51716
52123
  function charge(bytes) {
51717
52124
  if (!Number.isSafeInteger(bytes) || bytes < 0 || bytes > maximum10 - allocated) throw new PdfError("E_LIMIT", "JBIG2 working byte limit exceeded");
@@ -51880,7 +52287,7 @@ var PdfRetainedJbig2 = class _PdfRetainedJbig2 {
51880
52287
 
51881
52288
  // packages/pdf-ast/src/extract/retained-mask.ts
51882
52289
  import { readBytes as readBytes15 } from "@poe-platform/safe-fs/contracts";
51883
- function limit6(value, name) {
52290
+ function limit7(value, name) {
51884
52291
  if (value === void 0 || value === Infinity) return Number.MAX_SAFE_INTEGER;
51885
52292
  if (!Number.isSafeInteger(value) || value < 0) throw new RangeError(`Invalid ${name}`);
51886
52293
  return value;
@@ -51890,8 +52297,8 @@ async function* applyRetainedImageMask(rows, width, height, mask, options) {
51890
52297
  if (!Number.isSafeInteger(value) || value <= 0) throw new RangeError(`Invalid ${name}`);
51891
52298
  }
51892
52299
  if (options.mode !== "soft" && options.mode !== "explicit") throw new RangeError("Invalid mask mode");
51893
- const workingLimit = limit6(options.maxWorkingBytes, "maxWorkingBytes");
51894
- const outputLimit = limit6(options.maxOutputBytes, "maxOutputBytes");
52300
+ const workingLimit = limit7(options.maxWorkingBytes, "maxWorkingBytes");
52301
+ const outputLimit = limit7(options.maxOutputBytes, "maxOutputBytes");
51895
52302
  const pixels = width * height;
51896
52303
  const maskPixels = mask.width * mask.height;
51897
52304
  if (!Number.isSafeInteger(pixels) || pixels > Math.floor(outputLimit / 4)) throw new PdfError("E_LIMIT", "PDF masked output byte limit exceeded");
@@ -51933,7 +52340,7 @@ async function* applyRetainedImageMask(rows, width, height, mask, options) {
51933
52340
  }
51934
52341
 
51935
52342
  // packages/pdf-ast/src/extract/retained-samples.ts
51936
- function limit7(value, name) {
52343
+ function limit8(value, name) {
51937
52344
  if (value === void 0 || value === Infinity) return Number.MAX_SAFE_INTEGER;
51938
52345
  if (!Number.isSafeInteger(value) || value < 0) throw new RangeError(`Invalid ${name}`);
51939
52346
  return value;
@@ -51942,8 +52349,8 @@ async function* decodeRetainedSampleRows(source, width, height, bitsPerComponent
51942
52349
  for (const [name, value] of [["width", width], ["height", height], ["bitsPerComponent", bitsPerComponent], ["components", color.components]]) {
51943
52350
  if (!Number.isSafeInteger(value) || value <= 0) throw new RangeError(`Invalid ${name}`);
51944
52351
  }
51945
- const workingLimit = limit7(options.maxWorkingBytes, "maxWorkingBytes");
51946
- const outputLimit = limit7(options.maxOutputBytes, "maxOutputBytes");
52352
+ const workingLimit = limit8(options.maxWorkingBytes, "maxWorkingBytes");
52353
+ const outputLimit = limit8(options.maxOutputBytes, "maxOutputBytes");
51947
52354
  const pixels = width * height;
51948
52355
  if (!Number.isSafeInteger(pixels) || pixels > Math.floor(outputLimit / 4)) throw new PdfError("E_LIMIT", "PDF sample output byte limit exceeded");
51949
52356
  options.signal?.throwIfAborted();
@@ -55030,8 +55437,8 @@ async function resolveRetainedFont(document2, storage, resources, name, options
55030
55437
  }
55031
55438
  let value;
55032
55439
  if (step.value.kind === "resolve") {
55033
- const retained = await document2.lookup(step.value.node, options.resourceStorage ? { dictionaryStorage: options.resourceStorage, storedDictionaryKeys: ["Font", "XObject", "Properties"], storeRootDictionary: step.value.storeRootDictionary ?? false, arrayStorage: options.resourceStorage, storedArrayKeys: ["Widths", "W", "Differences"], storeRootArray: step.value.storeRootArray ?? false } : {});
55034
- value = retained?.value;
55440
+ const retained = await document2.lookup(step.value.node, options.resourceStorage ? { dictionaryStorage: options.resourceStorage, deferDictionaryValues: true, containerStorage: options.resourceStorage, stringStorage: options.resourceStorage, storedDictionaryKeys: ["Font", "XObject", "Properties"], storedDictionaryPaths: [["Resources", "*"]], storeRootDictionary: step.value.storeRootDictionary ?? false, arrayStorage: options.resourceStorage, storedArrayKeys: ["Widths", "W", "Differences"], storeRootArray: step.value.storeRootArray ?? false } : {}, step.value.arrayPathPrefix);
55441
+ value = retained ? await materializeResourceValue(retained.value, signal) : void 0;
55035
55442
  if (retained?.stream) {
55036
55443
  if (retained.value.kind !== "dict" || !retained.reference) throw new PdfError("E_PARSE", "Font stream has no retained identity");
55037
55444
  allocation.admit(256);
@@ -55223,9 +55630,9 @@ async function* evaluateRetainedContentSteps(document2, content, params, storage
55223
55630
  admitted += bytes;
55224
55631
  }
55225
55632
  const identities = /* @__PURE__ */ new WeakMap();
55226
- async function resolve2(node, storeRootArray = false, arrayPathPrefix) {
55633
+ async function resolve2(node, storeRootArray = false, arrayPathPrefix, storeRootDictionary = false) {
55227
55634
  charge(64);
55228
- const value = await document2.lookup(node, storeRootArray && options.imageStorage ? { arrayStorage: options.imageStorage, storeRootArray: true } : void 0, arrayPathPrefix);
55635
+ const value = await document2.lookup(node, void 0, arrayPathPrefix, storeRootDictionary, storeRootArray ? options.imageStorage : void 0);
55229
55636
  signal?.throwIfAborted();
55230
55637
  if (value?.stream && value.reference && value.value.kind === "dict") {
55231
55638
  charge(128);
@@ -55364,14 +55771,14 @@ async function* evaluateRetainedContentSteps(document2, content, params, storage
55364
55771
  }
55365
55772
  case "resolve":
55366
55773
  case "catalog":
55367
- reply = { kind: "resolved", node: await resolve2(request.kind === "catalog" ? document2.crossReference.rootRef : request.node, request.kind === "resolve" && request.storeRootArray, request.kind === "resolve" ? request.arrayPathPrefix : void 0) };
55774
+ reply = { kind: "resolved", node: await resolve2(request.kind === "catalog" ? document2.crossReference.rootRef : request.node, request.kind === "resolve" && request.storeRootArray, request.kind === "resolve" ? request.arrayPathPrefix : void 0, request.kind === "resolve" && request.storeRootDictionary) };
55368
55775
  break;
55369
55776
  case "dash-array": {
55370
55777
  reply = { kind: "dash-array", value: await storeDashArray(request.array, request.storage, request.resolveReferences ? resolve2 : async (node) => node, signal) };
55371
55778
  break;
55372
55779
  }
55373
55780
  case "dictionary-value":
55374
- reply = { kind: "resolved", node: await readPdfDictionaryValue(request.dict, request.key, signal) };
55781
+ reply = { kind: "resolved", node: await readPdfDictionaryValue(request.dict, request.key, signal, request.preserveDeferred ? { preserveDeferred: true } : {}) };
55375
55782
  break;
55376
55783
  case "array-reference":
55377
55784
  reply = { kind: "resolved", node: cosBool(await memberships.has(request.items, request.objectNumber)) };
@@ -56189,7 +56596,7 @@ function* generateDocumentFormAppearancesSteps(doc) {
56189
56596
  function generateDocumentFormAppearances(doc) {
56190
56597
  return drainWork(generateDocumentFormAppearancesSteps(doc));
56191
56598
  }
56192
- function decodeXmlEntities(text) {
56599
+ function decodeFormDataEntities(text) {
56193
56600
  let out = "";
56194
56601
  let i = 0;
56195
56602
  while (i < text.length) {
@@ -56253,7 +56660,7 @@ function extractAttributeValue(tagBody, attrName) {
56253
56660
  if (quote !== '"' && quote !== "'") return void 0;
56254
56661
  const end = tagBody.indexOf(quote, after + 1);
56255
56662
  if (end === -1) return void 0;
56256
- return decodeXmlEntities(tagBody.slice(after + 1, end));
56663
+ return decodeFormDataEntities(tagBody.slice(after + 1, end));
56257
56664
  }
56258
56665
  function parseXfdfString(text, out) {
56259
56666
  const fieldStack = [];
@@ -56285,7 +56692,7 @@ function parseXfdfString(text, out) {
56285
56692
  } else if (tagName === "value" && !selfClosing && fieldStack.length > 0) {
56286
56693
  const closeVal = text.indexOf("</value>", pos);
56287
56694
  if (closeVal !== -1) {
56288
- const rawVal = decodeXmlEntities(text.slice(pos, closeVal));
56695
+ const rawVal = decodeFormDataEntities(text.slice(pos, closeVal));
56289
56696
  const fullFieldName = fieldStack.filter(Boolean).join(".");
56290
56697
  if (fullFieldName) {
56291
56698
  if (rawVal === "Off") out.set(fullFieldName, false);
@@ -56493,9 +56900,9 @@ function parseFormDataBytes(bytes) {
56493
56900
  if (line.startsWith("FieldType:")) {
56494
56901
  curType = line.slice("FieldType:".length).trim();
56495
56902
  } else if (line.startsWith("FieldName:")) {
56496
- curName = decodeXmlEntities(line.slice("FieldName:".length).trim());
56903
+ curName = decodeFormDataEntities(line.slice("FieldName:".length).trim());
56497
56904
  } else if (line.startsWith("FieldValue:") && curName) {
56498
- const val = decodeXmlEntities(line.slice("FieldValue:".length).trim());
56905
+ const val = decodeFormDataEntities(line.slice("FieldValue:".length).trim());
56499
56906
  if (val === "Yes" || val === "On") {
56500
56907
  out.set(curName, true);
56501
56908
  } else if (val === "Off" || val === "false" || curType === "Button" && val === "") {
@@ -58655,7 +59062,7 @@ async function openStoredPdfObjectReader(store, storage, options) {
58655
59062
  validateIdentity(number, generation);
58656
59063
  const object = number === 0 ? void 0 : await store.get(number);
58657
59064
  if (object?.generationNumber !== generation || !object.stream || object.value.kind !== "dict") throw new PdfError("E_PARSE", "Expected an indexed PDF stream");
58658
- const dict = await resolvePdfStreamDictionary(object.value, (ref) => reader.get(ref.objectNumber, ref.generationNumber), /* @__PURE__ */ new Set([number]), options);
59065
+ const dict = await resolvePdfStreamDictionary(object.value, (ref) => reader.get(ref.objectNumber, ref.generationNumber), /* @__PURE__ */ new Set([number]), { ...options, referenceStorage: storage });
58659
59066
  const snapshot = object.stream;
58660
59067
  async function* input() {
58661
59068
  for await (const bytes of snapshot.chunks) {
@@ -59079,10 +59486,10 @@ async function* streamRawTextChunks(glyphs, storage, options = {}) {
59079
59486
  }
59080
59487
  })();
59081
59488
  const encoder = new TextEncoder(), buffer = new Uint8Array(chunkBytes);
59082
- function* encode3(text, offset = 0, limit10 = text.length) {
59083
- while (offset < limit10) {
59084
- let end = Math.min(limit10, offset + Math.floor(chunkBytes / 3));
59085
- if (end < limit10 && text.charCodeAt(end - 1) >= 55296 && text.charCodeAt(end - 1) <= 56319 && text.charCodeAt(end) >= 56320 && text.charCodeAt(end) <= 57343) end--;
59489
+ function* encode3(text, offset = 0, limit11 = text.length) {
59490
+ while (offset < limit11) {
59491
+ let end = Math.min(limit11, offset + Math.floor(chunkBytes / 3));
59492
+ if (end < limit11 && text.charCodeAt(end - 1) >= 55296 && text.charCodeAt(end - 1) <= 56319 && text.charCodeAt(end) >= 56320 && text.charCodeAt(end) <= 57343) end--;
59086
59493
  const { read, written } = encoder.encodeInto(text.slice(offset, end), buffer);
59087
59494
  offset += read;
59088
59495
  yield buffer.subarray(0, written);
@@ -59471,15 +59878,15 @@ var PdfStagedOutputs = class _PdfStagedOutputs {
59471
59878
  static async create(storage, input, options = {}) {
59472
59879
  const chunkBytes = maximum7(options.chunkBytes, 65536);
59473
59880
  if (chunkBytes < 32 || chunkBytes === Number.MAX_SAFE_INTEGER) throw new RangeError("PDF output chunkBytes must be finite and at least 32");
59474
- const limit10 = maximum7(options.maxStagingBytes, Infinity);
59881
+ const limit11 = maximum7(options.maxStagingBytes, Infinity);
59475
59882
  const nameLimit = maximum7(options.maxNameChars, 1048576);
59476
59883
  const { signal } = options;
59477
59884
  let written = 0;
59478
- const names = new PdfNameIndex(storage, () => limit10 - written, signal);
59885
+ const names = new PdfNameIndex(storage, () => limit11 - written, signal);
59479
59886
  let data;
59480
59887
  let index2;
59481
59888
  const charge = (size) => {
59482
- if (size > limit10 - written - names.stagedBytes) throw new PdfError("E_LIMIT", "PDF output staging byte limit exceeded");
59889
+ if (size > limit11 - written - names.stagedBytes) throw new PdfError("E_LIMIT", "PDF output staging byte limit exceeded");
59483
59890
  written += size;
59484
59891
  };
59485
59892
  async function* records2() {
@@ -59513,7 +59920,7 @@ var PdfStagedOutputs = class _PdfStagedOutputs {
59513
59920
  }
59514
59921
  }
59515
59922
  try {
59516
- data = await PdfFileSource.fromStream(storage.fs, storage.directory, records2(), { chunkBytes, cacheBytes: chunkBytes, maxInputBytes: limit10, ...signal ? { signal } : {} });
59923
+ data = await PdfFileSource.fromStream(storage.fs, storage.directory, records2(), { chunkBytes, cacheBytes: chunkBytes, maxInputBytes: limit11, ...signal ? { signal } : {} });
59517
59924
  await names.close();
59518
59925
  const source = data;
59519
59926
  async function* rows() {
@@ -59530,7 +59937,7 @@ var PdfStagedOutputs = class _PdfStagedOutputs {
59530
59937
  runEntries: 64,
59531
59938
  chunkBytes: indexChunk,
59532
59939
  cacheBytes: indexChunk,
59533
- maxStagingBytes: limit10 - data.size,
59940
+ maxStagingBytes: limit11 - data.size,
59534
59941
  ...signal ? { signal } : {}
59535
59942
  });
59536
59943
  return new _PdfStagedOutputs(data, index2, signal, nameLimit);
@@ -59624,7 +60031,7 @@ async function markedText(document2, page2, mcid, storage, options) {
59624
60031
  };
59625
60032
  var boundary = boundary2, scan = scan2;
59626
60033
  source = await PdfFileSource.fromStream(storage.fs, storage.directory, input(), { chunkBytes, cacheBytes: chunkBytes, maxInputBytes: maximum10, ...signal ? { signal } : {} });
59627
- const resources = (await document2.lookup(dictGet(page2, "Resources")))?.value;
60034
+ const resources = (await document2.lookup(dictGet(page2, "Resources"), void 0, ["Resources"]))?.value;
59628
60035
  const properties = resources?.kind === "dict" ? (await document2.lookup(dictGet(resources, "Properties"), void 0, ["Properties"]))?.value : void 0;
59629
60036
  const operators2 = parseContentRangeOperators(source, storage, { chunkBytes, maxStagingBytes: maximum10 - source.size, ...signal ? { signal } : {} });
59630
60037
  let pending, matching = false, inText = false, part = 0, recorded = false;
@@ -60054,7 +60461,7 @@ async function* walkRetainedImages(document2, storage, options) {
60054
60461
  let imageIndex = 0;
60055
60462
  let stagedBytes = 0;
60056
60463
  async function dictionary(node, resourceKey) {
60057
- const value = await document2.lookup(node, void 0, resourceKey ? [resourceKey] : void 0);
60464
+ const value = await document2.lookup(node, void 0, resourceKey ? resourceKey === "Resources" ? [resourceKey] : ["Resources", resourceKey] : void 0);
60058
60465
  return value?.value.kind === "dict" && !value.stream ? value.value : void 0;
60059
60466
  }
60060
60467
  async function number(node, fallback) {
@@ -60174,7 +60581,7 @@ async function* walkRetainedImages(document2, storage, options) {
60174
60581
  try {
60175
60582
  yield* content(
60176
60583
  document2.objects.decodeStream(ref.objectNumber, ref.generationNumber),
60177
- await dictionary(dictGet(target.value, "Resources")) ?? activeResources,
60584
+ await dictionary(dictGet(target.value, "Resources"), "Resources") ?? activeResources,
60178
60585
  transform,
60179
60586
  active,
60180
60587
  depth + 1
@@ -60204,7 +60611,7 @@ async function* walkRetainedImages(document2, storage, options) {
60204
60611
  if (value.stream && value.reference) {
60205
60612
  yield* content(
60206
60613
  document2.objects.decodeStream(value.reference.objectNumber, value.reference.generationNumber),
60207
- await dictionary(dictGet(value.value, "Resources")) ?? inherited,
60614
+ await dictionary(dictGet(value.value, "Resources"), "Resources") ?? inherited,
60208
60615
  identity,
60209
60616
  /* @__PURE__ */ new Set([value.reference.objectNumber]),
60210
60617
  0
@@ -60213,8 +60620,8 @@ async function* walkRetainedImages(document2, storage, options) {
60213
60620
  }
60214
60621
  try {
60215
60622
  yield* content(page2.streamContents(), resources, identity, /* @__PURE__ */ new Set(), 0);
60216
- const patterns = await dictionary(dictGet(resources, "Pattern"));
60217
- if (patterns) for (const entry of patterns.entries) yield* auxiliary(entry.value, resources);
60623
+ const patterns = await dictionary(dictGet(resources, "Pattern"), "Pattern");
60624
+ if (patterns) for await (const entry of readPdfDictionaryEntries(patterns, options.signal)) yield* auxiliary(entry.value, resources);
60218
60625
  const fonts = await dictionary(dictGet(resources, "Font"), "Font");
60219
60626
  if (fonts) for await (const entry of readPdfDictionaryEntries(fonts, options.signal)) {
60220
60627
  const font = await dictionary(entry.value);
@@ -60222,7 +60629,7 @@ async function* walkRetainedImages(document2, storage, options) {
60222
60629
  const subtype = (await document2.lookup(dictGet(font, "Subtype")))?.value;
60223
60630
  if (subtype?.kind !== "name" || subtype.decoded !== "Type3") continue;
60224
60631
  const procedures = await dictionary(dictGet(font, "CharProcs"));
60225
- const inherited = await dictionary(dictGet(font, "Resources")) ?? resources;
60632
+ const inherited = await dictionary(dictGet(font, "Resources"), "Resources") ?? resources;
60226
60633
  if (procedures) for (const entry2 of procedures.entries) yield* auxiliary(entry2.value, inherited);
60227
60634
  }
60228
60635
  const annotations = (await document2.lookup(dictGet(page2.dict, "Annots")))?.value;
@@ -60270,7 +60677,7 @@ async function* walkRetainedFonts(document2, storage, options) {
60270
60677
  if (!Number.isSafeInteger(first) || first < 1 || last !== Infinity && (!Number.isSafeInteger(last) || last < first)) throw new RangeError("Invalid PDF font page range");
60271
60678
  let failed = false;
60272
60679
  async function dictionary(node, resourceKey) {
60273
- const resolved = await document2.lookup(node, void 0, resourceKey ? [resourceKey] : void 0);
60680
+ const resolved = await document2.lookup(node, void 0, resourceKey ? resourceKey === "Resources" ? [resourceKey] : ["Resources", resourceKey] : void 0);
60274
60681
  return resolved?.value.kind === "dict" && !resolved.stream ? resolved.value : void 0;
60275
60682
  }
60276
60683
  async function* font(node, key, depth) {
@@ -60300,7 +60707,7 @@ async function* walkRetainedFonts(document2, storage, options) {
60300
60707
  const enc = (await document2.lookup(dictGet(value, "Encoding")))?.value;
60301
60708
  const encoding = enc?.kind === "name" ? enc.decoded === "WinAnsiEncoding" ? "WinAnsi" : enc.decoded === "MacRomanEncoding" ? "MacRoman" : enc.decoded === "StandardEncoding" ? "Standard" : enc.decoded : enc?.kind === "dict" ? "Custom" : "Builtin";
60302
60709
  yield { name, type, encoding, embedded, unicode: Boolean(dictGet(value, "ToUnicode")), ...node.kind === "ref" ? { reference: node } : {} };
60303
- if (raw === "Type3") yield* resources(await dictionary(dictGet(value, "Resources")), depth + 1);
60710
+ if (raw === "Type3") yield* resources(await dictionary(dictGet(value, "Resources"), "Resources"), depth + 1);
60304
60711
  }
60305
60712
  async function* resources(value, depth) {
60306
60713
  options.signal?.throwIfAborted();
@@ -60308,8 +60715,8 @@ async function* walkRetainedFonts(document2, storage, options) {
60308
60715
  if (depth > options.maxDepth) throw new PdfError("E_LIMIT", "PDF font resource depth limit exceeded");
60309
60716
  const fonts = await dictionary(dictGet(value, "Font"), "Font");
60310
60717
  if (fonts) for await (const entry of readPdfDictionaryEntries(fonts, options.signal)) yield* font(entry.value, entry.key.decoded, depth);
60311
- const states = await dictionary(dictGet(value, "ExtGState"));
60312
- if (states) for (const entry of states.entries) {
60718
+ const states = await dictionary(dictGet(value, "ExtGState"), "ExtGState");
60719
+ if (states) for await (const entry of readPdfDictionaryEntries(states, options.signal)) {
60313
60720
  const state = await dictionary(entry.value);
60314
60721
  const gsFont = state ? (await document2.lookup(dictGet(state, "Font")))?.value : void 0;
60315
60722
  if (gsFont?.kind === "array" && gsFont.items[0]) yield* font(gsFont.items[0], `ExtGS_${entry.key.decoded}`, depth);
@@ -60323,7 +60730,7 @@ async function* walkRetainedFonts(document2, storage, options) {
60323
60730
  if (!resolved?.stream || resolved.value.kind !== "dict") continue;
60324
60731
  const subtype = (await document2.lookup(dictGet(resolved.value, "Subtype")))?.value;
60325
60732
  if (key === "XObject" && !(subtype?.kind === "name" && subtype.decoded === "Form")) continue;
60326
- yield* resources(await dictionary(dictGet(resolved.value, "Resources")), depth + 1);
60733
+ yield* resources(await dictionary(dictGet(resolved.value, "Resources"), "Resources"), depth + 1);
60327
60734
  }
60328
60735
  }
60329
60736
  }
@@ -60341,10 +60748,10 @@ async function* walkRetainedFonts(document2, storage, options) {
60341
60748
  for (const key of ["N", "R", "D"]) {
60342
60749
  const ap = await document2.lookup(dictGet(appearance, key));
60343
60750
  if (ap?.value.kind !== "dict") continue;
60344
- if (ap.stream) yield* resources(await dictionary(dictGet(ap.value, "Resources")), 0);
60751
+ if (ap.stream) yield* resources(await dictionary(dictGet(ap.value, "Resources"), "Resources"), 0);
60345
60752
  else for (const entry of ap.value.entries) {
60346
60753
  const stream = await document2.lookup(entry.value);
60347
- if (stream?.stream && stream.value.kind === "dict") yield* resources(await dictionary(dictGet(stream.value, "Resources")), 0);
60754
+ if (stream?.stream && stream.value.kind === "dict") yield* resources(await dictionary(dictGet(stream.value, "Resources"), "Resources"), 0);
60348
60755
  }
60349
60756
  }
60350
60757
  }
@@ -60432,7 +60839,7 @@ async function* walkRetainedAttachments(document2, storage, options) {
60432
60839
  }
60433
60840
 
60434
60841
  // packages/pdf-ast/src/retained-document.ts
60435
- function limit8(value, name, fallback) {
60842
+ function limit9(value, name, fallback) {
60436
60843
  const result = value ?? fallback;
60437
60844
  if (result !== Infinity && (!Number.isSafeInteger(result) || result < 0)) throw new RangeError(`Invalid ${name}`);
60438
60845
  return result;
@@ -60461,9 +60868,9 @@ var PdfRetainedDocument = class _PdfRetainedDocument {
60461
60868
  walks = /* @__PURE__ */ new Set();
60462
60869
  closing;
60463
60870
  static async open(source, storage, options = {}) {
60464
- const maxPages = limit8(options.maxPages, "maxPages", Infinity);
60465
- const maxPageTreeDepth = limit8(options.maxPageTreeDepth, "maxPageTreeDepth", 100);
60466
- const maxTraversalStagingBytes = limit8(options.maxTraversalStagingBytes, "maxTraversalStagingBytes", Infinity);
60871
+ const maxPages = limit9(options.maxPages, "maxPages", Infinity);
60872
+ const maxPageTreeDepth = limit9(options.maxPageTreeDepth, "maxPageTreeDepth", 100);
60873
+ const maxTraversalStagingBytes = limit9(options.maxTraversalStagingBytes, "maxTraversalStagingBytes", Infinity);
60467
60874
  const controller = new AbortController();
60468
60875
  const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;
60469
60876
  const configured = { ...options, signal, maxPages, maxPageTreeDepth, maxTraversalStagingBytes };
@@ -60473,9 +60880,9 @@ var PdfRetainedDocument = class _PdfRetainedDocument {
60473
60880
  /** Read an editable caller-backed graph without normalizing it through a PDF
60474
60881
  * save. The caller retains ownership of the store and its object identities. */
60475
60882
  static async openStore(store, storage, options) {
60476
- const maxPages = limit8(options.maxPages, "maxPages", Infinity);
60477
- const maxPageTreeDepth = limit8(options.maxPageTreeDepth, "maxPageTreeDepth", 100);
60478
- const maxTraversalStagingBytes = limit8(options.maxTraversalStagingBytes, "maxTraversalStagingBytes", Infinity);
60883
+ const maxPages = limit9(options.maxPages, "maxPages", Infinity);
60884
+ const maxPageTreeDepth = limit9(options.maxPageTreeDepth, "maxPageTreeDepth", 100);
60885
+ const maxTraversalStagingBytes = limit9(options.maxTraversalStagingBytes, "maxTraversalStagingBytes", Infinity);
60479
60886
  const controller = new AbortController();
60480
60887
  const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;
60481
60888
  const configured = { ...options, signal, maxPages, maxPageTreeDepth, maxTraversalStagingBytes };
@@ -60487,8 +60894,10 @@ var PdfRetainedDocument = class _PdfRetainedDocument {
60487
60894
  this.options.signal?.throwIfAborted();
60488
60895
  }
60489
60896
  /** Resolve a bounded reference chain, retaining the final stream's identity. */
60490
- async lookup(node, arrays = this.options.valueArrays ?? {}, arrayPathPrefix) {
60897
+ async lookup(node, arrays = this.options.valueArrays ?? {}, arrayPathPrefix, storeRootDictionary = false, rootArrayStorage) {
60491
60898
  this.assertOpen();
60899
+ if (rootArrayStorage) arrays = { ...arrays, arrayStorage: arrays.arrayStorage ?? rootArrayStorage, storeRootArray: true };
60900
+ if (storeRootDictionary && arrays.dictionaryStorage) arrays = { ...arrays, storeRootDictionary: true };
60492
60901
  if (arrayPathPrefix) arrays = {
60493
60902
  ...arrays,
60494
60903
  arrayPathPrefix,
@@ -61064,7 +61473,7 @@ var PdfRetainedPage = class {
61064
61473
  for (const key of keys) {
61065
61474
  const entry = dictGet(current, key);
61066
61475
  if (values.has(key) || !entry) continue;
61067
- const value = (await this.document.lookup(entry))?.value;
61476
+ const value = (await this.document.lookup(entry, void 0, key === "Resources" ? ["Resources"] : void 0))?.value;
61068
61477
  if (key.endsWith("Box")) {
61069
61478
  const rectangle = await box(value, this.document);
61070
61479
  if (!rectangle) continue;
@@ -61281,6 +61690,82 @@ async function* encodeRetainedPng(width, height, input, storage, options = {}) {
61281
61690
  }
61282
61691
  }
61283
61692
 
61693
+ // packages/pdf-ast/src/render/svg-image-stream.ts
61694
+ async function* encodeSvgImageChunks(image, pageHeight, storage, options = {}) {
61695
+ const { signal } = options;
61696
+ signal?.throwIfAborted();
61697
+ if (!image.decodedRgba && !image.storedRgba) return;
61698
+ const { width, height } = image, chunkBytes = options.chunkBytes ?? 65536, maximum10 = options.maxOutputBytes ?? Infinity;
61699
+ if (![width, height].every((value) => Number.isSafeInteger(value) && value > 0 && value <= 4294967295) || !Number.isSafeInteger(width * height * 4)) throw new PdfError("E_LIMIT", "SVG image dimension limit exceeded");
61700
+ if (!Number.isSafeInteger(chunkBytes) || chunkBytes < 1) throw new RangeError("Invalid SVG image chunk size");
61701
+ if (maximum10 !== Infinity && (!Number.isSafeInteger(maximum10) || maximum10 < 0)) throw new RangeError("Invalid SVG output byte limit");
61702
+ const [a, b, c, d, e, f] = image.matrix;
61703
+ const prefix = `<image width="1" height="1" preserveAspectRatio="none" transform="matrix(${a} ${-b} ${-c} ${d} ${e + c} ${pageHeight - f - d})" href="data:image/png;base64,`, suffix = '"/>';
61704
+ const encoder = new TextEncoder(), header2 = encoder.encode(prefix), tail = encoder.encode(suffix), available = maximum10 - header2.length - tail.length;
61705
+ const pngMaximum = maximum10 === Infinity ? Infinity : Math.floor(available / 4) * 3;
61706
+ if (pngMaximum < 57) throw new PdfError("E_LIMIT", "SVG image output byte limit exceeded");
61707
+ let outputBytes = 0;
61708
+ function* emit(bytes) {
61709
+ if (bytes.length > maximum10 - outputBytes) throw new PdfError("E_LIMIT", "SVG image output byte limit exceeded");
61710
+ outputBytes += bytes.length;
61711
+ for (let at = 0; at < bytes.length; at += chunkBytes) {
61712
+ signal?.throwIfAborted();
61713
+ yield bytes.slice(at, at + chunkBytes);
61714
+ }
61715
+ }
61716
+ async function* pixels() {
61717
+ if (image.decodedRgba) {
61718
+ for (let at = 0; at < image.decodedRgba.length; at += chunkBytes) {
61719
+ signal?.throwIfAborted();
61720
+ yield image.decodedRgba.subarray(at, at + chunkBytes);
61721
+ }
61722
+ return;
61723
+ }
61724
+ const source = image.storedRgba;
61725
+ for (let at = 0; at < width * height * 4; ) {
61726
+ signal?.throwIfAborted();
61727
+ const count = Math.min(chunkBytes, width * height * 4 - at), bytes = await source.storage.read(source.position + at, count, signal ? { signal } : void 0);
61728
+ if (bytes.length > count) throw new Error("Oversized SVG pixel read");
61729
+ if (!bytes.length) return;
61730
+ yield bytes;
61731
+ at += bytes.length;
61732
+ }
61733
+ }
61734
+ yield* emit(header2);
61735
+ const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
61736
+ const buffer = new Uint8Array(Math.min(8192, Math.max(4, chunkBytes))), triple = new Uint8Array(3);
61737
+ let used = 0, pending = 0, work = 0;
61738
+ function group(count) {
61739
+ const n = triple[0] << 16 | triple[1] << 8 | triple[2];
61740
+ buffer[used++] = alphabet.charCodeAt(n >>> 18);
61741
+ buffer[used++] = alphabet.charCodeAt(n >>> 12 & 63);
61742
+ buffer[used++] = count > 1 ? alphabet.charCodeAt(n >>> 6 & 63) : 61;
61743
+ buffer[used++] = count > 2 ? alphabet.charCodeAt(n & 63) : 61;
61744
+ triple.fill(0);
61745
+ pending = 0;
61746
+ }
61747
+ const capacity = buffer.length - buffer.length % 4;
61748
+ for await (const bytes of encodeRetainedPng(width, height, pixels(), storage, { ...options, alpha: "rgba", maxOutputBytes: pngMaximum })) {
61749
+ for (const byte3 of bytes) {
61750
+ triple[pending++] = byte3;
61751
+ if (pending === 3) {
61752
+ group(3);
61753
+ if (used === capacity) {
61754
+ yield* emit(buffer.subarray(0, used));
61755
+ used = 0;
61756
+ }
61757
+ if (++work % 4096 === 0) {
61758
+ await new Promise((resolve2) => setTimeout(resolve2, 0));
61759
+ signal?.throwIfAborted();
61760
+ }
61761
+ }
61762
+ }
61763
+ }
61764
+ if (pending) group(pending);
61765
+ if (used) yield* emit(buffer.subarray(0, used));
61766
+ yield* emit(tail);
61767
+ }
61768
+
61284
61769
  // packages/pdf-ast/src/render/retained-tiff.ts
61285
61770
  function maximum9(value) {
61286
61771
  if (value === void 0 || value === Infinity) return Number.MAX_SAFE_INTEGER;
@@ -61855,6 +62340,12 @@ async function createRetainedPageCopy(input, indicesOrStorage, storageOrOptions,
61855
62340
  const value = await box(key);
61856
62341
  if (value[0] !== 0 || value[1] !== 0 || value[2] !== width || value[3] !== height) dictSet(page2, key, cosArray(value.map((value2) => cosNumber(value2))));
61857
62342
  }
62343
+ dictSet(page2, "Parent", cosRef(2));
62344
+ const boxes = options.pageBoxes?.({ width, height }, selection.index);
62345
+ for (const [key, value] of [["MediaBox", boxes?.mediaBox], ["CropBox", boxes?.cropBox]]) if (value) {
62346
+ if (value.length !== 4 || !value.every(Number.isFinite)) throw new RangeError("Invalid copied page box");
62347
+ dictSet(page2, key, cosArray(value.map((coordinate) => cosNumber(coordinate))));
62348
+ }
61858
62349
  await store.set({ objectNumber: pageRef.objectNumber, generationNumber: 0, value: page2 });
61859
62350
  }
61860
62351
  const sourceCatalog = await sourceValue(document2.crossReference.rootRef), acro = sourceCatalog?.kind === "dict" ? await sourceValue(dictGet(sourceCatalog, "AcroForm")) : void 0;
@@ -62017,13 +62508,13 @@ async function* copyRetainedPagesChunks(input, indicesOrStorage, storageOrOption
62017
62508
  }
62018
62509
 
62019
62510
  // packages/pdf-ast/src/cos/retained-objects.ts
62020
- function limit9(value) {
62511
+ function limit10(value) {
62021
62512
  if (value === void 0 || value === Infinity) return Number.MAX_SAFE_INTEGER;
62022
62513
  if (!Number.isSafeInteger(value) || value < 0) throw new RangeError("Invalid retained object limit");
62023
62514
  return value;
62024
62515
  }
62025
62516
  async function* retainedCosObjects(document2, storage, options = {}) {
62026
- const maxObjects = limit9(options.maxObjects), maxStreamBytes = limit9(options.maxStreamBytes), signal = options.signal;
62517
+ const maxObjects = limit10(options.maxObjects), maxStreamBytes = limit10(options.maxStreamBytes), signal = options.signal;
62027
62518
  let count = 0;
62028
62519
  for await (const entry of document2.crossReference.index.entries(signal)) {
62029
62520
  signal?.throwIfAborted();
@@ -62389,16 +62880,329 @@ async function* saveRetainedDocumentChunks(document2, storage, options = {}) {
62389
62880
  }
62390
62881
  }
62391
62882
 
62883
+ // packages/pdf-ast/src/edit/retained-flatten-forms.ts
62884
+ import { IntegerTable as IntegerTable8, PagedStorage as PagedStorage13 } from "@poe-platform/safe-fs/storage";
62885
+ async function flattenRetainedForms(document2, store, storage, signal) {
62886
+ if (!document2.crossReference.rootRef) return;
62887
+ const backing = new PagedStorage13({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4), names = new PdfNameIndex(storage, Infinity, signal), baked = new IntegerTable8(backing), active = new IntegerTable8(backing), fields2 = new IntegerTable8(backing), pagesSeen = new IntegerTable8(backing), walkMarks = new IntegerTable8(backing);
62888
+ let head = -1, fieldCount = 0, work = 0, walk = 0, failed = false;
62889
+ async function checkpoint(depth = 0) {
62890
+ signal.throwIfAborted();
62891
+ if (depth > document2.depthLimit) throw new PdfError("E_LIMIT", "PDF form field depth limit exceeded");
62892
+ if (++work % 64 === 0) {
62893
+ await new Promise((resolve3) => setTimeout(resolve3, 0));
62894
+ signal.throwIfAborted();
62895
+ }
62896
+ }
62897
+ const child = (location, key) => ({ reference: location.reference, path: [...location.path, key] });
62898
+ async function locate(location) {
62899
+ let owner = await store.get(location.reference.objectNumber);
62900
+ if (!owner || owner.generationNumber !== location.reference.generationNumber || owner.stream) return;
62901
+ let value = owner.value, path = [], reference = location.reference, refs = 0;
62902
+ for (let i = 0; i <= location.path.length; i++) {
62903
+ while (value?.kind === "ref") {
62904
+ await checkpoint(++refs);
62905
+ reference = value;
62906
+ owner = await store.get(value.objectNumber);
62907
+ if (!owner || owner.generationNumber !== reference.generationNumber || owner.stream) return;
62908
+ value = owner.value;
62909
+ path = [];
62910
+ }
62911
+ if (!value) return;
62912
+ if (i === location.path.length) return { value, owner, location: { reference, path } };
62913
+ const key = location.path[i];
62914
+ path.push(key);
62915
+ value = typeof key === "number" ? value.kind === "array" ? value.items[key] : void 0 : value.kind === "dict" ? dictGet(value, key) : void 0;
62916
+ }
62917
+ }
62918
+ async function identity(location) {
62919
+ return (await names.intern(`${location.reference.objectNumber}:${location.reference.generationNumber}:${JSON.stringify(location.path)}`)).index;
62920
+ }
62921
+ async function resolve2(node) {
62922
+ const found = await document2.lookup(node);
62923
+ return found?.stream ? void 0 : found?.value;
62924
+ }
62925
+ async function number(node, fallback) {
62926
+ const value = await resolve2(node);
62927
+ return value?.kind === "number" ? value.value : fallback;
62928
+ }
62929
+ async function push(frame) {
62930
+ head = await appendStoredRecord(backing, { frame, previous: head }, -1, signal);
62931
+ }
62932
+ async function set(location, key, value) {
62933
+ const found = await locate(location);
62934
+ if (found?.value.kind === "dict") {
62935
+ dictSet(found.value, key, value);
62936
+ await store.set(found.owner);
62937
+ }
62938
+ }
62939
+ async function stream(dict, chunks) {
62940
+ const source = await PdfFileSource.fromStream(storage.fs, storage.directory, chunks, { signal });
62941
+ let failed2 = false;
62942
+ try {
62943
+ dictSet(dict, "Length", cosNumber(source.size));
62944
+ const ref = await store.allocate();
62945
+ await store.set({ objectNumber: ref.objectNumber, generationNumber: 0, value: dict, stream: { length: source.size, chunks: source.stream(0, source.size, signal), decoded: true } });
62946
+ return ref;
62947
+ } catch (error) {
62948
+ failed2 = true;
62949
+ throw error;
62950
+ } finally {
62951
+ await source.close().catch((error) => {
62952
+ if (!failed2) throw error;
62953
+ });
62954
+ }
62955
+ }
62956
+ async function append(page2, ref) {
62957
+ const found = await locate(page2);
62958
+ if (found?.value.kind !== "dict") return;
62959
+ const existing = dictGet(found.value, "Contents");
62960
+ if (!existing) {
62961
+ dictSet(found.value, "Contents", ref);
62962
+ await store.set(found.owner);
62963
+ return;
62964
+ }
62965
+ const contents = await locate(child(page2, "Contents"));
62966
+ if (contents?.value.kind === "array") {
62967
+ contents.value.items.push(ref);
62968
+ await store.set(contents.owner);
62969
+ } else {
62970
+ dictSet(found.value, "Contents", cosArray([existing, ref]));
62971
+ await store.set(found.owner);
62972
+ }
62973
+ }
62974
+ async function inheritedResources(page2) {
62975
+ const mark = BigInt(++walk);
62976
+ let location = page2;
62977
+ while (location) {
62978
+ await checkpoint();
62979
+ const found = await locate(location);
62980
+ if (found?.value.kind !== "dict") return;
62981
+ const key = BigInt(await identity(found.location));
62982
+ if (await walkMarks.get(key) === mark) return;
62983
+ await walkMarks.set(key, mark);
62984
+ const node = dictGet(found.value, "Resources");
62985
+ if (node !== void 0) {
62986
+ const value = await resolve2(node);
62987
+ return value?.kind === "dict" ? value : void 0;
62988
+ }
62989
+ location = child(found.location, "Parent");
62990
+ }
62991
+ }
62992
+ const encoder = new TextEncoder();
62993
+ function* textChunks(text, x, y, font) {
62994
+ yield encoder.encode(`
62995
+ q BT /${font} 11 Tf `);
62996
+ const normalized = text.replaceAll("\r\n", "\n");
62997
+ let offset = 0, line = 0;
62998
+ while (offset <= normalized.length) {
62999
+ signal.throwIfAborted();
63000
+ const end = normalized.indexOf("\n", offset), part = normalized.slice(offset, end < 0 ? normalized.length : end);
63001
+ yield encoder.encode(line++ ? " 0 -13 Td (" : `${Math.round(x)} ${Math.round(y)} Td (`);
63002
+ let escaped = "";
63003
+ for (const char of part) {
63004
+ escaped += (char === "(" || char === ")" || char === "\\" ? "\\" : "") + char;
63005
+ if (escaped.length >= 2048) {
63006
+ yield encoder.encode(escaped);
63007
+ escaped = "";
63008
+ }
63009
+ }
63010
+ if (escaped) yield encoder.encode(escaped);
63011
+ yield encoder.encode(") Tj");
63012
+ if (end < 0) break;
63013
+ offset = end + 1;
63014
+ }
63015
+ yield encoder.encode(" ET Q\n");
63016
+ }
63017
+ async function draw(page2, text, x, y) {
63018
+ if (!text) return;
63019
+ let resources = await locate(child(page2, "Resources"));
63020
+ if (resources?.value.kind !== "dict") {
63021
+ await set(page2, "Resources", cosDict({}));
63022
+ resources = await locate(child(page2, "Resources"));
63023
+ }
63024
+ const resourceLocation = resources.location;
63025
+ let fonts = await locate(child(resourceLocation, "Font"));
63026
+ if (fonts?.value.kind !== "dict") {
63027
+ await set(resourceLocation, "Font", cosDict({}));
63028
+ fonts = await locate(child(resourceLocation, "Font"));
63029
+ }
63030
+ const font = fonts.value, key = dictGet(font, "F1") ? "F_AcroFlat" : "F1";
63031
+ if (!dictGet(font, key)) {
63032
+ dictSet(font, key, await store.allocate(cosDict({ Type: cosName("Font"), Subtype: cosName("Type1"), BaseFont: cosName("Helvetica") })));
63033
+ await store.set(fonts.owner);
63034
+ }
63035
+ await append(page2, await stream(cosDict({}), textChunks(text, x, y, key)));
63036
+ }
63037
+ async function textValue(node, arrays) {
63038
+ if (node?.kind === "string") return decodePdfString(node);
63039
+ if (node?.kind === "name" && node.decoded !== "Off") return node.decoded;
63040
+ if (node?.kind === "boolean" && node.value) return "Yes";
63041
+ if (arrays && node?.kind === "array") {
63042
+ let text = "", count = 0;
63043
+ for (const item of node.items) {
63044
+ await checkpoint();
63045
+ const value = await resolve2(item);
63046
+ if (value?.kind === "string" || value?.kind === "name") text += (count++ ? ", " : "") + (value.kind === "string" ? decodePdfString(value) : value.decoded);
63047
+ }
63048
+ return text;
63049
+ }
63050
+ return "";
63051
+ }
63052
+ const root = { reference: document2.crossReference.rootRef, path: [] }, form = child(root, "AcroForm");
63053
+ try {
63054
+ const fieldArray = await locate(child(form, "Fields"));
63055
+ if (fieldArray?.value.kind === "array") for (let i = fieldArray.value.items.length - 1; i >= 0; i--) {
63056
+ await checkpoint();
63057
+ await push({ location: child(fieldArray.location, i), named: false, ft: "", depth: 0 });
63058
+ }
63059
+ while (head !== -1) {
63060
+ const record = (await readStoredRecord(backing, head, signal)).value;
63061
+ head = record.previous;
63062
+ const frame = record.frame;
63063
+ if ("exit" in frame) {
63064
+ await active.set(BigInt(frame.exit), 0n);
63065
+ continue;
63066
+ }
63067
+ await checkpoint(frame.depth);
63068
+ const found = await locate(frame.location);
63069
+ if (found?.value.kind !== "dict") continue;
63070
+ const id = await identity(found.location);
63071
+ if (await active.get(BigInt(id))) continue;
63072
+ await active.set(BigInt(id), 1n);
63073
+ await push({ exit: id });
63074
+ const name = await resolve2(dictGet(found.value, "T")), type = await resolve2(dictGet(found.value, "FT")), named = frame.named || (name?.kind === "string" ? !!decodePdfString(name) : name?.kind === "name" ? !!name.decoded : false), ft = type?.kind === "name" ? type.decoded : frame.ft;
63075
+ const kids = await locate(child(found.location, "Kids"));
63076
+ let descend = false;
63077
+ if (kids?.value.kind === "array" && kids.value.items.length) {
63078
+ let namedKids = false;
63079
+ for (let i = 0; i < kids.value.items.length; i++) {
63080
+ await checkpoint();
63081
+ const kid = await locate(child(kids.location, i));
63082
+ if (kid?.value.kind === "dict" && dictGet(kid.value, "T")) {
63083
+ namedKids = true;
63084
+ break;
63085
+ }
63086
+ }
63087
+ descend = namedKids || !ft || !named;
63088
+ if (descend) for (let i = kids.value.items.length - 1; i >= 0; i--) {
63089
+ await checkpoint();
63090
+ await push({ location: child(kids.location, i), named, ft, depth: frame.depth + 1 });
63091
+ }
63092
+ }
63093
+ if (!descend && named) {
63094
+ const at = await appendStoredRecord(backing, found.location, -1, signal);
63095
+ await fields2.set(BigInt(fieldCount++), BigInt(at));
63096
+ }
63097
+ }
63098
+ let firstPage;
63099
+ for await (const page2 of document2.pages()) {
63100
+ await checkpoint();
63101
+ if (!page2.reference) throw new PdfError("E_PARSE", "Expected retained form page reference");
63102
+ const pageLocation = { reference: page2.reference, path: [] };
63103
+ if (!firstPage) firstPage = pageLocation;
63104
+ if (await pagesSeen.get(BigInt(page2.reference.objectNumber))) continue;
63105
+ await pagesSeen.set(BigInt(page2.reference.objectNumber), 1n);
63106
+ const annotations = await locate(child(pageLocation, "Annots"));
63107
+ if (annotations?.value.kind !== "array") continue;
63108
+ const survivors = [];
63109
+ for (let i = 0; i < annotations.value.items.length; i++) {
63110
+ await checkpoint();
63111
+ const annotation = await locate(child(annotations.location, i));
63112
+ if (annotation?.value.kind !== "dict") {
63113
+ survivors.push(annotations.value.items[i]);
63114
+ continue;
63115
+ }
63116
+ const subtype = await resolve2(dictGet(annotation.value, "Subtype"));
63117
+ if (!(subtype?.kind === "name" && subtype.decoded === "Widget") && !dictGet(annotation.value, "FT") && !dictGet(annotation.value, "T")) {
63118
+ survivors.push(annotations.value.items[i]);
63119
+ continue;
63120
+ }
63121
+ await baked.set(BigInt(await identity(annotation.location)), 1n);
63122
+ const parent = await locate(child(annotation.location, "Parent"));
63123
+ if (parent?.value.kind === "dict") await baked.set(BigInt(await identity(parent.location)), 1n);
63124
+ const rect = await resolve2(dictGet(annotation.value, "Rect")), items = rect?.kind === "array" ? rect.items : [];
63125
+ const x = await number(items[0], 50), y = await number(items[1], 700), ownState = await resolve2(dictGet(annotation.value, "AS"));
63126
+ const value = ownState ?? await resolve2(dictGet(annotation.value, "V") ?? (parent?.value.kind === "dict" ? dictGet(parent.value, "V") ?? dictGet(parent.value, "AS") : void 0));
63127
+ const appearance = await locate(child(annotation.location, "AP"));
63128
+ let normal = appearance?.value.kind === "dict" ? await document2.lookup(dictGet(appearance.value, "N")) : void 0;
63129
+ if (normal?.value.kind === "dict" && !normal.stream && value?.kind === "name" && value.decoded !== "Off") normal = await document2.lookup(dictGet(normal.value, value.decoded));
63130
+ if (normal?.stream && normal.reference && normal.value.kind === "dict") {
63131
+ const inherited = await inheritedResources(pageLocation), resources = { kind: "dict", entries: [...inherited?.entries ?? []] };
63132
+ const old = await resolve2(dictGet(resources, "XObject")), objects = { kind: "dict", entries: [...old?.kind === "dict" ? old.entries : []] };
63133
+ let suffix = 1;
63134
+ while (dictGet(objects, `AcroAppearance${suffix}`)) {
63135
+ await checkpoint();
63136
+ suffix++;
63137
+ }
63138
+ const name = `AcroAppearance${suffix}`, dict = { kind: "dict", entries: [...normal.value.entries] };
63139
+ dictSet(dict, "Type", cosName("XObject"));
63140
+ dictSet(dict, "Subtype", cosName("Form"));
63141
+ const original = await store.get(normal.reference.objectNumber), ref = await store.allocate();
63142
+ if (!original?.stream) throw new PdfError("E_PARSE", "Missing retained appearance stream");
63143
+ await store.set({ ...original, objectNumber: ref.objectNumber, generationNumber: 0, value: dict });
63144
+ dictSet(objects, name, ref);
63145
+ dictSet(resources, "XObject", objects);
63146
+ await set(pageLocation, "Resources", resources);
63147
+ const r2 = await resolve2(items[2]), r3 = await resolve2(items[3]), width = r2?.kind === "number" ? Math.max(1, Math.abs(r2.value - x)) : 20, height = r3?.kind === "number" ? Math.max(1, Math.abs(r3.value - y)) : 20;
63148
+ const bbox = await resolve2(dictGet(dict, "BBox"));
63149
+ let bx0 = 0, by0 = 0, bx1 = width, by1 = height;
63150
+ if (bbox?.kind === "array" && bbox.items.length >= 4) {
63151
+ const b = await Promise.all(bbox.items.slice(0, 4).map(resolve2));
63152
+ if (b.every((v) => v?.kind === "number")) {
63153
+ const n = b;
63154
+ bx0 = Math.min(n[0].value, n[2].value);
63155
+ by0 = Math.min(n[1].value, n[3].value);
63156
+ bx1 = Math.max(n[0].value, n[2].value);
63157
+ by1 = Math.max(n[1].value, n[3].value);
63158
+ }
63159
+ }
63160
+ const matrix2 = await resolve2(dictGet(dict, "Matrix")), values = matrix2?.kind === "array" && matrix2.items.length >= 6 ? await Promise.all(matrix2.items.slice(0, 6).map((v) => number(v, 0))) : [1, 0, 0, 1, 0, 0];
63161
+ const [ma, mb, mc, md, me, mf] = values, corners = [[bx0 * ma + by0 * mc + me, bx0 * mb + by0 * md + mf], [bx1 * ma + by0 * mc + me, bx1 * mb + by0 * md + mf], [bx0 * ma + by1 * mc + me, bx0 * mb + by1 * md + mf], [bx1 * ma + by1 * mc + me, bx1 * mb + by1 * md + mf]];
63162
+ const minX = Math.min(...corners.map((c) => c[0])), minY = Math.min(...corners.map((c) => c[1])), bw = Math.max(1, Math.max(...corners.map((c) => c[0])) - minX), bh = Math.max(1, Math.max(...corners.map((c) => c[1])) - minY);
63163
+ const sx = Number((width / bw).toFixed(6)), sy = Number((height / bh).toFixed(6)), tx = Number((x - minX * sx).toFixed(6)), ty = Number((y - minY * sy).toFixed(6));
63164
+ await append(pageLocation, await stream(cosDict({}), [encoder.encode(`
63165
+ q ${sx} 0 0 ${sy} ${tx} ${ty} cm /${name} Do Q
63166
+ `)]));
63167
+ } else await draw(pageLocation, await textValue(value, true), x + 2, y + 4);
63168
+ }
63169
+ await set(pageLocation, "Annots", cosArray(survivors));
63170
+ }
63171
+ if (!firstPage) return;
63172
+ for (let i = 0; i < fieldCount; i++) {
63173
+ await checkpoint();
63174
+ const location = (await readStoredRecord(backing, Number(await fields2.get(BigInt(i))), signal)).value, field2 = await locate(location);
63175
+ if (field2?.value.kind !== "dict" || await baked.get(BigInt(await identity(field2.location)))) continue;
63176
+ const rect = await resolve2(dictGet(field2.value, "Rect")), items = rect?.kind === "array" ? rect.items : [], x = await number(items[0], 50), y = await number(items[1], 700), value = await resolve2(dictGet(field2.value, "V") ?? dictGet(field2.value, "AS"));
63177
+ await draw(firstPage, await textValue(value, false), x + 2, y + 4);
63178
+ }
63179
+ const latest = await locate(form);
63180
+ if (latest?.value.kind === "dict") {
63181
+ dictSet(latest.value, "Fields", cosArray([]));
63182
+ dictSet(latest.value, "NeedAppearances", cosBool(false));
63183
+ await store.set(latest.owner);
63184
+ }
63185
+ } catch (error) {
63186
+ failed = true;
63187
+ throw error;
63188
+ } finally {
63189
+ const results = await Promise.allSettled([backing.close(), names.close()]);
63190
+ if (!failed) {
63191
+ for (const result of results) if (result.status === "rejected") await Promise.reject(result.reason);
63192
+ }
63193
+ }
63194
+ }
63195
+
62392
63196
  // packages/pdf-ast/src/edit/retained-info-updates.ts
62393
- import { PagedStorage as PagedStorage14 } from "@poe-platform/safe-fs/storage";
63197
+ import { PagedStorage as PagedStorage15 } from "@poe-platform/safe-fs/storage";
62394
63198
 
62395
63199
  // packages/pdf-ast/src/edit/retained-bookmarks.ts
62396
- import { PagedStorage as PagedStorage13 } from "@poe-platform/safe-fs/storage";
63200
+ import { PagedStorage as PagedStorage14 } from "@poe-platform/safe-fs/storage";
62397
63201
  async function setRetainedBookmarks(store, storage, root, pageCount, pageReference, bookmarks, signal, maxDepth = Infinity) {
62398
63202
  if (!pageCount) return;
62399
63203
  const catalog = await store.get(root.objectNumber);
62400
63204
  if (catalog?.value.kind !== "dict") return;
62401
- const frames = new PagedStorage13({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
63205
+ const frames = new PagedStorage14({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
62402
63206
  const base = frames.allocate(0);
62403
63207
  let depth = 0, capacity = 0, failed = false, work = 0;
62404
63208
  async function write(index2, frame) {
@@ -62471,7 +63275,7 @@ async function setRetainedBookmarks(store, storage, root, pageCount, pageReferen
62471
63275
 
62472
63276
  // packages/pdf-ast/src/edit/retained-info-updates.ts
62473
63277
  async function applyRetainedInfoUpdates(document2, store, storage, count, getPage, updates, signal, maxDepth) {
62474
- const pages = new PagedStorage14({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
63278
+ const pages = new PagedStorage15({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
62475
63279
  const base = pages.allocate(count * 4 * 48), heads = [-1, -1, -1, -1], tails = [-1, -1, -1, -1];
62476
63280
  const labels = new PdfMutableObjectStore(storage, { signal }), bookmarks = new PdfMutableObjectStore(storage, { signal });
62477
63281
  let infoRef = document2.crossReference.infoRef, idArray = document2.crossReference.idArray, labelCount = 0, work = 0, failed = false;
@@ -62713,7 +63517,7 @@ async function appendRetainedAttachments(document2, target, storage, attachments
62713
63517
  }
62714
63518
 
62715
63519
  // packages/pdf-ast/src/edit/retained-form-appearances.ts
62716
- import { IntegerTable as IntegerTable8, PagedStorage as PagedStorage15 } from "@poe-platform/safe-fs/storage";
63520
+ import { IntegerTable as IntegerTable9, PagedStorage as PagedStorage16 } from "@poe-platform/safe-fs/storage";
62717
63521
 
62718
63522
  // packages/pdf-ast/src/edit/form-appearance-chunks.ts
62719
63523
  function* serializeFormAppearanceChunks(text, options) {
@@ -62801,7 +63605,7 @@ function* operators(text, options) {
62801
63605
  // packages/pdf-ast/src/edit/retained-form-appearances.ts
62802
63606
  async function generateRetainedFormAppearances(document2, store, storage, signal, update) {
62803
63607
  if (!document2.crossReference.rootRef) return;
62804
- const backing = new PagedStorage15({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4), active = new IntegerTable8(backing);
63608
+ const backing = new PagedStorage16({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4), active = new IntegerTable9(backing);
62805
63609
  let head = -1, failed = false, work = 0;
62806
63610
  let matched = false;
62807
63611
  let defaultAppearance;
@@ -62848,6 +63652,7 @@ async function generateRetainedFormAppearances(document2, store, storage, signal
62848
63652
  const source = await PdfFileSource.fromStream(storage.fs, storage.directory, chunks, { signal });
62849
63653
  let failed2 = false;
62850
63654
  try {
63655
+ if (update && dict.kind === "dict") dictSet(dict, "Length", cosNumber(source.size));
62851
63656
  const ref = await store.allocate();
62852
63657
  await store.set({ objectNumber: ref.objectNumber, generationNumber: 0, value: dict, stream: { length: source.size, chunks: source.stream(0, source.size, signal), decoded: true } });
62853
63658
  return ref;
@@ -63099,17 +63904,17 @@ async function generateRetainedFormAppearances(document2, store, storage, signal
63099
63904
  }
63100
63905
 
63101
63906
  // packages/pdf-ast/src/edit/retained-flatten-annotations.ts
63102
- import { IntegerTable as IntegerTable10, PagedStorage as PagedStorage19 } from "@poe-platform/safe-fs/storage";
63907
+ import { IntegerTable as IntegerTable11, PagedStorage as PagedStorage20 } from "@poe-platform/safe-fs/storage";
63103
63908
 
63104
63909
  // packages/pdf-ast/src/edit/retained-content-edit.ts
63105
- import { IntegerTable as IntegerTable9, PagedStorage as PagedStorage16 } from "@poe-platform/safe-fs/storage";
63910
+ import { IntegerTable as IntegerTable10, PagedStorage as PagedStorage17 } from "@poe-platform/safe-fs/storage";
63106
63911
  var RetainedContentEditor = class _RetainedContentEditor {
63107
63912
  constructor(store, storage, signal) {
63108
63913
  this.store = store;
63109
63914
  this.storage = storage;
63110
63915
  this.signal = signal;
63111
- this.backing = new PagedStorage16({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
63112
- this.counts = new IntegerTable9(this.backing);
63916
+ this.backing = new PagedStorage17({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
63917
+ this.counts = new IntegerTable10(this.backing);
63113
63918
  this.identities = new PdfNameIndex(storage, Infinity, signal);
63114
63919
  }
63115
63920
  store;
@@ -63180,14 +63985,14 @@ var RetainedContentEditor = class _RetainedContentEditor {
63180
63985
  };
63181
63986
 
63182
63987
  // packages/pdf-ast/src/edit/retained-name-replacement.ts
63183
- import { PagedStorage as PagedStorage17 } from "@poe-platform/safe-fs/storage";
63988
+ import { PagedStorage as PagedStorage18 } from "@poe-platform/safe-fs/storage";
63184
63989
  async function* replaceRetainedPdfName(input, oldName, newName, storage, options = {}) {
63185
63990
  const chunkBytes = options.chunkBytes ?? 16384, maximum10 = options.maxOutputBytes ?? Infinity;
63186
63991
  if (!Number.isSafeInteger(chunkBytes) || chunkBytes < 1) throw new RangeError("Invalid name replacement chunk size");
63187
63992
  if (maximum10 !== Infinity && (!Number.isSafeInteger(maximum10) || maximum10 < 0)) throw new RangeError("Invalid name replacement output limit");
63188
63993
  const signal = options.signal ?? new AbortController().signal;
63189
63994
  signal.throwIfAborted();
63190
- const table = new PagedStorage17({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4), length = oldName.length + 1;
63995
+ const table = new PagedStorage18({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4), length = oldName.length + 1;
63191
63996
  const base = table.allocate(length * 8), record = new Uint8Array(8), view = new DataView(record.buffer);
63192
63997
  const pattern = (at) => at ? oldName.charCodeAt(at - 1) : 47;
63193
63998
  let buffer = new Uint8Array(chunkBytes), used = 0, total = 0, work = 0, failed = false;
@@ -63265,10 +64070,10 @@ async function* replaceRetainedPdfName(input, oldName, newName, storage, options
63265
64070
  }
63266
64071
 
63267
64072
  // packages/pdf-ast/src/edit/retained-draw-text.ts
63268
- import { PagedStorage as PagedStorage18 } from "@poe-platform/safe-fs/storage";
64073
+ import { PagedStorage as PagedStorage19 } from "@poe-platform/safe-fs/storage";
63269
64074
  async function drawRetainedAnnotationText(page2, editor, storage, text, x, y, isolated, font, signal) {
63270
64075
  const source = await PdfFileSource.fromStream(storage.fs, storage.directory, page2.streamContents(), { signal });
63271
- const backing = new PagedStorage18({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
64076
+ const backing = new PagedStorage19({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
63272
64077
  let failed = false;
63273
64078
  try {
63274
64079
  const name = await font(), position = backing.allocate(text.length);
@@ -63344,7 +64149,7 @@ async function flattenRetainedAnnotations(document2, store, storage, mode, signa
63344
64149
  for await (const page2 of document2.pages()) {
63345
64150
  const annotations = await array(dictGet(page2.dict, "Annots"));
63346
64151
  if (!annotations) continue;
63347
- const survivorStorage = new PagedStorage19({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
64152
+ const survivorStorage = new PagedStorage20({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
63348
64153
  const survivorBase = survivorStorage.allocate(0);
63349
64154
  let pageFailed = false;
63350
64155
  try {
@@ -63430,7 +64235,7 @@ async function flattenRetainedAnnotations(document2, store, storage, mode, signa
63430
64235
  }
63431
64236
  if (normal?.stream && normal.reference && normal.value.kind === "dict") {
63432
64237
  let content = await PdfFileSource.fromStream(storage.fs, storage.directory, document2.objects.decodeStream(normal.reference.objectNumber, normal.reference.generationNumber), { signal });
63433
- const backing = new PagedStorage19({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4), renames = new IntegerTable10(backing), names = new PdfNameIndex(storage, Infinity, signal);
64238
+ const backing = new PagedStorage20({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4), renames = new IntegerTable11(backing), names = new PdfNameIndex(storage, Infinity, signal);
63434
64239
  let appearanceFailed = false, count = 0;
63435
64240
  try {
63436
64241
  if (content.size) {
@@ -63549,11 +64354,11 @@ q ${scaleX} 0 0 ${scaleY} ${tx} ${ty} cm${matSuffix}
63549
64354
  }
63550
64355
 
63551
64356
  // packages/pdf-ast/src/edit/retained-name-map.ts
63552
- import { PagedStorage as PagedStorage20 } from "@poe-platform/safe-fs/storage";
64357
+ import { PagedStorage as PagedStorage21 } from "@poe-platform/safe-fs/storage";
63553
64358
  async function* replaceRetainedPdfNames(input, names, storage, options = {}) {
63554
64359
  const signal = options.signal ?? new AbortController().signal, size = options.chunkBytes ?? 16384;
63555
64360
  if (!Number.isSafeInteger(size) || size < 1) throw new RangeError("Invalid name replacement chunk size");
63556
- const trie = new PagedStorage20({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4), pending = new PagedStorage20({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
64361
+ const trie = new PagedStorage21({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4), pending = new PagedStorage21({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
63557
64362
  const root = trie.allocate(40), prefixBase = pending.allocate(0);
63558
64363
  let output = new Uint8Array(size), used = 0, failed = false, work = 0;
63559
64364
  const body = (byte3) => byte3 >= 48 && byte3 <= 57 || byte3 >= 65 && byte3 <= 90 || byte3 >= 97 && byte3 <= 122 || [95, 46, 43, 45].includes(byte3);
@@ -63835,7 +64640,7 @@ async function preserveRetainedStamp(document2, source, page2, other, store, edi
63835
64640
  }
63836
64641
 
63837
64642
  // packages/pdf-ast/src/edit/retained-stamps.ts
63838
- import { IntegerTable as IntegerTable11, PagedStorage as PagedStorage21 } from "@poe-platform/safe-fs/storage";
64643
+ import { IntegerTable as IntegerTable12, PagedStorage as PagedStorage22 } from "@poe-platform/safe-fs/storage";
63839
64644
  async function stampRetainedPages(document2, store, storage, getPage, stamps, signal) {
63840
64645
  const editor = await RetainedContentEditor.open(store, storage, signal);
63841
64646
  let counter = 1, failed = false, work = 0;
@@ -63846,7 +64651,7 @@ async function stampRetainedPages(document2, store, storage, getPage, stamps, si
63846
64651
  try {
63847
64652
  for await (const stamp of stamps) {
63848
64653
  const source = await editRetainedDocument(stamp.source, storage, { signal });
63849
- const backing = new PagedStorage21({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4), memo = new IntegerTable11(backing);
64654
+ const backing = new PagedStorage22({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4), memo = new IntegerTable12(backing);
63850
64655
  let stampFailed = false;
63851
64656
  async function clone(node, depth = 0) {
63852
64657
  await checkpoint();
@@ -64032,12 +64837,12 @@ ${fmt6(s)} 0 0 ${fmt6(s)} ${fmt4(tx)} ${fmt4(ty)} cm
64032
64837
  }
64033
64838
 
64034
64839
  // packages/pdf-ast/src/edit/retained-inline-images.ts
64035
- import { PagedStorage as PagedStorage22 } from "@poe-platform/safe-fs/storage";
64840
+ import { PagedStorage as PagedStorage23 } from "@poe-platform/safe-fs/storage";
64036
64841
  async function externalizeRetainedInlineImages(document2, store, storage, options, signal) {
64037
64842
  const minimum = options.minBytes ?? 1024;
64038
64843
  if (!Number.isSafeInteger(minimum) || minimum < 0) throw new RangeError("Invalid inline-image minimum size");
64039
64844
  const editor = await RetainedContentEditor.open(store, storage, signal);
64040
- const paths = new PagedStorage22({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
64845
+ const paths = new PagedStorage23({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
64041
64846
  const keys = { BPC: "BitsPerComponent", CS: "ColorSpace", D: "Decode", DP: "DecodeParms", F: "Filter", H: "Height", IM: "ImageMask", I: "Interpolate", W: "Width" };
64042
64847
  const colors = { G: "DeviceGray", RGB: "DeviceRGB", CMYK: "DeviceCMYK", I: "Indexed" };
64043
64848
  const filters = { AHx: "ASCIIHexDecode", A85: "ASCII85Decode", LZW: "LZWDecode", Fl: "FlateDecode", RL: "RunLengthDecode", CCF: "CCITTFaxDecode", DCT: "DCTDecode" };
@@ -64129,7 +64934,7 @@ async function externalizeRetainedInlineImages(document2, store, storage, option
64129
64934
  }
64130
64935
 
64131
64936
  // packages/pdf-ast/src/edit/retained-resource-pruning.ts
64132
- import { IntegerTable as IntegerTable12, PagedStorage as PagedStorage23 } from "@poe-platform/safe-fs/storage";
64937
+ import { IntegerTable as IntegerTable13, PagedStorage as PagedStorage24 } from "@poe-platform/safe-fs/storage";
64133
64938
  async function collectNames(input, names, found, signal) {
64134
64939
  const iterator = input[Symbol.asyncIterator](), pending = [];
64135
64940
  let chunk = new Uint8Array(), at = 0, ended = false, changed = false, work = 0, failed = false;
@@ -64211,7 +65016,7 @@ async function pruneRetainedResources(document2, store, storage, signal) {
64211
65016
  return { ...found2, value: same(page2.reference) ? page2.dict : same(resources?.reference) ? resources.value : found2.value };
64212
65017
  }
64213
65018
  const names = new PdfNameIndex(storage, Infinity, signal), visitedNames = new PdfNameIndex(storage, Infinity, signal);
64214
- const backing = new PagedStorage23({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4), found = new IntegerTable12(backing);
65019
+ const backing = new PagedStorage24({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4), found = new IntegerTable13(backing);
64215
65020
  let failed = false;
64216
65021
  try {
64217
65022
  const referenced = async (name) => await found.get(BigInt((await names.intern(name)).index)) !== void 0;
@@ -64341,7 +65146,7 @@ async function flattenRetainedRotations(document2, store, storage, signal) {
64341
65146
  }
64342
65147
 
64343
65148
  // packages/pdf-ast/src/edit/retained-attachment-edits.ts
64344
- import { IntegerTable as IntegerTable13, PagedStorage as PagedStorage24 } from "@poe-platform/safe-fs/storage";
65149
+ import { IntegerTable as IntegerTable14, PagedStorage as PagedStorage25 } from "@poe-platform/safe-fs/storage";
64345
65150
  var PdfDuplicateAttachment = class extends PdfError {
64346
65151
  constructor(key) {
64347
65152
  super("E_CAPABILITY", `Duplicate attachment key: ${key}`);
@@ -64352,7 +65157,7 @@ var PdfDuplicateAttachment = class extends PdfError {
64352
65157
  async function editRetainedAttachments(document2, target, storage, remove, additions, signal, preserveTree = false) {
64353
65158
  const pairs = new PdfMutableObjectStore(storage, { signal });
64354
65159
  const names = new PdfNameIndex(storage, Infinity, signal), removed = new PdfNameIndex(storage, Infinity, signal);
64355
- const backing = new PagedStorage24({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4), first = new IntegerTable13(backing), removals = new IntegerTable13(backing);
65160
+ const backing = new PagedStorage25({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4), first = new IntegerTable14(backing), removals = new IntegerTable14(backing);
64356
65161
  let failed = false, count = 0, work = 0;
64357
65162
  async function checkpoint() {
64358
65163
  signal.throwIfAborted();
@@ -64554,13 +65359,13 @@ async function* retainedAttachmentNameTokens(document2, storage, root, signal, r
64554
65359
  }
64555
65360
 
64556
65361
  // packages/pdf-ast/src/edit/retained-graph.ts
64557
- import { PagedStorage as PagedStorage25 } from "@poe-platform/safe-fs/storage";
65362
+ import { PagedStorage as PagedStorage26 } from "@poe-platform/safe-fs/storage";
64558
65363
  async function editRetainedDocument(source, storage, options = {}) {
64559
65364
  if (options.maxPages !== void 0 && options.maxPages !== Infinity && (!Number.isSafeInteger(options.maxPages) || options.maxPages < 0)) throw new RangeError("Invalid page limit");
64560
65365
  if (options.maxRecursionDepth !== void 0 && options.maxRecursionDepth !== Infinity && (!Number.isSafeInteger(options.maxRecursionDepth) || options.maxRecursionDepth < 1)) throw new RangeError("Invalid edit depth");
64561
65366
  const signal = options.signal ?? new AbortController().signal;
64562
65367
  const store = new PdfMutableObjectStore(storage, { ...options, signal });
64563
- const pages = new PagedStorage25({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
65368
+ const pages = new PagedStorage26({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
64564
65369
  const base = pages.allocate(0);
64565
65370
  let count = 0, document2;
64566
65371
  let closing;
@@ -64687,6 +65492,10 @@ async function editRetainedDocument(source, storage, options = {}) {
64687
65492
  await generateRetainedFormAppearances(document2, store, storage, signal);
64688
65493
  addedObjects = true;
64689
65494
  }
65495
+ if (options.flattenForms) {
65496
+ await flattenRetainedForms(document2, store, storage, signal);
65497
+ addedObjects = true;
65498
+ }
64690
65499
  if (options.removeInfo) {
64691
65500
  await removeRoot(["Metadata"]);
64692
65501
  const found = await document2.lookup(infoRef);
@@ -64794,10 +65603,10 @@ async function* copyRetainedAttachments(document2, storage, options = {}) {
64794
65603
  }
64795
65604
 
64796
65605
  // packages/pdf-ast/src/cos/retained-object-order.ts
64797
- import { IntegerTable as IntegerTable14, PagedStorage as PagedStorage26 } from "@poe-platform/safe-fs/storage";
65606
+ import { IntegerTable as IntegerTable15, PagedStorage as PagedStorage27 } from "@poe-platform/safe-fs/storage";
64798
65607
  async function* retainedObjectOrder(document2, source, storage, signal) {
64799
- const backing = new PagedStorage26({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
64800
- const seen = new IntegerTable14(backing), streams = new IntegerTable14(backing);
65608
+ const backing = new PagedStorage27({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
65609
+ const seen = new IntegerTable15(backing), streams = new IntegerTable15(backing);
64801
65610
  let failed = false, work = 0;
64802
65611
  async function candidate(number) {
64803
65612
  signal.throwIfAborted();
@@ -64811,7 +65620,7 @@ async function* retainedObjectOrder(document2, source, storage, signal) {
64811
65620
  try {
64812
65621
  if (document2.crossReference.revisionCount) {
64813
65622
  for (const kind of ["uncompressed", "compressed"]) {
64814
- const revisions = new IntegerTable14(backing);
65623
+ const revisions = new IntegerTable15(backing);
64815
65624
  let offset = document2.crossReference.xrefOffset;
64816
65625
  while (offset !== void 0 && await revisions.get(BigInt(offset)) === void 0) {
64817
65626
  await revisions.set(BigInt(offset), 1n);
@@ -64933,14 +65742,14 @@ async function* encryptRetainedPdfChunks(source, storage, options = {}) {
64933
65742
  }
64934
65743
 
64935
65744
  // packages/pdf-ast/src/cos/qpdf-json-values.ts
64936
- import { IntegerTable as IntegerTable15, PagedStorage as PagedStorage27 } from "@poe-platform/safe-fs/storage";
65745
+ import { IntegerTable as IntegerTable16, PagedStorage as PagedStorage28 } from "@poe-platform/safe-fs/storage";
64937
65746
  var QpdfJsonValues = class _QpdfJsonValues {
64938
65747
  constructor(tree, storage, signal) {
64939
65748
  this.tree = tree;
64940
65749
  this.signal = signal;
64941
- this.scratch = new PagedStorage27({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
64942
- this.first = new IntegerTable15(this.scratch, 64);
64943
- this.next = new IntegerTable15(this.scratch, 64);
65750
+ this.scratch = new PagedStorage28({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4);
65751
+ this.first = new IntegerTable16(this.scratch, 64);
65752
+ this.next = new IntegerTable16(this.scratch, 64);
64944
65753
  }
64945
65754
  tree;
64946
65755
  signal;
@@ -65038,7 +65847,7 @@ var QpdfJsonValues = class _QpdfJsonValues {
65038
65847
  await this.cooperate();
65039
65848
  const header2 = await this.tree.describe(position);
65040
65849
  if (header2.kind === "object") {
65041
- const hashes = new IntegerTable15(this.scratch, 64);
65850
+ const hashes = new IntegerTable16(this.scratch, 64);
65042
65851
  let head = 0, tail = 0;
65043
65852
  for await (const { key } of order.entries(position)) {
65044
65853
  let hash2 = 0;
@@ -65331,19 +66140,19 @@ var QpdfJsonValues = class _QpdfJsonValues {
65331
66140
  };
65332
66141
 
65333
66142
  // packages/pdf-ast/src/cos/qpdf-json-document.ts
65334
- import { IntegerTable as IntegerTable16, PagedStorage as PagedStorage28 } from "@poe-platform/safe-fs/storage";
66143
+ import { IntegerTable as IntegerTable17, PagedStorage as PagedStorage29 } from "@poe-platform/safe-fs/storage";
65335
66144
  var QpdfJsonDocument = class _QpdfJsonDocument {
65336
66145
  constructor(storage, options = {}) {
65337
66146
  this.storage = storage;
65338
66147
  this.signal = options.signal ? AbortSignal.any([options.signal, this.controller.signal]) : this.controller.signal;
65339
66148
  this.store = new PdfMutableObjectStore(storage, { signal: this.signal });
65340
- this.backing = new PagedStorage28(
66149
+ this.backing = new PagedStorage29(
65341
66150
  { fs: storage.fs, cwd: storage.directory, env: {}, signal: this.signal },
65342
66151
  4
65343
66152
  );
65344
- this.positions = new IntegerTable16(this.backing, 64);
65345
- this.order = new IntegerTable16(this.backing, 64);
65346
- this.catalogs = new IntegerTable16(this.backing, 64);
66153
+ this.positions = new IntegerTable17(this.backing, 64);
66154
+ this.order = new IntegerTable17(this.backing, 64);
66155
+ this.catalogs = new IntegerTable17(this.backing, 64);
65347
66156
  }
65348
66157
  storage;
65349
66158
  rootRef;
@@ -65406,7 +66215,7 @@ var QpdfJsonDocument = class _QpdfJsonDocument {
65406
66215
  env: {},
65407
66216
  signal: this.signal
65408
66217
  };
65409
- const tape = new PagedStorage28(context, 4), scratch = new PagedStorage28(context, 4);
66218
+ const tape = new PagedStorage29(context, 4), scratch = new PagedStorage29(context, 4);
65410
66219
  let values, failed = false, work = 0;
65411
66220
  const cooperate = async (units = 1) => {
65412
66221
  this.signal.throwIfAborted();
@@ -65627,6 +66436,382 @@ var QpdfJsonDocument = class _QpdfJsonDocument {
65627
66436
  })();
65628
66437
  }
65629
66438
  };
66439
+
66440
+ // packages/pdf-ast/src/edit/retained-form-data.ts
66441
+ import { IntegerTable as IntegerTable19, PagedStorage as PagedStorage31 } from "@poe-platform/safe-fs/storage";
66442
+
66443
+ // packages/pdf-ast/src/edit/retained-form-data-fdf.ts
66444
+ import { IntegerTable as IntegerTable18, PagedStorage as PagedStorage30 } from "@poe-platform/safe-fs/storage";
66445
+ async function parseRetainedFdf(source, storage, set, signal) {
66446
+ const backing = new PagedStorage30({ fs: storage.fs, cwd: storage.directory, env: {}, signal }, 4), tokens = new IntegerTable18(backing), starts = new IntegerTable18(backing), children = new IntegerTable18(backing), visited = new IntegerTable18(backing), names = new PdfNameIndex(storage, Infinity, signal);
66447
+ let count = 0, cursor = 0, head = -1, work = 0, failed = false;
66448
+ const cache = /* @__PURE__ */ new Map();
66449
+ async function checkpoint() {
66450
+ signal.throwIfAborted();
66451
+ if (++work % 128 === 0) {
66452
+ await new Promise((resolve2) => setTimeout(resolve2, 0));
66453
+ signal.throwIfAborted();
66454
+ }
66455
+ }
66456
+ async function token2(index2) {
66457
+ if (index2 < 0 || index2 >= count) return;
66458
+ const cached = cache.get(index2);
66459
+ if (cached) return cached;
66460
+ const at = Number(await tokens.get(BigInt(index2))) - 1, result = (await readStoredRecord(backing, at, signal)).value;
66461
+ if (cache.size >= 8) cache.delete(cache.keys().next().value);
66462
+ cache.set(index2, result);
66463
+ return result;
66464
+ }
66465
+ async function objectKey(object) {
66466
+ return BigInt((await names.intern(String(object))).index);
66467
+ }
66468
+ async function push(frame) {
66469
+ head = await appendStoredRecord(backing, { frame, previous: head }, -1, signal);
66470
+ }
66471
+ function dict(prefix) {
66472
+ return { kind: "dict", prefix, partial: "", value: "", hasValue: false, children: -1 };
66473
+ }
66474
+ function text(token3) {
66475
+ return token3.kind === "name" ? token3.decoded : token3.kind === "string" || token3.kind === "hex-string" ? decodePdfString({ kind: "string", bytes: token3.bytes, encoding: token3.kind === "string" ? "literal" : "hex" }) : "";
66476
+ }
66477
+ async function reference(index2) {
66478
+ const a = await token2(index2), b = await token2(index2 + 1), c = await token2(index2 + 2);
66479
+ return a?.kind === "number" && b?.kind === "number" && c?.kind === "keyword" && c.value === "R" ? a.value : void 0;
66480
+ }
66481
+ try {
66482
+ const lexer = new CosRangeLexer(source, { signal, compactNumbers: true });
66483
+ for (let next = await lexer.nextToken(); next; next = await lexer.nextToken()) {
66484
+ await checkpoint();
66485
+ const at = await appendStoredRecord(backing, next, -1, signal);
66486
+ await tokens.set(BigInt(count++), BigInt(at + 1));
66487
+ }
66488
+ for (let i = 0; i < count; i++) {
66489
+ await checkpoint();
66490
+ const a = await token2(i), b = await token2(i + 1), c = await token2(i + 2), d = await token2(i + 3);
66491
+ if (a?.kind === "number" && b?.kind === "number" && c?.kind === "keyword" && c.value === "obj" && d?.kind === "dict-start") await starts.set(await objectKey(a.value), BigInt(i + 5));
66492
+ if (a?.kind === "name" && a.decoded === "Kids" && b?.kind === "array-start") {
66493
+ let depth = 1;
66494
+ for (let k = i + 2; k < count && depth > 0; k++) {
66495
+ await checkpoint();
66496
+ const next = await token2(k);
66497
+ if (next?.kind === "array-start") depth++;
66498
+ else if (next?.kind === "array-end") depth--;
66499
+ else if (depth === 1) {
66500
+ const ref = await reference(k);
66501
+ if (ref !== void 0) {
66502
+ await children.set(await objectKey(ref), 1n);
66503
+ k += 2;
66504
+ }
66505
+ }
66506
+ }
66507
+ }
66508
+ }
66509
+ await push({ kind: "scan" });
66510
+ while (head !== -1) {
66511
+ await checkpoint();
66512
+ const record = await readStoredRecord(backing, head, signal);
66513
+ head = record.value.previous;
66514
+ const frame = record.value.frame;
66515
+ if (frame.kind === "restore") {
66516
+ cursor = frame.cursor;
66517
+ continue;
66518
+ }
66519
+ if (frame.kind === "ref") {
66520
+ const key = await objectKey(frame.object), start = await starts.get(key);
66521
+ if (start && !await visited.get(key)) {
66522
+ await visited.set(key, 1n);
66523
+ cursor = Number(start) - 1;
66524
+ await push(dict(frame.prefix));
66525
+ }
66526
+ continue;
66527
+ }
66528
+ if (frame.kind === "children") {
66529
+ let ref = frame.refs;
66530
+ while (ref !== -1) {
66531
+ const row = await readStoredRecord(backing, ref, signal);
66532
+ await push({ kind: "ref", object: row.value.object, prefix: frame.prefix });
66533
+ ref = row.value.previous;
66534
+ }
66535
+ cursor = frame.start;
66536
+ await push({ kind: "range", end: frame.end, prefix: frame.prefix });
66537
+ continue;
66538
+ }
66539
+ if (frame.kind === "scan" || frame.kind === "range") {
66540
+ const end = frame.kind === "range" ? frame.end : count;
66541
+ while (cursor < end) {
66542
+ await checkpoint();
66543
+ const a = await token2(cursor);
66544
+ if (frame.kind === "scan" && a?.kind === "number") {
66545
+ const b = await token2(cursor + 1), c = await token2(cursor + 2);
66546
+ if (b?.kind === "number" && c?.kind === "keyword" && c.value === "obj") {
66547
+ const key = await objectKey(a.value);
66548
+ if (await children.get(key) || await visited.get(key)) {
66549
+ cursor += 3;
66550
+ while (cursor < count) {
66551
+ await checkpoint();
66552
+ const t = await token2(cursor++);
66553
+ if (t?.kind === "keyword" && t.value === "endobj") break;
66554
+ }
66555
+ continue;
66556
+ }
66557
+ }
66558
+ }
66559
+ cursor++;
66560
+ if (a?.kind === "dict-start") {
66561
+ await push(frame);
66562
+ await push(dict(frame.kind === "range" ? frame.prefix : ""));
66563
+ break;
66564
+ }
66565
+ }
66566
+ continue;
66567
+ }
66568
+ let nested = false;
66569
+ while (cursor < count) {
66570
+ await checkpoint();
66571
+ const next = await token2(cursor++);
66572
+ if (next?.kind === "dict-end") break;
66573
+ if (next?.kind === "dict-start") {
66574
+ await push(frame);
66575
+ await push(dict(frame.prefix && frame.partial ? `${frame.prefix}.${frame.partial}` : frame.partial || frame.prefix));
66576
+ nested = true;
66577
+ break;
66578
+ }
66579
+ if (next?.kind !== "name") continue;
66580
+ const value = await token2(cursor);
66581
+ if (next.decoded === "T" && (value?.kind === "string" || value?.kind === "hex-string" || value?.kind === "name")) {
66582
+ frame.partial = text(value);
66583
+ cursor++;
66584
+ } else if (next.decoded === "V" && value) {
66585
+ if (value.kind === "string" || value.kind === "hex-string" || value.kind === "name") {
66586
+ const decoded = text(value);
66587
+ frame.value = value.kind === "name" ? decoded === "Off" ? false : decoded === "Yes" || decoded === "On" ? true : decoded : decoded;
66588
+ frame.hasValue = true;
66589
+ cursor++;
66590
+ } else if (value.kind === "number" || value.kind === "boolean") {
66591
+ frame.value = value.kind === "number" ? String(value.value) : value.value;
66592
+ frame.hasValue = true;
66593
+ cursor++;
66594
+ } else if (value.kind === "array-start") {
66595
+ cursor++;
66596
+ let depth = 1, joined = "", items = 0;
66597
+ while (cursor < count && depth > 0) {
66598
+ await checkpoint();
66599
+ const t = await token2(cursor++);
66600
+ if (t?.kind === "array-start") depth++;
66601
+ else if (t?.kind === "array-end") depth--;
66602
+ else if (depth === 1 && t && (t.kind === "string" || t.kind === "hex-string" || t.kind === "name")) {
66603
+ joined += (items++ ? "," : "") + text(t);
66604
+ }
66605
+ }
66606
+ frame.value = joined;
66607
+ frame.hasValue = true;
66608
+ }
66609
+ } else if ((next.decoded === "Kids" || next.decoded === "Fields") && value?.kind === "array-start") {
66610
+ cursor++;
66611
+ const start = cursor;
66612
+ let depth = 1, refs = -1;
66613
+ while (cursor < count && depth > 0) {
66614
+ await checkpoint();
66615
+ const t = await token2(cursor++);
66616
+ if (t?.kind === "array-start") depth++;
66617
+ else if (t?.kind === "array-end") depth--;
66618
+ else if (depth === 1) {
66619
+ const ref = await reference(cursor - 1);
66620
+ if (ref !== void 0) {
66621
+ refs = await appendStoredRecord(backing, { object: ref, previous: refs }, -1, signal);
66622
+ cursor += 2;
66623
+ }
66624
+ }
66625
+ }
66626
+ frame.children = await appendStoredRecord(backing, { start, end: cursor - 1, refs, previous: frame.children }, -1, signal);
66627
+ }
66628
+ }
66629
+ if (nested) continue;
66630
+ const name = frame.prefix && frame.partial ? `${frame.prefix}.${frame.partial}` : frame.partial || frame.prefix;
66631
+ if (name && frame.hasValue) await set(name, frame.value);
66632
+ if (frame.children !== -1) {
66633
+ await push({ kind: "restore", cursor });
66634
+ let child = frame.children;
66635
+ while (child !== -1) {
66636
+ const row = (await readStoredRecord(backing, child, signal)).value;
66637
+ await push({ kind: "children", start: row.start, end: row.end, refs: row.refs, prefix: name });
66638
+ child = row.previous;
66639
+ }
66640
+ }
66641
+ }
66642
+ } catch (error) {
66643
+ failed = true;
66644
+ throw error;
66645
+ } finally {
66646
+ const results = await Promise.allSettled([backing.close(), names.close()]);
66647
+ if (!failed) {
66648
+ for (const result of results) if (result.status === "rejected") await Promise.reject(result.reason);
66649
+ }
66650
+ }
66651
+ }
66652
+
66653
+ // packages/pdf-ast/src/edit/retained-form-data.ts
66654
+ var FormText = class {
66655
+ constructor(backing, signal) {
66656
+ this.backing = backing;
66657
+ this.signal = signal;
66658
+ this.base = backing.allocate(0);
66659
+ }
66660
+ backing;
66661
+ signal;
66662
+ length = 0;
66663
+ base;
66664
+ async load(source) {
66665
+ const decoder = new TextDecoder();
66666
+ const append = async (text) => {
66667
+ for (let start = 0; start < text.length; start += 4096) {
66668
+ this.signal.throwIfAborted();
66669
+ const length = Math.min(4096, text.length - start), bytes = new Uint8Array(length * 2), view = new DataView(bytes.buffer);
66670
+ for (let i = 0; i < length; i++) view.setUint16(i * 2, text.charCodeAt(start + i), true);
66671
+ await this.backing.write(this.backing.allocate(bytes.length), bytes);
66672
+ this.length += length;
66673
+ }
66674
+ };
66675
+ for await (const chunk of source.stream(0, source.size, this.signal)) await append(decoder.decode(chunk, { stream: true }));
66676
+ await append(decoder.decode());
66677
+ }
66678
+ async read(start, end) {
66679
+ let result = "";
66680
+ for (let at = start; at < end; at += 4096) {
66681
+ this.signal.throwIfAborted();
66682
+ const length = Math.min(4096, end - at), bytes = await this.backing.read(this.base + at * 2, length * 2), view = new DataView(bytes.buffer, bytes.byteOffset, bytes.length);
66683
+ const units = [];
66684
+ for (let i = 0; i < length; i++) units.push(view.getUint16(i * 2, true));
66685
+ result += String.fromCharCode(...units);
66686
+ }
66687
+ return result;
66688
+ }
66689
+ async indexOf(needle, start = 0) {
66690
+ for (let at = start; at < this.length; at += 4096) {
66691
+ const part = await this.read(at, Math.min(this.length, at + 4096 + needle.length - 1)), index2 = part.indexOf(needle);
66692
+ if (index2 >= 0) return at + index2;
66693
+ }
66694
+ return -1;
66695
+ }
66696
+ async prefix() {
66697
+ for (let at = 0; at < this.length; at += 4096) {
66698
+ const part = await this.read(at, Math.min(this.length, at + 4096)), trimmed = part.trimStart();
66699
+ if (trimmed) return this.read(at + part.length - trimmed.length, Math.min(this.length, at + part.length - trimmed.length + 5));
66700
+ }
66701
+ return "";
66702
+ }
66703
+ };
66704
+ async function* parseRetainedFormData(source, storage, options = {}) {
66705
+ const signal = options.signal ?? new AbortController().signal, context = { fs: storage.fs, cwd: storage.directory, env: {}, signal };
66706
+ const textBacking = new PagedStorage31(context, 2), state = new PagedStorage31(context, 4), names = new PdfNameIndex(storage, Infinity, signal), values = new IntegerTable19(state);
66707
+ const text = new FormText(textBacking, signal);
66708
+ let count = 0, failed = false, work = 0;
66709
+ async function checkpoint() {
66710
+ signal.throwIfAborted();
66711
+ if (++work % 64 === 0) {
66712
+ await new Promise((resolve2) => setTimeout(resolve2, 0));
66713
+ signal.throwIfAborted();
66714
+ }
66715
+ }
66716
+ async function set(name, value, append = false) {
66717
+ await checkpoint();
66718
+ const key = await names.intern(name), at = await values.get(BigInt(key.index));
66719
+ if (key.added) count++;
66720
+ if (append && typeof value === "string" && at) {
66721
+ const previous = (await readStoredRecord(state, Number(at) - 1, signal)).value.value;
66722
+ if (typeof previous === "string" && previous.length) value = `${previous},${value}`;
66723
+ }
66724
+ const offset = await appendStoredRecord(state, { name, value }, -1, signal);
66725
+ await values.set(BigInt(key.index), BigInt(offset + 1));
66726
+ }
66727
+ try {
66728
+ await text.load(source);
66729
+ const prefix = await text.prefix();
66730
+ if (prefix === "%FDF-" || await text.indexOf("/FDF") >= 0 && await text.indexOf("/Fields") >= 0) await parseRetainedFdf(source, storage, set, signal);
66731
+ else if (prefix === "<?xml" || prefix === "<xfdf" || await text.indexOf("<fields") >= 0) {
66732
+ let position = 0, head = -1, field2 = "";
66733
+ while (position < text.length) {
66734
+ await checkpoint();
66735
+ const lt = await text.indexOf("<", position);
66736
+ if (lt < 0) break;
66737
+ const gt = await text.indexOf(">", lt + 1);
66738
+ if (gt < 0) break;
66739
+ const raw = (await text.read(lt + 1, gt)).trim();
66740
+ position = gt + 1;
66741
+ if (raw.startsWith("?") || raw.startsWith("!")) continue;
66742
+ if (raw.startsWith("/")) {
66743
+ if (raw.slice(1).trim().toLowerCase() === "field" && head !== -1) {
66744
+ const row = (await readStoredRecord(state, head, signal)).value;
66745
+ field2 = row.field;
66746
+ head = row.previous;
66747
+ }
66748
+ continue;
66749
+ }
66750
+ const selfClosing = raw.endsWith("/"), tag = selfClosing ? raw.slice(0, -1).trim() : raw, space = tag.indexOf(" "), name = (space < 0 ? tag : tag.slice(0, space)).toLowerCase();
66751
+ if (name === "field") {
66752
+ let part = "";
66753
+ const at = tag.indexOf("name=");
66754
+ if (at >= 0) {
66755
+ const quote = tag[at + 5];
66756
+ if (quote === '"' || quote === "'") {
66757
+ const end = tag.indexOf(quote, at + 6);
66758
+ if (end >= 0) part = decodeFormDataEntities(tag.slice(at + 6, end));
66759
+ }
66760
+ }
66761
+ if (!selfClosing) {
66762
+ head = await appendStoredRecord(state, { field: field2, previous: head }, -1, signal);
66763
+ field2 = field2 && part ? `${field2}.${part}` : field2 || part;
66764
+ }
66765
+ } else if (name === "value" && !selfClosing && head !== -1) {
66766
+ const close = await text.indexOf("</value>", position);
66767
+ if (close >= 0) {
66768
+ const value = decodeFormDataEntities(await text.read(position, close));
66769
+ if (field2) await set(field2, value === "Off" ? false : value === "Yes" || value === "On" ? true : value, true);
66770
+ position = close + 8;
66771
+ }
66772
+ }
66773
+ }
66774
+ } else {
66775
+ const report = await text.indexOf("FieldName:") >= 0;
66776
+ let position = 0, name = "", type = "";
66777
+ while (position < text.length) {
66778
+ await checkpoint();
66779
+ const newline = await text.indexOf("\n", position), end = newline < 0 ? text.length : newline, line = (await text.read(position, end)).trim();
66780
+ position = end + 1;
66781
+ if (report) {
66782
+ if (line === "---") {
66783
+ name = "";
66784
+ type = "";
66785
+ } else if (line.startsWith("FieldType:")) type = line.slice(10).trim();
66786
+ else if (line.startsWith("FieldName:")) name = decodeFormDataEntities(line.slice(10).trim());
66787
+ else if (line.startsWith("FieldValue:") && name) {
66788
+ const value = decodeFormDataEntities(line.slice(11).trim());
66789
+ await set(name, value === "Yes" || value === "On" ? true : value === "Off" || value === "false" || type === "Button" && value === "" ? false : value, true);
66790
+ }
66791
+ } else {
66792
+ if (!line || line.startsWith("#")) continue;
66793
+ const equals = line.indexOf("="), colon = line.indexOf(":"), separator = equals >= 0 ? equals : colon;
66794
+ if (separator > 0) {
66795
+ const name2 = line.slice(0, separator).trim(), value = line.slice(separator + 1).trim();
66796
+ await set(name2, value === "true" || value === "Yes" || value === "On" ? true : value === "false" || value === "Off" ? false : value);
66797
+ }
66798
+ }
66799
+ }
66800
+ }
66801
+ for (let index2 = 0; index2 < count; index2++) {
66802
+ await checkpoint();
66803
+ yield (await readStoredRecord(state, Number(await values.get(BigInt(index2))) - 1, signal)).value;
66804
+ }
66805
+ } catch (error) {
66806
+ failed = true;
66807
+ throw error;
66808
+ } finally {
66809
+ const results = await Promise.allSettled([textBacking.close(), state.close(), names.close()]);
66810
+ if (!failed) {
66811
+ for (const result of results) if (result.status === "rejected") await Promise.reject(result.reason);
66812
+ }
66813
+ }
66814
+ }
65630
66815
  export {
65631
66816
  CosByteLexer,
65632
66817
  CosRangeLexer,
@@ -65692,6 +66877,7 @@ export {
65692
66877
  decodeCcittFax,
65693
66878
  decodeCcittFaxChunks,
65694
66879
  decodeFlate,
66880
+ decodeFormDataEntities,
65695
66881
  decodeInlineImageNodeToRgba,
65696
66882
  decodeInlineImageNodeToRgbaSteps,
65697
66883
  decodeJbig2ToRgba,
@@ -65753,6 +66939,9 @@ export {
65753
66939
  encodeRgbaToPng,
65754
66940
  encodeRgbaToPngSteps,
65755
66941
  encodeRunLength,
66942
+ encodeSvgImageChunks,
66943
+ encodeSvgPathDataChunks,
66944
+ encodeSvgPathPaintChunks,
65756
66945
  encodeTiff,
65757
66946
  encodeTiffSteps,
65758
66947
  encodeWinAnsiBytes,
@@ -65815,6 +67004,7 @@ export {
65815
67004
  parseCosRangeObject,
65816
67005
  parseCosRangeValue,
65817
67006
  parseFormDataBytes,
67007
+ parseRetainedFormData,
65818
67008
  parseToUnicodeCMap,
65819
67009
  parseToUnicodeCMapSteps,
65820
67010
  parseTrueTypeFont,