sandforge 1.84.1 → 1.86.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (277) hide show
  1. package/README.md +1 -1
  2. package/lib/{chunk-S42RBRH2.mjs → chunk-22L43JMK.mjs} +1 -1
  3. package/lib/{chunk-Y2DRK37K.mjs → chunk-2LSGWTWX.mjs} +1 -1
  4. package/lib/{chunk-24RFOFYT.mjs → chunk-2YJJTQNC.mjs} +1 -1
  5. package/lib/chunk-34SMB5PA.mjs +10 -0
  6. package/lib/chunk-35B73566.mjs +7 -0
  7. package/lib/{chunk-3TZSBHEY.mjs → chunk-35IJ4WEU.mjs} +1 -1
  8. package/lib/chunk-3EHPAFKV.mjs +7 -0
  9. package/lib/{chunk-6YL7BNYD.mjs → chunk-3HAVVEXF.mjs} +1 -1
  10. package/lib/{chunk-6JWWSDM6.mjs → chunk-3I6FXFCN.mjs} +1 -1
  11. package/lib/{chunk-WUUKFE2U.mjs → chunk-3KJCSYXY.mjs} +1 -1
  12. package/lib/{chunk-2HVOZUM4.mjs → chunk-3L6DVNCR.mjs} +1 -1
  13. package/lib/chunk-3LRFPGYZ.mjs +7 -0
  14. package/lib/{chunk-GWZRR3MM.mjs → chunk-3MVWGL5A.mjs} +1 -1
  15. package/lib/{chunk-KGU4SVIT.mjs → chunk-4CSBZZAL.mjs} +1 -1
  16. package/lib/{chunk-JE6SCT6R.mjs → chunk-4NSXPONF.mjs} +1 -1
  17. package/lib/{chunk-UIOMAX56.mjs → chunk-4VLP6RHC.mjs} +1 -1
  18. package/lib/{chunk-YA6ATMTB.mjs → chunk-4XROG5CT.mjs} +1 -1
  19. package/lib/chunk-54V4FVEY.mjs +7 -0
  20. package/lib/chunk-55OJJT2Q.mjs +7 -0
  21. package/lib/{chunk-6QE6R6RL.mjs → chunk-5EHHQ5UX.mjs} +1 -1
  22. package/lib/{chunk-FITPY3L4.mjs → chunk-5JMQXHJ2.mjs} +1 -1
  23. package/lib/{chunk-W6PN6TJG.mjs → chunk-65AMXOQU.mjs} +1 -1
  24. package/lib/{chunk-3Q353S2R.mjs → chunk-6HHSAPIM.mjs} +1 -1
  25. package/lib/chunk-6KVBCFVS.mjs +7 -0
  26. package/lib/chunk-6NG7C2U3.mjs +476 -0
  27. package/lib/chunk-6ROL3KBM.mjs +7 -0
  28. package/lib/{chunk-2JDAOWUW.mjs → chunk-72AWCN7U.mjs} +1 -1
  29. package/lib/{chunk-JLSIWO4Z.mjs → chunk-7KHA5UIQ.mjs} +1 -1
  30. package/lib/chunk-7O6EFNQS.mjs +10 -0
  31. package/lib/{chunk-WWTCWWZI.mjs → chunk-A2CH2QGX.mjs} +1 -1
  32. package/lib/chunk-A2TXLAC3.mjs +276 -0
  33. package/lib/chunk-ALWVNR34.mjs +7 -0
  34. package/lib/{chunk-D4GF4FAB.mjs → chunk-ATBQIE2V.mjs} +1 -1
  35. package/lib/{chunk-NED4MBIM.mjs → chunk-ATQML7ZK.mjs} +1 -1
  36. package/lib/chunk-AVY742BJ.mjs +7 -0
  37. package/lib/{chunk-YWEQQL3C.mjs → chunk-AXTB2HJS.mjs} +1 -1
  38. package/lib/chunk-BBZUGKBZ.mjs +10 -0
  39. package/lib/chunk-BIDXK7KA.mjs +7 -0
  40. package/lib/{chunk-O677VOGO.mjs → chunk-BLMJ4WVI.mjs} +1 -1
  41. package/lib/{chunk-RE7RYF3B.mjs → chunk-BNHJCJJM.mjs} +1 -1
  42. package/lib/{chunk-5M5FQ7RP.mjs → chunk-BNPQEQXC.mjs} +1 -1
  43. package/lib/chunk-C5AUNG6T.mjs +37 -0
  44. package/lib/{chunk-ETDCBLGU.mjs → chunk-C5EQ7GFC.mjs} +1 -1
  45. package/lib/{chunk-MJZU3U5O.mjs → chunk-C7CKDZMC.mjs} +61 -61
  46. package/lib/{chunk-HCGXK7G7.mjs → chunk-CB4U22NR.mjs} +1 -1
  47. package/lib/chunk-CJAWKLAL.mjs +7 -0
  48. package/lib/chunk-CL75DEMQ.mjs +9 -0
  49. package/lib/{chunk-VCUXCK36.mjs → chunk-CLUNF4FK.mjs} +1 -1
  50. package/lib/chunk-CSMGP53U.mjs +7 -0
  51. package/lib/{chunk-7YNM6KFZ.mjs → chunk-CT324C7I.mjs} +1 -1
  52. package/lib/{chunk-7UVKIWKV.mjs → chunk-CZXDJXQP.mjs} +1 -1
  53. package/lib/{chunk-43TOMFV4.mjs → chunk-D2X6U3MS.mjs} +1 -1
  54. package/lib/{chunk-M6K34KGF.mjs → chunk-DAUX63UB.mjs} +1 -1
  55. package/lib/chunk-DB7JNALQ.mjs +10 -0
  56. package/lib/chunk-DDNCJVZ2.mjs +17 -0
  57. package/lib/{chunk-FP7CYB2F.mjs → chunk-DLSU66MY.mjs} +1 -1
  58. package/lib/{chunk-JKJ74BX5.mjs → chunk-DO6PSHQZ.mjs} +1 -1
  59. package/lib/{chunk-MDMPJEV3.mjs → chunk-DUBECLZV.mjs} +1 -1
  60. package/lib/{chunk-KZTZDC7H.mjs → chunk-DYHF6DNT.mjs} +1 -1
  61. package/lib/chunk-E5FSPXYH.mjs +930 -0
  62. package/lib/{chunk-Q7GIJBCD.mjs → chunk-EGL3I3IX.mjs} +1 -1
  63. package/lib/chunk-EIYMQPMG.mjs +7 -0
  64. package/lib/{chunk-RHNTHGNU.mjs → chunk-EUIALBMX.mjs} +1 -1
  65. package/lib/{chunk-NCZKWSC7.mjs → chunk-FI3R5ZOQ.mjs} +1 -1
  66. package/lib/{chunk-PAXNWTYK.mjs → chunk-FM4QCTO7.mjs} +1 -1
  67. package/lib/{chunk-HV7VPEXP.mjs → chunk-FRSIEASH.mjs} +1 -1
  68. package/lib/{chunk-QAFPQ3YB.mjs → chunk-FV6MOSHD.mjs} +1 -1
  69. package/lib/chunk-FYG47CNA.mjs +7 -0
  70. package/lib/chunk-GB6W4Q56.mjs +7 -0
  71. package/lib/chunk-GEV2DCMK.mjs +7 -0
  72. package/lib/{chunk-NSQWI7ZY.mjs → chunk-GFB2DNCB.mjs} +1 -1
  73. package/lib/chunk-GFGMGFSH.mjs +7 -0
  74. package/lib/{chunk-RGUQOSBU.mjs → chunk-GIFQXB2Q.mjs} +1 -1
  75. package/lib/{chunk-JAEDM4SI.mjs → chunk-GP5J3DGS.mjs} +1 -1
  76. package/lib/chunk-GQZEX7LH.mjs +231 -0
  77. package/lib/{chunk-JSAJS3MY.mjs → chunk-GYDTM62J.mjs} +1 -1
  78. package/lib/{chunk-OPMO6I45.mjs → chunk-GYFIXUJG.mjs} +1 -1
  79. package/lib/chunk-GZW2GNFK.mjs +7 -0
  80. package/lib/chunk-H6BHWAX7.mjs +8 -0
  81. package/lib/{chunk-EAC5QCE3.mjs → chunk-HDDJ3CVN.mjs} +1 -1
  82. package/lib/{chunk-5SMWFNE7.mjs → chunk-HDWB4ZOG.mjs} +1 -1
  83. package/lib/chunk-HGVPBJR6.mjs +7 -0
  84. package/lib/{chunk-BBRWFKS5.mjs → chunk-HLROVOR6.mjs} +1 -1
  85. package/lib/{chunk-LKTNQEBS.mjs → chunk-HUOR4M2L.mjs} +1 -1
  86. package/lib/chunk-HZCS6EED.mjs +8 -0
  87. package/lib/{chunk-36JOHEJL.mjs → chunk-HZUI56KZ.mjs} +1 -1
  88. package/lib/chunk-IAB5H7WN.mjs +7 -0
  89. package/lib/{chunk-X4BXESMQ.mjs → chunk-IQ5UKRHU.mjs} +1 -1
  90. package/lib/{chunk-54WZUS7J.mjs → chunk-IRQ4WANV.mjs} +1 -1
  91. package/lib/{chunk-5IZTFMJM.mjs → chunk-IT3DGX37.mjs} +1 -1
  92. package/lib/chunk-J347SPU6.mjs +49 -0
  93. package/lib/{chunk-QO53K5W2.mjs → chunk-JANBNTR5.mjs} +1 -1
  94. package/lib/chunk-JFXQZPRY.mjs +9 -0
  95. package/lib/{chunk-KAZS5Z6W.mjs → chunk-JRLYWVF4.mjs} +1 -1
  96. package/lib/{chunk-GKY2JMHY.mjs → chunk-JSNMUTY6.mjs} +1 -1
  97. package/lib/chunk-JTNJKSAA.mjs +7 -0
  98. package/lib/{chunk-7WATA4SB.mjs → chunk-JV2LAKWQ.mjs} +1 -1
  99. package/lib/{chunk-WAPSSYMT.mjs → chunk-JV7K2ZHK.mjs} +1 -1
  100. package/lib/{chunk-ZBAWJUG2.mjs → chunk-K4TQ7YHX.mjs} +1 -1
  101. package/lib/chunk-K5PUMHZU.mjs +7 -0
  102. package/lib/chunk-KH4KLCYG.mjs +7 -0
  103. package/lib/{chunk-OLCVHL7I.mjs → chunk-KQVLZVOP.mjs} +1 -1
  104. package/lib/chunk-KWUS7UAV.mjs +19 -0
  105. package/lib/{chunk-JGZPD4IM.mjs → chunk-L6G73FXM.mjs} +1 -1
  106. package/lib/{chunk-BAWCOKRW.mjs → chunk-LG466Q5H.mjs} +1 -1
  107. package/lib/{chunk-GMIGWR6U.mjs → chunk-LHNAR6FC.mjs} +1 -1
  108. package/lib/chunk-LT4GHEI2.mjs +7 -0
  109. package/lib/{chunk-EC72TIEG.mjs → chunk-MR262Y3B.mjs} +1 -1
  110. package/lib/{chunk-LA4KIATH.mjs → chunk-NCCHOV2N.mjs} +1 -1
  111. package/lib/chunk-NICRSGLS.mjs +7 -0
  112. package/lib/chunk-NV5QA2HY.mjs +7 -0
  113. package/lib/{chunk-PR3XCSPO.mjs → chunk-O3GIN5TU.mjs} +1 -1
  114. package/lib/chunk-O6FHK6NQ.mjs +13 -0
  115. package/lib/{chunk-M4BLK6HJ.mjs → chunk-O7YIEFG7.mjs} +1 -1
  116. package/lib/chunk-OCUVAA5E.mjs +7 -0
  117. package/lib/chunk-OLCS7JCT.mjs +14 -0
  118. package/lib/chunk-ON7Y63FK.mjs +9 -0
  119. package/lib/{chunk-N4WPCWJO.mjs → chunk-OO2WY3UB.mjs} +1 -1
  120. package/lib/{chunk-MSIEU5MR.mjs → chunk-OT2NHL2V.mjs} +1 -1
  121. package/lib/{chunk-6WX5ZU7Q.mjs → chunk-P2M5ZXWU.mjs} +1 -1
  122. package/lib/{chunk-GNRSF65U.mjs → chunk-P4YOHLZ4.mjs} +1 -1
  123. package/lib/chunk-PBHDPTT6.mjs +343 -0
  124. package/lib/chunk-PE7CHD2W.mjs +7 -0
  125. package/lib/{chunk-PBY2O6OF.mjs → chunk-PIQ2I67B.mjs} +1 -1
  126. package/lib/chunk-PKYDNZJK.mjs +7 -0
  127. package/lib/chunk-PVZ72OOQ.mjs +7 -0
  128. package/lib/chunk-QACFTHJM.mjs +8 -0
  129. package/lib/{chunk-J3DND3BC.mjs → chunk-QGVL5EW3.mjs} +1 -1
  130. package/lib/chunk-QHE2RUWX.mjs +7 -0
  131. package/lib/{chunk-QKEKG2LD.mjs → chunk-RCW5BZNW.mjs} +1 -1
  132. package/lib/{chunk-4JE4BYXK.mjs → chunk-RJ6HHG7J.mjs} +1 -1
  133. package/lib/{chunk-ZQWIVYVM.mjs → chunk-RPTEEI4R.mjs} +1 -1
  134. package/lib/chunk-RQW5S67A.mjs +7 -0
  135. package/lib/chunk-RTCMYMED.mjs +7 -0
  136. package/lib/chunk-RWVX7XSD.mjs +7 -0
  137. package/lib/{chunk-WY5V5PR3.mjs → chunk-RZOINFNL.mjs} +1 -1
  138. package/lib/chunk-SOOTWGMQ.mjs +7 -0
  139. package/lib/chunk-STQ2JMIZ.mjs +7 -0
  140. package/lib/{chunk-6PD6K7LP.mjs → chunk-SUIPDW5O.mjs} +1 -1
  141. package/lib/{chunk-TNT27RBG.mjs → chunk-SZOJ7BEJ.mjs} +1 -1
  142. package/lib/{chunk-4EOHEDFP.mjs → chunk-T542Z54E.mjs} +1 -1
  143. package/lib/chunk-TAN2CIRI.mjs +21 -0
  144. package/lib/{chunk-A3MYSOOC.mjs → chunk-TCNBINOG.mjs} +1 -1
  145. package/lib/chunk-TFDF3DBN.mjs +7 -0
  146. package/lib/chunk-TICZXC53.mjs +9 -0
  147. package/lib/chunk-TLX45X5U.mjs +7 -0
  148. package/lib/{chunk-QTG6LUZT.mjs → chunk-TMIV3IWH.mjs} +1 -1
  149. package/lib/chunk-TQ6HEJ73.mjs +11 -0
  150. package/lib/chunk-TTU5EQZ6.mjs +7 -0
  151. package/lib/chunk-TYUYPFDJ.mjs +7 -0
  152. package/lib/chunk-TZXYVMZC.mjs +7 -0
  153. package/lib/chunk-UCUFLFNK.mjs +7 -0
  154. package/lib/chunk-UK3QLBHW.mjs +7 -0
  155. package/lib/{chunk-IZGCEOYO.mjs → chunk-UM2B4GR7.mjs} +1 -1
  156. package/lib/chunk-UZFTTNOP.mjs +7 -0
  157. package/lib/chunk-V3AXSKSU.mjs +7 -0
  158. package/lib/chunk-VA6EEI6X.mjs +21 -0
  159. package/lib/{chunk-OFTT7J2M.mjs → chunk-VFKG2G37.mjs} +1 -1
  160. package/lib/chunk-VJNEW5MQ.mjs +7 -0
  161. package/lib/{chunk-L53JWJ3S.mjs → chunk-VKREON6Q.mjs} +1 -1
  162. package/lib/{chunk-NOBQTEQD.mjs → chunk-VNNDYPBL.mjs} +1 -1
  163. package/lib/{chunk-ZJW6YOMV.mjs → chunk-VRBETPHY.mjs} +1 -1
  164. package/lib/{chunk-EPFCERGL.mjs → chunk-VT6P3X6R.mjs} +1 -1
  165. package/lib/{chunk-ZV7ZFQQC.mjs → chunk-VUTQY76O.mjs} +1 -1
  166. package/lib/chunk-WF5S4FW5.mjs +7 -0
  167. package/lib/{chunk-Z4LKKOFY.mjs → chunk-WJGK6VGU.mjs} +1 -1
  168. package/lib/{chunk-5CRLRHOJ.mjs → chunk-WJHMB3SL.mjs} +1 -1
  169. package/lib/{chunk-OUZQPYT3.mjs → chunk-WQCXOZEJ.mjs} +1 -1
  170. package/lib/{chunk-L2E5WBGD.mjs → chunk-WVVFR4E3.mjs} +1 -1
  171. package/lib/{chunk-PWRJRL5U.mjs → chunk-XBYXT74L.mjs} +1 -1
  172. package/lib/chunk-XJE3LJHP.mjs +7 -0
  173. package/lib/{chunk-CPQIZGG5.mjs → chunk-XV4CVZYD.mjs} +1 -1
  174. package/lib/chunk-Y37ED7AS.mjs +7 -0
  175. package/lib/{chunk-YTLUYSMF.mjs → chunk-YGBNZYT4.mjs} +1 -1
  176. package/lib/{chunk-4CVUUVGJ.mjs → chunk-YGTOX7IL.mjs} +1 -1
  177. package/lib/{chunk-OMNMLKDT.mjs → chunk-YJ27WHKR.mjs} +1 -1
  178. package/lib/chunk-YRULC27A.mjs +7 -0
  179. package/lib/{chunk-RMFU4BAL.mjs → chunk-YSVAHT4Q.mjs} +4 -4
  180. package/lib/chunk-YTOTMJTY.mjs +15 -0
  181. package/lib/{chunk-B63POIPQ.mjs → chunk-YZKZC62O.mjs} +1 -1
  182. package/lib/{chunk-DPMRIMUC.mjs → chunk-YZQN7BRB.mjs} +1 -1
  183. package/lib/{chunk-7SQSWVAU.mjs → chunk-Z5IUK2QO.mjs} +1 -1
  184. package/lib/{chunk-M2ABR4JM.mjs → chunk-ZEGSMW5A.mjs} +1 -1
  185. package/lib/{chunk-PR42EZSR.mjs → chunk-ZIKLQZBG.mjs} +1 -1
  186. package/lib/chunk-ZVU7MD2S.mjs +7 -0
  187. package/lib/sandforge-autopilot.mjs +33 -27
  188. package/lib/sandforge-backup.mjs +19 -19
  189. package/lib/sandforge-checkpoint.mjs +1 -1
  190. package/lib/sandforge-cleanup.mjs +1 -1
  191. package/lib/sandforge-clone.mjs +1 -1
  192. package/lib/sandforge-compare.mjs +32 -14
  193. package/lib/sandforge-dataops.mjs +1 -1
  194. package/lib/sandforge-empty.mjs +11 -13
  195. package/lib/sandforge-env.mjs +105 -105
  196. package/lib/sandforge-frozen.mjs +1 -1
  197. package/lib/sandforge-mcp.mjs +2 -2
  198. package/lib/sandforge-monitor.mjs +1 -1
  199. package/lib/sandforge-pipeline.mjs +13 -13
  200. package/lib/sandforge-seed.mjs +1 -1
  201. package/lib/sandforge-sync.mjs +1 -1
  202. package/lib/sandforge-users.mjs +13 -15
  203. package/lib/sandforge.mjs +1 -1
  204. package/lib/sf/sandforge/dataops.mjs +2 -2
  205. package/lib/sfPlugin.mjs +1 -1
  206. package/oclif.manifest.json +1 -1
  207. package/package.json +1 -1
  208. package/lib/chunk-23SEDORH.mjs +0 -11
  209. package/lib/chunk-26POJDIT.mjs +0 -7
  210. package/lib/chunk-2AZQHBEF.mjs +0 -7
  211. package/lib/chunk-2METQHGG.mjs +0 -7
  212. package/lib/chunk-2WFIVO4F.mjs +0 -13
  213. package/lib/chunk-2YHZBUZE.mjs +0 -7
  214. package/lib/chunk-326AJTIU.mjs +0 -272
  215. package/lib/chunk-3PVRGTVK.mjs +0 -7
  216. package/lib/chunk-5XTUSN72.mjs +0 -8
  217. package/lib/chunk-6I6TWNV5.mjs +0 -7
  218. package/lib/chunk-6O222PW6.mjs +0 -7
  219. package/lib/chunk-6ZLKIT3H.mjs +0 -7
  220. package/lib/chunk-7QYHEHMA.mjs +0 -9
  221. package/lib/chunk-B3FBHVNN.mjs +0 -21
  222. package/lib/chunk-BEA27DLS.mjs +0 -7
  223. package/lib/chunk-BRY3PLIZ.mjs +0 -7
  224. package/lib/chunk-CBH3TOWK.mjs +0 -341
  225. package/lib/chunk-CVHNXJH3.mjs +0 -7
  226. package/lib/chunk-DGDRQRCW.mjs +0 -7
  227. package/lib/chunk-DUN2EPRC.mjs +0 -7
  228. package/lib/chunk-E3A3LOCY.mjs +0 -7
  229. package/lib/chunk-F2424IKX.mjs +0 -7
  230. package/lib/chunk-F3AQW6IU.mjs +0 -7
  231. package/lib/chunk-FNJ4SGWO.mjs +0 -7
  232. package/lib/chunk-GOOVPVWX.mjs +0 -7
  233. package/lib/chunk-H2BHESDA.mjs +0 -9
  234. package/lib/chunk-H4CGM6YO.mjs +0 -7
  235. package/lib/chunk-HIDW7FNV.mjs +0 -9
  236. package/lib/chunk-HSBXRQTI.mjs +0 -7
  237. package/lib/chunk-HUZPBE47.mjs +0 -7
  238. package/lib/chunk-I6E6T6YY.mjs +0 -7
  239. package/lib/chunk-IUM4NFKI.mjs +0 -10
  240. package/lib/chunk-IVFVNNGB.mjs +0 -37
  241. package/lib/chunk-JCFBFF4Y.mjs +0 -7
  242. package/lib/chunk-JTJK2D36.mjs +0 -7
  243. package/lib/chunk-KB4ZHM4Q.mjs +0 -10
  244. package/lib/chunk-KJWFYBMU.mjs +0 -15
  245. package/lib/chunk-LC3NDW4N.mjs +0 -7
  246. package/lib/chunk-OM5NORJG.mjs +0 -7
  247. package/lib/chunk-OVNMB6Q2.mjs +0 -7
  248. package/lib/chunk-PEDQPM2P.mjs +0 -926
  249. package/lib/chunk-PH7SP4YK.mjs +0 -21
  250. package/lib/chunk-PMN4PAC3.mjs +0 -19
  251. package/lib/chunk-PMWAFDUB.mjs +0 -48
  252. package/lib/chunk-PPLVFX6N.mjs +0 -7
  253. package/lib/chunk-PZBZ7MNC.mjs +0 -7
  254. package/lib/chunk-QROPNEGY.mjs +0 -14
  255. package/lib/chunk-RGBGUCJA.mjs +0 -156
  256. package/lib/chunk-RKTFFCNS.mjs +0 -7
  257. package/lib/chunk-ROV3QXEF.mjs +0 -475
  258. package/lib/chunk-RT47RKLY.mjs +0 -7
  259. package/lib/chunk-SI267LYR.mjs +0 -8
  260. package/lib/chunk-SRPWW4A2.mjs +0 -10
  261. package/lib/chunk-T3G6VZNS.mjs +0 -7
  262. package/lib/chunk-T63U4OZJ.mjs +0 -7
  263. package/lib/chunk-TEIBWMJM.mjs +0 -7
  264. package/lib/chunk-TW3N6W5Z.mjs +0 -7
  265. package/lib/chunk-UBIKR5VO.mjs +0 -7
  266. package/lib/chunk-UI3JQVRU.mjs +0 -8
  267. package/lib/chunk-UX3BVH2Y.mjs +0 -7
  268. package/lib/chunk-VINGECAJ.mjs +0 -10
  269. package/lib/chunk-VOXJHJIE.mjs +0 -7
  270. package/lib/chunk-WB2RIVO3.mjs +0 -7
  271. package/lib/chunk-WXDLQT2O.mjs +0 -10
  272. package/lib/chunk-XBQGZGWR.mjs +0 -7
  273. package/lib/chunk-XGGOUNPP.mjs +0 -7
  274. package/lib/chunk-XKWW3GKF.mjs +0 -7
  275. package/lib/chunk-YHR4WQPR.mjs +0 -7
  276. package/lib/chunk-ZQQXSCVI.mjs +0 -7
  277. package/lib/chunk-ZRUDYB7O.mjs +0 -7
@@ -1 +1 @@
1
- {"commands":{"sandforge":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge takes","name":"argv"}},"description":"sandforge — SandForge's command lines, without the editor: Seed, Forge's clone, Sync, Checkpoints, DataOps, Frozen Dataset, the emptying of a sandbox, the users of a sandbox, sandforge.yaml environments, Automation pipelines, and the MCP server.\n\nIts commands: sf sandforge --help. The whole help of one, its options and its exit codes: sf sandforge <command> --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"SandForge's command lines: seed, clone, sync, checkpoints, masking, Frozen Datasets, sandforge.yaml, pipelines, MCP","isESM":true,"relativePath":["lib","sf","sandforge","index.mjs"]},"sandforge:autopilot":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge autopilot takes","name":"argv"}},"description":"sandforge autopilot — run an Autopilot copy between two orgs, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge autopilot --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:autopilot","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"run an Autopilot copy between two orgs","isESM":true,"relativePath":["lib","sf","sandforge","autopilot.mjs"]},"sandforge:backup":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge backup takes","name":"argv"}},"description":"sandforge backup — take and restore DataOps snapshots, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge backup --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:backup","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"take and restore DataOps snapshots","isESM":true,"relativePath":["lib","sf","sandforge","backup.mjs"]},"sandforge:checkpoint":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge checkpoint takes","name":"argv"}},"description":"sandforge checkpoint — take a checkpoint of an org's data, and rewind the org to it, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge checkpoint --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:checkpoint","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"take a checkpoint of an org's data, and rewind the org to it","isESM":true,"relativePath":["lib","sf","sandforge","checkpoint.mjs"]},"sandforge:cleanup":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge cleanup takes","name":"argv"}},"description":"sandforge cleanup — Bulk delete records you created on a sandbox in the --since window, whether or not a clone wrote them. Preview with --dry-run and narrow with --objects before deleting.\n\nThe whole help, its options and its exit codes: sf sandforge cleanup --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:cleanup","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"Bulk delete records you created on a sandbox in a time window","isESM":true,"relativePath":["lib","sf","sandforge","cleanup.mjs"]},"sandforge:clone":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge clone takes","name":"argv"}},"description":"sandforge clone — Forge a clone of one record, or of whole tables, from a source org to a target sandbox, or remove what a run of it created.\n\nThe whole help, its options and its exit codes: sf sandforge clone --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:clone","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"clone a record, or whole tables, from one org to a sandbox, or remove a run","isESM":true,"relativePath":["lib","sf","sandforge","clone.mjs"]},"sandforge:compare":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge compare takes","name":"argv"}},"description":"sandforge compare — compare two orgs the way the Compare page does, without the editor, and deploy what differs as its Deploy tab does.\n\nThe whole help, its options and its exit codes: sf sandforge compare --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:compare","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"compare two orgs the way the Compare page does, and deploy what differs","isESM":true,"relativePath":["lib","sf","sandforge","compare.mjs"]},"sandforge:dataops":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge dataops takes","name":"argv"}},"description":"sandforge dataops — mask an org's records, and put them back, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge dataops --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:dataops","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"mask an org's records, and put them back","isESM":true,"relativePath":["lib","sf","sandforge","dataops.mjs"]},"sandforge:empty":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge empty takes","name":"argv"}},"description":"sandforge empty — empty objects of a sandbox, or the whole of it, without the editor: a dry run first, then the deletes, to the recycle bin with an undo, or for good.\n\nThe whole help, its options and its exit codes: sf sandforge empty --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:empty","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"empty objects of a sandbox, or the whole of it","isESM":true,"relativePath":["lib","sf","sandforge","empty.mjs"]},"sandforge:env":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge env takes","name":"argv"}},"description":"sandforge env — apply a sandforge.yaml to an org: the data an environment needs, declared in your repository, created, kept and taken back, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge env --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:env","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"apply a sandforge.yaml to an org, and take it back","isESM":true,"relativePath":["lib","sf","sandforge","env.mjs"]},"sandforge:frozen":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge frozen takes","name":"argv"}},"description":"sandforge frozen — build and replay a Frozen Dataset, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge frozen --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:frozen","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"build and replay a Frozen Dataset","isESM":true,"relativePath":["lib","sf","sandforge","frozen.mjs"]},"sandforge:mcp":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge mcp takes","name":"argv"}},"description":"sandforge mcp — Seed, Forge's clone of a record, of the records a query chooses or of the whole org, the removal of a run, the emptying of objects or of a whole org, Checkpoints and their replay into another org, the environments of a sandforge.yaml and the plan of an Automation pipeline, as tools for an AI agent, over the Model Context Protocol on stdio.\n\nThe whole help, its options and its exit codes: sf sandforge mcp --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:mcp","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"the MCP server: these scripts as tools for an AI agent, on stdio","isESM":true,"relativePath":["lib","sf","sandforge","mcp.mjs"]},"sandforge:monitor":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge monitor takes","name":"argv"}},"description":"sandforge monitor — read an org the way the Monitor page does, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge monitor --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:monitor","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"read an org the way the Monitor page does","isESM":true,"relativePath":["lib","sf","sandforge","monitor.mjs"]},"sandforge:pipeline":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge pipeline takes","name":"argv"}},"description":"sandforge pipeline — run an Automation pipeline exported from VS Code, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge pipeline --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:pipeline","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"plan and run an Automation pipeline exported from VS Code","isESM":true,"relativePath":["lib","sf","sandforge","pipeline.mjs"]},"sandforge:seed":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge seed takes","name":"argv"}},"description":"sandforge seed — fill an org from a seed template, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge seed --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:seed","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"fill an org from a seed template","isESM":true,"relativePath":["lib","sf","sandforge","seed.mjs"]},"sandforge:sync":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge sync takes","name":"argv"}},"description":"sandforge sync — run a Sync between two orgs, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge sync --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:sync","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"run a Sync between two orgs","isESM":true,"relativePath":["lib","sf","sandforge","sync.mjs"]},"sandforge:users":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge users takes","name":"argv"}},"description":"sandforge users — set up the users of a sandbox handed back to its testers, a scratch org or a Developer Edition org: an address the copy put under .invalid asked back, a user activated, frozen or unfrozen, a profile, permission sets, permission set groups, groups and queues given; and take a run back.\n\nThe whole help, its options and its exit codes: sf sandforge users --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:users","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"set up the users of a sandbox after its refresh, and take them back","isESM":true,"relativePath":["lib","sf","sandforge","users.mjs"]},"sandforge:hardis-commands":{"aliases":[],"args":{"argv":{"description":"nothing, or --json for the document the extension reads","name":"argv"}},"description":"The entries SandForge adds to the menus of the sfdx-hardis VS Code extension, each reaching no org. With --json, the document the extension reads, alone on stdout.","flags":{},"hasDynamicHelp":false,"hidden":true,"hiddenAliases":[],"id":"sandforge:hardis-commands","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"the menus of SandForge in the sfdx-hardis VS Code extension","isESM":true,"relativePath":["lib","sf","sandforge","hardis-commands.mjs"]}},"version":"1.84.1"}
1
+ {"commands":{"sandforge":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge takes","name":"argv"}},"description":"sandforge — SandForge's command lines, without the editor: Seed, Forge's clone, Sync, Checkpoints, DataOps, Frozen Dataset, the emptying of a sandbox, the users of a sandbox, sandforge.yaml environments, Automation pipelines, and the MCP server.\n\nIts commands: sf sandforge --help. The whole help of one, its options and its exit codes: sf sandforge <command> --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"SandForge's command lines: seed, clone, sync, checkpoints, masking, Frozen Datasets, sandforge.yaml, pipelines, MCP","isESM":true,"relativePath":["lib","sf","sandforge","index.mjs"]},"sandforge:autopilot":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge autopilot takes","name":"argv"}},"description":"sandforge autopilot — run an Autopilot copy between two orgs, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge autopilot --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:autopilot","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"run an Autopilot copy between two orgs","isESM":true,"relativePath":["lib","sf","sandforge","autopilot.mjs"]},"sandforge:backup":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge backup takes","name":"argv"}},"description":"sandforge backup — take and restore DataOps snapshots, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge backup --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:backup","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"take and restore DataOps snapshots","isESM":true,"relativePath":["lib","sf","sandforge","backup.mjs"]},"sandforge:checkpoint":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge checkpoint takes","name":"argv"}},"description":"sandforge checkpoint — take a checkpoint of an org's data, and rewind the org to it, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge checkpoint --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:checkpoint","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"take a checkpoint of an org's data, and rewind the org to it","isESM":true,"relativePath":["lib","sf","sandforge","checkpoint.mjs"]},"sandforge:cleanup":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge cleanup takes","name":"argv"}},"description":"sandforge cleanup — Bulk delete records you created on a sandbox in the --since window, whether or not a clone wrote them. Preview with --dry-run and narrow with --objects before deleting.\n\nThe whole help, its options and its exit codes: sf sandforge cleanup --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:cleanup","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"Bulk delete records you created on a sandbox in a time window","isESM":true,"relativePath":["lib","sf","sandforge","cleanup.mjs"]},"sandforge:clone":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge clone takes","name":"argv"}},"description":"sandforge clone — Forge a clone of one record, or of whole tables, from a source org to a target sandbox, or remove what a run of it created.\n\nThe whole help, its options and its exit codes: sf sandforge clone --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:clone","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"clone a record, or whole tables, from one org to a sandbox, or remove a run","isESM":true,"relativePath":["lib","sf","sandforge","clone.mjs"]},"sandforge:compare":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge compare takes","name":"argv"}},"description":"sandforge compare — compare two orgs the way the Compare page does, without the editor, and deploy what differs as its Deploy tab does.\n\nThe whole help, its options and its exit codes: sf sandforge compare --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:compare","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"compare two orgs the way the Compare page does, and deploy what differs","isESM":true,"relativePath":["lib","sf","sandforge","compare.mjs"]},"sandforge:dataops":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge dataops takes","name":"argv"}},"description":"sandforge dataops — mask an org's records and put them back, verify a masking, list templates, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge dataops --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:dataops","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"mask an org's records and put them back, verify a masking, list templates","isESM":true,"relativePath":["lib","sf","sandforge","dataops.mjs"]},"sandforge:empty":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge empty takes","name":"argv"}},"description":"sandforge empty — empty objects of a sandbox, or the whole of it, without the editor: a dry run first, then the deletes, to the recycle bin with an undo, or for good.\n\nThe whole help, its options and its exit codes: sf sandforge empty --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:empty","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"empty objects of a sandbox, or the whole of it","isESM":true,"relativePath":["lib","sf","sandforge","empty.mjs"]},"sandforge:env":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge env takes","name":"argv"}},"description":"sandforge env — apply a sandforge.yaml to an org: the data an environment needs, declared in your repository, created, kept and taken back, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge env --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:env","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"apply a sandforge.yaml to an org, and take it back","isESM":true,"relativePath":["lib","sf","sandforge","env.mjs"]},"sandforge:frozen":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge frozen takes","name":"argv"}},"description":"sandforge frozen — build and replay a Frozen Dataset, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge frozen --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:frozen","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"build and replay a Frozen Dataset","isESM":true,"relativePath":["lib","sf","sandforge","frozen.mjs"]},"sandforge:mcp":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge mcp takes","name":"argv"}},"description":"sandforge mcp — Seed, Forge's clone of a record, of the records a query chooses or of the whole org, the removal of a run, the emptying of objects or of a whole org, Checkpoints and their replay into another org, the environments of a sandforge.yaml and the plan of an Automation pipeline, as tools for an AI agent, over the Model Context Protocol on stdio.\n\nThe whole help, its options and its exit codes: sf sandforge mcp --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:mcp","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"the MCP server: these scripts as tools for an AI agent, on stdio","isESM":true,"relativePath":["lib","sf","sandforge","mcp.mjs"]},"sandforge:monitor":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge monitor takes","name":"argv"}},"description":"sandforge monitor — read an org the way the Monitor page does, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge monitor --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:monitor","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"read an org the way the Monitor page does","isESM":true,"relativePath":["lib","sf","sandforge","monitor.mjs"]},"sandforge:pipeline":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge pipeline takes","name":"argv"}},"description":"sandforge pipeline — run an Automation pipeline exported from VS Code, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge pipeline --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:pipeline","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"plan and run an Automation pipeline exported from VS Code","isESM":true,"relativePath":["lib","sf","sandforge","pipeline.mjs"]},"sandforge:seed":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge seed takes","name":"argv"}},"description":"sandforge seed — fill an org from a seed template, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge seed --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:seed","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"fill an org from a seed template","isESM":true,"relativePath":["lib","sf","sandforge","seed.mjs"]},"sandforge:sync":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge sync takes","name":"argv"}},"description":"sandforge sync — run a Sync between two orgs, without the editor.\n\nThe whole help, its options and its exit codes: sf sandforge sync --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:sync","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"run a Sync between two orgs","isESM":true,"relativePath":["lib","sf","sandforge","sync.mjs"]},"sandforge:users":{"aliases":[],"args":{"argv":{"description":"the words npx sandforge users takes","name":"argv"}},"description":"sandforge users — set up the users of a sandbox handed back to its testers, a scratch org or a Developer Edition org: an address the copy put under .invalid asked back, a user activated, frozen or unfrozen, a profile, permission sets, permission set groups, groups and queues given; and take a run back.\n\nThe whole help, its options and its exit codes: sf sandforge users --help.","flags":{},"hasDynamicHelp":false,"hidden":false,"hiddenAliases":[],"id":"sandforge:users","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"set up the users of a sandbox after its refresh, and take them back","isESM":true,"relativePath":["lib","sf","sandforge","users.mjs"]},"sandforge:hardis-commands":{"aliases":[],"args":{"argv":{"description":"nothing, or --json for the document the extension reads","name":"argv"}},"description":"The entries SandForge adds to the menus of the sfdx-hardis VS Code extension, each reaching no org. With --json, the document the extension reads, alone on stdout.","flags":{},"hasDynamicHelp":false,"hidden":true,"hiddenAliases":[],"id":"sandforge:hardis-commands","pluginAlias":"sandforge","pluginName":"sandforge","pluginType":"core","strict":false,"summary":"the menus of SandForge in the sfdx-hardis VS Code extension","isESM":true,"relativePath":["lib","sf","sandforge","hardis-commands.mjs"]}},"version":"1.86.0"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sandforge",
3
- "version": "1.84.1",
3
+ "version": "1.86.0",
4
4
  "description": "SandForge's command lines, without the editor: seed, clone and sync Salesforce orgs, checkpoints and rewinds, masking, Frozen Datasets, sandforge.yaml environments, and an MCP server for AI agents.",
5
5
  "keywords": [
6
6
  "salesforce",
@@ -1,11 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{b as _}from"./chunk-CA5NAXSU.mjs";import{dd as I,s as L}from"./chunk-PMWAFDUB.mjs";import{b as m,e as A,l as y,o as R,s as E}from"./chunk-WZQEK4WT.mjs";import{appendFileSync as U,mkdirSync as z,readFileSync as $,renameSync as J,writeFileSync as K}from"node:fs";import{homedir as Y}from"node:os";import{join as S,resolve as V}from"node:path";var Z=10,Q=1440*6e4,j=200,H=448,w=384,x=6e4;function D(t=process.env){let e=t.SANDFORGE_JOURNAL_DIR,r=e!==void 0&&e.trim()!==""?V(e):S(Y(),".sandforge");return S(r,"storage-written")}var X=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function N(t,e){if(X.test(t))return S(e.dir??D(),`${t.slice(0,15)}.ndjson`)}var q=R([y({at:m(),saidMB:A()}),y({at:m(),wrote:E(m(),A())})]);function M(t){let e;try{e=$(t,"utf8")}catch{return[]}let r=[];for(let o of e.split(`
8
- `)){if(o.trim()==="")continue;let n;try{n=q.safeParse(JSON.parse(o))}catch{continue}if(!n.success)continue;let i=Date.parse(n.data.at);Number.isNaN(i)||r.push("saidMB"in n.data?{at:i,saidMB:n.data.saidMB}:{at:i,wrote:n.data.wrote})}return r.sort((o,n)=>o.at-n.at)}function v(t,e,r){let o=N(t,r);if(!o)return;let n=(r.now??new Date).getTime();try{z(r.dir??D(),{recursive:!0,mode:H}),U(o,`${JSON.stringify(e)}
9
- `,{encoding:"utf8",mode:w});let i=M(o);if(i.length<=j)return;let s=i.filter(c=>n-c.at<=Q).slice(-j/2).map(c=>JSON.stringify({...c,at:new Date(c.at).toISOString()})),a=`${o}.${process.pid}.tmp`;K(a,s.length>0?`${s.join(`
10
- `)}
11
- `:"",{encoding:"utf8",mode:w}),J(a,o)}catch{}}function Ae(t,e,r={}){let o=(r.now??new Date).toISOString();v(t,{at:o,saidMB:e},r)}function T(t,e,r={}){let o=Object.fromEntries(Object.entries(e).filter(([,i])=>Number.isFinite(i)&&i!==0));if(Object.keys(o).length===0)return;let n=(r.now??new Date).toISOString();v(t,{at:n,wrote:o},r)}function B(t){let e={};for(let{objectApiName:r,created:o,deleted:n,upserted:i=0}of t)e[r]=(e[r]??0)+o+i-n;return e}function ye(t,e,r,o={}){let n=N(t,o);if(!n)return;let i=(o.now??new Date).getTime(),s=M(n),a=d=>"wrote"in d&&d.at<=i&&i-d.at<=Z*x,c=s.filter(a).map(d=>({at:d.at,bytes:Object.entries(d.wrote).reduce((b,[P,O])=>b+Math.sign(O)*r(P,Math.abs(O)),0)}));if(c.length===0)return;let u=s.slice(0,s.findIndex(a)).filter(d=>"saidMB"in d).at(-1),f=u?ee(c,(u.saidMB-e)*1048576):0,g=c.slice(f),l=g.reduce((d,b)=>d+b.bytes,0);if(l<=0)return;let W=g[0]?.at??i;return{mb:l/1048576,runs:g.filter(d=>d.bytes>0).length,minutes:Math.max(1,Math.ceil((i-W)/x))}}function ee(t,e){let r=0,o=Math.abs(e),n=0;return t.forEach((i,s)=>{n+=i.bytes;let a=Math.abs(e-n);a<o&&(o=a,r=s+1)}),r}import{createHash as ne}from"node:crypto";var C="lineage:runs",te="lineage";function G(t){let e=t.objects.filter(s=>s.records>0);if(e.length===0)return null;let r="source",o="target",n=[{id:r,type:"source",label:t.source.label,origin:t.source.origin,...t.source.orgId?{orgId:t.source.orgId}:{}}],i=[];for(let s of e){let a=`object:${s.objectApiName}`;n.push({id:a,type:"object",label:s.objectApiName,objectApiName:s.objectApiName,recordCount:s.records}),i.push({sourceId:r,targetId:a}),i.push({sourceId:a,targetId:o,recordCount:s.records})}return n.push({id:o,type:"destination",label:t.target.label,orgId:t.target.orgId,origin:"org"}),{nodes:n,edges:i,operationId:t.operationId,generatedAt:t.generatedAt,module:t.module,action:t.action}}var p=class{constructor(e,r=100){this.configStore=e;this.limit=r}configStore;limit;save(e){let r=this.read().filter(o=>o.operationId!==e.operationId);r.push(e),this.configStore.set(C,r.slice(-this.limit),te)}get(e){let r=this.read();return e===void 0?r[r.length-1]??null:r.find(o=>o.operationId===e)??null}runs(){return this.read().reverse().map(e=>({operationId:e.operationId,generatedAt:e.generatedAt,...e.module?{module:e.module}:{},...e.action?{action:e.action}:{},...re(e)}))}read(){let e=this.configStore.get(C);return Array.isArray(e)?e.filter(oe):[]}};function re(t){let e=t.nodes.find(r=>r.type==="destination");return e?{targetLabel:e.label}:{}}function oe(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.operationId=="string"&&typeof e.generatedAt=="string"&&Array.isArray(e.nodes)&&Array.isArray(e.edges)}var ie=100,k="audit:trail",se="audit",h=class{constructor(e,r=L){this.configStore=e;this.limit=r}configStore;limit;append(e){let r=this.read();r.push(e),this.configStore.set(k,r.slice(-this.limit),se)}list(e={}){let r=this.read().reverse(),o=r.filter(s=>(e.module===void 0||s.module===e.module)&&(e.orgId===void 0||s.orgId===e.orgId)),n=e.offset??0,i=e.limit??ie;return{entries:o.slice(n,n+i),total:o.length,offset:n,facets:ae(r)}}read(){let e=this.configStore.get(k);return Array.isArray(e)?e.filter(ce):[]}};function ae(t){let e=new Set,r=new Map;for(let o of t)e.add(o.module),o.orgId!==void 0&&!r.has(o.orgId)&&r.set(o.orgId,o.orgAlias);return{modules:[...e].sort(),orgs:[...r].map(([o,n])=>n?{orgId:o,orgAlias:n}:{orgId:o})}}function ce(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.id=="string"&&typeof e.action=="string"&&typeof e.module=="string"&&typeof e.timestamp=="string"}var _e="ABORTED_BEFORE_START";function de(t){let e=t?.trim().toLowerCase();if(e)return`sha256:${ne("sha256").update(e).digest("hex").slice(0,12)}`}var ge=new Set(["seed_execute","sync_execute","backup_restore","delete_execute","forge_execute","seed_csv_import","seed_clone","autopilot_execute","frozen_load","realtime_sync","subject_erase","cleanup_delete","empty_undo","checkpoint_rewind","checkpoint_undo","checkpoint_replay"]);function ue(t,e=new Date){ge.has(t.action)&&T(t.orgId,B(t.objects??[]),{now:e})}function je(t,e,r=new Date){try{let o=t.services?.getSandforgeSetting?.("safety.auditLogging",!0)!==!1;if(!o&&e.outcome==="stopped"&&e.code===void 0)return;let n=r.toISOString(),i=t.orgManager.getOrg(e.orgId),s=i?I(i):void 0,a=de(i?.username),c=e.source?.origin==="org"?e.source.orgId:void 0,u=c!==void 0?t.orgManager.getOrg(c):void 0,f=u?I(u):void 0,g=e.objects??[];if(ue(e,r),new h(t.configStore).append({id:crypto.randomUUID(),action:e.action,module:e.module,orgId:e.orgId,...s?{orgAlias:s}:{},...c!==void 0?{sourceOrgId:c}:{},...f?{sourceOrgAlias:f}:{},operationId:e.operationId,outcome:e.outcome,...o&&e.guard?{guard:e.guard}:{},objects:[...g],...e.leftBy?{leftBy:e.leftBy}:{},...a?{userId:a}:{},...e.context?{context:e.context}:{},...e.verdict?{verdict:e.verdict}:{},...e.muted?{muted:e.muted}:{},...e.checkpointId?{checkpointId:e.checkpointId}:{},...e.beforeRun?{beforeRun:{...e.beforeRun}}:{},...e.fit?{fit:{...e.fit}}:{},details:{...e.details,...e.code?{code:e.code}:{}},timestamp:n}),!e.source)return;let l=G({operationId:e.operationId,module:e.module,action:e.action,source:e.source.origin==="org"?{origin:"org",orgId:e.source.orgId,label:f??e.source.orgId}:{origin:e.source.origin,label:e.source.label??""},target:{label:s??e.orgId,orgId:e.orgId},objects:fe(g,e.carried),generatedAt:n});l&&new p(t.configStore).save(l)}catch(o){t.log(`[WARN] audit trail: run ${e.operationId} was not recorded \u2014 ${_(o)}`)}}function fe(t,e){return e?Object.entries(e).map(([r,o])=>({objectApiName:r,records:o})):t.map(r=>({objectApiName:r.objectApiName,records:r.created+r.updated+(r.upserted??0)}))}function we(t){return{objectApiName:t,created:0,updated:0,deleted:0,failed:0}}export{p as a,Z as b,Ae as c,ye as d,h as e,_e as f,de as g,ue as h,je as i,we as j};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{e as a}from"./chunk-S42RBRH2.mjs";var c="FIELD_CUSTOM_VALIDATION_EXCEPTION",g="INVALID_OR_NULL_FOR_RESTRICTED_PICKLIST",R="FIELD_FILTER_VALIDATION_EXCEPTION",F="INACTIVE_OWNER_OR_USER",w=/\[(005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?)\]/,E="005",h=["CreatedById","LastModifiedById"];function L(e,n){if(e.statusCode!==F)return;let r=f(n,"OwnerId"),t=r===void 0?void 0:n[r],o=w.exec(e.message)?.[1];if(!(typeof t!="string"||o===void 0))return t.slice(0,15)===o.slice(0,15)?o.slice(0,15):void 0}function O(e,n,r){let t=f(n,"OwnerId");if(t===void 0||t.toLowerCase()===r?.toLowerCase())return;let o=n[t];if(!(typeof o!="string"||!o.startsWith(E)||e.fields.some(u=>u.toLowerCase()!=="ownerid")||!(w.test(e.message)?L(e,n)!==void 0:h.every(u=>f(n,u)===void 0))))return{field:t,refusedBy:"inactive-owner",reason:a(e)}}var I=new Map([[c,"validation-rule"],[g,"restricted-picklist"],[R,"lookup-filter"]]);function _(e){return e!=null&&e!==""}function f(e,n){let r=n.toLowerCase();return Object.keys(e).find(t=>t.toLowerCase()===r&&_(e[t]))}function m(e,n,r,t,o){if(!e||e.length===0)return;let d=new Map;for(let s of e){let u=I.get(s.statusCode);if(!u){let i=o?.inactiveOwner===!0&&s.statusCode===F?O(s,n,r):void 0;if(!i)return;d.has(i.field)||d.set(i.field,i);continue}let l=s.fields.map(i=>f(n,i)).filter(i=>i!==void 0&&i.toLowerCase()!==r?.toLowerCase());if(l.length===0||u==="lookup-filter"&&!l.every(i=>t?.(i)===!0))return;for(let i of l)d.has(i)||d.set(i,{field:i,refusedBy:u,reason:a(s)})}return[...d.values()]}function A(e){return(e??[]).some(n=>n.statusCode===c&&n.fields.length===0)}function C(e,n){let r=new Set(n.map(t=>t.field));return Object.fromEntries(Object.entries(e).filter(([t])=>!r.has(t)))}function S(e,n){let r=e??{rows:0,fields:[]};r.rows+=n.rows;for(let t of n.fields){let o=r.fields.find(d=>d.field===t.field&&d.reason===t.reason);o?o.rows+=t.rows:r.fields.push({...t})}return r}var p={"validation-rule":"a validation rule of the target refused it","restricted-picklist":"a restricted picklist of the target refused its value","lookup-filter":"a lookup filter of the target refused the record it names","inactive-owner":"the target holds the owner it names inactive"};function v(e){return(e?.fields??[]).map(({field:n,refusedBy:r="validation-rule",reason:t,rows:o,replacedWith:d})=>{let s=d===void 0?`written without ${n}`:`written with ${n} set to "${d}"`;return`, ${o} ${s}: ${p[r]}, ${t}`}).join("")}function W(e){let n=`${e.rows} record(s) written again without the fields the target refused them on${v(e)}`;return n.endsWith(".")?n:`${n}.`}export{g as a,R as b,F as c,L as d,f as e,m as f,A as g,C as h,S as i,v as j,W as k};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as v}from"./chunk-SRPWW4A2.mjs";import"./chunk-4TLYUZD5.mjs";import{ic as D}from"./chunk-PMWAFDUB.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";function x(e){return{async retrieve(n){return{id:(await e.metadata.retrieve(n)).id}},checkRetrieveStatus:n=>e.metadata.checkRetrieveStatus(n),async deploy(n,t){return{id:(await e.metadata.deploy(n,t)).id}},checkDeployStatus:(n,t)=>e.metadata.checkDeployStatus(n,t)}}var N={pollMs:3e3,retrieveTimeoutMs:D.retrieve*6e4,deployTimeoutMs:D.deploy*6e4,sleep:e=>new Promise(n=>setTimeout(n,e)),now:Date.now},b=class extends Error{constructor(t,o,s,a){super(t==="deployment"?`Deployment ${o} was still ${s} after ${a} min; it goes on in the target org, and Setup \u203A Deployment Status follows it.`:`Retrieval ${o} was still ${s} after ${a} min; nothing was deployed.`);this.kind=t;this.asyncId=o;this.status=s;this.name="DeploymentStillRunning"}kind;asyncId;status};function d(e,n){return`${e}\0${k(n)}`}function k(e){try{return decodeURIComponent(e)}catch{return e}}function g(e){return e==null?[]:Array.isArray(e)?e:[e]}function R(e){return e===!0||e==="true"}function h(e){if(e==null||e==="")return;let n=Number(e);return Number.isFinite(n)?n:void 0}var P=/^Entity of type '(.+?)' named '(.+)' cannot be found$/;async function M(e,n,t,o){let s=new Map;for(let{componentType:i,fullName:m}of t)s.set(i,[...s.get(i)??[],m]);let a={apiVersion:Number(n),singlePackage:!0,unpackaged:{objectPermissions:[],types:[...s].map(([i,m])=>({members:m,name:i})),version:n}},{id:p}=await e.retrieve(a),u=o.now();for(;;){let i=await e.checkRetrieveStatus(p);if(i.done){if(i.success===!1||i.status==="Failed")throw new Error(`Retrieval ${p} from the source failed: ${i.errorMessage??i.status??"no reason given"}`);return i}if(o.now()-u>=o.retrieveTimeoutMs)throw new b("retrieval",p,i.status??"running",Math.round(o.retrieveTimeoutMs/6e4));await o.sleep(o.pollMs)}}async function I(e,n,t,o={}){let s=o.waiting??N;o.onProgress?.({step:"retrieve",done:0,total:t.length});let a=await M(e,n,t,s),p=new Map(t.map(l=>[d(l.componentType,l.fullName),l])),u=new Map,i=[];for(let l of g(a.messages)){let f=l.problem??"",T=P.exec(f),y=T?p.get(d(T[1],T[2])):void 0;y?u.set(d(y.componentType,y.fullName),{...y,problem:f}):f&&i.push(l.fileName?`${l.fileName}: ${f}`:f)}let m=t.filter(l=>!u.has(d(l.componentType,l.fullName))),r=a;m.length===0?r={...a,zipFile:""}:u.size>0&&(r=await M(e,n,m,s)),o.onProgress?.({step:"retrieve",done:m.length,total:t.length});let c=g(r.fileProperties).filter(l=>v(l)).map(l=>p.get(d(l.type??"",l.fullName??""))).filter(l=>l!==void 0);return{zipFile:r.zipFile??"",retrieved:m,missing:[...u.values()],managed:c,problems:i}}function A(e,n,t){return{allowMissingFiles:!1,autoUpdatePackage:!1,checkOnly:e,ignoreWarnings:!1,performRetrieve:!1,purgeOnDelete:!1,rollbackOnError:!0,...n==="RunSpecifiedTests"?{runTests:[...t]}:{},singlePackage:!0,testLevel:n}}async function E(e,n,t,o={}){let s=o.waiting??N,{id:a}=await e.deploy(n,t),p=s.now();for(;;){let u=await e.checkDeployStatus(a,!1);if(u.done)return e.checkDeployStatus(a,!0);if(o.onProgress?.(w(u)),s.now()-p>=s.deployTimeoutMs)throw new b("deployment",a,u.status??"running",Math.round(s.deployTimeoutMs/6e4));await s.sleep(s.pollMs)}}function w(e){let n=e.numberTestsTotal??0,t=e.numberComponentsTotal??0,o=(e.numberComponentsDeployed??0)+(e.numberComponentErrors??0);return n>0&&o>=t?{step:"tests",done:(e.numberTestsCompleted??0)+(e.numberTestErrors??0),total:n}:{step:"components",done:o,total:t}}function C(e){let n=/line (\d+), column \d+/.exec(e??"");return n?Number(n[1]):void 0}function O(e){let n=h(e.lineNumber),t=h(e.columnNumber),o=e.problemType==="Warning"||e.problemType==="Error"?e.problemType:void 0,s={componentType:e.componentType??"",fullName:e.fullName??"",...e.fileName?{fileName:e.fileName}:{}};if(!R(e.success))return{...s,outcome:"failed",...e.problem?{problem:e.problem}:{},...o?{problemType:o}:{},...n!==void 0?{line:n}:{},...t!==void 0?{column:t}:{}};let a=R(e.created)?"created":R(e.changed)?"changed":"unchanged";return{...s,outcome:a}}function $(e,n,t){let o=e?.details??void 0,s=new Map,a=[...g(o?.componentFailures),...g(o?.componentSuccesses)];for(let r of a){if(!r.componentType&&r.fullName==="package.xml")continue;let c=O(r),l=d(c.componentType,c.fullName);s.has(l)||s.set(l,c)}let p=n.missing.map(r=>({componentType:r.componentType,fullName:r.fullName,outcome:"not_retrieved",...r.problem?{problem:r.problem}:{}})),u=o?.runTestResult??void 0,i=g(u?.failures).map(r=>{let c=C(r.stackTrace);return{className:r.name??"",...r.methodName?{methodName:r.methodName}:{},message:r.message??"",...r.stackTrace?{stackTrace:r.stackTrace}:{},...c!==void 0?{line:c}:{}}}),m=g(u?.codeCoverageWarnings).map(r=>r.name?`${r.name}: ${r.message??""}`:r.message??"").filter(r=>r!=="");return{...e?.id?{deployId:e.id}:{},checkOnly:t.checkOnly,status:e?.status??"NotStarted",success:e?.success===!0&&n.missing.length===0,...e?.errorMessage?{errorMessage:e.errorMessage}:{},sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,testLevel:t.testLevel,runTests:[...t.runTests],components:[...s.values(),...p],counts:{componentsTotal:e?.numberComponentsTotal??0,componentsDeployed:e?.numberComponentsDeployed??0,componentErrors:e?.numberComponentErrors??0,testsTotal:e?.numberTestsTotal??0,testsCompleted:e?.numberTestsCompleted??0,testErrors:e?.numberTestErrors??0},testFailures:i,coverageWarnings:m,...n.problems.length>0?{retrieveProblems:[...n.problems]}:{},...e?.startDate?{startedAt:e.startDate}:{},...e?.completedDate?{completedAt:e.completedDate}:{}}}export{N as DEFAULT_WAITING,b as DeploymentStillRunning,A as deployOptions,E as deployPackage,$ as deploymentReport,x as metadataApiOf,I as retrieveComponents};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as R,b as S,c as E,d as y}from"./chunk-RKTFFCNS.mjs";import{homedir as O}from"node:os";import{join as N,resolve as I}from"node:path";var P="SANDFORGE_JOURNAL_DIR";function k(e=process.env){let n=e[P];return n!==void 0&&n.trim()!==""?I(n):N(O(),".sandforge")}import{spawn as T}from"node:child_process";import{join as Y}from"node:path";import{StringDecoder as C}from"node:string_decoder";function G(){return process.execArgv.filter(e=>!/^--inspect/.test(e))}function j(e){return Y(__dirname,`${e}.mjs`)}var a="SANDFORGE_RELAYED_BY";function q(e={}){let n=(e.platform??process.platform)==="win32",A=e.scriptPath??j;return(v,w,o,i={})=>new Promise((B,L)=>{let p=i.relayedBy??e.relayedBy,b={...process.env,...p!==void 0?{[a]:p}:{},...n?{[y]:"ipc"}:{}},r=T(process.execPath,[...G(),A(v),...w],{stdio:n?["ignore","pipe","pipe","ipc"]:["ignore","pipe","pipe"],env:b,detached:!n,windowsHide:!0}),f=[],u=[],l=i.onStderr!==void 0?new C("utf8"):void 0;r.stdout?.on("data",t=>f.push(t)),r.stderr?.on("data",t=>{u.push(t),process.stderr.write(t);let d=l?.write(t);d&&i.onStderr?.(d)});let s=()=>{if(!n||!r.connected){r.kill("SIGINT");return}r.send(E,t=>{t&&r.kill("SIGINT")})};o.aborted?s():o.addEventListener("abort",s,{once:!0}),r.on("error",t=>{o.removeEventListener("abort",s),L(t)}),r.on("close",(t,d)=>{o.removeEventListener("abort",s);let m=l?.end();m&&i.onStderr?.(m);let g=R.find(h=>h===d);B({code:t??(g!==void 0?S(g):1),stdout:Buffer.concat(f).toString("utf8"),stderr:Buffer.concat(u).toString("utf8")})})})}function c(){let e=process.env[a]?.trim();return e===void 0||e===""?void 0:e}function _(){return c()?.startsWith("sandforge env")===!0}function ee(e,n){return _()?n:e}var F="sandforge mcp clone_org_plan",x="sandforge mcp clone_org",J=new Map([["sandforge env",["--sweep","--include-changed"]],["sandforge env, relayed by sandforge mcp",["--include-changed"]],["sandforge mcp",["--mute-automation","--leave-undeletable","--store","--include-changed","--preview"]],[F,["--max-total","--exclude-object","--exclude","--filter","--fit","--fit-within","--fit-seed","--fit-draw","--fit-parents","--fit-children","--fit-whole","--fit-floor","--anonymize","--accept-automation","--accept-emails","--mute-automation","--checkpoint-first"]],[x,[]]]);function ne(){return _()||c()===x}function H(e){let n=c();return n===void 0||J.get(n)?.includes(e)===!0}function te(e,n){return H(e)?e:n===void 0?`this script's own ${e}`:`this script's own ${n} with ${e}`}export{k as a,a as b,q as c,c as d,_ as e,ee as f,F as g,x as h,ne as i,H as j,te as k};
@@ -1,13 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{e as vs,f as Is}from"./chunk-7QYHEHMA.mjs";import{a as gs,b as ms,c as ke,d as ws,e as ys,f as ut,g as ks,h as bs,i as Rs,j as Ss}from"./chunk-WXDLQT2O.mjs";import{i as As,l as Os}from"./chunk-NSQWI7ZY.mjs";import{c as us}from"./chunk-GNRSF65U.mjs";import{b as ls}from"./chunk-O677VOGO.mjs";import{a as Mt,b as os,c as Se,d as Ut,e as $t,f as as,g as ds,m as cs}from"./chunk-PWRJRL5U.mjs";import{d as Ft,f as Me,l as Dt,n as dt}from"./chunk-UIOMAX56.mjs";import{a as ps,b as hs}from"./chunk-QAFPQ3YB.mjs";import{Bc as Tn,Cc as Fn,xc as it}from"./chunk-XGGOUNPP.mjs";import{a as Nn,b as Bn,c as En,e as rt,f as Cn,h as ss,i as rs}from"./chunk-L53JWJ3S.mjs";import{a as Ct,d as zn,f as Wn,h as _n,j as qn,k as xn,l as ot,m as Gn,p as Jn,q as Kn}from"./chunk-HIDW7FNV.mjs";import{B as es,C as ts,D as ns,a as jn,w as Xn,y as Qn}from"./chunk-VINGECAJ.mjs";import{G as ie,H as An,I as Bt,J as On,M as Pn,O as st}from"./chunk-H4CGM6YO.mjs";import{a as Nt,b as In}from"./chunk-YDXMTWAT.mjs";import{l as Ln}from"./chunk-PMN4PAC3.mjs";import{B as Ue,E as is,F as lt,i as xe,j as Tt,l as Ne,p as Fe,q as Yn,r as at,z as ct}from"./chunk-FP7CYB2F.mjs";import{b as L,e as De,g as Zn}from"./chunk-NED4MBIM.mjs";import{A as Ge,H,N as Vn,d as Oe,g as Hn,x as Le,y as Te,z as ye}from"./chunk-KGU4SVIT.mjs";import{b as V,d as he,e as vn}from"./chunk-JAEDM4SI.mjs";import{c as Dn}from"./chunk-LC3NDW4N.mjs";import{j as Et,m as Mn,n as Un,o as $n,pc as fs}from"./chunk-KB4ZHM4Q.mjs";import{i as nt}from"./chunk-INIT2UKJ.mjs";import{E as Sn}from"./chunk-YA6ATMTB.mjs";import{g as Ce,h as oe,i as bn,q as Rn}from"./chunk-M6K34KGF.mjs";import{da as tt,ja as yn,ka as kn}from"./chunk-TNT27RBG.mjs";import{h as de}from"./chunk-TZE3Y7IQ.mjs";import{b as ee}from"./chunk-CA5NAXSU.mjs";import{Nd as wn,Ra as pn,Ta as et,Ua as hn,Uc as mn,Vd as jt,Yd as Lt,vc as gn}from"./chunk-PMWAFDUB.mjs";import{b as X,e as Xe,f as qe,i as Pt,k as ge,l as q,o as Qe,p as ln,s as un,u as Ee,v as Q,z as fn}from"./chunk-WZQEK4WT.mjs";import{randomBytes as dr}from"node:crypto";import{rm as cr}from"node:fs/promises";import{join as lr}from"node:path";var Br=5,Er="005",Cr=new Set(["001"]),Wt="Kept: a file's link to a user is never removed, and Salesforce refuses to remove its owner's ('FIELD_INTEGRITY_EXCEPTION').",ft="Its sharing type stays as it is: Salesforce doesn't change the sharing type of a file's link to an account ('The sharing type cannot be updated because updates are not currently supported for the linked Entity type').";function me(){return{done:0,already:0,refused:0,notSent:0,notReached:0,reasons:[],left:[],made:[],cancelled:!1}}function $e(i,e){i.done+=e.done,i.already+=e.already,i.refused+=e.refused,i.notSent+=e.notSent,i.notReached+=e.notReached;for(let t of e.reasons)pt(i.reasons,t);i.left.push(...e.left),i.made.push(...e.made),i.cancelled||=e.cancelled}function pt(i,e){i.length<Br&&!i.includes(e)&&i.push(e)}var Tr=q({success:qe(),id:X().nullish(),errors:ge(Qe([X(),q({statusCode:X().optional(),message:X().optional()}).loose()])).optional()}).loose();function Fr(i,e){let t=Array.isArray(i)?i:[i];return Array.from({length:e},(n,s)=>{let r=Tr.safeParse(t[s]);if(!r.success)return{success:!1,words:"The org gave no answer for it."};let{success:o,id:a,errors:d}=r.data,c=(d??[])[0],p=typeof c=="object"?c.statusCode:void 0,l=(d??[]).map(u=>typeof u=="string"?u:[u.statusCode,u.message].filter(f=>f).join(": ")).filter(u=>u!=="").join("; ");return{success:o,...typeof a=="string"?{id:a}:{},...p!==void 0?{code:p}:{},...l!==""?{words:l}:{}}})}function Dr(i){let e=[];for(let t=0;t<i.length;t+=V)e.push(i.slice(t,t+V));return e}async function _t(i,e,t,n){let s=me();for(let r of Dr(i)){if(s.cancelled||e.stopped?.()===!0){s.cancelled=!0,s.notReached+=r.length;for(let d of r)s.left.push({id:d.Id,reason:"Not reached: stopped."});continue}await e.before?.(r);let o=Fr(await t(r),r.length),a={done:[],made:[],left:[]};r.forEach((d,c)=>{let p=o[c],l=n(p);if(l==="done"){s.done++,a.done.push(d),p.id!==void 0&&a.made.push({from:d.Id,id:p.id});return}if(a.left.push(d.Id),l==="already"){s.already++;return}let u=p.words??"The org gave no reason.";s.refused++,pt(s.reasons,u),s.left.push({id:d.Id,reason:u})}),s.made.push(...a.made),await e.after?.(a)}return s}function Ps(i,e,t,n){let s=[];for(let r of i){if(!e(r)){s.push(r);continue}n.notSent++,pt(n.reasons,t),n.left.push({id:r.Id,reason:t})}return s}async function ht(i,e,t={}){let n=me(),s=Ps(e,o=>o.LinkedEntityId?.startsWith(Er)===!0,Wt,n),r=await _t(s,t,o=>i.destroy(oe,o.map(a=>a.Id)),o=>o.success?"done":o.code==="ENTITY_IS_DELETED"||o.code==="NOT_FOUND"?"already":"refused");return $e(r,n),r}async function gt(i,e,t={},n=s=>s){return _t(e,t,s=>i.create(oe,s.map(r=>({ContentDocumentId:n(r.ContentDocumentId),LinkedEntityId:n(r.LinkedEntityId),ShareType:r.ShareType,Visibility:r.Visibility}))),s=>s.success&&s.id!==void 0?"done":s.code==="DUPLICATE_VALUE"?"already":"refused")}async function mt(i,e,t={}){let n=d=>Cr.has(d.LinkedEntityId.slice(0,3)),s=me(),r=new Map,o=Ps(e,d=>d.Visibility===d.now.Visibility&&n(d),ft,s);for(let d of o){let c=d.ShareType!==d.now.ShareType&&!n(d);d.ShareType!==d.now.ShareType&&n(d)&&pt(s.reasons,ft),r.set(d.Id,{Id:d.Id,...c?{ShareType:d.ShareType}:{},...d.Visibility!==d.now.Visibility?{Visibility:d.Visibility}:{}})}let a=await _t(o,t,d=>i.update(oe,d.map(c=>r.get(c.Id)??{Id:c.Id})),d=>d.success?"done":d.code==="ENTITY_IS_DELETED"?"already":"refused");return $e(s,a),s}import{randomBytes as Cs}from"node:crypto";import{closeSync as Mr,createReadStream as Ts,fsyncSync as Ur,openSync as $r,readFileSync as zr,renameSync as Wr,writeSync as _r}from"node:fs";import{open as kt,readdir as Fs,rm as Ds,stat as qr,truncate as Ms}from"node:fs/promises";import{dirname as Us,join as ne}from"node:path";import{createInterface as $s}from"node:readline";var ze="journal.ndjson",xr="before.json",J=2e3,zs=X().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),xt=X().regex(/^005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/,"Not a User Id"),Ie=X().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Not an API name").max(80),Y=fn.datetime({offset:!0}),ce=ge(zs).min(1).max(J),Kt=Xe().int().positive(),Ws=q({kind:Q("head"),version:Q(1),rewindId:et,checkpointId:pn,organizationId:hn,startedAt:Y,userId:xt,automatedProcessUserId:xt.optional(),backup:X().min(1).max(200),at:Y}),Gr=q({kind:Q("resumed"),startedAt:Y,userId:xt,at:Y}),Jr=q({kind:Ee(["bringingBack","withParent","givingBack"]),objectApiName:Ie,ids:ce,parents:ce.optional(),carriers:Q(!0).optional(),at:Y}),Kr=q({kind:Q("bringBackLeft"),objectApiName:Ie,ids:ce,at:Y}),Hr=q({kind:Q("recreating"),objectApiName:Ie,ids:ce,at:Y}),Vr=q({kind:Q("recreated"),objectApiName:Ie,ids:ce,from:ce,at:Y}),Yr=q({kind:Ee(["deleting","deleteLeft"]),step:Kt,objectApiName:Ie,ids:ce,at:Y}),Zr=q({kind:Q("heldInPlace"),objectApiName:Ie,by:ge(Ie).min(1).max(100),ids:ce,at:Y}),Xr=q({kind:Q("beforeParent"),objectApiName:Ie,ids:ce,parents:ce,at:Y}),Qr=q({kind:Q("goingAlong"),step:Kt,objectApiName:Ie,ids:ce,parents:ce,at:Y}),ei=q({kind:Q("deleted"),step:Kt,at:Y}),ti=q({kind:Q("removal"),state:Pt(),at:Y}),ni=q({kind:Q("unlinking"),links:ge(Se).min(1).max(J),at:Y}),si=q({kind:Ee(["unlinkLeft","linksUpdateLeft"]),ids:ce,at:Y}),ri=q({kind:Q("relinked"),ids:ce,from:ce,at:Y}),_s=Se.pick({Id:!0,LinkedEntityId:!0,ShareType:!0,Visibility:!0}),ii=q({kind:Q("linksUpdating"),links:ge(_s).min(1).max(J),at:Y}),oi=q({kind:Q("linksUndone"),part:Ee(["reinserted","removed","shared"]),ids:ce,at:Y}),ai=q({kind:Q("wrote"),at:Y}),di=q({kind:Q("end"),at:Y}),ci=q({kind:Q("undo"),state:Pt(),status:Ee(["success","partial","failure","cancelled"]),at:Y}),li=ln("kind",[Ws,Gr,Jr,Kr,Zr,Xr,Hr,Vr,Yr,Qr,ei,ti,ni,si,ri,ii,oi,ai,di,ci]),ui=new Set(["bringingBack","withParent","bringBackLeft","givingBack","recreating","recreated","deleting","goingAlong","deleteLeft","deleted","removal","unlinking","unlinkLeft","relinked","linksUpdating","linksUpdateLeft","wrote"]);async function Gt(i){let e;try{e=await kt(i,"r"),await e.sync()}catch{}finally{await e?.close().catch(()=>{})}}async function Ht(i,e){let t=await kt(i,"a",Oe);try{await t.appendFile(e,"utf8"),await t.sync()}finally{await t.close()}}function fi(i,e){let t=`${i}.${process.pid}-${Cs(4).toString("hex")}.tmp`,n=Buffer.from(e,"utf8"),s=$r(t,"wx",Oe);try{for(let r=0;r<n.length;)r+=_r(s,n,r,n.length-r);Ur(s)}finally{Mr(s)}Wr(t,i)}function pi(i){let e=[];try{let n=JSON.parse(zr(i,"utf8"));Array.isArray(n.openings)&&(e=n.openings)}catch{}let t=e.length;return{set:(n,s)=>{e[t]=s,fi(i,`${JSON.stringify({version:1,openings:e})}
8
- `)}}}function W(i){return i.slice(0,15)}function be(i){let e=[];for(let t=0;t<i.length;t+=J)e.push(i.slice(t,t+J));return e}async function*hi(i){if(!On(i)){for(let{objectApiName:e,ids:t}of i)t.length>0&&(yield{objectApiName:e,ids:[...t]});return}for(let{objectApiName:e}of i.objects)for await(let t of i.pages(e))t.length>0&&(yield{objectApiName:e,ids:[...t]})}var wt=class i{constructor(e,t,n,s,r,o){this.dir=t;this.resumed=n;this.handle=s;this.step=r;this.now=o;this.rewindId=e.rewindId,this.backup=e.backup;let a=new Set,d=new rs({...ss(t),appendFile:async(p,l)=>{await Ht(p,l),a.has(p)||(a.add(p),await Gt(Us(p)))}}),c={begin:()=>ye(ne(t,"backups")),append:(p,l,u)=>d.append(p,l,u)};if(this.kept=hs({runId:e.rewindId,orgId:e.organizationId,organizationId:e.organizationId,files:c,meta:pi(ne(t,xr)),now:o}),this.kept.id!==e.backup)throw new H("damaged","The rewind\u2019s journal names another backup of its values than the one they are kept in.");this.values=d,this.keep=async(p,l)=>{await this.kept.keep(p,l);let u=l.flatMap(f=>typeof f.Id=="string"?[f.Id]:[]);for(let f of be(u))await this.append({kind:"givingBack",objectApiName:p,ids:f})}}dir;resumed;handle;step;now;keep;values;queue=Promise.resolve();closed=!1;openStep;kept;rewindId;backup;static async opened(e,t,n,s,r){let o=await kt(ne(e,ze),"a",Oe);try{return new i(t,e,n,o,s,r)}catch(a){throw await o.close(),a}}append(e){if(this.closed)return Promise.reject(new Error("The rewind\u2019s journal is closed."));let t=`${JSON.stringify({...e,at:this.now().toISOString()})}
9
- `,n=this.queue.then(async()=>{await this.handle.appendFile(t,"utf8"),await this.handle.sync()});return this.queue=n.catch(()=>{}),n}async appendIds(e,t,n,s=!1){for(let r of be(n))await this.append({kind:e,objectApiName:t,ids:r,...s?{carriers:s}:{}})}bringingBack(e,t,n={}){let s=new Map;for(let{objectApiName:r,ids:o}of e){let[a]=o;a!==void 0&&s.set(a.slice(0,3),r)}return async r=>{let o=new Set(r.map(d=>s.get(d.slice(0,3)))),[a]=[...o];if(o.size!==1||a===void 0)throw new Error("These records are not of the plan the journal names: none was sent.");return await this.appendIds("bringingBack",a,r,n.carriers===!0),t(r)}}async withParent(e,t,n,s={}){let r=s.carriers===!0;if(n===void 0){await this.appendIds("withParent",e,t,r);return}if(n.length!==t.length)throw new Error("Each record that comes back with a parent is named beside that parent.");for(let o=0;o<t.length;o+=J)await this.append({kind:"withParent",objectApiName:e,ids:t.slice(o,o+J),parents:n.slice(o,o+J),...r?{carriers:r}:{}})}async bringBackLeft(e,t){for(let n of be(t))await this.append({kind:"bringBackLeft",objectApiName:e,ids:n})}async heldInPlace(e,t,n){if(t.length!==0)for(let s of be(n))await this.append({kind:"heldInPlace",objectApiName:e,by:[...t],ids:s})}async beforeParent(e,t){for(let n=0;n<t.length;n+=J){let s=t.slice(n,n+J);await this.append({kind:"beforeParent",objectApiName:e,ids:s.map(({id:r})=>r),parents:s.map(({parent:r})=>r)})}}async recreating(e,t){for(let n of be(t))await this.append({kind:"recreating",objectApiName:e,ids:n})}async recreated(e,t){for(let n=0;n<t.length;n+=J){let s=t.slice(n,n+J);await this.append({kind:"recreated",objectApiName:e,ids:s.map(({id:r})=>r),from:s.map(({from:r})=>r)})}}async deleting(e){let t=++this.step;this.openStep=t;for await(let{objectApiName:n,ids:s}of hi(e))for(let r of be(s))await this.append({kind:"deleting",step:t,objectApiName:n,ids:r})}async goingAlong(e,t){let n=this.openStep;if(n===void 0)throw new Error("No removal was named to the journal before it.");for(let s=0;s<t.length;s+=J){let r=t.slice(s,s+J);await this.append({kind:"goingAlong",step:n,objectApiName:e,ids:r.map(({id:o})=>o),parents:r.map(({parent:o})=>o)})}}async deleted(e){let t=this.openStep;if(t===void 0)throw new Error("No removal was named to the journal before it.");for await(let{objectApiName:n,ids:s}of e.left())for(let r of be(s))await this.append({kind:"deleteLeft",step:t,objectApiName:n,ids:r});await this.append({kind:"deleted",step:t}),this.openStep=void 0}async removal(e){let t={...e.removalStamps&&Object.keys(e.removalStamps).length>0?{removalStamps:e.removalStamps}:{},...e.removalSpans&&e.removalSpans.length>0?{removalSpans:e.removalSpans}:{}};Object.keys(t).length!==0&&await this.append({kind:"removal",state:{version:1,...t}})}async unlinking(e){for(let t=0;t<e.length;t+=J)await this.append({kind:"unlinking",links:e.slice(t,t+J)})}async unlinkLeft(e){for(let t of be(e))await this.append({kind:"unlinkLeft",ids:t})}async relinked(e){for(let t=0;t<e.length;t+=J){let n=e.slice(t,t+J);await this.append({kind:"relinked",ids:n.map(({id:s})=>s),from:n.map(({from:s})=>s)})}}async linksUpdating(e){for(let t=0;t<e.length;t+=J){let n=e.slice(t,t+J).map(s=>({Id:s.Id,LinkedEntityId:s.LinkedEntityId,ShareType:s.ShareType,Visibility:s.Visibility}));await this.append({kind:"linksUpdating",links:n})}}async linksUpdateLeft(e){for(let t of be(e))await this.append({kind:"linksUpdateLeft",ids:t})}async linksUndone(e,t){for(let n of be(t))await this.append({kind:"linksUndone",part:e,ids:n})}async wrote(){await this.append({kind:"wrote"})}async end(){await this.append({kind:"end"})}async undone(e,t){await this.append({kind:"undo",state:{version:1,...e},status:t})}async read(){return await this.queue,qs(ne(this.dir,ze))}async facts(){return await this.queue,mi(ne(this.dir,ze))}async close(){if(!this.closed){this.closed=!0;try{this.kept.close()}catch{}await this.queue,await this.handle.close()}}};async function ve(i,e){let t=(await qr(i)).size,n=t===0;if(t>0){let p=await kt(i,"r");try{let l=Buffer.alloc(1);await p.read(l,0,1,t-1),n=l[0]===10}finally{await p.close()}}let s=0,r=0,o=async p=>{r+=Buffer.byteLength(p,"utf8")+1;let l;try{l=JSON.parse(p)}catch{l=void 0}let u=li.safeParse(l);if(!u.success)throw new H("damaged",`The rewind\u2019s journal is damaged at line ${s+1}: it is not used.`);gi(u.data),s++,await e(u.data)},a=Ts(i,{encoding:"utf8"}),d=$s({input:a,crlfDelay:1/0}),c;try{for await(let p of d)c!==void 0&&await o(c),c=p}finally{d.close(),a.destroy()}return c!==void 0&&n&&await o(c),{count:s,whole:r,size:t}}function gi(i){if(i.kind==="relinked"&&i.from.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names links inserted again without the links they stand for.");if(i.kind==="recreated"&&i.from.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names records made again without the Ids they had.");if(i.kind==="goingAlong"&&i.parents.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names records that went with a parent without it.");if(i.kind==="beforeParent"&&i.parents.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names records deleted before a parent without their parent.");if((i.kind==="withParent"||i.kind==="bringingBack")&&i.parents!==void 0&&i.parents.length!==i.ids.length)throw new H("damaged","The rewind\u2019s journal names records that came back with a parent without it.")}var Re=class{byObject=new Map;add(e,t){let n=this.byObject.get(e)??new Map;for(let s of t)n.has(W(s))||n.set(W(s),s);this.byObject.set(e,n)}drop(e,t){let n=this.byObject.get(e);if(n)for(let s of t)n.delete(W(s))}list(e=()=>!0){return[...this.byObject].flatMap(([t,n])=>{let s=[...n].filter(([r])=>e(r)).map(([,r])=>r);return s.length>0?[{objectApiName:t,ids:s}]:[]})}keys(){return new Set([...this.byObject.values()].flatMap(e=>[...e.keys()]))}};function js(i){let e={};for(let t of i)e={...e,...t,...t.removalStamps||e.removalStamps?{removalStamps:{...e.removalStamps,...t.removalStamps}}:{},...t.removalSpans||e.removalSpans?{removalSpans:[...e.removalSpans??[],...t.removalSpans??[]]}:{}};return e}function Ls(i){let e=Ln(i);if(e===void 0)throw new H("damaged","The rewind\u2019s journal holds a state it cannot read.");return e}var Je=class{head;step=0;passes=[];rewindStates=[];undoStates=[];undos=[];lastWrite=Number.NEGATIVE_INFINITY;endedAt;line(e){if(this.head===void 0){if(e.kind!=="head")throw new H("damaged","The rewind\u2019s journal does not begin with its head.");this.head=e,this.passes=[{startedAt:e.startedAt,userId:e.userId}];return}switch(ui.has(e.kind)&&(this.lastWrite=Math.max(this.lastWrite,Date.parse(e.at))),"step"in e&&(this.step=Math.max(this.step,e.step)),e.kind){case"head":throw new H("damaged","The rewind\u2019s journal has two heads.");case"resumed":this.passes.push({startedAt:e.startedAt,userId:e.userId});break;case"removal":this.rewindStates.push(Ls(e.state));break;case"end":this.endedAt=e.at;break;case"undo":this.undoStates.push(Ls(e.state)),this.undos.push({status:e.status,at:e.at});break;default:break}}result(){let e=this.head;if(e===void 0)throw new H("damaged","The rewind\u2019s journal does not begin with its head.");return{head:{rewindId:e.rewindId,checkpointId:e.checkpointId,organizationId:e.organizationId,startedAt:e.startedAt,userId:e.userId,...e.automatedProcessUserId!==void 0?{automatedProcessUserId:e.automatedProcessUserId}:{},backup:e.backup},passes:this.passes,...Number.isFinite(this.lastWrite)?{lastWriteAt:new Date(this.lastWrite).toISOString()}:{},...this.endedAt!==void 0?{endedAt:this.endedAt}:{},rewind:js(this.rewindStates),undo:js(this.undoStates),undos:this.undos}}},Jt=class{broughtBack=new Re;recreated=new Re;carriers=new Re;carried=new Map;givenBack=new Re;held=new Re;heldBy=new Map;beforeParent=[];withParents=new Map;steps=new Map;stepOf(e){let t=this.steps.get(e);return t||(t={deleting:new Re,left:new Set,answered:!1},this.steps.set(e,t)),t}line(e){switch(e.kind){case"bringingBack":case"withParent":this.broughtBack.add(e.objectApiName,e.ids),e.carriers===!0&&e.kind==="bringingBack"&&this.carriers.add(e.objectApiName,e.ids),e.parents?.forEach((t,n)=>{let s=e.ids[n],r=e.carriers===!0?this.carried:this.withParents;r.has(W(s))||r.set(W(s),{objectApiName:e.objectApiName,id:s,parent:t})});break;case"bringBackLeft":this.broughtBack.drop(e.objectApiName,e.ids),this.carriers.drop(e.objectApiName,e.ids);for(let t of e.ids)this.withParents.delete(W(t)),this.carried.delete(W(t));break;case"givingBack":this.givenBack.add(e.objectApiName,e.ids);break;case"recreated":this.recreated.add(e.objectApiName,e.ids);break;case"heldInPlace":{this.held.add(e.objectApiName,e.ids);let t=this.heldBy.get(e.objectApiName)??new Set;for(let n of e.by)t.add(n);this.heldBy.set(e.objectApiName,t);break}case"beforeParent":e.ids.forEach((t,n)=>{this.beforeParent.push({objectApiName:e.objectApiName,id:t,parent:e.parents[n]})});break;case"deleting":this.stepOf(e.step).deleting.add(e.objectApiName,e.ids);break;case"deleteLeft":for(let t of e.ids)this.stepOf(e.step).left.add(W(t));break;case"deleted":this.stepOf(e.step).answered=!0;break;default:break}}result(){let e=new Re;for(let{deleting:u,left:f,answered:h}of this.steps.values())for(let{objectApiName:w,ids:m}of u.list(k=>!h||!f.has(k)))e.add(w,m);let t=this.held.list().map(({objectApiName:u,ids:f})=>({objectApiName:u,ids:f,by:[...this.heldBy.get(u)??[]]})),n=e.keys(),s=new Set([...this.steps.values()].flatMap(({deleting:u})=>[...u.keys()])),r=new Re;for(let{objectApiName:u,id:f,parent:h}of this.beforeParent){let w=W(h);n.has(W(f))&&(n.has(w)||!s.has(w))&&r.add(u,[f])}let o=r.list(),a=u=>{let f=new Map;for(let{objectApiName:h,id:w,parent:m}of u){let k=f.get(h)??{objectApiName:h,ids:[],parents:[]};k.ids.push(w),k.parents.push(m),f.set(h,k)}return[...f.values()]},d=a(this.withParents.values()),c=a(this.carried.values()),p=this.carriers.list(),l=this.recreated.list();return{broughtBack:this.broughtBack.list(),deleted:e.list(),givenBack:this.givenBack.list(),...t.length>0?{heldInPlace:t}:{},...o.length>0?{deletedBeforeParent:o}:{},...d.length>0?{withParents:d}:{},...l.length>0?{recreated:l}:{},...p.length>0?{carriers:p}:{},...c.length>0?{carried:c}:{}}}};async function qs(i){let e=new Je,t=new Jt;try{await ve(i,n=>{e.line(n),t.line(n)})}catch(n){throw n instanceof H?n:new H("notFound","No journal of this rewind is kept.")}return{...e.result(),did:t.result()}}async function mi(i){let e=new Je;try{await ve(i,t=>e.line(t))}catch(t){throw t instanceof H?t:new H("notFound","No journal of this rewind is kept.")}return e.result()}function wi(i,e,t){if(i.head.rewindId!==t||i.head.checkpointId!==e.checkpointId||i.head.organizationId.slice(0,15)!==e.organizationId.slice(0,15))throw new H("damaged","The rewind\u2019s journal names another rewind, checkpoint or org than its folder.")}async function Vo(i,e){let t=await Ke(i,e);if(!t)throw new H("notFound","No journal of this rewind is kept.");return qs(t.file)}function xs(i,e){if(i.organizationId.slice(0,15)!==e.organizationId.slice(0,15))throw new H("invalid","A rewind\u2019s journal is written under its org\u2019s lock.")}async function Ke(i,e){let t=Te(i,e),n=ne(t,ze),s=new Je,r;try{r=await ve(n,a=>s.line(a))}catch(a){if(a instanceof H)throw a;return}if(r.count===0||s.head===void 0)return;let o=s.result();return wi(o,i,e),{dir:t,file:n,head:s.head,step:s.step,whole:r.whole,size:r.size,facts:o}}async function Gs(i,e){return i.whole<i.size&&await Ms(i.file,i.whole),wt.opened(i.dir,i.head,!0,i.step,e)}var Ns=18;async function yi(i){let e;try{e=(await Fs(i.rewindsDir,{withFileTypes:!0})).filter(n=>n.isDirectory()&&et.safeParse(n.name).success).map(n=>n.name).sort().reverse()}catch{return[]}let[t]=e;return t===void 0?[]:e.filter(n=>n.slice(0,Ns)===t.slice(0,Ns))}async function Js(i){let{folder:e}=i;xs(i.lock,e);let t=i.now??(()=>new Date),n;for(let d of await yi(e)){let c=await Ke(e,d);if(!c){n??=d;continue}if(c.facts.endedAt!==void 0||c.facts.undos.length>0)continue;let p=await Gs(c,t);try{await p.append({kind:"resumed",startedAt:i.startedAt,userId:i.userId})}catch(l){throw await p.close(),l}return p}let s=n??Ge("rw",t()),r=Te(e,s);await ye(r),await ye(ne(r,"backups")),await Ms(ne(r,ze),0).catch(()=>{});let o=Ws.safeParse({kind:"head",version:1,rewindId:s,checkpointId:e.checkpointId,organizationId:e.organizationId,startedAt:i.startedAt,userId:i.userId,...i.automatedProcessUserId!==void 0?{automatedProcessUserId:i.automatedProcessUserId}:{},backup:ps(s),at:t().toISOString()});if(!o.success)throw new H("invalid",`Not a rewind to journal: ${o.error.message}`);let a=await wt.opened(r,o.data,!1,0,t);try{await a.append(o.data),await Gt(r),await Gt(e.rewindsDir)}catch(d){throw await a.close(),d}return a}async function Ks(i,e,t,n=()=>new Date){xs(t,i);let s=await Ke(i,e);if(!s)throw new H("notFound","No journal of this rewind is kept.");return Gs(s,n)}async function Hs(i,e,t){let n=await i.checkpointsOf(e.organizationId),s=Vn(n),r=[],o=[...n].sort((a,d)=>a.folder.checkpointId<d.folder.checkpointId?-1:1);for(let{folder:a,checkpoint:d}of o){if(d===void 0)continue;let c;try{c=(await Fs(a.rewindsDir,{withFileTypes:!0})).filter(l=>l.isDirectory()&&et.safeParse(l.name).success).map(l=>l.name).sort()}catch{continue}let p=(l,u)=>u?.checkpointId===a.checkpointId&&u.rewindId===l;for(let l of c){if(p(l,t)||p(l,s))continue;let u=await Ke(a,l).catch(()=>{});u===void 0||u.facts.endedAt===void 0&&u.facts.undos.length===0||(await Ds(Te(a,l),{recursive:!0,force:!0}),r.push({checkpointId:a.checkpointId,name:d.name,rewindId:l}))}}return r}var yt=class i{constructor(e,t,n){this.dir=e;this.objects=t;this.keys=n}dir;objects;keys;get count(){return this.objects.reduce((e,t)=>e+t.count,0)}static async written(e,t){await ye(e);let n=new L,s=new Map,r=new Map,o=async a=>{let d=r.get(a)??[];d.length!==0&&(await Ht(Bs(e,a),d.join("")),r.set(a,[]))};await t(async(a,{id:d,parent:c})=>{if(!n.add(d))return;s.set(a,(s.get(a)??0)+1);let p=r.get(a)??[];p.push(`${d} ${c}
10
- `),r.set(a,p),p.length>=J&&await o(a)});for(let a of s.keys())await o(a);return new i(e,[...s].map(([a,d])=>({objectApiName:a,count:d})),n)}async*pages(e,t=J){if(!this.objects.some(o=>o.objectApiName===e))return;let n=Ts(Bs(this.dir,e),{encoding:"utf8"}),s=$s({input:n,crlfDelay:1/0}),r=[];try{for await(let o of s){let[a,d]=o.split(" ");a===void 0||d===void 0||(r.push({id:a,parent:d}),r.length>=t&&(yield r,r=[]))}}finally{s.close(),n.destroy()}r.length>0&&(yield r)}};function Bs(i,e){return ne(i,`${mn(e)}.pairs`)}async function qt(i,e,t){return e.length>0&&(await ye(Us(i)),await Ht(i,e.map(n=>`${JSON.stringify(n)}
11
- `).join(""))),{count:e.length,pages:async function*(){if(e.length===0)return;let n=[];for await(let s of Ue(i))n.push(t(s)),n.length>=J&&(yield n,n=[]);n.length>0&&(yield n)}}}async function ki(i,e){let t=new Map,n=new Map,s=new Map,r=new Set,o=new Set,a=new Set,d=new Set;await ve(i,u=>{switch(u.kind){case"unlinking":for(let f of u.links)t.has(W(f.Id))||t.set(W(f.Id),f);break;case"unlinkLeft":for(let f of u.ids)t.delete(W(f));break;case"relinked":for(let f of u.ids)n.set(W(f),{Id:f});break;case"linksUpdating":r=new Set;for(let f of u.links)s.has(W(f.Id))||(s.set(W(f.Id),f),r.add(W(f.Id)));break;case"linksUpdateLeft":for(let f of u.ids)r.has(W(f))&&s.delete(W(f));break;case"linksUndone":{let f=u.part==="reinserted"?o:u.part==="removed"?a:d;for(let h of u.ids)f.add(W(h));break}default:break}});for(let u of[...n.keys()])t.has(u)&&(n.delete(u),t.delete(u));let c=[...t].filter(([u])=>!o.has(u)).map(([,u])=>u),p=[...n].filter(([u])=>!a.has(u)).map(([,u])=>u),l=[...s].filter(([u])=>!d.has(u)).map(([,u])=>u);if(c.length+p.length+l.length!==0)return{reinsert:await qt(ne(e,"links.reinsert.ndjson"),c,u=>Se.parse(u)),remove:await qt(ne(e,"links.remove.ndjson"),p,u=>({Id:q({Id:zs}).parse(u).Id})),share:await qt(ne(e,"links.share.ndjson"),l,u=>_s.parse(u))}}function Es(i,e){let t=new Map(i.map(s=>[s.objectApiName,s.readOrder])),n=s=>t.get(s)??-1;return s=>[...s].sort((r,o)=>e?n(o.objectApiName)-n(r.objectApiName):n(r.objectApiName)-n(o.objectApiName))}async function Vt(i,e,t){let n=ne(i,ze),s=ne(i,`undo-${Cs(4).toString("hex")}`),r=()=>Ds(s,{recursive:!0,force:!0});try{let o=b=>{if(b===void 0)return()=>!0;let S=new L;for(let E of b)S.add(E);return E=>S.has(E)},a=o(e.undo.removalLeft),d=o(e.undo.undeleteLeft),c=o(e.undo.restoreLeft),p=new L,l=new Set,u=new Map,f=new L,h=new Map,w=new L,m=new Set,k=new Map;await ve(n,b=>{switch(b.kind){case"bringBackLeft":for(let S of b.ids)m.add(W(S));break;case"bringingBack":case"withParent":case"recreated":for(let S of b.ids)p.add(S),m.size>0&&m.delete(W(S));b.kind==="withParent"&&b.carriers===!0&&b.parents&&b.ids.forEach((S,E)=>{let te=b.parents?.[E];te!==void 0&&!k.has(W(S))&&k.set(W(S),{objectApiName:b.objectApiName,id:S,parent:W(te)})});break;case"givingBack":for(let S of b.ids)w.add(S);break;case"deleteLeft":{let S=u.get(b.step)??new L;for(let E of b.ids)S.add(E);u.set(b.step,S);break}case"deleted":l.add(b.step);break;case"heldInPlace":{for(let E of b.ids)f.add(E);let S=h.get(b.objectApiName)??new Set;for(let E of b.by)S.add(E);h.set(b.objectApiName,S);break}default:break}});let g=b=>p.has(b)&&!m.has(b),y=new L,I=new De(ne(s,"bringBack"));await ve(n,async b=>{if(b.kind!=="deleting")return;let S=l.has(b.step)?u.get(b.step):void 0;for(let E of b.ids){if(S?.has(E)===!0)continue;let te=W(E);g(te)?y.add(E):d(te)&&await I.add(b.objectApiName,E)}});let v=new L,T=await yt.written(ne(s,"comesWithParent"),async b=>{await ve(n,async S=>{if(S.kind!=="goingAlong")return;let E=l.has(S.step)?u.get(S.step):void 0;for(let[te,we]of S.ids.entries()){let le=S.parents[te];E?.has(le)===!0||I.keys.has(we)||!v.add(we)||I.keys.has(le)&&await b(S.objectApiName,{id:we,parent:le})}})}),j=new L;for(let b=k.size>0;b;){b=!1;for(let{id:S,parent:E}of k.values())j.has(S)||w.has(S)||(y.has(E)||j.has(E))&&(j.add(S),b=!0)}let N=b=>y.has(b)||j.has(b),A=b=>!m.has(b)&&!N(b)&&a(b),x=new L,_=new L;await ve(n,b=>{b.kind!=="withParent"||b.parents===void 0||b.ids.forEach((S,E)=>{if(!_.add(S))return;let te=W(b.parents?.[E]??"");A(W(S))&&g(te)&&A(te)&&x.add(S)})});let K=new L,z=new Map;for(let{objectApiName:b,id:S,parent:E}of k.values())!A(W(S))||x.has(S)||!w.has(S)||A(E)&&k.has(E)||(K.add(S),z.set(b,(z.get(b)??0)+1));let B=new De(ne(s,"remove")),M=new De(ne(s,"giveBack")),G=new L,R=new Map,D=await yt.written(ne(s,"goesWithParent"),async b=>{await ve(n,async S=>{if(S.kind==="givingBack"){for(let E of S.ids)c(W(E))&&await M.add(S.objectApiName,E);return}if(S.kind==="recreated"){for(let E of S.ids)!A(W(E))||!await B.add(S.objectApiName,E)||(G.add(E),R.set(S.objectApiName,(R.get(S.objectApiName)??0)+1));return}if(!(S.kind!=="bringingBack"&&S.kind!=="withParent"))for(let[E,te]of S.ids.entries()){let we=W(te);if(!A(we))continue;let le=S.parents?.[E];x.has(we)?le!==void 0&&await b(S.objectApiName,{id:te,parent:le}):await B.add(S.objectApiName,te)}})}),C=await M.finish(),re=await ki(n,s),$=new L,Z=new Map;for(let{objectApiName:b}of C.objects)for await(let S of C.pages(b))for(let E of S)f.has(E)&&($.add(E),Z.set(b,(Z.get(b)??0)+1));return{remove:await Zn.of(B,Es(t,!1)),bringBack:await I.finish(Es(t,!0)),giveBack:C,giveBackKeys:M.keys,backup:e.head.backup,held:{keys:$,objects:[...Z].map(([b,S])=>({objectApiName:b,count:S,by:[...h.get(b)??[]]}))},goesWithParent:D,comesWithParent:T,remade:{keys:G,objects:[...R].map(([b,S])=>({objectApiName:b,count:S}))},compensated:{has:b=>N(W(String(b)))},carriedAlone:{keys:K,objects:[...z].map(([b,S])=>({objectApiName:b,count:S}))},...re?{links:re}:{},dispose:r}}catch(o){throw await r(),o}}async function Yo(i,e,t){let n=await Ke(i,e);if(!n)throw new H("notFound","No journal of this rewind is kept.");return Vt(n.dir,n.facts,t)}function Zo(i){let e=new Map,t=s=>{let r=e.get(s);return r||(r={objectApiName:s,deleted:0,broughtBack:0,givenBack:0},e.set(s,r)),r};for(let{objectApiName:s,count:r}of i.bringBack.objects)r>0&&(t(s).deleted+=r);for(let{objectApiName:s,count:r}of i.remove.objects)r>0&&(t(s).broughtBack+=r);for(let{objectApiName:s,count:r}of i.giveBack.objects)r>0&&(t(s).givenBack+=r);for(let{objectApiName:s,count:r}of i.held.objects){let o=t(s);o.givenBackHeld=(o.givenBackHeld??0)+r}let n=i.links;if(n){let s=t(oe);s.deleted+=n.reinsert.count,s.broughtBack+=n.remove.count,s.givenBack+=n.share.count}return[...e.values()]}import{readFile as bi,writeFile as Ri}from"node:fs/promises";import{join as Ys}from"node:path";var Yt="DuplicateRecordItem",Vs=1e3,Si=["createdSince","broughtBackSince"],Zs="duplicate-record-sets.ids";function We(i){return i.slice(0,15)}async function Zt(i,e,t){let n=Date.parse(t.takenAt),s=Date.parse(t.readAt);if(!Number.isFinite(n)||!Number.isFinite(s))return[];let r=(Math.floor(n/Vs)+1)*Vs;return An(i,{has:o=>e.has(o),start:r,end:s,madeFrom:r})}async function aa(i,e,t,n){let s=new Map;for(let o of e.objects){if(o.toDelete.createdSince+o.toDelete.broughtBackSince===0||!o.outside.some(({objectApiName:d})=>d===Yt))continue;let a=new L;for(let d of Si)if(o.toDelete[d]!==0)for await(let c of Ue(ke(t,o.objectApiName,d)))typeof c.Id=="string"&&a.add(c.Id);a.size>0&&s.set(o.objectApiName,a)}if(s.size===0)return 0;let r=await Zt(i,{has:o=>[...s.values()].some(a=>a.has(o))},{takenAt:n,readAt:e.readAt});if(r.length===0)return 0;for(let o of e.objects){let a=s.get(o.objectApiName);if(!a)continue;let d=r.filter(p=>p.names.some(l=>a.has(l)));if(d.length===0)continue;let c=new Set(d.flatMap(p=>p.names.filter(l=>a.has(l))));o.outside=[...o.outside.filter(({objectApiName:p})=>p!==ie),{objectApiName:ie,count:d.length,parents:c.size}].sort((p,l)=>p.objectApiName<l.objectApiName?-1:1)}return await ye(t),await Ri(Ys(t,Zs),r.map(o=>`${o.id}
12
- `).join(""),{encoding:"utf8",mode:Oe}),r.length}function da(i){return i.objects.reduce((e,t)=>e+t.outside.filter(({objectApiName:n})=>n===ie).reduce((n,{count:s})=>n+s,0),0)}async function Xs(i){let e;try{e=await bi(Ys(i,Zs),"utf8")}catch(t){if(t.code==="ENOENT")return new Set;throw t}return new Set(e.split(`
13
- `).filter(t=>/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/.test(t)).map(We))}async function bt(i,e){let t=new Map;for(let n of he([...e])){let{records:s}=await i.query(`SELECT Id FROM ${ie} WHERE Id IN (${n})`);for(let r of s)typeof r.Id=="string"&&t.set(We(r.Id),{id:r.Id,items:0})}for(let n of he([...t.values()].map(s=>s.id))){let{records:s}=await i.query(`SELECT DuplicateRecordSetId FROM ${Yt} WHERE DuplicateRecordSetId IN (${n})`);for(let r of s){let o=typeof r.DuplicateRecordSetId=="string"?t.get(We(r.DuplicateRecordSetId)):void 0;o&&o.items++}}return[...t.values()]}async function Qs(i,e){let t=new Set,n=[];for(let s of he([...e])){let{records:r}=await i.queryDeleted(`SELECT Id, DuplicateRecordSetId FROM ${Yt} WHERE DuplicateRecordSetId IN (${s}) AND IsDeleted = true`);for(let o of r)typeof o.Id=="string"&&(n.push(o.Id),typeof o.DuplicateRecordSetId=="string"&&t.add(We(o.DuplicateRecordSetId)))}return{sets:t.size,items:n}}function er(i,e){if(e.length===0)return i;let t=new Set(e.map(We));return{objects:[{objectApiName:ie,count:e.length},...i.objects],pages:n=>n===ie?(async function*(){yield[...e]})():i.pages(n),has:n=>t.has(We(n))||i.has(n)}}var tr=50,vi=/Entity is not in the recycle bin/,Ii="Salesforce still lists it as deleted but will not bring it back: emptied from the recycle bin, or kept there for good \u2014 deleted on its own, then a record it hangs from was deleted after it, it can no longer come back, with that record or without; deleted with a record still in the bin, it comes back only with that record (the org answers 'UNDELETE_FAILED: Entity is not in the recycle bin')",Ai=100;function fe(i){return i.slice(0,15)}var Oi=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function Pi(i,e){return{batches:async(t,n,s)=>{let r=await i.batches(t,n,s);return r?{async*[Symbol.asyncIterator](){for await(let o of r)yield o.map(a=>Object.fromEntries(Object.entries(a).filter(([d,c])=>d==="Id"||typeof c!="string"||!Oi.test(c)||!e.has(c))))}}:null}}}function ji(i){return{objects:[],cancelled:i,gone:[],stamps:{},left:async function*(){}}}function nr(i,e){if(e){i.restored+=e.restored,i.keptChanged+=e.keptChanged,i.alreadyGone+=e.alreadyGone,i.refused+=e.refused,i.notKept+=e.notKept,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached),e.restoredWithout&&(i.restoredWithout=(i.restoredWithout??0)+e.restoredWithout);for(let t of e.reasons)i.reasons.length<5&&!i.reasons.includes(t)&&i.reasons.push(t)}}async function*sr(i,e,t,n=()=>!0){let s=[];for await(let r of i.pages(e,t))for(let o of r)n(fe(o))&&(s.push(o),s.length>=t&&(yield s,s=[]));s.length>0&&(yield s)}function Li(i){let e=i.bringBack.objects.filter(({count:r})=>r>0).map(({objectApiName:r})=>r),t=new Set(i.held.objects.flatMap(({by:r})=>r)),n=e.findIndex(r=>t.has(r)),s=n<0||i.held.keys.size===0?e.length:n;return{bringFirst:e.slice(0,s),bringAfter:e.slice(s),held:r=>i.held.keys.has(r)}}function rr(i,e){i.planned+=e.planned,i.undeleted+=e.undeleted,i.alreadyBack+=e.alreadyBack,i.goneForGood+=e.goneForGood,i.refused+=e.refused,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached);for(let t of e.reasons)i.reasons.length<5&&!i.reasons.includes(t)&&i.reasons.push(t)}function Ni(i,e){if(!i)return e;let t=i.objects.map(n=>({...n,reasons:[...n.reasons]}));for(let n of e.objects){let s=t.find(r=>r.objectApiName===n.objectApiName);s?rr(s,n):t.push({...n,reasons:[...n.reasons]})}return{objects:t,left:[...i.left,...e.left],wrote:i.wrote||e.wrote,cancelled:i.cancelled||e.cancelled,stamps:{...i.stamps,...e.stamps}}}function Bi(i,e){if(!i)return e;let t=i.objects.map(n=>({...n,reasons:[...n.reasons]}));for(let n of e.objects){let s=t.find(r=>r.objectApiName===n.objectApiName);if(!s){t.push(n);continue}s.planned+=n.planned,nr(s,n)}return{objects:t,left:[...i.left,...e.left],wrote:i.wrote||e.wrote,cancelled:i.cancelled||e.cancelled,stamps:{...i.stamps,...e.stamps}}}async function Xt(i,e,t,n){if(e.cancelled)return e;let s=new Set(e.left.map(fe)),r=new Set,o=[];for(let a of e.objects){let d=a.reasons.find(f=>vi.test(f));if(d===void 0||a.refused===0){o.push(a);continue}let c=t.filter(({objectApiName:f})=>f===a.objectApiName).flatMap(f=>f.ids.filter(h=>s.has(fe(h)))),p=0;try{let f=de(a.objectApiName);for(let h of he(c,V)){let w=await i.query(`SELECT Id FROM ${f} WHERE Id IN (${h})`);for(let m of w.records)typeof m.Id!="string"||r.has(fe(m.Id))||(r.add(fe(m.Id)),p++)}}catch(f){n.push(`Whether the ${a.objectApiName} records the org answered were not in the recycle bin came back with their parent could not be read (${ee(f)}): they are counted refused.`),o.push(a);continue}let l=Math.min(p,a.refused),u=a.refused-l;o.push({...a,refused:u,alreadyBack:a.alreadyBack+l,reasons:u===0?a.reasons.filter(f=>f!==d):a.reasons.map(f=>f===d?Ii:f)})}return{...e,objects:o,left:e.left.filter(a=>!r.has(fe(a)))}}async function Ei(i,e,t,n){let s=new Map(n.map(a=>[fe(a),a])),r=new Map,o=await i.batches(e,t,V);for await(let a of o??[])for(let d of a){if(typeof d.Id!="string")continue;let c=s.get(fe(d.Id));if(c===void 0)continue;let p=r.get(fe(c))??{id:c,values:{}};for(let[l,u]of Object.entries(d))l!=="Id"&&!(l in p.values)&&(p.values[l]=u);r.set(fe(c),p)}return r}async function Ci(i,e,t,n){let s=new L;for(let d of t.get(ie)??[])s.add(d);let r=[];for await(let d of e.pages(ie))for(let c of d)s.has(c)||r.push(c);if(r.length===0)return;let o,a;try{o=(await bt(i,r)).filter(d=>d.items===0).map(d=>d.id),a=o.length>0?(await Qs(i,o)).items.length:0}catch(d){n.push(`Whether the ${ie} records the undo brought back came back with their items could not be read (${ee(d)}).`);return}if(o.length!==0)return{objectApiName:ie,count:o.length,ids:o.slice(0,tr),by:{},reason:"notBack",...a>0?{message:`${a} of their items`}:{}}}async function Ti(i,e,t,n,s){let r=[],o=e.backup;for(let{objectApiName:a}of e.giveBack.objects){let d=de(a),c={objectApiName:a,count:0,ids:[],by:{}};try{for await(let p of sr(e.giveBack,a,Ne,l=>!n.has(l))){let l=await Ei(t,o,a,p);if(l.size===0)continue;let u=new Set;for(let{values:m}of l.values())for(let k of Object.keys(m))u.add(de(k));let f=["Id","LastModifiedById",...u],h=f.length>Ai?V/4:V,w=async m=>(await i.query(m)).records;for(let m of he([...l.values()].map(k=>k.id),h)){let k=await nt(`SELECT ${f.join(", ")} FROM ${d} WHERE Id IN (${m})`,w);for(let g of k){if(typeof g.Id!="string")continue;let y=l.get(fe(g.Id));if(!y||!Object.entries(y.values).some(([T,j])=>!Nn(j,g[T])))continue;c.count++,c.ids.length<tr&&c.ids.push(y.id);let v=typeof g.LastModifiedById=="string"?g.LastModifiedById:"unknown";c.by[v]=(c.by[v]??0)+1}}}}catch(p){s.push(`The ${a} records the undo gave back could not be read again (${ee(p)}): whether they all hold their values from before the rewind was not checked.`)}c.count>0&&r.push(c)}return r}async function Fi(i,e,t,n,s){let r=new Map(Object.entries(n).map(([a,d])=>[fe(a),Date.parse(d)])),o=new L;for(let{objectApiName:a}of e.objects){let d=de(a);for await(let c of e.pages(a))for(let p of he(c,V)){if(s?.aborted)return o;let l;try{l=(await i.query(`SELECT Id, LastModifiedDate FROM ${d} WHERE Id IN (${p})`)).records}catch{continue}for(let u of l){if(typeof u.Id!="string")continue;let f=fe(u.Id),h=Date.parse(String(u.LastModifiedDate??""));(h<=t||h<=(r.get(f)??Number.NaN))&&o.add(u.Id)}}}return o}async function Ia(i){let e=await Ks(i.folder,i.rewindId,i.lock);try{let t=await e.facts(),n=await Vt(e.dir,t,i.objects);try{return await Di(e,t,n,i)}finally{await n.dispose()}}finally{await e.close()}}async function Di(i,e,t,n){let{org:s,signal:r}=n,o=t.goesWithParent,a=Pi(i.values,t.compensated),d={remove:t.remove.spool.count+o.count,bringBack:t.bringBack.count,giveBack:t.giveBack.count},c=[],p={...e.rewind.removalStamps,...e.undo.removalStamps},l=Object.keys(p).length>0?p:void 0,u=[...e.rewind.removalSpans??[],...e.undo.removalSpans??[]],f=Bn(s),h,w=new L,m={},k=new Set(n.objects.filter(O=>O.customSetting!==void 0).map(O=>O.objectApiName)),g=O=>!k.has(O),y=Li(t),I,v,T=new Map,j=await Mi(t.comesWithParent),N=new L,A=async O=>{for(let F of O)for await(let U of t.bringBack.pages(F)){let ae=(I?.cancelled??!1)||r?.aborted===!0;if(!ae&&j.size>0)for(let ue of U)j.has(ue)&&N.add(ue);let pe=ae?{objects:[{objectApiName:F,planned:U.length,undeleted:0,alreadyBack:0,goneForGood:0,refused:0,notReached:U.length,reasons:[]}],left:[...U],wrote:!1,cancelled:!0,stamps:{}}:await it({org:s,plan:[{objectApiName:F,ids:U}],undelete:n.undelete,...r?{signal:r}:{}});T.set(F,[...T.get(F)??[],...pe.left]),I=Ni(I,pe)}return!(I?.cancelled??!1)&&r?.aborted!==!0},x=async(O,F=g)=>{for(let{objectApiName:U}of t.giveBack.objects){if(!F(U))continue;let ae=de(U),pe={objectApiName:U,planned:0,restored:0,keptChanged:0,alreadyGone:0,refused:0,notKept:0,reasons:[]},ue={objects:[pe],left:[],wrote:!1,cancelled:!1,stamps:{}};for await(let je of sr(t.giveBack,U,Ne,O)){if(pe.planned+=je.length,(v?.cancelled??!1)||ue.cancelled||r?.aborted){ue.cancelled=!0,pe.notReached=(pe.notReached??0)+je.length,ue.left.push(...je);continue}if(h!==void 0){let Lr=je.filter(Nr=>w.has(Nr));Object.assign(m,await Cn(s,ae,Lr,h,f))}let cn={...p,...m},_e=await rt({org:s,plan:[{objectApiName:U,backup:t.backup,ids:je}],backups:a,...e.lastWriteAt!==void 0?{lastWriteAt:e.lastWriteAt}:{},includeChanged:!1,...Object.keys(cn).length>0?{stamps:cn}:{},...r?{signal:r}:{}});nr(pe,_e.objects[0]),ue.left.push(..._e.left),ue.wrote||=_e.wrote,ue.cancelled||=_e.cancelled,Object.assign(ue.stamps,_e.stamps)}pe.planned>0&&(v=Bi(v,ue))}return!(v?.cancelled??!1)&&r?.aborted!==!0},_=async()=>{if(t.bringBack.count>0&&t.giveBack.count>0){let F=await En(s);h=Date.now()+F-Bt;let U=Date.parse(e.lastWriteAt??""),ae=Number.isFinite(U)?U+F+Bt:Number.NEGATIVE_INFINITY;w=await Fi(s,t.giveBack,ae,p,r)}return await A(y.bringFirst.filter(g))&&await x(y.held)&&await A(y.bringAfter.filter(g))&&(I&&(I=await Xt(s,I,[...T].map(([F,U])=>({objectApiName:F,ids:U})),c)),await x(F=>!y.held(F))),(I?.wrote??!1)||(v?.wrote??!1)},K,z=(O,F)=>{if(typeof O.Id!="string"||!o.keys.has(O.Id))return!1;if(K===void 0){let pe=new L;for(let ue of v?.left??[])pe.add(ue);K={stamps:new Map(Object.entries({...p,...m}).map(([ue,je])=>[fe(ue),Date.parse(je)])),notGiven:pe}}let U=Date.parse(String(O.LastModifiedDate??O.SystemModstamp??"")),ae=fe(O.Id);return U<=F||U<=(K.stamps.get(ae)??Number.NaN)?!0:t.giveBackKeys.has(ae)&&v!==void 0&&!K.notGiven.has(ae)},B=t.links,M={removed:me(),reinserted:me(),shared:me()};if(B&&B.remove.count>0&&!r?.aborted)for await(let O of B.remove.pages())$e(M.removed,await ht(s,O,{after:async({done:F})=>{F.length>0&&await i.linksUndone("removed",F.map(U=>U.Id))},stopped:()=>r?.aborted===!0}));let G;if(t.remove.spool.count>0?G=await st(s,t.remove,{...n.splitting?{splitting:n.splitting}:{},runStartedAt:new Date(e.head.startedAt),...e.lastWriteAt!==void 0?{runRecordedAt:new Date(e.lastWriteAt)}:{},...l?{removalStamps:l}:{},...u.length>0?{removalSpans:u}:{},includeChanged:!1,...o.count>0?{goesWithParent:z,goesWithParentReadBelow:!0}:{},...t.bringBack.count>0||t.giveBack.count>0?{sweep:_}:{},...n.onUndeletable?{onUndeletable:n.onUndeletable}:{},...r?{signal:r}:{},...n.onProgress?{onProgress:n.onProgress}:{}}):(r?.aborted||await _(),G=ji(r?.aborted===!0&&!I&&!v)),k.size>0&&!G.stoppedForUndeletable&&(await x(()=>!0,O=>k.has(O)),await A([...y.bringFirst,...y.bringAfter].filter(O=>k.has(O)))),B&&!G.stoppedForUndeletable&&!r?.aborted){let O=s.create?.bind(s);for await(let F of B.reinsert.pages()){if(!O){M.reinserted.refused+=F.length,M.reinserted.reasons.push("The links the rewind removed could not be inserted again: this connection inserts no record.");continue}$e(M.reinserted,await gt({create:O},F,{after:async({made:U})=>{U.length>0&&await i.linksUndone("reinserted",U.map(ae=>ae.from))},stopped:()=>r?.aborted===!0}))}for await(let F of B.share.pages())$e(M.shared,await mt(s,F.map(U=>({...U,now:{ShareType:"",Visibility:""}})),{after:async({done:U})=>{U.length>0&&await i.linksUndone("shared",U.map(ae=>ae.Id))},stopped:()=>r?.aborted===!0}))}let R=B?{unlinked:M.removed.done,relinked:M.reinserted.done,linksUpdated:M.shared.done,linksRefused:M.removed.refused+M.reinserted.refused+M.shared.refused}:void 0;for(let O of[...M.removed.reasons,...M.reinserted.reasons,...M.shared.reasons])c.includes(O)||c.push(`A link between a file and a record: ${O}`);let D=new Date().toISOString();if(G.stoppedForUndeletable)return{rewindId:n.rewindId,status:"cancelled",deleted:[],restored:[],undeleted:[],residual:[],planned:d,notes:[],stoppedForUndeletable:!0,finishedAt:D};let C=[],re=new L,$=new Map,Z=new Map;for await(let{objectApiName:O,ids:F}of G.left())for(let U of F)re.add(U),C.push(U),t.remade.keys.has(U)&&$.set(O,($.get(O)??0)+1),t.carriedAlone.keys.has(U)&&Z.set(O,(Z.get(O)??0)+1);let b=t.remade.objects.map(({objectApiName:O,count:F})=>({objectApiName:O,count:F-($.get(O)??0)})).filter(({count:O})=>O>0),S=t.carriedAlone.objects.map(({objectApiName:O,count:F})=>({objectApiName:O,count:F-(Z.get(O)??0)})).filter(({count:O})=>O>0),E=[];for(let{objectApiName:O}of o.objects){let F=0;for await(let U of o.pages(O))for(let{id:ae,parent:pe}of U)re.has(pe)?C.push(ae):F++;F!==0&&E.push({objectApiName:O,planned:F,deleted:F,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],unchecked:[],reasons:[]})}let te=[...E,...G.objects],we=await Ui(t.comesWithParent,N,I),le=Tn(Fn(jn(te,G.cancelled),te,v),te,v,I),Ze=[];if(v&&le!=="cancelled"){let O=new L;for(let F of v.left)O.add(F);Ze=await Ti(s,t,a,O,c)}if(le!=="cancelled"){let O=await Ci(s,t.bringBack,T,c);O&&Ze.push(O)}Ze.length>0&&le==="success"&&(le="partial"),(R?.linksRefused??0)>0&&le==="success"&&(le="partial");let Or=t.remove.spool.count>0,Pr=v?.objects.some(O=>O.restored+(O.restoredWithout??0)>0)===!0,dn={...m,...G.stamps},jr={...Object.keys(dn).length>0?{removalStamps:dn}:{},...G.span?{removalSpans:[G.span]}:{},...Or?{removalLeft:C}:{},...v?{restoreLeft:v.left}:{},...Pr?{restoredAt:D}:{},...I?{undeleteLeft:I.left}:{},...I&&!I.cancelled?{undeletedAt:D}:{}};try{await i.undone(jr,le)}catch(O){c.push(`What this undo did could not be kept in the rewind\u2019s journal (${ee(O)}): an undo after it may set out to take back what it took back already.`)}return{rewindId:n.rewindId,status:le,deleted:te,...b.length>0?{remade:b}:{},...S.length>0?{carriedAlone:S}:{},...E.length>0?{wentAlong:E.map(({objectApiName:O,deleted:F})=>({objectApiName:O,count:F}))}:{},...we.length>0?{cameBackAlong:we}:{},restored:v?.objects??[],undeleted:$i(I?.objects??[],we),...R?{files:R}:{},residual:Ze,planned:d,notes:c,finishedAt:D}}async function Mi(i){let e=new L;for(let{objectApiName:t}of i.objects)for await(let n of i.pages(t))for(let{parent:s}of n)e.add(s);return e}async function Ui(i,e,t){if(t===void 0||e.size===0)return[];let n=new L;for(let r of t.left)n.add(r);let s=[];for(let{objectApiName:r}of i.objects){let o=0;for await(let a of i.pages(r))for(let{parent:d}of a)e.has(d)&&!n.has(d)&&o++;o>0&&s.push({objectApiName:r,count:o})}return s}function $i(i,e){let t=i.map(n=>({...n,reasons:[...n.reasons]}));for(let{objectApiName:n,count:s}of e){let r={objectApiName:n,planned:s,undeleted:s,alreadyBack:0,goneForGood:0,refused:0,reasons:[]},o=t.find(a=>a.objectApiName===n);o?rr(o,r):t.push(r)}return t}import{readFile as zi,writeFile as Wi}from"node:fs/promises";import{join as ir}from"node:path";var or="dependents-pointing.json",_i=un(X(),Xe().int().nonnegative()),Ea=V;async function Ca(i,e,t){if(e.length===0)return 0;let n=new Array(e.length).fill(!1);return(await ct(i,e.map(({childSObject:r,field:o})=>{let a=de(r);return{objectApiName:a,soql:`SELECT Id FROM ${a} WHERE ${de(o)} != null LIMIT 1`,scanAll:!1}}),(r,o)=>{o.length>0&&(n[r]=!0)},t,{oneRow:!0})).filter((r,o)=>!r.read||n[o]).length}async function Ta(i,e){e.size!==0&&(await ye(i),await Wi(ir(i,or),JSON.stringify(Object.fromEntries(e)),{encoding:"utf8",mode:Oe}))}async function ar(i){let e;try{e=JSON.parse(await zi(ir(i,or),"utf8"))}catch{return new Map}let t=_i.safeParse(e);return t.success?new Map(Object.entries(t.data)):new Map}var ur=1e3,qi=Hn*24*60*6e4,fr=50,yr=5,kr=["createdSince","broughtBackSince","comesBackWithParent","giveBack","inBin","withParent","deletedWhileTaken","toRecreate","carrier"],pr=[...kr.filter(i=>i!=="carrier"),"goneForGood","convertedLead","activatedContract","deletedWithCreatedParent","deletedWithParentOutside","deletedByOther","outOfReach"],xi="Left in the recycle bin: deleted since by another user, which only a user with View All Data and Modify All Data restores. Not made again: it is there still.",rn="Left as it is: out of the user's reach. Without View All Data and Modify All Data, nothing proves the user sees what others deleted of this object in the recycle bin, so it may be there out of sight, and it is never made again.",Gi={convertedLead:"Left converted: Salesforce can't unconvert a lead, and refuses any update of a converted one.",activatedContract:"Left activated: Salesforce won't set an activated contract back to Draft, so it is not given back.",deletedWithCreatedParent:"Left in the recycle bin: deleted with a record created since that Salesforce does not undelete on its own, it comes back with that record only.",deletedWithParentOutside:"Left in the recycle bin: deleted with its parent, a record of an object the checkpoint does not hold, it comes back with that record only. A checkpoint that holds that object brings it back.",deletedByOther:xi,outOfReach:rn},Rt={createdSince:"removal",broughtBackSince:"removal",comesBackWithParent:"removal",giveBack:"restore",inBin:"undelete",withParent:"undelete",deletedWhileTaken:"undelete",toRecreate:"recreate",carrier:"undelete"},Qt={outsideNotAccepted:"Kept: records outside the checkpoint created since hang from it, and their deletion was not accepted.",holdsLeft:"Kept: a record the rewind left hangs from it, and its deletion would take that record along.",noUndoNotAccepted:"Kept: Undo couldn't bring it back once deleted on its own, and that was not accepted.",beforeParentNotAccepted:"Kept: Undo couldn't bring it back once deleted before a record it points at, which the rewind deletes next, and that was not accepted.",keyTaken:"Kept in the recycle bin: a row of this custom setting made or changed since holds its owner or its name, and brought back beside it the setting would hold two. It comes back once that row is gone."};function Ji(i){return`Kept: records it does not delete hang from it (${i.join(", ")}), and its deletion would take them along.`}var en="It still differs from the checkpoint once the org was read again.",He=/Entity is not in the recycle bin/,Ki="Salesforce still lists it as deleted but will not bring it back: emptied from the recycle bin, or kept there for good (the org answers 'UNDELETE_FAILED: Entity is not in the recycle bin'). Make them again, with new Ids, or --accept-recreate on the command line, makes it again with a new Id.",Be="No record was written.",hr=4;function Hi(i,e,t){let n=e.some(a=>tt[a]!==void 0)?"as it is created or given its status back":"as it is created",s=[...new Set(t.fired.map(a=>`${a.objectApiName}: '${a.name}'`))],r=s.length-hr;return`Kept as it is: Salesforce answered it is no longer in the recycle bin, and ${s.length>0?`making it again runs what ${i} runs ${n} (${s.slice(0,hr).join(", ")}${r>0?` and ${r} more`:""})`:`what ${i} runs ${n} could not all be read`}, which this rewind did not ask about. Rewind again: its preview counts it to make again, and asks.`}var Vi="Account",Yi="Contact",Zi="001",Xi="005",Qi=q({sobjects:ge(q({name:X(),queryable:qe().optional()}).loose())}).loose(),eo=/No such column 'IsDeleted'/;function tn(i){return i.toLowerCase()===oe.toLowerCase()}function to(i,e){let t=Array.isArray(i)?i:[i];return e.filter((n,s)=>{let r=t[s];if(typeof r!="object"||r===null)return!1;let{success:o,errors:a}=r;return o===!0?!1:(Array.isArray(a)?a:[a]).some(d=>{let c=typeof d=="string"?d:typeof d=="object"&&d!==null?String(d.message??""):"";return He.test(c)})})}function no(i,e){let t=Array.isArray(i)?i:[i];return e.filter((n,s)=>{let r=t[s];return typeof r=="object"&&r!==null&&r.success===!1})}function Rd(i){let e=us(i),t=Pn(i,"Checkpoint rewind"),n=t.bulkDestroy;return{get version(){return e.version},request:s=>e.request(s),query:async(s,r)=>await i.query(s,{scanAll:r?.scanAll===!0}),queryMore:s=>e.queryMore(s),describeGlobal:()=>e.describeGlobal(),serverTime:()=>e.serverTime(),userId:()=>e.userId(),describe:s=>t.describe(s),update:(s,r)=>t.update(s,r),create:(s,r)=>i.sobject(s).create(r,{headers:gn()}),destroy:(s,r)=>t.destroy(s,r),queryDeleted:s=>t.queryDeleted(s),...n?{bulkDestroy:(s,r,o)=>n(s,r,o)}:{}}}async function so(i,e,t){if(!i||!e)return e?{automation:e}:{};try{let n=await i(e,Lt(t));return{automation:n.automation??e,mute:n}}catch(n){if(!Et(n))throw n;let s=Mn(e,Lt(t));return{refusal:{code:"MUTE",message:`${n.message} ${Be}`},automation:s.automation,plan:s.plan}}}async function ro(i,e,t,n){let s=i?.prepared?await i.prepared.acquire(e):void 0;i&&!s&&n(i.muted);let r;try{r=await t(s)}catch(o){if(!s)throw o;let a=await s.release();throw n(a),Object.assign(o instanceof Error?o:new Error(String(o)),{mutedAutomation:a})}return s&&n(await s.release()),r}var Ve=class extends Error{constructor(){super("The rewind was stopped before it wrote anything to the org."),this.name="RewindStopped"}};function P(i){return i.slice(0,15)}function St(i){let e=Sn(i);return e===null?Number.NaN:Date.parse(e)}async function*se(i){try{for await(let e of Ue(i))yield e}catch(e){if(e.code!=="ENOENT")throw e}}async function gr(i,e){let t=[];for await(let n of se(i)){let s=Se.safeParse(n);if(!s.success)throw new Error(`A line of ${i} names no ${e} link: the plan is not whole.`);t.push(s.data)}return t}async function io(i){let e=[];for await(let t of se(i)){let n=$t.safeParse(t);if(!n.success)throw new Error(`A line of ${i} names no link: the plan is not whole.`);e.push(n.data)}return e}var oo=q({sobjects:ge(q({name:X(),keyPrefix:X().nullish()}).loose())}).loose();function ao(i){return{query:e=>i.query(e),queryMore:e=>i.queryMore(e)}}function co(i,e){return{rewound:!1,refusal:{code:i,message:e}}}function mr(i,e){return{rewound:!1,refusal:i,...e.length>0?{alsoRefused:[...e]}:{}}}function lo(i,e){return{code:"RUN_WRITING",message:`${e.operation==="take"?`A checkpoint of ${i} is being taken`:e.operation==="rewind"?`A rewind is writing to ${i}`:e.operation==="undo"?`An undo is writing to ${i}`:e.operation==="empty"?`An emptying of its objects is writing to ${i}`:`SandForge is deleting checkpoints of ${i}`} (process ${e.pid} on ${e.host}): rewind once it has ended. No record was read or written.`}}var br=new Set(["noUndoNotAccepted","beforeParentNotAccepted"]),uo={noUndoNotAccepted:"Salesforce undeletes them only with their parent, which stays",beforeParentNotAccepted:"deleted before a record they point at, which the rewind deletes next, Salesforce cannot bring them back after that"};function fo(i){return{code:"NO_UNDO",message:`${[...br].flatMap(t=>{let n=i.filter(o=>o.reason===t);if(n.length===0)return[];let s=n.reduce((o,a)=>o+a.count,0),r=[...new Set(n.map(o=>o.objectApiName))].join(", ");return[`Undo couldn't bring back ${s} ${r} record(s) this rewind deletes: ${uo[t]??""}.`]}).join(" ")} Rewind refused; accept that Undo couldn't bring them back to rewind all the same. ${Be}`}}function po(i){let e=i.reduce((n,s)=>n+s.count,0),t=[...new Set(i.map(n=>n.objectApiName))].join(", ");return{code:"RECREATE",message:`${e} ${t} record(s) deleted since are no longer in the recycle bin, or Salesforce keeps them there for good: this rewind makes them again from the checkpoint, with new Ids. Anything outside Salesforce that names their old Ids \u2014 an integration, a link, a report filter \u2014 no longer finds them. Rewind refused; accept that they get new Ids to rewind all the same. ${Be}`}}function ho(i,e){return{code:"UNSEEN",message:`${e.map(({objectApiName:n,children:s,records:r})=>`Deleting ${r} ${n} record(s) created since also deletes what ${i} can't see under them in ${s.join(", ")}: Rewind can't count those.`).join(" ")} Rewind refused; accept that it deletes what ${i} can't see to rewind all the same. ${Be}`}}function go(i,e){return(i.unseen??[]).flatMap(t=>{let n=e.objects.find(r=>r.objectApiName===t.objectApiName),s=(n?.deleted??0)+(n?.withParentDeleted??0);return s>0?[{...t,records:s}]:[]})}function mo(i,e){if(e.kind==="org")return[];if(i.access.kind==="org")return["View All Data and Modify All Data"];let t=new Set(i.unread.map(n=>n.objectApiName));return[...e.notHeld].filter(([n])=>!t.has(n)).map(([n,s])=>`${n}: ${s}`)}function wo(i,e){return{code:"PERMISSIONS",message:`The preview read ${i} with permissions its user no longer has (${e.join("; ")}). Preview the rewind again: it reads the org as the user can now. ${Be}`}}var yo="accept that it runs to rewind all the same";function ko(i,e,t,n){let s=jt(e,t),r=[...new Set(s.map(d=>d.objectApiName))],o=(t.recreate??[]).length>0?"makes them again, ":"",a=s.length>0?`${vs(s)} flow(s), trigger(s) or rule(s) of ${r.join(", ")} run as the rewind brings records back, ${o}gives them their values back or deletes them`:"what runs as the rewind writes could not all be read, so automation may run";return{code:"AUTOMATION",message:`${i}: ${a}. ${xn("rewind",n)}Rewind refused; ${yo}. ${Be}`}}function bo(i,e){return{objectsRead:[...i],objects:[],unread:["flows","triggers","processes","workflowRules"].map(t=>({part:t,reason:e})),conditionsNotRead:0,conditionsBound:0,requests:0}}function wr(i){return i.replace(/the value from before is no longer taken/g,"the checkpoint's value is no longer taken").replace(/left as the run wrote it\b/g,"left as it is").replace(/left as the run wrote them\b/g,"left as they are").replace(/^The values from before the run could not be read:/,"The checkpoint's values could not be read:").replace(/record\(s\) of the run stay, and were not sent\./,"record(s) the rewind would delete stay, and were not sent.")}function Ae(i,e){i.length<yr&&!i.includes(e)&&i.push(e)}function vt(i,e,t){let n=t;for(let s of e){if(n<=0)return;let r=Number(i[s]??0),o=Math.min(r,n);i[s]=r-o,n-=o}}function At(i){return{objectApiName:i,planned:0,restored:0,keptChanged:0,alreadyGone:0,refused:0,notKept:0,reasons:[]}}function Rr(i,e){i.planned+=e.planned,i.restored+=e.restored,i.keptChanged+=e.keptChanged,i.alreadyGone+=e.alreadyGone,i.refused+=e.refused,i.notKept+=e.notKept,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached),e.restoredWithout&&(i.restoredWithout=(i.restoredWithout??0)+e.restoredWithout);for(let t of e.reasons)Ae(i.reasons,t)}function Ot(i){return{objectApiName:i,planned:0,undeleted:0,alreadyBack:0,goneForGood:0,refused:0,reasons:[]}}function Sr(i,e){i.planned+=e.planned,i.undeleted+=e.undeleted,i.alreadyBack+=e.alreadyBack,i.goneForGood+=e.goneForGood,i.refused+=e.refused,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached);for(let t of e.reasons)Ae(i.reasons,t)}function Pe(i){return{objectApiName:i,planned:0,created:0,refused:0,reasons:[]}}function vr(i,e){i.planned+=e.planned,i.created+=e.created,i.refused+=e.refused,e.notReached&&(i.notReached=(i.notReached??0)+e.notReached);for(let t of e.reasons)Ae(i.reasons,t)}function an(i,e){i.planned+=e.planned,i.deleted+=e.deleted,i.alreadyGone+=e.alreadyGone,i.keptChanged+=e.keptChanged,i.keptDependents+=e.keptDependents,i.refused+=e.refused,e.notVisible&&(i.notVisible=(i.notVisible??0)+e.notVisible),e.notReached&&(i.notReached=(i.notReached??0)+e.notReached);for(let t of e.heldBy)i.heldBy.includes(t)||i.heldBy.push(t);for(let t of e.unchecked)i.unchecked.includes(t)||i.unchecked.push(t);for(let t of e.reasons)Ae(i.reasons,t);e.filesLeft&&(i.filesLeft={count:(i.filesLeft?.count??0)+e.filesLeft.count,names:[...i.filesLeft?.names??[],...e.filesLeft.names].slice(0,yr)})}var Ye=class{restored=new Map;undeleted=new Map;recreated=new Map;deleted=new Map;wentAlong=new Map;left={restore:new Map,undelete:new Map,recreate:new Map,removal:new Map};heldInPlace=new Map;notInBin=new Map;notAsked=new Map;draftsLeft=new Map;lost=new Map;outOfReach=new Map;links={unlink:me(),relink:me(),share:me()};wrote=!1;cancelled=!1;leftBy(e,t,n){let s=this.left[e].get(t);s||(s=new L,this.left[e].set(t,s));for(let r of n)s.add(r)}mark(e,t,n){let s=this[e].get(t);s||(s=new L,this[e].set(t,s)),s.add(n)}cameBackGiven=new Map;cameBackRestored=0;restore(e,t){let n=this.restored.get(e.objectApiName)??At(e.objectApiName),s=t?.restored.length??0,r=t?.alreadyGone.length??0;if(Rr(n,{...e,planned:e.planned-s-r,restored:e.restored-s,alreadyGone:e.alreadyGone-r,reasons:e.reasons.map(wr)}),this.restored.set(e.objectApiName,n),s+r===0||!t)return;let o=this.cameBackGiven.get(e.objectApiName)??new L;for(let a of[...t.restored,...t.alreadyGone])o.add(a);this.cameBackGiven.set(e.objectApiName,o),this.cameBackRestored+=s}undelete(e){let t=this.undeleted.get(e.objectApiName)??Ot(e.objectApiName);Sr(t,e),this.undeleted.set(e.objectApiName,t)}recreate(e){let t=this.recreated.get(e.objectApiName)??Pe(e.objectApiName);vr(t,e),this.recreated.set(e.objectApiName,t)}delete(e){for(let t of e){let n=this.deleted.get(t.objectApiName),s={...t,reasons:t.reasons.map(wr)};n?an(n,s):this.deleted.set(t.objectApiName,structuredClone(s))}}goneAlong(e){this.delete(e.map(({objectApiName:t,count:n})=>({objectApiName:t,planned:n,deleted:n,alreadyGone:0,keptChanged:0,keptDependents:0,refused:0,heldBy:[],unchecked:[],reasons:[]})));for(let{objectApiName:t,count:n}of e)this.wentAlong.set(t,(this.wentAlong.get(t)??0)+n)}};async function Ro(i,e){let t=[];for(let{objectApiName:n,file:s}of i){let r=0;for await(let o of se(s))typeof o.parent=="string"&&!e(o.parent)&&r++;r>0&&t.push({objectApiName:n,count:r})}return t}async function So(i){let e=new Map;for(let t of i)for(let{objectApiName:n}of t.objects){let s=e.get(n)??new L;for await(let r of t.pages(n))for(let o of r)s.add(o);e.set(n,s)}return e}async function It(i,e,t){let n=await So(e),s=new Map,r=new Map;for(let o of i)for(let{objectApiName:a}of o.objects){let d=n.get(a);if(!d)continue;let c=s.get(a)??new L;s.set(a,c);let p=t?.get(a);for await(let l of o.pages(a))for(let u of l)d.has(u)&&p?.has(u)!==!0&&c.add(u)&&r.set(a,(r.get(a)??0)+1)}return r}async function vo(i,e){let t=i.tally,n=new Map([...t.deleted].map(([d,c])=>[d,structuredClone(c)])),s=new Map([...t.restored].map(([d,c])=>[d,structuredClone(c)])),r=new Map([...t.undeleted].map(([d,c])=>[d,structuredClone(c)])),o=new Map([...t.recreated].map(([d,c])=>[d,structuredClone(c)]));if(e){let{tally:d,plan:c}=e,p=await It([c.giveBack.beforeDeletes,c.giveBack.afterDeletes],[i.plan.giveBack.beforeDeletes,i.plan.giveBack.afterDeletes],t.cameBackGiven);for(let[h,w]of d.restored){let m=s.get(h)??At(h),k=p.get(h)??0;vt(m,["refused","notReached","notKept","keptChanged","restoredWithout","alreadyGone","restored"],k),m.planned-=Math.min(k,m.planned),Rr(m,w),s.set(h,m)}let l=await It([c.bringBack],[i.plan.bringBack]);for(let[h,w]of d.undeleted){let m=r.get(h)??Ot(h),k=l.get(h)??0;vt(m,["refused","notReached","goneForGood","alreadyBack","undeleted"],k),m.planned-=Math.min(k,m.planned),Sr(m,w),r.set(h,m)}let u=await It([c.recreate],[i.plan.recreate]);for(let[h,w]of d.recreated){let m=o.get(h)??Pe(h),k=u.get(h)??0;vt(m,["refused","notReached","created"],k),m.planned-=Math.min(k,m.planned),vr(m,w),o.set(h,m)}let f=await It([c.deletes.spool],[i.plan.deletes.spool]);for(let[h,w]of d.deleted){let m=n.get(h);if(!m){n.set(h,structuredClone(w));continue}let k=f.get(h)??0;vt(m,["refused","keptDependents","keptChanged","notVisible","alreadyGone","deleted"],k),m.planned-=Math.min(k,m.planned),an(m,w)}}for(let[d,{reason:c}]of[...t.heldInPlace,...e?.tally.heldInPlace??[]]){let p=s.get(d);p&&Ae(p.reasons,c)}let a=new Map(t.wentAlong);for(let[d,c]of e?.tally.wentAlong??[])a.set(d,(a.get(d)??0)+c);return{deleted:[...n.values()],restored:[...s.values()],undeleted:[...r.values()],recreated:[...o.values()],wentAlong:[...a].map(([d,c])=>({objectApiName:d,count:c}))}}function Io(i){let e=new Map;return{bodies:e,reader:{lane:()=>i.lane(),tooling:t=>i.tooling(t),calls:()=>i.calls(),describe:async(t,n)=>{let s=await i.describe(t,n);return"body"in s&&e.set(t,s.body),s}}}}function Ao(i){let e=i.objects,t=e.filter(n=>n.deleted+n.withParentDeleted+n.nextPassDeleted>0).map(n=>n.objectApiName);return{bringBack:e.filter(n=>n.broughtBack+n.backWithParent+(n.carriers??0)>0).map(n=>n.objectApiName),recreate:e.filter(n=>n.recreated>0).map(n=>n.objectApiName),giveBack:e.filter(n=>n.givenBackFirst+n.givenBackAfter+n.givenBackNextPass+Wn(n)>0).map(n=>n.objectApiName),setToDraft:e.filter(n=>zn(n)>0).map(n=>n.objectApiName),delete:t}}function Oo(i){let e=Ao(i),{unlink:t,relink:n,share:s,unlinkFrom:r}=i.links,o=(a,d)=>d?[...a??[],oe]:[...a??[]];return{...e,delete:o(e.delete,t.count+r.count>0),recreate:o(e.recreate,n.count>0),giveBack:o(e.giveBack,s.count>0)}}function Ir(i){let{unlink:e,relink:t,share:n,unlinkFrom:s}=i.links;return e.count+t.count+n.count+s.count}function nn(i){return i.deletes.spool.count+i.bringBack.count+i.recreate.count+i.giveBack.beforeDeletes.count+i.giveBack.afterDeletes.count+Ir(i)>0}function Po(i,e){let t=0,n=r=>(t++,r()),s=i.bulkDestroy?.bind(i);return{org:{get version(){return i.version},request:r=>n(()=>i.request(r)),query:(r,o)=>n(()=>i.query(r,o)),queryMore:r=>n(()=>i.queryMore(r)),describeGlobal:()=>n(()=>i.describeGlobal()),serverTime:()=>n(()=>i.serverTime()),userId:()=>n(()=>i.userId()),describe:r=>n(()=>i.describe(r)),update:(r,o)=>n(()=>i.update(r,o)),create:(r,o)=>n(()=>i.create(r,o)),destroy:(r,o)=>n(()=>i.destroy(r,o)),queryDeleted:r=>n(()=>i.queryDeleted(r)),...s?{bulkDestroy:async(r,o,a)=>{let d=1;try{let c=await s(r,o,a);return d=c.requests??1,c}finally{t+=d}}}:{}},undelete:r=>n(()=>e(r)),used:()=>t,add:r=>{t+=r}}}async function Sd(i,e){let{checkpoint:t,orgName:n}=e;if(e.reusesPreview&&e.reusesPreview.previewId!==e.previewId)throw new Error("A rewind acts on the preview it names: the one given is another.");let s=Po(i.org,i.undelete),r,o=await ls(ao(s.org),{act:"rewind",orgName:n,registered:e.registered,username:e.username,organizationId:t.org.organizationId,customSettings:Rn(t)},{userId:async()=>r=await s.org.userId()});if(!o.allowed)return{rewound:!1,refusal:o.refusal};let a=i.store.lock(t.org.organizationId,"rewind",t.checkpointId);if("busy"in a)return{rewound:!1,refusal:lo(n,a.busy)};let d=new on(i,e,s,a.lock,o.queryAllFiles,{grants:o.grants,...r!==void 0?{userId:r}:{}});try{let c=await i.runWriting?.(o.org.id);return c!==void 0?co("RUN_WRITING",c):await d.go()}finally{await d.cleanUp(),a.lock.release()}}var on=class{constructor(e,t,n,s,r,o){this.deps=e;this.request=t;this.count=n;this.lock=s;this.queryAllFiles=r;this.user=o;this.org=this.clock.watched(n.org),this.signal=e.signal,this.now=e.now??(()=>new Date),this.kept=Io(Tt(this.org,this.signal)),this.picked=t.objects!==void 0?new Set(t.objects):void 0}deps;request;count;lock;queryAllFiles;user;org;signal;now;notes=[];ownDirs=[];ended=!1;kept;global;cascadesOfObject=new Map;lifecycles=new Map;unqueried;noBin=new Set;splitting=Nt();stamps={};stampOf=new Map;spans=[];userId="";owners=new Set;carried=new L;comesBack=new L;before=Number.NaN;confirmedSets=new Set;setsRefused=new Set;clock=new As(()=>this.now().getTime());access=gs;picked;leftFields=new Map;asked;emailsCounted;stopped(){return this.signal?.aborted===!0}progress(e,t,n,s){this.deps.onProgress?.({phase:e,pass:t,percentage:n,step:s})}describeGlobal(){return this.global??=this.org.describeGlobal()}async diff(e){let t=Ge("pv",this.now()),n=Le(this.request.folder,t);return this.ownDirs.push(n),{diff:await ys({checkpoint:this.request.checkpoint,folder:this.request.folder,reader:this.kept.reader,describeGlobal:()=>this.describeGlobal(),previewId:t,readAt:e,queryAllFiles:this.queryAllFiles,access:this.access,...this.signal?{signal:this.signal}:{}}),dir:n}}async plan(e,t,n,s){let r=await bs({checkpoint:this.request.checkpoint,pass:e,confirmedDir:t,freshDir:n.dir,readAt:s,ownWriters:ut(this.request.checkpoint.takenBy,this.userId),acceptOutside:this.request.acceptOutside,acceptNoUndo:this.request.acceptNoUndo,acceptRecreate:this.request.acceptRecreate,...e===2&&Object.keys(this.stamps).length>0?{removalStamps:{...this.stamps}}:{},...e===2&&this.spans.length>0?{removalSpans:[...this.spans]}:{},...e===2?{recreated:await Fe.read(this.request.folder)}:{},...this.picked!==void 0?{objects:this.picked,heldRows:Ss(this.request.checkpoint,this.request.folder)}:{},dir:lr(n.dir,`plan${e}-${dr(4).toString("hex")}`),...this.signal?{signal:this.signal}:{}}),o=new Map;for(let{objectApiName:a}of this.request.checkpoint.objects){let d=new L;for(let c of kr){let p=c==="inBin"||c==="withParent";for await(let l of se(ke(r.dir,a,c)))typeof l.Id=="string"&&(d.add(l.Id),p&&this.comesBack.add(l.Id))}d.size>0&&o.set(a,d)}return{plan:r,acted:o}}async relationships(){let e=this.global,t=e?new Set((await vn({describeGlobal:()=>e})).keys()):void 0,n=new Set(this.request.checkpoint.objects.map(({objectApiName:o})=>o.toLowerCase()));if(this.request.checkpoint.files!==void 0)for(let o of[oe,bn])n.add(o.toLowerCase());let s=await ar(Le(this.request.folder,this.request.previewId)),r=new Map;for(let[o,a]of this.kept.bodies){let d=Xn(a,{inCheckpoint:n,...t?{worked:t}:{}}),c=s.get(o);r.set(o,c!==void 0?{...d,pointing:c}:d)}return r}async go(){let{checkpoint:e,orgName:t,folder:n}=this.request,s=await es(this.org,t);if(this.stopped())throw new Ve;this.progress("reading",1,5,`Reading ${t} again`);let r=this.request.reusesPreview,o,a,d;try{this.access=await ms({grants:this.user.grants,...this.user.userId!==void 0?{userId:this.user.userId}:{},username:this.request.username,checkpoint:e,reader:this.kept.reader});let $=r?mo(r,this.access):[];if($.length>0)return{rewound:!1,refusal:wo(t,$)};if(o=r?r.readAt:await this.org.serverTime(),this.before=Date.parse(o)-ur,!Number.isFinite(this.before))throw new Error(`Not a date: ${o}`);a=r?{diff:r,dir:Le(n,this.request.previewId)}:await this.diff(o),d=await this.plan(1,Le(n,this.request.previewId),a,o),this.confirmedSets=await Xs(Le(n,this.request.previewId))}catch($){throw $ instanceof xe||this.stopped()?new Ve:$}let c=[],p=d.plan.left.filter($=>br.has($.reason));p.length>0&&c.push(fo(p));let l=d.plan.left.filter($=>$.reason==="recreateNotAccepted");l.length>0&&c.push(po(l));let u=go(a.diff,d.plan);u.length>0&&!this.request.acceptUnseen&&c.push(ho(this.request.username,u));let f=ns("rewind",await this.bringBackFiles(d.plan,a.dir),s.fileStorage?.remaining,t);f&&c.push(f);let h=e.lastRewind,w=h!==void 0&&h.endedAt===void 0&&h.undoneAt===void 0,m=nn(d.plan);if(!m){let[$,...Z]=c;if($)return mr($,Z);if(!w)return this.wroteNothing(a,d,s.remaining)}let k=Oo(d.plan),g;if(m&&this.deps.readAutomation){let $=[...new Set([...k.bringBack??[],...k.recreate??[],...k.giveBack??[],...k.setToDraft??[],...k.delete??[]])];try{g=await this.deps.readAutomation($)}catch(Z){g=bo($,ee(Z))}this.count.add(g.requests)}let y=g,I=m?await so(this.deps.mute,g,k):{},v="refusal"in I?I:void 0,T="refusal"in I?void 0:I.mute;v&&c.push(v.refusal),I.automation&&(g=I.automation);let j=v?v.plan:T?.plan,N=this.request.acceptEmails===!0,A=m&&y?await Jn({act:"rewind",orgName:t,automation:y,steps:k,...j?{plan:j}:{},accepted:N,mayMute:this.deps.mute===void 0&&this.request.canMute===!0,read:()=>Dn(this.org)}):void 0,x=Rs(a.diff,this.picked),_=Qn({objects:e.objects,diff:this.picked!==void 0?{...x,withParentDeleted:d.plan.objects.flatMap(({objectApiName:$,withParentDeleted:Z})=>Z>0?[{objectApiName:$,count:Z}]:[])}:x,...this.picked!==void 0?{readDiff:a.diff}:{},automationRequests:0,relationships:await this.relationships(),...this.confirmedSets.size>0?{duplicateSets:this.confirmedSets.size}:{},...r?{reusesPreview:!0}:{}}),K=fs(A?.ofRun),z=ts("rewind",{run:this.count.used()-(K.deliverability??0)+_.apiRequests,...K,...$n(j)},s,t);m&&z&&c.push(z),this.splitting=Nt(In(s.remaining,this.count.used()+_.apiRequests+Un(j)));let B=_n(d.plan.objects),M=g?Gn("rewind",ot(B,g,s.emails),t):void 0;m&&M&&c.push(M);let G=g?qn(B,g):void 0;g&&!this.request.acceptAutomation&&(jt(g,k).length>0||wn(g.unread)||G!==void 0)&&c.push(ko(t,g,k,G)),m&&A?.refusal&&c.push(A.refusal);let[R,...D]=c;if(R)return mr(R,D);if(g&&(this.asked={automation:g,steps:k,accepted:this.request.acceptAutomation},this.emailsCounted={written:[...B],limits:s.emails}),this.stopped())throw new Ve;this.userId=await this.org.userId(),this.owners=new Set(ut(e.takenBy,this.userId).map(P));let C=await Js({folder:n,lock:this.lock,startedAt:o,userId:this.userId,...e.takenBy.automatedProcessUserId!==void 0?{automatedProcessUserId:e.takenBy.automatedProcessUserId}:{},now:this.now}),re;try{let $=await ro(T,`rewind ${e.checkpointId} ${o}`,b=>{let S=b&&j&&y&&A?Kn({act:"rewind",orgName:t,automation:y,steps:k,plan:j,held:b.outcome,planned:A.ofRun.senders,...A.ofRun.read?{reading:A.ofRun.read.reading}:{},accepted:N}):void 0;return S?Promise.resolve({rewound:!1,refusal:S}):this.passes(C,o,a,d,s.remaining)},b=>{re=b}).catch(b=>{if(Et(b))return{rewound:!1,refusal:{code:"MUTE",message:`${b.message} ${Be}`}};throw b}),Z=A?.gate.audit;return $.rewound?{...$,...re?{result:{...$.result,mutedAutomation:re}}:{},...Z!==void 0?{deliverability:Z}:{}}:$}finally{await C.close()}}async wroteNothing(e,t,n){let s=await this.residualOf(e,e,[t],new Ye),r=this.pickedOnly(e.diff.unread),o=await this.scopeOf(e,e),a=await this.setsLeft();return this.ended=!0,{rewound:!0,result:this.resultOf({rewindId:Ge("rw",this.now()),status:s.length>0||r.length>0?"partial":"success",tally:{deleted:a?[a]:[],restored:[],undeleted:[],recreated:[],wentAlong:[]},residual:s,unread:r,passes:1,leftToday:n,...o?{scope:o}:{}}),notes:this.notes}}async passes(e,t,n,s,r){let{checkpoint:o}=this.request,a=await e.read();this.addStamps(a.rewind.removalStamps??{}),this.spans.push(...a.rewind.removalSpans??[]);for(let{ids:R}of a.did.carried??[])for(let D of R)this.carried.add(D);let d=new Date(Date.parse(a.head.startedAt)+qi).toISOString(),c;await this.deps.store.update(o.checkpointId,R=>(R.lastRewind?.rewindId!==e.rewindId&&(c=R.lastRewind),{...R,lastRewind:{rewindId:e.rewindId,undoUntil:d}}));let p=nn(s.plan),l=p?await this.pass(e,s.plan,n.diff,1):new Ye,u=[s],f,h,w=l.cancelled;try{if(!w&&l.wrote){this.progress("reading",2,70,`Reading ${this.request.orgName} again`);let R=await this.diff(await this.org.serverTime()),D=await this.plan(2,s.plan.dir,R,t);if(u.push(D),h=R,nn(D.plan)){let C=await this.pass(e,D.plan,R.diff,2);f={tally:C,plan:D.plan},w=C.cancelled,!w&&C.wrote&&(this.progress("checking",2,90,`Checking ${this.request.orgName}`),h=await this.diff(await this.org.serverTime()))}}else!w&&p?(this.progress("checking",1,90,`Checking ${this.request.orgName}`),h=await this.diff(await this.org.serverTime())):w||(h=n)}catch(R){if(!(R instanceof xe)&&!this.stopped())throw R;w=!0}this.stopped()&&(w=!0);let m=await vo({tally:l,plan:s.plan},f),k=w?void 0:await this.setsLeft();if(k){let R=m.deleted.find(D=>D.objectApiName===ie);R?an(R,k):m.deleted.push(k)}let g=!w&&h?await this.residualOf(h,n,u,l,f?.tally):[],y=!w&&h?this.pickedOnly(h.diff.unread):[],I=await this.scopeOf(w?void 0:h,n),v=m.deleted.some(R=>R.deleted>0)||m.restored.some(R=>R.restored+(R.restoredWithout??0)>0)||m.undeleted.some(R=>R.undeleted>0)||m.recreated.some(R=>R.created>0)||l.cameBackRestored+(f?.tally.cameBackRestored??0)>0,T=w?"cancelled":g.some(R=>R.reason==="changedDuringRewind")?"unstable":g.length>0||y.length>0?v?"partial":"failure":"success",j=this.filesOf(g,[l,...f?[f.tally]:[]]),N=(j?.unlinked??0)+(j?.relinked??0)+(j?.linksUpdated??0),A=v||N>0||(w||e.resumed)&&(await e.facts()).lastWriteAt!==void 0,x=[];if(w&&!A)try{await this.deps.store.update(o.checkpointId,R=>(delete R.lastRewind,c?{...R,lastRewind:c}:R))}catch(R){this.notes.push(`The checkpoint could not be told the rewind stopped before it wrote anything (${ee(R)}): its list may not offer to undo the rewind before it.`)}if(!w){await e.end(),this.ended=!0;let R=h?.diff.readAt??this.now().toISOString(),D=A?{rewindId:e.rewindId,endedAt:R,undoUntil:d}:c;try{await this.deps.store.update(o.checkpointId,C=>(delete C.lastRewind,D?{...C,lastRewind:D}:C))}catch(C){this.notes.push(A?`The checkpoint could not be told when the rewind ended (${ee(C)}): its list may not offer to undo it.`:`The checkpoint could not be told the rewind wrote nothing (${ee(C)}): its list may not offer to undo the rewind before it.`)}try{A&&(x=await Hs(this.deps.store,this.lock,{checkpointId:o.checkpointId,rewindId:e.rewindId}))}catch(C){this.notes.push(`The journals of the earlier rewinds of ${this.request.orgName} could not be deleted (${ee(C)}): they stay until their checkpoint goes.`)}}let _=await e.read(),K=this.undoCannotOf(_),z=(_.did.carriers??[]).map(({objectApiName:R,ids:D})=>({objectApiName:R,count:D.length}));if(w){let R=new Set(_.did.deleted.flatMap(({ids:C})=>C.map(P))),D=(_.did.carriers??[]).map(({objectApiName:C,ids:re})=>({objectApiName:C,count:re.filter($=>!R.has(P($))).length})).filter(({count:C})=>C>0);D.length>0&&this.notes.push(`Stopped with ${D.map(({objectApiName:C,count:re})=>`${re} ${C}`).join(", ")} record(s) brought back for a moment still in the org: they had taken records of the checkpoint along. Rewind again to delete them, with what came back with them.`)}let B=new Map;for(let R of[l,...f?[f.tally]:[]])for(let[D,C]of R.draftsLeft)B.set(D,[...B.get(D)??[],...C]);let M=[...B].map(([R,D])=>({objectApiName:R,count:D.length,ids:D.slice(0,fr)})),G={rewound:!0,result:this.resultOf({rewindId:e.rewindId,status:T,tally:m,residual:g,unread:y,passes:f?2:1,leftToday:r,...A?{undo:{until:d,cannot:K}}:{},removedJournals:x,carriers:z,draftsLeft:M,...j?{files:j}:{},...I?{scope:I}:{}}),notes:this.notes};if(v||_.lastWriteAt!==void 0&&(w||e.resumed)){let R=await Os({folder:this.request.folder,lock:this.lock,checkpoint:o,result:G.result,startedAt:t,...!w&&h?{endedAt:h.diff.readAt}:{},clock:this.clock});R!==void 0&&this.notes.push(R)}if(!A){await e.close();try{await cr(Te(this.request.folder,e.rewindId),{recursive:!0,force:!0})}catch(R){this.notes.push(`The journal of this rewind, which wrote nothing, could not be deleted (${ee(R)}): it stays until a later rewind that writes ends, or its checkpoint goes.`)}}return G}filesOf(e,t){if(this.request.checkpoint.files===void 0)return;let n=r=>t.reduce((o,a)=>o+a.links[r].done,0),s={unlinked:n("unlink"),relinked:n("relink"),linksUpdated:n("share"),linksRefused:e.filter(r=>r.objectApiName===oe&&r.reason==="refused").reduce((r,o)=>r+o.count,0)};return s.unlinked+s.relinked+s.linksUpdated+s.linksRefused>0?s:void 0}async bringBackFiles(e,t){let n=new L;for await(let r of e.bringBack.pages(Ce))for(let o of r)n.add(o);if(n.size===0)return{files:0,bytes:0};let s=new Map;for await(let r of se(lt(t,Ce)))typeof r.Id=="string"&&typeof r.ContentSize=="number"&&n.has(r.Id)&&s.set(P(r.Id),r.ContentSize);if(s.size<n.size&&this.request.checkpoint.files!==void 0)for await(let r of cs(this.request.folder))n.has(r.Id)&&!s.has(P(r.Id))&&r.ContentSize!==null&&s.set(P(r.Id),r.ContentSize);return{files:n.size,bytes:[...s.values()].reduce((r,o)=>r+o,0)}}undoCannotOf(e){let t=new Set(this.request.checkpoint.objects.filter(o=>!o.undeletable).map(o=>o.objectApiName)),n=new Set(e.did.broughtBack.flatMap(({ids:o})=>o.map(P))),s=new Set((e.did.deletedBeforeParent??[]).flatMap(({ids:o})=>o.map(P))),r=[];for(let{objectApiName:o,ids:a}of e.did.deleted){let d=a.map(P).filter(l=>!n.has(l)),c=d.filter(l=>s.has(l)).length,p=t.has(o)?d.length-c:0;p>0&&r.push({objectApiName:o,count:p}),c>0&&r.push({objectApiName:o,count:c,reason:"deletedBeforeParent"})}return r}resultOf(e){let t=this.count.used();return{checkpointId:this.request.checkpoint.checkpointId,rewindId:e.rewindId,status:e.status,deleted:e.tally.deleted,...e.tally.wentAlong.length>0?{wentAlong:e.tally.wentAlong}:{},restored:e.tally.restored.filter(n=>n.planned>0),undeleted:e.tally.undeleted.filter(n=>n.planned>0),...e.tally.recreated.length>0?{recreated:e.tally.recreated}:{},...(e.carriers??[]).length>0?{carriers:e.carriers}:{},...(e.draftsLeft??[]).length>0?{draftsLeft:e.draftsLeft}:{},residual:e.residual,...e.unread.length>0?{unread:[...e.unread]}:{},passes:e.passes,...e.undo?{undo:e.undo}:{},...(e.removedJournals??[]).length>0?{removedJournals:e.removedJournals}:{},...e.files?{files:e.files}:{},apiRequests:{used:t,leftToday:Math.max(0,e.leftToday-t)},finishedAt:this.now().toISOString(),...e.scope?{scope:e.scope}:{}}}pickedOnly(e){let t=this.picked;return t===void 0?[...e]:e.filter(n=>t.has(n.objectApiName))}async scopeOf(e,t){let n=this.picked;if(n===void 0)return;let{checkpoint:s}=this.request,r=s.objects.map(({objectApiName:d})=>d).filter(d=>n.has(d)),o=[],a=0;if(e!==void 0){let d=[...s.objects].sort((c,p)=>c.readOrder-p.readOrder);for(let{objectApiName:c}of d){if(n.has(c))continue;let p=new L;for await(let u of se(ke(t.dir,c,"goneForGood")))typeof u.Id=="string"&&p.add(u.Id);let l=new L;for(let u of pr)for await(let f of se(ke(e.dir,c,u)))typeof f.Id!="string"||p.has(f.Id)||l.add(f.Id);l.size>0&&(o.push(c),a+=l.size)}if(s.files!==void 0&&!n.has(Ce)){let c=new L;for(let p of["linkAdded","linkRemoved","linkChanged"])for await(let l of se(Ut(e.dir,p)))typeof l.Id=="string"&&c.add(l.Id);c.size>0&&(o.push(oe),a+=c.size)}}return{objects:r,notRewound:{objects:o,records:a}}}async readLeftFields(e){let t=e.limited?.leftFields;if(!(t===void 0||t.count===0))for await(let n of se(t.file)){if(typeof n.Id!="string"||!Array.isArray(n.fields))continue;let s=this.leftFields.get(P(n.Id))??new Set;for(let r of n.fields)typeof r=="string"&&s.add(r.toLowerCase());this.leftFields.set(P(n.Id),s)}}async cleanUp(){let e=[...this.ownDirs];this.ended&&e.push(Le(this.request.folder,this.request.previewId));for(let t of e)await cr(t,{recursive:!0,force:!0}).catch(()=>{})}async pass(e,t,n,s){let r=new Ye;await this.readLeftFields(t);let o={},a=f=>{Object.assign(o,f),this.addStamps(f)},d=this.allowLists(n),c=new L;for(let{objectApiName:f}of t.giveBack.afterDeletes.objects){let h=t.giveBack.heldBy.find(w=>w.objectApiName===f)?.by;for await(let w of t.giveBack.afterDeletes.pages(f)){for(let m of w)c.add(m);h&&await e.heldInPlace(f,h,w)}}await this.keepFirst(e,t.giveBack.afterDeletes,d);let p=this.request.acceptRecreate?new De(lr(t.dir,`remake-${dr(4).toString("hex")}`)):void 0,l=async()=>{t.bringBack.count>0&&(this.progress("bringingBack",s,s===1?25:80,"Bringing back what was deleted since"),await this.bringBack(e,t.bringBack,t.carriers,r,a,p));let f=p&&p.objects.length>0?await this.withPlanned(p,t.recreate):t.recreate;if(!r.cancelled&&!this.stopped()&&f.count>0)this.progress("recreating",s,s===1?32:81,"Making again what the recycle bin no longer holds"),await this.recreate(e,f,r);else if(f.count>0){for(let{objectApiName:h,count:w}of f.objects)r.recreate({...Pe(h),planned:w,notReached:w});r.cancelled=!0}return!r.cancelled&&!this.stopped()&&t.giveBack.beforeDeletes.count>0&&(this.progress("givingBack",s,s===1?40:82,"Giving back what was changed since"),await this.giveBack(e,t,t.giveBack.beforeDeletes,"before",d,c,r,a)),r.wrote},u;if(t.deletes.spool.count>0){this.progress("deleting",s,s===1?55:85,"Deleting what was created since");for(let{objectApiName:g,file:y}of t.beforeParent){let I=[];for await(let v of se(y)){let T=Array.isArray(v.parents)?v.parents:[];for(let j of T)typeof v.Id=="string"&&typeof j=="string"&&I.push({id:v.Id,parent:j});I.length>=J&&await e.beforeParent(g,I.splice(0))}I.length>0&&await e.beforeParent(g,I)}let f=await this.withSets(t);await e.deleting(f);for(let{objectApiName:g,file:y}of t.along){let I=[];for await(let v of se(y))typeof v.Id=="string"&&typeof v.parent=="string"&&I.push({id:v.Id,parent:v.parent}),I.length>=J&&await e.goingAlong(g,I.splice(0));I.length>0&&await e.goingAlong(g,I)}let h={...this.stamps,...t.removal.removalStamps},w=[...this.spans,...t.removal.removalSpans??[]].filter((g,y,I)=>I.findIndex(v=>JSON.stringify(v)===JSON.stringify(g))===y),m=(g,y)=>{if(typeof g.Id!="string"||!this.carried.has(g.Id)&&!t.goesAlong.has(g.Id))return!1;let I=St(g.LastModifiedDate??g.SystemModstamp);return I<=y||I<=(this.stampOf.get(P(g.Id))??Number.NaN)};u=await st(this.org,f,{splitting:this.splitting,runStartedAt:t.removal.runStartedAt,runEndedAt:t.removal.runEndedAt,includeChanged:t.removal.includeChanged,alongAccepted:!0,...Object.keys(h).length>0?{removalStamps:h}:{},...w.length>0?{removalSpans:w}:{},...this.carried.size+t.carriers.size+t.goesAlong.size>0?{goesWithParent:m}:{},...t.alongToDraft.spool.count>0?{alongToDraft:t.alongToDraft}:{},...t.bringBack.count+t.recreate.count+t.giveBack.beforeDeletes.count>0?{sweep:l}:{},...this.deps.onUndeletable?{onUndeletable:this.deps.onUndeletable}:{},...this.signal?{signal:this.signal}:{},onProgress:(g,y,I)=>this.progress("deleting",s,s===1?55:85,`Deleting ${I}: ${g} / ${y}`)}),await e.deleted(u);for await(let{objectApiName:g,ids:y}of u.left())r.leftBy("removal",g,y);let k=[...r.left.removal.values()];r.goneAlong(await Ro(t.along,g=>k.some(y=>y.has(g)))),r.delete(u.objects),u.cancelled&&(r.cancelled=!0),(u.objects.some(g=>g.deleted>0)||u.span)&&(r.wrote=!0),a(u.stamps),u.span&&this.spans.push(u.span)}else this.stopped()?r.cancelled=!0:await l();return!r.cancelled&&!this.stopped()&&t.giveBack.afterDeletes.count>0&&(this.progress("givingBack",s,s===1?65:88,"Giving back what the deleted records held in place"),await this.giveBack(e,t,t.giveBack.afterDeletes,"after",d,c,r,a)),!r.cancelled&&!this.stopped()&&Ir(t)>0&&(this.progress("givingBack",s,s===1?68:89,"Putting back the links between files and records"),await this.writeLinks(e,t,r)),this.stopped()&&(r.cancelled=!0),await e.removal({removalStamps:o,removalSpans:u?.span?[u.span]:[]}),r}async withSets(e){let t=e.deletes;if(this.confirmedSets.size===0)return t;let n=(await Zt(this.org,{has:o=>t.has(o)||e.goesAlong.has(o)},{takenAt:this.request.checkpoint.takenAt,readAt:new Date(this.before+ur).toISOString()})).filter(o=>this.confirmedSets.has(P(o.id)));if(n.length===0)return t;let s=new Set(n.map(o=>P(o.id)));this.confirmedSets=new Set([...this.confirmedSets].filter(o=>!s.has(o)));let r;try{r=(await this.org.describe(ie))?.deletable!==!1}catch{r=!1}if(!r){for(let o of s)this.setsRefused.add(o);return t}return er(t,n.map(o=>o.id))}async setsLeft(){let e=[...new Set([...this.confirmedSets,...this.setsRefused])];if(e.length===0)return;let t;try{t=await bt(this.org,e)}catch(o){this.notes.push(`Whether the ${ie} records its preview named are still in ${this.request.orgName} could not be read (${ee(o)}).`);return}if(t.length===0)return;let n=t.filter(o=>this.setsRefused.has(P(o.id))).length,s=t.filter(o=>!this.setsRefused.has(P(o.id))&&o.items>=2).length,r=t.length-n-s;return{objectApiName:ie,planned:t.length,deleted:0,alreadyGone:0,keptChanged:0,keptDependents:s+r,refused:n,heldBy:[],unchecked:[],reasons:[...n>0?[`${this.request.username} may not delete ${ie} records`]:[],...s>0?["they still report records alike that this rewind keeps"]:[],...r>0?[`they report nothing any more, and no rewind takes an empty set: delete them in ${this.request.orgName}, from the Duplicate Record Sets tab`]:[]]}}async writeLinks(e,t,n){let s=()=>this.stopped(),r=async d=>{d!==0&&(n.wrote=!0,await e.wrote())},o=await gr(t.links.unlink.file,"linkAdded"),a=new Set(o.map(d=>P(d.Id)));for(let d of await this.heldLinksOf(t.links.unlinkFrom,t))a.has(P(d.Id))||o.push(d);if(n.links.unlink=await ht(this.org,o,{before:d=>e.unlinking(d),after:async({done:d,left:c})=>{c.length>0&&await e.unlinkLeft(c),await r(d.length)},stopped:s}),n.links.unlink.cancelled&&(n.cancelled=!0),!n.cancelled&&t.links.relink.count>0){let d=await Fe.read(this.request.folder);n.links.relink=await gt(this.org,await gr(t.links.relink.file,"linkRemoved"),{after:async({made:c})=>{c.length>0&&await e.relinked(c),await r(c.length)},stopped:s},c=>d.currentOf(P(c))??c),n.links.relink.cancelled&&(n.cancelled=!0)}if(!n.cancelled&&t.links.share.count>0){let d=await io(t.links.share.file),c=new Map(d.map(p=>[P(p.Id),p.now]));n.links.share=await mt(this.org,d,{before:p=>e.linksUpdating(p.map(l=>({...l,...c.get(P(l.Id))??{}}))),after:async({done:p,left:l})=>{l.length>0&&await e.linksUpdateLeft(l),await r(p.length)},stopped:s}),n.links.share.cancelled&&(n.cancelled=!0)}}async heldLinksOf(e,t){if(e.count===0)return[];let n=oo.safeParse(await this.describeGlobal()),s=as(n.success?n.data.sobjects:[],this.request.checkpoint.objects.map(({objectApiName:o})=>o)),r=[];for await(let o of e.pages(Ce,Mt))for(let a of he(o,Mt)){let d=await this.org.query(`SELECT ${os.join(", ")} FROM ${oe} WHERE ContentDocumentId IN (${a})`);for(;;){for(let c of d.records){let p=Se.safeParse(c);!p.success||ds(p.data,s)===void 0||t.deletes.has(P(p.data.LinkedEntityId))||r.push(p.data)}if(d.done||!d.nextRecordsUrl)break;d=await this.org.queryMore(d.nextRecordsUrl)}}return r}allowLists(e){let t=new Map(e.objects.map(s=>[s.objectApiName,new Set(s.notCompared.map(r=>r.toLowerCase()))])),n=new Map(this.request.checkpoint.objects.map(s=>[s.objectApiName,s]));return s=>{let r=n.get(s),o=t.get(s);return Dt(s,r?.fields??[],this.request.checkpoint.ignoredFields).filter(a=>!o?.has(a.toLowerCase()))}}async keepFirst(e,t,n){for(let{objectApiName:s}of t.objects){let r=n(s);if(r.length===0)continue;let o=de(s),d=this.request.checkpoint.objects.find(l=>l.objectApiName===s)?.fields.some(l=>l===Me)===!0,c=["Id",...r.map(de),...d?[Me]:[]],p=async l=>(await this.org.query(l)).records;try{for await(let l of t.pages(s))for(let u of he(l,V)){if(this.stopped())return;let h=(await nt(`SELECT ${c.join(", ")} FROM ${o} WHERE Id IN (${u})`,p)).map(w=>dt(s,w,r));h.length>0&&await e.keep(s,h)}}catch(l){if(l instanceof xe)return;this.notes.push(`What the ${s} records given back after the deletions held could not be kept before the rewind wrote (${ee(l)}): Undo gives them back what they held once the deletions were through.`)}}}async cascadesOf(e){let t=this.kept.bodies.get(e);if(t===void 0){let a=await this.kept.reader.describe(e);t="body"in a?a.body:void 0}let n=Ft.safeParse(t);if(!n.success)throw new Error(`The org gave no describe of ${e}.`);let s=e===Vi&&n.data.fields.some(a=>a.name===Me),r=(n.data.childRelationships??[]).filter(a=>a.cascadeDelete===!0);if(r.length===0)return[];let o=await this.unqueriedObjects();return r.filter(a=>!o.has(a.childSObject)).map(a=>({child:a.childSObject,field:a.field,...s&&a.childSObject===Yi&&a.field==="AccountId"?{persons:!0}:{}}))}unqueriedObjects(){return this.unqueried??=this.describeGlobal().then(e=>{let t=Qi.safeParse(e);return t.success?new Set(t.data.sobjects.filter(n=>n.queryable===!1).map(n=>n.name)):new Set},()=>(this.global=void 0,new Set)),this.unqueried}async insertFieldsOf(e){let t=this.kept.bodies.get(e);if(t===void 0){let d=await this.kept.reader.describe(e);t="body"in d?d.body:void 0}let n=Ft.safeParse(t);if(!n.success)throw new Error(`The org gave no describe of ${e}.`);let s=new Map(n.data.fields.map(d=>[d.name.toLowerCase(),d])),r=this.request.checkpoint.objects.find(d=>d.objectApiName===e),o=Dt(e,r?.fields??[],this.request.checkpoint.ignoredFields).filter(d=>s.get(d.toLowerCase())?.createable===!0),a=o.filter(d=>s.get(d.toLowerCase())?.type==="reference");return{fields:o.map(de),lookups:a}}async withPlanned(e,t){for(let{objectApiName:s}of t.objects)for await(let r of t.pages(s))for(let o of r)await e.add(s,o);let n=new Map(this.request.checkpoint.objects.map(s=>[s.objectApiName,s.readOrder]));return e.finish(s=>[...s].sort((r,o)=>(n.get(o.objectApiName)??0)-(n.get(r.objectApiName)??0)))}async recreate(e,t,n){let{checkpoint:s,folder:r}=this.request,o=new L;for(let{objectApiName:u}of t.objects)for await(let f of t.pages(u))for(let h of f)o.add(h);let a=await Fe.read(r),d=new Set,c=u=>a.originalOf(u.slice(0,15))??u.slice(0,15),p=[],l=new Map;for(let{objectApiName:u,count:f}of t.objects){if(n.cancelled||this.stopped()){n.recreate({...Pe(u),planned:f,notReached:f}),n.cancelled=!0;continue}let h;try{h=await this.insertFieldsOf(u)}catch(k){if(k instanceof xe){n.cancelled=!0,n.recreate({...Pe(u),planned:f,notReached:f});continue}let g=ee(k);n.recreate({...Pe(u),planned:f,refused:f,reasons:[g]});for await(let y of t.pages(u))n.leftBy("recreate",u,y);continue}let w=h.fields.find(k=>k.toLowerCase()==="status"),m=w!==void 0?await this.lifecycleOf(u):void 0;for await(let k of t.pages(u,Ne)){if(n.cancelled||this.stopped()){n.recreate({...Pe(u),planned:k.length,notReached:k.length}),n.cancelled=!0;continue}let g=await at.read(r,s.snapshotId,u,a),y=[],I=await g.chunk(k).batches(s.snapshotId,u,V);for await(let N of I??[])y.push(...N);let v={...Pe(u),planned:k.length},T=new L;for(let N of y)typeof N.Id=="string"&&T.add(N.Id);let j=k.filter(N=>!T.has(N));j.length>0&&(v.refused+=j.length,Ae(v.reasons,"The checkpoint holds no values of it."),n.leftBy("recreate",u,j));for(let N=0;N<y.length;N+=V){if(this.stopped()){let M=y.length-N;v.notReached=(v.notReached??0)+M,n.leftBy("recreate",u,y.slice(N).map(G=>String(G.Id))),n.cancelled=!0;break}let A=y.slice(N,N+V),x=A.map(M=>g.snapshotIdOf(String(M.Id))),_=new Map,K=A.map((M,G)=>{let R=dt(u,M,h.fields);delete R.Id;let D=w!==void 0&&m?kn(R[w],m):void 0;w!==void 0&&D!==void 0&&(_.set(G,String(R[w])),R[w]=D),Ar(R,this.leftFields.get(P(x[G])));for(let C of h.lookups){let re=R[C];if(typeof re!="string"||re.length<15||!o.has(re))continue;let $=c(re),Z=d.has($)?a.currentOf($):void 0;if(Z!==void 0){R[C]=Z;continue}p.push({objectApiName:u,from:x[G].slice(0,15),field:C,target:$}),R[C]=null}return R});await e.recreating(u,x);let z=sn(await this.org.create(u,K)),B=[];if(A.forEach((M,G)=>{let R=z[G];if(R?.success===!0&&typeof R.id=="string"){B.push({objectApiName:u,from:x[G],to:R.id});let D=_.get(G);if(w!==void 0&&D!==void 0){let C=l.get(u)??[];C.push({id:R.id,field:w,status:D}),l.set(u,C)}return}v.refused++,Ae(v.reasons,R?.error??"The org gave no answer for it."),n.leftBy("recreate",u,[String(M.Id)])}),B.length>0){await Fe.add(r,B),await e.recreated(u,B.map(M=>({from:M.from,id:M.to}))),await e.wrote(),n.wrote=!0,v.created+=B.length;for(let M of B)d.add(M.from.slice(0,15));a=await Fe.read(r)}}n.recreate(v)}}await this.fillOwed(p,a,d,n),await this.giveStatusesBack(l,n)}lifecycleOf(e){let t=tt[e];if(t===void 0)return Promise.resolve(void 0);let n=this.lifecycles.get(e);return n||(n=yn(async s=>(await this.org.query(s)).records,t),this.lifecycles.set(e,n)),n}async giveStatusesBack(e,t){let n=[...e];for(let[s,[r,o]]of n.entries())for(let a=0;a<o.length;a+=V){if(this.stopped()){let l=[[r,o.slice(a)],...n.slice(s+1)];for(let[u,f]of l)f.length!==0&&t.draftsLeft.set(u,[...t.draftsLeft.get(u)??[],...f.map(({id:h})=>h)]);return}let d=o.slice(a,a+V),c=sn(await this.org.update(r,d.map(({id:l,field:u,status:f})=>({Id:l,[u]:f})))),p=t.recreated.get(r);d.forEach(({id:l},u)=>{let f=c[u];f?.success!==!0&&(p&&Ae(p.reasons,`Made again as a draft, but its status was refused: ${f?.error??"the org gave no answer for it."}`),t.leftBy("recreate",r,[l]))})}}async fillOwed(e,t,n,s){let r=new Map;for(let{objectApiName:o,from:a,field:d,target:c}of e){if(!n.has(a)||!n.has(c))continue;let p=t.currentOf(a),l=t.currentOf(c);if(p===void 0||l===void 0)continue;let u=r.get(o)??new Map;u.set(p,{...u.get(p),Id:p,[d]:l}),r.set(o,u)}for(let[o,a]of r){let d=[...a.values()];for(let c=0;c<d.length;c+=V){if(this.stopped())return;let p=d.slice(c,c+V),l=sn(await this.org.update(o,p)),u=s.recreated.get(o);l.forEach((f,h)=>{f.success||(u&&Ae(u.reasons,`Made again, but a lookup to a record made after it was refused: ${f.error}`),s.leftBy("recreate",o,[String(p[h].Id)]))})}}}async bringBack(e,t,n,s,r,o){let a=Tt(this.org),d=this.makesAgain();for(let{objectApiName:c,count:p}of t.objects){if(s.cancelled||this.stopped()){s.undelete({...Ot(c),planned:p,notReached:p}),s.cancelled=!0;continue}let l;try{l=await this.cascadesOf(c)}catch(f){l=[],this.notes.push(`The records that come back with ${c} could not be told (${ee(f)}): Undo may not send those ${c} records back to the recycle bin.`)}let u=async function*(){for await(let f of t.pages(c,Ne)){let h=f.filter(m=>n.has(m));h.length>0&&(yield{ids:h,asCarriers:!0});let w=h.length>0?f.filter(m=>!n.has(m)):f;w.length>0&&(yield{ids:w,asCarriers:!1})}};for await(let{ids:f,asCarriers:h}of u()){if(s.cancelled||this.stopped()){s.undelete({...Ot(c),planned:f.length,notReached:f.length}),s.cancelled=!0;continue}let w=e.bringingBack([{objectApiName:c,ids:f}],this.count.undelete,{carriers:h}),m=new Map,k=new Map,g=async v=>{let{byParent:T,under:j}=await this.nameChildren(e,a,l,c,v,h),N=await w(v);r(await this.undeleteStamps(c,v,T));for(let A of to(N,v))m.set(P(A),j.get(P(A))??[]);for(let A of no(N,v))k.set(P(A),{id:A,under:j.get(P(A))??[]});return N},y=await Xt(this.org,await it({org:this.org,plan:[{objectApiName:c,ids:f}],undelete:g,...this.signal?{signal:this.signal}:{}}),[{objectApiName:c,ids:f}],this.notes);await this.notBroughtBack(e,c,k,y.left);let I=await this.settleGone(c,y,m,s,o,d);for(let v of I.objects)s.undelete(v);s.leftBy("undelete",c,I.left),I.wrote&&(s.wrote=!0,await e.wrote()),I.cancelled&&(s.cancelled=!0)}}}makesAgain(){let e=new Map,{checkpoint:t,folder:n}=this.request;return async(s,r)=>{let o=t.objects.find(d=>d.objectApiName===s);if(!o||!ws(o))return!1;let a=e.get(s);return a||(a=at.read(n,t.snapshotId,s).catch(()=>{}),e.set(s,a)),(await a)?.has(r)===!0}}remakeUnaskedWords(e){let t=this.asked;if(!t)return;let n=[...new Set(e)],s=Is(t.automation,t.steps,n,t.accepted);if(!(s.fired.length===0&&!s.blind))return Hi(this.request.orgName,n,s)}remakeEmailsWords(e){let t=this.emailsCounted,n=this.asked;if(!t||!n)return;let s=e.flatMap(c=>[{objectApiName:c,write:"insert",records:1},...tt[c]!==void 0?[{objectApiName:c,write:"update",records:1}]:[]]),r=ot(t.written,n.automation,t.limits),a=ot([...t.written,...s],n.automation,t.limits).filter(c=>c.verdict==="exceeds");if(a.length===0){t.written.push(...s);return}return`Kept as it is: Salesforce answered it is no longer in the recycle bin, and making it again sends ${a.map(c=>{let p=c.emails-(r.find(l=>l.limit===c.limit)?.emails??0);return`${Ct(p,c.limit)} more than the ${Ct(c.emails-p,c.limit)} it counted, past the ${c.remaining??0} of ${c.max??0} ${this.request.orgName} has left today`}).join("; ")}. Rewind again: its preview counts it to make again, and its emails.`}async settleGone(e,t,n,s,r,o){let a=t.left.filter(h=>n.has(P(h)));if(a.length===0)return t;let d=new Set,c=0,p=0,l,u=h=>this.access.heldAs(h)==="parent";await this.keepNotInBin(e,a);for(let h of a){if(u(e)){p++,s.mark("outOfReach",e,h);for(let g of n.get(P(h))??[])s.mark("outOfReach",g.objectApiName,g.id);continue}if(!await o(e,h)){s.mark("lost",e,h);continue}let w=[];for(let g of n.get(P(h))??[])u(g.objectApiName)?s.mark("outOfReach",g.objectApiName,g.id):await o(g.objectApiName,g.id)&&w.push(g);let m=[e,...w.map(g=>g.objectApiName)],k=r?this.remakeUnaskedWords(m)??this.remakeEmailsWords(m):void 0;if(r&&k===void 0){await r.add(e,h);for(let g of w)await r.add(g.objectApiName,g.id);d.add(P(h));continue}if(k!==void 0){l=k,s.notAsked.set(P(h),k);for(let g of w)s.notAsked.set(P(g.id),k);continue}c++,s.mark("notInBin",e,h);for(let g of w)s.mark("notInBin",g.objectApiName,g.id)}let f=a.length-d.size;return{...t,objects:t.objects.map(h=>{if(h.objectApiName!==e)return h;let w=f===0?h.reasons.filter(m=>!He.test(m)):c>0?h.reasons.map(m=>He.test(m)?Ki:m):l!==void 0?h.reasons.map(m=>He.test(m)?l??m:m):p>0?h.reasons.map(m=>He.test(m)?rn:m):h.reasons;return{...h,planned:h.planned-d.size,refused:Math.max(0,h.refused-d.size),reasons:w}}),left:t.left.filter(h=>!d.has(P(h)))}}async notBroughtBack(e,t,n,s){if(n.size===0)return;let r=new Set(s.map(P)),o=new Map,a=(d,c)=>{let p=o.get(d)??[];p.push(c),o.set(d,p)};for(let[d,{id:c,under:p}]of n)if(r.has(d)){a(t,c);for(let l of p)a(l.objectApiName,l.id)}try{for(let[d,c]of o)await e.bringBackLeft(d,c)}catch(d){this.notes.push(`Which ${t} records ${this.request.orgName} refused to bring back could not be kept in the rewind\u2019s journal (${ee(d)}): its undo may count them among what it sends back to the recycle bin.`)}}async keepNotInBin(e,t){try{await Yn.add(this.request.folder,e,t)}catch(n){this.notes.push(`The ${e} records ${this.request.orgName} answered are no longer in the recycle bin could not be kept with the checkpoint (${ee(n)}): a later preview counts them to bring back again.`)}}async nameChildren(e,t,n,s,r,o=!1){let a=new Map,d=new Map,c=new Set(r.map(P)),p=new Map(r.map(h=>[P(h),P(h)])),l=new Map,u=new Map,f=[{objectApiName:s,cascades:n,ids:[...r]}];for(;f.length>0;){let h=new Map;for(let{objectApiName:w,cascades:m,ids:k}of f)for(let g of he(k,V)){let y=m.filter(({child:T})=>!this.noBin.has(T));if(y.length===0)break;let I=y.map(({child:T,field:j,persons:N})=>({objectApiName:T,soql:`SELECT Id, ${de(j)}${N?`, ${Me}`:""}${tn(T)?", IsDeleted":""} FROM ${de(T)} WHERE ${j} IN (${g})${tn(T)?"":" AND IsDeleted = true"}`,scanAll:!0}));(await ct(t,I,(T,j)=>{let{child:N,field:A,persons:x}=y[T];for(let _ of j){let K=_[A];if(typeof _.Id!="string"||typeof K!="string"||tn(N)&&_.IsDeleted!==!0)continue;let z=P(_.Id),B=p.get(P(K));B===void 0||c.has(z)||(c.add(z),p.set(z,B),a.set(B,[...a.get(B)??[],_.Id]),!(x&&_[Me]===!0)&&(d.set(B,[...d.get(B)??[],{objectApiName:N,id:_.Id}]),l.set(N,[...l.get(N)??[],_.Id]),u.set(N,[...u.get(N)??[],o?P(K):B]),h.set(N,[...h.get(N)??[],_.Id])))}})).forEach((T,j)=>{if(!T.read){if(eo.test(T.reason)){this.noBin.add(y[j].child);return}this.notes.push(`The ${y[j].child} records that come back with ${w} could not be read (${T.reason}): Undo may not send those ${s} records back to the recycle bin.`)}})}f=[];for(let[w,m]of h)f.push({objectApiName:w,cascades:await this.cascadesUnder(w),ids:m})}for(let[h,w]of l)await e.withParent(h,w,u.get(h),{carriers:o});if(o)for(let h of a.values())for(let w of h)this.carried.add(w);return{byParent:a,under:d}}cascadesUnder(e){let t=this.cascadesOfObject.get(e);return t||(t=this.cascadesOf(e).catch(n=>(this.notes.push(`The records that come back with ${e} records could not be told (${ee(n)}): Undo may not send them back to the recycle bin.`),[])),this.cascadesOfObject.set(e,t)),t}async undeleteStamps(e,t,n){let s={},r=de(e);try{for(let o of he(t,V)){let a=await this.org.query(`SELECT Id, LastModifiedDate FROM ${r} WHERE Id IN (${o})`);for(let d of a.records)if(!(typeof d.Id!="string"||typeof d.LastModifiedDate!="string")){s[d.Id]=d.LastModifiedDate;for(let c of n.get(P(d.Id))??[])s[c]=d.LastModifiedDate}}}catch(o){this.notes.push(`What bringing back ${e} records left on them could not be read (${ee(o)}): the second pass may read them as changed by someone else.`)}return s}async giveBack(e,t,n,s,r,o,a,d){let{checkpoint:c,folder:p}=this.request;for(let{objectApiName:l,count:u}of n.objects){if(a.cancelled||this.stopped()){a.restore({...At(l),planned:u,notReached:u}),a.cancelled=!0;continue}let f=r(l),h=await at.read(p,c.snapshotId,l),w=t.giveBack.heldBy.find(k=>k.objectApiName===l),m=f.find(k=>k.toLowerCase()==="status");for await(let k of n.pages(l,Ne)){let g=k.filter(A=>!h.retired(A));if(g.length===0)continue;if(a.cancelled||this.stopped()){a.restore({...At(l),planned:g.length,notReached:g.length}),a.cancelled=!0;continue}let y=async(A,x,_,K)=>{let z=await rt({org:this.org,plan:[{objectApiName:l,backup:c.snapshotId,ids:[...A]}],backups:jo(h.chunk(A),l,x,_,this.leftFields),fields:{[l]:[...x]},changedAfter:t.restore.changedAfter,ownWriters:ut(c.takenBy,this.userId),includeChanged:!1,stamps:{...t.restore.stamps,...this.stamps},keep:e.keep,stampsFor:()=>!0,...K?{counted:K}:{},...this.signal?{signal:this.signal}:{}});return d(z.stamps),z.wrote&&(a.wrote=!0,await e.wrote()),z.cancelled&&(a.cancelled=!0),z};if(l==="Order"&&m!==void 0&&(await y(g,[m],A=>A[m]==="Draft"),a.cancelled))continue;let I=s==="before"?g.filter(A=>o.has(A)):[];if(I.length>0&&(await y(I,f),a.cancelled))continue;let v=I.length>0?g.filter(A=>!o.has(A)):g;if(v.length===0)continue;let T={restored:[],alreadyGone:[]},j=await y(v,f,void 0,(A,x)=>{this.comesBack.has(A)&&T[x].push(A)});for(let A of j.objects)a.restore(A,T);a.leftBy("restore",l,j.left);let N=j.objects[0];if(s==="after"&&w&&N&&N.refused+(N.restoredWithout??0)>0){let A=a.heldInPlace.get(l)??{reason:ks(l,w.by),ids:new L};for(let x of j.left)A.ids.add(x);a.heldInPlace.set(l,A)}}}}async residualOf(e,t,n,s,r){let o=new Map,a=(u,f,h,w={})=>{let m=`${u}\0${f}\0${w.by??""}\0${w.message??""}`,k=o.get(m);k||(k={objectApiName:u,reason:f,...w.by!==void 0?{by:w.by}:{},count:0,ids:[],...w.message!==void 0?{message:w.message}:{}},o.set(m,k)),k.count++,k.ids.length<fr&&k.ids.push(h)},d=n[n.length-1],c=r?[r,s]:[s],p=[...this.request.checkpoint.objects].sort((u,f)=>u.readOrder-f.readOrder),l=await this.throughCarriers(e.dir);for(let u of p){let f=u.objectApiName;if(this.picked!==void 0&&!this.picked.has(f))continue;let h=[];for(let g of pr)for await(let y of se(ke(e.dir,f,g)))typeof y.Id=="string"&&(g==="comesBackWithParent"&&l.has(y.Id)||h.push({cls:g,id:y.Id}));if(h.length===0)continue;let w=await this.whoChanged(e.dir,f,h),m=this.keptOf(d,f),k=new L;for await(let g of se(ke(t.dir,f,"goneForGood")))typeof g.Id=="string"&&k.add(g.Id);for(let{cls:g,id:y}of h){if(k.has(y))continue;if(g==="goneForGood"){a(f,"goneForGood",y);continue}let I=Gi[g];if(I!==void 0){a(f,"kept",y,{message:I});continue}let v=w.get(P(y)),T=St(v?.at)>this.before,j=T&&this.isOwn(y,v);if(T&&!j){a(f,"changedDuringRewind",y,v?.by?{by:v.by}:{});continue}let N=n.map(({plan:z})=>z.limited?.why.get(P(y))).find(z=>z!==void 0);if(N!==void 0){a(f,"kept",y,{message:N});continue}if(!n.some(({acted:z})=>z.get(f)?.has(y)===!0)){a(f,j?"automation":"changedSincePreview",y);continue}let x=m(y,g);if(x!==void 0){a(f,"kept",y,{message:x});continue}if(g==="withParent"&&c.some(z=>z.left.restore.get(f)?.has(y)===!0)){a(f,"refused",y,{message:this.refusalOf(c,"restore",f,y)});continue}if(j){a(f,"automation",y);continue}if(Rt[g]==="undelete"||g==="toRecreate"){if(c.some(B=>B.outOfReach.get(f)?.has(y)===!0)){a(f,"kept",y,{message:rn});continue}if(c.some(B=>B.lost.get(f)?.has(y)===!0)){a(f,"goneForGood",y);continue}let z=c.map(B=>B.notAsked.get(P(y))).find(B=>B!==void 0);if(z!==void 0){a(f,"kept",y,{message:z});continue}if(c.some(B=>B.notInBin.get(f)?.has(y)===!0)){a(f,"notInBin",y);continue}}let _=Rt[g]==="undelete"&&c.some(z=>z.left.recreate.get(f)?.has(y)===!0)?"recreate":Rt[g],K=_==="removal"?this.keptForDependents(c,f,y):void 0;if(K!==void 0){a(f,"kept",y,{message:Ji(K)});continue}a(f,"refused",y,{message:_?this.refusalOf(c,_,f,y):en})}}return await this.linksStillDiffering(e.dir,n,c,a),[...o.values()]}async linksStillDiffering(e,t,n,s){if(this.request.checkpoint.files===void 0||this.picked!==void 0&&!this.picked.has(Ce))return;let r=d=>`${P(d.ContentDocumentId)}:${P(d.LinkedEntityId)}`,o=new Set;for(let{plan:d}of t)for(let{file:c}of[d.links.unlink,d.links.relink,d.links.share])for await(let p of se(c)){let l=Se.safeParse(p);l.success&&o.add(r(l.data))}let a=new Map;for(let d of[...n].reverse())for(let c of["unlink","relink","share"])for(let{id:p,reason:l}of d.links[c].left)a.set(P(p),l);for(let d of["linkAdded","linkRemoved","linkChanged"])for await(let c of se(Ut(e,d))){let p=Se.safeParse(c);if(!p.success)continue;let l=p.data,u=d==="linkChanged"?$t.safeParse(c):void 0;if(u?.success===!0&&u.data.now.Visibility===l.Visibility&&u.data.now.ShareType!==l.ShareType&&l.LinkedEntityId.startsWith(Zi)){s(oe,"kept",l.Id,{message:ft});continue}if(d==="linkAdded"&&l.LinkedEntityId.startsWith(Xi)){s(oe,"kept",l.Id,{message:Wt});continue}if(!o.has(r(l))){s(oe,"changedSincePreview",l.Id);continue}s(oe,"refused",l.Id,{message:a.get(P(l.Id))??en})}}async throughCarriers(e){let t=new L,n=this.request.checkpoint.objects;for(let{objectApiName:s}of n)for await(let r of se(ke(e,s,"carrier")))typeof r.Id=="string"&&t.add(r.Id);for(let s=t.size>0;s;){s=!1;for(let r of n){let o=new L;for await(let a of se(ke(e,r.objectApiName,"comesBackWithParent")))typeof a.Id=="string"&&o.add(a.Id);if(o.size!==0)for await(let a of se(lt(e,r.objectApiName)))typeof a.Id!="string"||!o.has(a.Id)||t.has(a.Id)||r.cascadeParents.some(d=>t.has(a[d]))&&(t.add(a.Id),s=!0)}}return t}async whoChanged(e,t,n){let s=new Set(n.map(({id:o})=>P(o))),r=new Map;for(let o of[is(e,t),lt(e,t)])for await(let a of se(o))typeof a.Id!="string"||!s.has(P(a.Id))||r.set(P(a.Id),{...typeof a.LastModifiedById=="string"?{by:a.LastModifiedById}:{},...typeof a.LastModifiedDate=="string"?{at:a.LastModifiedDate}:{}});return r}isOwn(e,t){return t?.by!==void 0&&this.owners.has(P(t.by))?!0:St(t?.at)<=(this.stampOf.get(P(e))??Number.NaN)}addStamps(e){for(let[t,n]of Object.entries(e)){this.stamps[t]=n;let s=St(n),r=P(t);Number.isFinite(s)&&!((this.stampOf.get(r)??Number.NEGATIVE_INFINITY)>s)&&this.stampOf.set(r,s)}}keptOf(e,t){let n=e.plan.left.filter(s=>s.objectApiName===t&&Qt[s.reason]!==void 0);return(s,r)=>{if(n.length===0)return;let o=n.find(a=>a.ids.some(d=>P(d)===P(s)));if(o)return Qt[o.reason];if(Rt[r]==="removal"&&!e.plan.deletes.has(P(s)))return Qt[n[0].reason]}}keptForDependents(e,t,n){for(let s of e){if(s.left.removal.get(t)?.has(n)!==!0)continue;let r=s.deleted.get(t);return r&&r.refused===0&&r.keptDependents>0&&r.heldBy.length>0?r.heldBy:void 0}}refusalOf(e,t,n,s){let r=t==="restore"?e.map(o=>o.heldInPlace.get(n)).find(o=>o?.ids.has(s)===!0)?.reason:void 0;for(let o of e){if(o.left[t].get(n)?.has(s)!==!0)continue;let d=(t==="restore"?o.restored.get(n)?.reasons:t==="undelete"?o.undeleted.get(n)?.reasons:t==="recreate"?o.recreated.get(n)?.reasons:o.deleted.get(n)?.reasons)?.find(c=>c!==r);if(d!==void 0)return r?`${d} \u2014 ${r}`:d}return r??en}};function jo(i,e,t,n,s){return{batches:async(r,o,a)=>{let d=await i.batches(r,o,a);return d?{async*[Symbol.asyncIterator](){for await(let c of d){let p=c.filter(l=>n?.(l)??!0).map(l=>Ar(dt(e,l,t),typeof l.Id=="string"?s?.get(P(l.Id)):void 0));p.length>0&&(yield p)}}}:null}}}function Ar(i,e){if(e===void 0)return i;for(let t of Object.keys(i))t!=="Id"&&e.has(t.toLowerCase())&&delete i[t];return i}var Lo=q({success:qe(),id:X().nullish(),errors:ge(Qe([X(),q({statusCode:X().optional(),message:X().optional()}).loose()])).optional()}).loose();function sn(i){return(Array.isArray(i)?i:[i]).map(t=>{let n=Lo.safeParse(t);if(!n.success)return{success:!1};let{success:s,id:r,errors:o}=n.data,a=(o??[]).map(d=>typeof d=="string"?d:[d.statusCode,d.message].filter(c=>c).join(": ")).filter(d=>d!=="");return{success:s,...typeof r=="string"?{id:r}:{},...a.length>0?{error:a.join("; ")}:{}}})}export{aa as a,da as b,Vo as c,Yo as d,Zo as e,Ia as f,Ea as g,Ca as h,Ta as i,fr as j,xi as k,rn as l,Ki as m,Hi as n,Rd as o,so as p,ro as q,Ve as r,yo as s,bo as t,wr as u,Po as v,Sd as w};
@@ -1,7 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{c as Be,d as Pe,e as je,f as We,p as xe,q as Le,t as _e,v as ze}from"./chunk-2WFIVO4F.mjs";import{e as Me}from"./chunk-7QYHEHMA.mjs";import{b as Te,f as Ne}from"./chunk-WXDLQT2O.mjs";import{m as Fe}from"./chunk-NSQWI7ZY.mjs";import{b as Ee}from"./chunk-O677VOGO.mjs";import{i as we,j as ke,k as ye,l as be,m as Re,p as Ae,q as Oe}from"./chunk-HIDW7FNV.mjs";import{A as Ue,B as Ie,C as $e,D as ve}from"./chunk-VINGECAJ.mjs";import{B as ge}from"./chunk-H4CGM6YO.mjs";import{a as le,b as fe}from"./chunk-YDXMTWAT.mjs";import{i as Ce,j as Se}from"./chunk-FP7CYB2F.mjs";import{b as ue,d as ce}from"./chunk-JAEDM4SI.mjs";import{c as me}from"./chunk-LC3NDW4N.mjs";import{j as pe,o as he,pc as De}from"./chunk-KB4ZHM4Q.mjs";import{g as L,h as _,q as de}from"./chunk-M6K34KGF.mjs";import{b as x}from"./chunk-CA5NAXSU.mjs";import{Nd as se,Vd as W}from"./chunk-PMWAFDUB.mjs";var S=class extends Error{constructor(){super("The undo was stopped before it wrote anything to the org."),this.name="UndoStopped"}},z="No record was written.",Ke="accept that it runs to undo the rewind all the same";function Ge(e){return e.slice(0,15)}function Ye(e){return{query:n=>e.query(n),queryMore:n=>e.queryMore(n)}}function Qe(e,n,t){if(e.kind==="org")return;let s=e.userKey;if(n.users.some(i=>i.slice(0,15)!==s))return{code:"PERMISSIONS",message:`This rewind was made as another user than ${t}: what it deleted is that user's deletion in the recycle bin, which Salesforce brings back only for a user with View All Data and Modify All Data. Undo it as the user it was made as, or as a user with View All Data and Modify All Data. ${z}`};let r=n.objects.flatMap(i=>{let l=e.notHeld.get(i);return l===void 0?[]:[`${i}: ${l}`]});if(r.length!==0)return{code:"PERMISSIONS",message:`Undo takes back what the rewind did to objects ${t} no longer holds whole (${r.join("; ")}), and does not stop part way: an undo left part way could not be offered again. Undo it once the user has View All and Modify All on them again, or as a user with View All Data and Modify All Data. ${z}`}}function Xe(e,n){return{undone:!1,refusal:{code:e,message:n}}}function Ze(e,n){return{code:"RUN_WRITING",message:`${n.operation==="take"?`A checkpoint of ${e} is being taken`:n.operation==="rewind"?`A rewind is writing to ${e}`:n.operation==="undo"?`An undo is writing to ${e}`:`SandForge is deleting checkpoints of ${e}`} (process ${n.pid} on ${n.host}): undo the rewind once it has ended. No record was read or written.`}}function et(e,n,t,s){let r=W(n,t),i=[...new Set(r.map(b=>b.objectApiName))],l=(t.setToDraft??[]).length>0?", sets an order back to Draft":"",h=r.length>0?`${Me(r)} flow(s), trigger(s) or rule(s) of ${i.join(", ")} run as the undo brings records back, gives them their values back${l} or sends them back to the recycle bin`:"what runs as the undo writes could not all be read, so automation may run";return{code:"AUTOMATION",message:`${e}: ${h}. ${ye("undo",s)}Undo refused; ${Ke}. ${z}`}}async function tt(e,n){let t=0,s=0;for await(let r of n.bringBack.pages(L)){t+=r.length;for(let i of ce(r,ue)){let l=await e.queryDeleted(`SELECT Id, ContentSize FROM ${L} WHERE Id IN (${i}) AND IsDeleted = true`);for(let h of l.records)typeof h.ContentSize=="number"&&(s+=h.ContentSize)}}return{files:t,bytes:s}}function nt(e,n){return e.status==="cancelled"||e.status==="failure"?e.status:n.some(t=>t.reason==="changedDuringRewind")?"unstable":e.status}function ot(e,n){return e.map(t=>{if(t.reason==="notBack")return{objectApiName:t.objectApiName,reason:"notBack",count:t.count,ids:[...t.ids],...t.message!==void 0?{message:t.message}:{}};let s=Object.keys(t.by).filter(i=>!n.has(Ge(i)));if(s.length===0)return{objectApiName:t.objectApiName,reason:"automation",count:t.count,ids:[...t.ids]};let r=s.length===1&&s[0]!=="unknown"?s[0]:void 0;return{objectApiName:t.objectApiName,reason:"changedDuringRewind",...r!==void 0?{by:r}:{},count:t.count,ids:[...t.ids]}})}async function Ct(e,n){let{checkpoint:t,folder:s,orgName:r,rewindId:i}=n,l=e.signal,h=()=>l?.aborted===!0,b=(I,k)=>e.onProgress?.({percentage:I,step:k}),c=ze(e.org,e.undelete),T,U=await Ee(Ye(c.org),{act:"undo",orgName:r,registered:n.registered,username:n.username,organizationId:t.org.organizationId,customSettings:de(t)},{userId:async()=>T=await c.org.userId()});if(!U.allowed)return{undone:!1,refusal:U.refusal};let R=e.store.lock(t.org.organizationId,"undo",t.checkpointId);if("busy"in R)return{undone:!1,refusal:Ze(r,R.busy)};try{let I=await e.runWriting?.(U.org.id);if(I!==void 0)return Xe("RUN_WRITING",I);let k=await Ie(c.org,r);if(h())throw new S;b(5,"Reading what the rewind did");let g=await Pe(s,i,t.objects),G=je(g),N=g.goesWithParent.objects,qe=g.remade.keys.size>0?"Sending back to the recycle bin what the rewind brought back, and deleting again what it made again":"Sending back to the recycle bin what the rewind brought back",A=o=>o.filter(u=>u.count>0).map(u=>u.objectApiName),M=g.links,q=o=>o>0?[_]:[],B=g.remade.objects.filter(({objectApiName:o,count:u})=>u>0&&ge([o]).length>0),m={bringBack:A(g.bringBack.objects),giveBack:[...A(g.giveBack.objects),...q(M?.share.count??0)],...B.length>0?{setToDraft:A(B)}:{},delete:[...new Set([...A(N),...A(g.remove.objects),...q(M?.remove.count??0)])],...(M?.reinsert.count??0)>0?{recreate:[_]}:{}},H;try{H=await tt(c.org,g)}finally{await g.dispose()}let V=ve("undo",H,k.fileStorage?.remaining,r);if(V)return{undone:!1,refusal:V};let w=[...new Set([...m.bringBack??[],...m.giveBack??[],...m.setToDraft??[],...m.delete??[],...m.recreate??[]])],P;try{P=await Te({grants:U.grants,...T!==void 0?{userId:T}:{},username:n.username,checkpoint:t,reader:Se(c.org,l)})}catch(o){throw o instanceof Ce||h()?new S:o}if(P.kind==="perObject"){let o=await Be(s,i),u=Qe(P,{users:o.passes.map(f=>f.userId),objects:w},n.username);if(u)return{undone:!1,refusal:u}}let d;if(w.length>0&&e.readAutomation){try{d=await e.readAutomation(w)}catch(o){d=_e(w,x(o))}c.add(d.requests)}let $=d,y=w.length>0?await xe(e.mute,d,m):{},v="refusal"in y?y:void 0,J="refusal"in y?void 0:y.mute;y.automation&&(d=y.automation);let O=v?v.plan:J?.plan,K=n.acceptEmails===!0,p=w.length>0&&$?await Ae({act:"undo",orgName:r,automation:$,steps:m,...O?{plan:O}:{},accepted:K,mayMute:e.mute===void 0&&n.canMute===!0,read:()=>me(c.org)}):void 0,Y=we(G,N,B),Q=d?ke(Y,d):void 0,C=v?[v.refusal]:[];d&&!n.acceptAutomation&&(W(d,m).length>0||se(d.unread)||Q!==void 0)&&C.push(et(r,d,m,Q));let X=Ue({objects:t.objects,rewound:G,along:N,automationRequests:0}),Z=De(p?.ofRun),ee=$e("undo",{run:c.used()-(Z.deliverability??0)+X.apiRequests,...Z,...he(O)},k,r);w.length>0&&ee&&C.push(ee);let te=d?Re("undo",be(Y,d,k.emails),r):void 0;w.length>0&&te&&C.push(te),p?.refusal&&C.push(p.refusal);let[ne,...oe]=C;if(ne)return{undone:!1,refusal:ne,...oe.length>0?{alsoRefused:oe}:{}};if(h())throw new S;let He=await c.org.userId(),Ve=new Set(Ne(t.takenBy,He).map(Ge));b(20,"Bringing back what the rewind deleted and giving back what it wrote over");let j,E;try{E=await Le(J,`undo ${t.checkpointId} ${i}`,o=>{let u=o&&O&&$&&p?Oe({act:"undo",orgName:r,automation:$,steps:m,plan:O,held:o.outcome,planned:p.ofRun.senders,...p.ofRun.read?{reading:p.ofRun.read.reading}:{},accepted:K}):void 0;return u?Promise.resolve({relit:u}):We({folder:s,rewindId:i,lock:R.lock,objects:t.objects,org:c.org,undelete:c.undelete,splitting:le(fe(k.remaining,c.used()+X.apiRequests)),...l?{signal:l}:{},...e.onUndeletable?{onUndeletable:e.onUndeletable}:{},onProgress:(f,ae,Je)=>b(20+Math.round(70*f/Math.max(ae,1)),`${qe}: ${Je} ${f} / ${ae}`)})},o=>{j=o})}catch(o){if(!pe(o))throw o;return{undone:!1,refusal:{code:"MUTE",message:`${o.message} No record was written.`}}}if("relit"in E)return{undone:!1,refusal:E.relit};let a=E,re=ot(a.residual,Ve),D=nt(a,re),F=[...a.notes];if(D!=="cancelled"&&D!=="failure"){let o=(e.now??(()=>new Date))().toISOString();try{await e.store.update(t.checkpointId,f=>f.lastRewind?.rewindId===i?{...f,lastRewind:{...f.lastRewind,undoneAt:o}}:f)}catch(f){F.push(`The checkpoint could not be told the rewind was undone (${x(f)}): its list may still offer to undo it.`)}let u=await Fe({folder:s,lock:R.lock,checkpoint:t,rewindId:i,status:D,undoneAt:o});u!==void 0&&F.push(u)}let ie=c.used();return{undone:!0,result:{checkpointId:t.checkpointId,rewindId:i,status:D,deleted:a.deleted,...a.remade?{remade:a.remade}:{},...a.carriedAlone?{carriedAlone:a.carriedAlone}:{},...a.wentAlong?{wentAlong:a.wentAlong}:{},...a.cameBackAlong?{cameBackAlong:a.cameBackAlong}:{},restored:a.restored,undeleted:a.undeleted,...a.files?{files:a.files}:{},residual:re,passes:1,apiRequests:{used:ie,leftToday:Math.max(0,k.remaining-ie)},finishedAt:a.finishedAt,...j?{mutedAutomation:j}:{}},notes:F,...p?.gate.audit!==void 0?{deliverability:p.gate.audit}:{}}}finally{R.lock.release()}}export{S as a,Ke as b,Ct as c};