sandforge 1.85.0 → 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 (274) hide show
  1. package/README.md +1 -1
  2. package/lib/{chunk-THYQOG24.mjs → chunk-22L43JMK.mjs} +1 -1
  3. package/lib/{chunk-U4S27YRP.mjs → chunk-2LSGWTWX.mjs} +1 -1
  4. package/lib/{chunk-MRN72UEO.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-YZKE6D3K.mjs → chunk-35IJ4WEU.mjs} +1 -1
  8. package/lib/chunk-3EHPAFKV.mjs +7 -0
  9. package/lib/{chunk-3OKDWZ32.mjs → chunk-3HAVVEXF.mjs} +1 -1
  10. package/lib/{chunk-32ZB5ICW.mjs → chunk-3I6FXFCN.mjs} +1 -1
  11. package/lib/{chunk-JFVY66BS.mjs → chunk-3KJCSYXY.mjs} +1 -1
  12. package/lib/{chunk-ULEYGOZU.mjs → chunk-3L6DVNCR.mjs} +1 -1
  13. package/lib/chunk-3LRFPGYZ.mjs +7 -0
  14. package/lib/{chunk-GHUA6OQQ.mjs → chunk-3MVWGL5A.mjs} +1 -1
  15. package/lib/{chunk-SF52ZSIV.mjs → chunk-4CSBZZAL.mjs} +1 -1
  16. package/lib/{chunk-FBYFCKPG.mjs → chunk-4NSXPONF.mjs} +1 -1
  17. package/lib/{chunk-A3QNSALB.mjs → chunk-4VLP6RHC.mjs} +1 -1
  18. package/lib/{chunk-TWYNQ2OO.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-JRI6A24G.mjs → chunk-5EHHQ5UX.mjs} +1 -1
  22. package/lib/{chunk-VPGX5Z5D.mjs → chunk-5JMQXHJ2.mjs} +1 -1
  23. package/lib/{chunk-CI2O7WBH.mjs → chunk-65AMXOQU.mjs} +1 -1
  24. package/lib/{chunk-5T3LFDJ5.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-F2424IKX.mjs → chunk-6ROL3KBM.mjs} +1 -1
  28. package/lib/{chunk-7ZYCRIHE.mjs → chunk-72AWCN7U.mjs} +1 -1
  29. package/lib/{chunk-MQLTEXB7.mjs → chunk-7KHA5UIQ.mjs} +1 -1
  30. package/lib/chunk-7O6EFNQS.mjs +10 -0
  31. package/lib/{chunk-73SLYGWD.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-JBOGAUGH.mjs → chunk-ATBQIE2V.mjs} +1 -1
  35. package/lib/{chunk-C2MHMI7U.mjs → chunk-ATQML7ZK.mjs} +1 -1
  36. package/lib/chunk-AVY742BJ.mjs +7 -0
  37. package/lib/{chunk-VLAU5QQT.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-KYLHS74X.mjs → chunk-BLMJ4WVI.mjs} +1 -1
  41. package/lib/{chunk-A7YP27GQ.mjs → chunk-BNHJCJJM.mjs} +1 -1
  42. package/lib/{chunk-ZDMSTL2L.mjs → chunk-BNPQEQXC.mjs} +1 -1
  43. package/lib/chunk-C5AUNG6T.mjs +37 -0
  44. package/lib/{chunk-LY6EPMIP.mjs → chunk-C5EQ7GFC.mjs} +1 -1
  45. package/lib/{chunk-LOO42EW5.mjs → chunk-C7CKDZMC.mjs} +62 -62
  46. package/lib/{chunk-ZP3WJGS3.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-7L6FE5PP.mjs → chunk-CLUNF4FK.mjs} +1 -1
  50. package/lib/chunk-CSMGP53U.mjs +7 -0
  51. package/lib/{chunk-S6BMJSLD.mjs → chunk-CT324C7I.mjs} +1 -1
  52. package/lib/{chunk-YXOPKGDX.mjs → chunk-CZXDJXQP.mjs} +1 -1
  53. package/lib/{chunk-PGG4ULEW.mjs → chunk-D2X6U3MS.mjs} +1 -1
  54. package/lib/{chunk-FG4Y4ZVL.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-YGE4AUXG.mjs → chunk-DLSU66MY.mjs} +1 -1
  58. package/lib/{chunk-DCJBP3LE.mjs → chunk-DO6PSHQZ.mjs} +1 -1
  59. package/lib/{chunk-ROTDZKOE.mjs → chunk-DUBECLZV.mjs} +1 -1
  60. package/lib/{chunk-SES5HPBZ.mjs → chunk-DYHF6DNT.mjs} +1 -1
  61. package/lib/chunk-E5FSPXYH.mjs +930 -0
  62. package/lib/{chunk-QAXKUEJT.mjs → chunk-EGL3I3IX.mjs} +1 -1
  63. package/lib/chunk-EIYMQPMG.mjs +7 -0
  64. package/lib/{chunk-AX3YF7SC.mjs → chunk-EUIALBMX.mjs} +1 -1
  65. package/lib/{chunk-57QRXYAZ.mjs → chunk-FI3R5ZOQ.mjs} +1 -1
  66. package/lib/{chunk-FCZDWGQI.mjs → chunk-FM4QCTO7.mjs} +1 -1
  67. package/lib/{chunk-74HZ274R.mjs → chunk-FRSIEASH.mjs} +1 -1
  68. package/lib/{chunk-G6IYOZEH.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-NZJXEULY.mjs → chunk-GFB2DNCB.mjs} +1 -1
  73. package/lib/chunk-GFGMGFSH.mjs +7 -0
  74. package/lib/{chunk-EFHDE7W4.mjs → chunk-GIFQXB2Q.mjs} +1 -1
  75. package/lib/{chunk-P6A22FMQ.mjs → chunk-GP5J3DGS.mjs} +1 -1
  76. package/lib/chunk-GQZEX7LH.mjs +231 -0
  77. package/lib/{chunk-BRN42U26.mjs → chunk-GYDTM62J.mjs} +1 -1
  78. package/lib/{chunk-GNCEHAJY.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-GUYEXPJ4.mjs → chunk-HDDJ3CVN.mjs} +1 -1
  82. package/lib/{chunk-3GATEVHC.mjs → chunk-HDWB4ZOG.mjs} +1 -1
  83. package/lib/chunk-HGVPBJR6.mjs +7 -0
  84. package/lib/{chunk-55VBV2WK.mjs → chunk-HLROVOR6.mjs} +1 -1
  85. package/lib/{chunk-HV3TDLFR.mjs → chunk-HUOR4M2L.mjs} +1 -1
  86. package/lib/chunk-HZCS6EED.mjs +8 -0
  87. package/lib/{chunk-WZX6VCIT.mjs → chunk-HZUI56KZ.mjs} +1 -1
  88. package/lib/chunk-IAB5H7WN.mjs +7 -0
  89. package/lib/{chunk-RY7WUJXH.mjs → chunk-IQ5UKRHU.mjs} +1 -1
  90. package/lib/{chunk-OUWR5M5G.mjs → chunk-IRQ4WANV.mjs} +1 -1
  91. package/lib/{chunk-F44EHXLI.mjs → chunk-IT3DGX37.mjs} +1 -1
  92. package/lib/chunk-J347SPU6.mjs +49 -0
  93. package/lib/{chunk-IZ2M2RGO.mjs → chunk-JANBNTR5.mjs} +1 -1
  94. package/lib/chunk-JFXQZPRY.mjs +9 -0
  95. package/lib/{chunk-VKA5OZBJ.mjs → chunk-JRLYWVF4.mjs} +1 -1
  96. package/lib/{chunk-FM5ESRH6.mjs → chunk-JSNMUTY6.mjs} +1 -1
  97. package/lib/chunk-JTNJKSAA.mjs +7 -0
  98. package/lib/{chunk-4D6OHSX3.mjs → chunk-JV2LAKWQ.mjs} +1 -1
  99. package/lib/{chunk-BY42YL4D.mjs → chunk-JV7K2ZHK.mjs} +1 -1
  100. package/lib/{chunk-A6IJUOLB.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-FZF6FB65.mjs → chunk-KQVLZVOP.mjs} +1 -1
  104. package/lib/chunk-KWUS7UAV.mjs +19 -0
  105. package/lib/{chunk-2UUSF32M.mjs → chunk-L6G73FXM.mjs} +1 -1
  106. package/lib/{chunk-LUNGNCM3.mjs → chunk-LG466Q5H.mjs} +1 -1
  107. package/lib/{chunk-YTBM3TSW.mjs → chunk-LHNAR6FC.mjs} +1 -1
  108. package/lib/chunk-LT4GHEI2.mjs +7 -0
  109. package/lib/{chunk-P3OYE2FS.mjs → chunk-MR262Y3B.mjs} +1 -1
  110. package/lib/{chunk-TSTCHIBU.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-6HAKOS6W.mjs → chunk-O3GIN5TU.mjs} +1 -1
  114. package/lib/chunk-O6FHK6NQ.mjs +13 -0
  115. package/lib/{chunk-OXIIKAUZ.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-K2WOT75I.mjs → chunk-OO2WY3UB.mjs} +1 -1
  120. package/lib/{chunk-3EOIAC2M.mjs → chunk-OT2NHL2V.mjs} +1 -1
  121. package/lib/{chunk-BK5SRDAD.mjs → chunk-P2M5ZXWU.mjs} +1 -1
  122. package/lib/{chunk-DCZYWMSA.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-LU7M5URW.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-LNAZHI3J.mjs → chunk-QGVL5EW3.mjs} +1 -1
  130. package/lib/chunk-QHE2RUWX.mjs +7 -0
  131. package/lib/{chunk-4RNP65FV.mjs → chunk-RCW5BZNW.mjs} +1 -1
  132. package/lib/{chunk-OTKXTBTX.mjs → chunk-RJ6HHG7J.mjs} +1 -1
  133. package/lib/{chunk-IVDBVWKK.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-2UUS4IGB.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-RC25QQVF.mjs → chunk-SUIPDW5O.mjs} +1 -1
  141. package/lib/{chunk-Z354SAEF.mjs → chunk-SZOJ7BEJ.mjs} +1 -1
  142. package/lib/{chunk-45375WT5.mjs → chunk-T542Z54E.mjs} +1 -1
  143. package/lib/chunk-TAN2CIRI.mjs +21 -0
  144. package/lib/{chunk-BGJBYDRW.mjs → chunk-TCNBINOG.mjs} +1 -1
  145. package/lib/chunk-TFDF3DBN.mjs +7 -0
  146. package/lib/{chunk-B5A4JHNN.mjs → chunk-TICZXC53.mjs} +1 -1
  147. package/lib/chunk-TLX45X5U.mjs +7 -0
  148. package/lib/{chunk-W6SLQZKQ.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-4N425UJC.mjs → chunk-UCUFLFNK.mjs} +1 -1
  154. package/lib/chunk-UK3QLBHW.mjs +7 -0
  155. package/lib/{chunk-SKGAERV4.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-LSEM2BZH.mjs → chunk-VFKG2G37.mjs} +1 -1
  160. package/lib/chunk-VJNEW5MQ.mjs +7 -0
  161. package/lib/{chunk-EYFP3NA6.mjs → chunk-VKREON6Q.mjs} +1 -1
  162. package/lib/{chunk-TIVI2KGB.mjs → chunk-VNNDYPBL.mjs} +1 -1
  163. package/lib/{chunk-J3FJ3BWE.mjs → chunk-VRBETPHY.mjs} +1 -1
  164. package/lib/{chunk-UX4AOSMU.mjs → chunk-VT6P3X6R.mjs} +1 -1
  165. package/lib/{chunk-CUOWQMGW.mjs → chunk-VUTQY76O.mjs} +1 -1
  166. package/lib/chunk-WF5S4FW5.mjs +7 -0
  167. package/lib/{chunk-JHJDDQDE.mjs → chunk-WJGK6VGU.mjs} +1 -1
  168. package/lib/{chunk-IZREPWYQ.mjs → chunk-WJHMB3SL.mjs} +1 -1
  169. package/lib/{chunk-XZRON54U.mjs → chunk-WQCXOZEJ.mjs} +1 -1
  170. package/lib/{chunk-N2MXYD67.mjs → chunk-WVVFR4E3.mjs} +1 -1
  171. package/lib/{chunk-GG5I52UT.mjs → chunk-XBYXT74L.mjs} +1 -1
  172. package/lib/chunk-XJE3LJHP.mjs +7 -0
  173. package/lib/{chunk-3QCUSZIZ.mjs → chunk-XV4CVZYD.mjs} +1 -1
  174. package/lib/chunk-Y37ED7AS.mjs +7 -0
  175. package/lib/{chunk-MN3XBJPE.mjs → chunk-YGBNZYT4.mjs} +1 -1
  176. package/lib/{chunk-SBDF4AE5.mjs → chunk-YGTOX7IL.mjs} +1 -1
  177. package/lib/{chunk-SQM32AOQ.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-SU24AE3H.mjs → chunk-YZKZC62O.mjs} +1 -1
  182. package/lib/{chunk-LJNRN7MY.mjs → chunk-YZQN7BRB.mjs} +1 -1
  183. package/lib/{chunk-NMF55UBQ.mjs → chunk-Z5IUK2QO.mjs} +1 -1
  184. package/lib/{chunk-6ZWY36LK.mjs → chunk-ZEGSMW5A.mjs} +1 -1
  185. package/lib/{chunk-YV7JYHJP.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 +29 -16
  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-26EGXYZ4.mjs +0 -21
  209. package/lib/chunk-2JRVBXJL.mjs +0 -7
  210. package/lib/chunk-2METQHGG.mjs +0 -7
  211. package/lib/chunk-3XU7CEJQ.mjs +0 -7
  212. package/lib/chunk-4BQPAVMP.mjs +0 -14
  213. package/lib/chunk-4KMKOE77.mjs +0 -156
  214. package/lib/chunk-4RPA7Z52.mjs +0 -7
  215. package/lib/chunk-5C7LQXYS.mjs +0 -7
  216. package/lib/chunk-5EESNYE3.mjs +0 -8
  217. package/lib/chunk-6ZW6BLV5.mjs +0 -7
  218. package/lib/chunk-AAOMUI7S.mjs +0 -15
  219. package/lib/chunk-AIUAEBHR.mjs +0 -7
  220. package/lib/chunk-BD724WOH.mjs +0 -7
  221. package/lib/chunk-CRPLDXJU.mjs +0 -48
  222. package/lib/chunk-CSSOLHE3.mjs +0 -7
  223. package/lib/chunk-D63HEQ3B.mjs +0 -7
  224. package/lib/chunk-DN7YBILC.mjs +0 -21
  225. package/lib/chunk-DNE7JI3A.mjs +0 -11
  226. package/lib/chunk-EFHM2U4D.mjs +0 -7
  227. package/lib/chunk-EINEGS6E.mjs +0 -7
  228. package/lib/chunk-EM5EFMHA.mjs +0 -272
  229. package/lib/chunk-FH5UR35W.mjs +0 -7
  230. package/lib/chunk-FN7TOBJR.mjs +0 -7
  231. package/lib/chunk-HGJFATSI.mjs +0 -10
  232. package/lib/chunk-HOEE3PE5.mjs +0 -7
  233. package/lib/chunk-HV63UGL5.mjs +0 -7
  234. package/lib/chunk-JKFCGYJE.mjs +0 -7
  235. package/lib/chunk-KATBU46O.mjs +0 -7
  236. package/lib/chunk-LD34JNCC.mjs +0 -7
  237. package/lib/chunk-LPN4WYTP.mjs +0 -478
  238. package/lib/chunk-MAOUFJ47.mjs +0 -7
  239. package/lib/chunk-MB2DG66I.mjs +0 -13
  240. package/lib/chunk-NCASRA7L.mjs +0 -9
  241. package/lib/chunk-NEKNAILD.mjs +0 -7
  242. package/lib/chunk-NN2IO4WE.mjs +0 -7
  243. package/lib/chunk-O3ZQSWDN.mjs +0 -10
  244. package/lib/chunk-OFQOKSEW.mjs +0 -7
  245. package/lib/chunk-PP7PJXRJ.mjs +0 -341
  246. package/lib/chunk-PT2E2HFD.mjs +0 -7
  247. package/lib/chunk-PZBZ7MNC.mjs +0 -7
  248. package/lib/chunk-QBYK5XIT.mjs +0 -8
  249. package/lib/chunk-RFD6NPWJ.mjs +0 -8
  250. package/lib/chunk-RIIJJRGF.mjs +0 -7
  251. package/lib/chunk-RKTFFCNS.mjs +0 -7
  252. package/lib/chunk-RM5G4IP6.mjs +0 -19
  253. package/lib/chunk-RTPNK7OB.mjs +0 -7
  254. package/lib/chunk-RZXEO5IE.mjs +0 -7
  255. package/lib/chunk-SAHGDSZQ.mjs +0 -37
  256. package/lib/chunk-SRPWW4A2.mjs +0 -10
  257. package/lib/chunk-SVNSAHG3.mjs +0 -7
  258. package/lib/chunk-T63U4OZJ.mjs +0 -7
  259. package/lib/chunk-TE2W76II.mjs +0 -10
  260. package/lib/chunk-TEIBWMJM.mjs +0 -7
  261. package/lib/chunk-TFGJDZFE.mjs +0 -7
  262. package/lib/chunk-TG52WNGV.mjs +0 -10
  263. package/lib/chunk-TQONVFI3.mjs +0 -7
  264. package/lib/chunk-TW3N6W5Z.mjs +0 -7
  265. package/lib/chunk-UZMLPKW6.mjs +0 -7
  266. package/lib/chunk-WB2RIVO3.mjs +0 -7
  267. package/lib/chunk-WQO7RXEB.mjs +0 -926
  268. package/lib/chunk-X3MBY2RX.mjs +0 -7
  269. package/lib/chunk-XMJRXXUN.mjs +0 -7
  270. package/lib/chunk-YNMU5I7P.mjs +0 -7
  271. package/lib/chunk-YSQJKIO6.mjs +0 -7
  272. package/lib/chunk-YVVPJRZC.mjs +0 -7
  273. package/lib/chunk-ZLQHBI6V.mjs +0 -9
  274. package/lib/chunk-ZRUDYB7O.mjs +0 -7
@@ -0,0 +1,7 @@
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 Re}from"./chunk-TZXYVMZC.mjs";import{a as re}from"./chunk-BOGNK4LV.mjs";import{n as we}from"./chunk-7O6EFNQS.mjs";import{f as ke,g as Se,h as De,i as Te}from"./chunk-HZCS6EED.mjs";import{a as Ee,e as Ne,j as Oe}from"./chunk-NV5QA2HY.mjs";import{d as ye,e as Q}from"./chunk-TYUYPFDJ.mjs";import{Bc as We,Hb as ve,Nb as Be,Qc as Ke,db as je,kc as Ge,nc as Ue,pb as _e,rb as ae,sc as $e,tb as xe,ub as Me,vc as ze,wb as Le,xb as Fe,zb as qe}from"./chunk-OLCS7JCT.mjs";import{a as G}from"./chunk-4TLYUZD5.mjs";import{i as he}from"./chunk-INIT2UKJ.mjs";import{b as Ie}from"./chunk-UCUFLFNK.mjs";import{a as Ce}from"./chunk-EADHKH3A.mjs";import{b as ne,d as ie}from"./chunk-DAUX63UB.mjs";import{q as W,r as Y}from"./chunk-SZOJ7BEJ.mjs";import{a as U,h as _}from"./chunk-TZE3Y7IQ.mjs";import{b as z}from"./chunk-CA5NAXSU.mjs";import{a as J,j as Pe}from"./chunk-ICIYL45C.mjs";import{Gc as fe,Hc as me,Lc as te,Mc as ge,Nc as V,Oc as be,Sc as X,Tc as oe,Wd as Ae}from"./chunk-J347SPU6.mjs";import{b as Z,f as ee,k as ue,l as pe}from"./chunk-WZQEK4WT.mjs";function et(o){let e=0,t=n=>(...a)=>(e++,n(...a)),{queryMore:r,tooling:i}=o;return{conn:{describe:t(n=>o.describe(n)),describeGlobal:t(()=>o.describeGlobal()),query:t(n=>o.query(n)),...r?{queryMore:t(n=>r.call(o,n))}:{},...i?{tooling:{describeGlobal:t(()=>i.describeGlobal())}}:{}},requests:()=>e}}var tt=De,ot=Se,K=200;function nt(o,e){let t=new Set(e?.fields.map(i=>i.name)??[]),r=new Set(o.split(", "));for(let i of[J,oe])t.has(i)&&r.add(i);return[...r].join(", ")}var it=10,rt=new Set([W]),v="IsPersonAccount",He="IsStandard",Ve=class{maxConcurrent;constructor(e=10){this.maxConcurrent=e}async listObjects(e,t,r){let[i,n]=await Promise.all([e.describeGlobal(),t.describeGlobal()]),a=new Set(i.sobjects.filter(l=>l.createable).map(l=>l.name)),s=ie(n.sobjects.filter(l=>!a.has(l.name)),await this.toolingObjects(t)),d=new Map(n.sobjects.map(l=>[l.name,l.createable!==!1]));return i.sobjects.filter(l=>l.queryable&&(l.createable||d.get(l.name)===!0)).filter(l=>r||l.custom).filter(l=>!ne(l.name,s)).map(l=>({apiName:l.name,label:l.label,custom:l.custom,...d.has(l.name)?d.get(l.name)===!1?{notCreateableInTarget:!0}:{}:{missingInTarget:!0}}))}async countObjects(e,t){return this.countRecords(e,t)}async scan(e,t,r,i,n={}){let a=et(e),s=a.conn,d=ce(n.maxDepth,tt),l=ce(n.maxObjects,ot),h=ce(n.maxRecordsPerObject,5e4),R=n.onProgress??(()=>{});if(r.length===0)throw new Error("Choose the objects to copy: a scan starts from them, and with none chosen it would describe and count every object of the org.");let c=await s.describeGlobal(),f=[...r],y=await t.describeGlobal(),w=ie(y.sobjects,await this.toolingObjects(t)),S=A=>ne(A,w);f=f.filter(A=>!S(A)),R(`describing ${f.length} selected object(s)\u2026`);let C=await this.describeAll(s,f),D=new Set(C.keys()),x=new Map(c.sobjects.map(A=>[A.name,A.custom])),E=new Map;for(let A of c.sobjects)A.keyPrefix&&E.set(A.keyPrefix,A.name);let g=await this.walkRecords(s,C,D,{isStandard:A=>x.get(A)===!1||!x.has(A)&&!A.includes("__"),includeStandardObjects:i,leftOut:S,keyPrefixes:E,maxDepth:d,maxObjects:l,maxRecords:h,say:R}),T=new Set(y.sobjects.map(A=>A.name)),M=[...C.keys()].filter(A=>!T.has(A)),L=await this.currenciesOf(s,t,C),B=await this.personAccountsOf(s,C,D,g.parentIds,{cutShort:g.cutShort,cutAt:g.cutAt});return{objectDescribes:C,autoDiscoveredObjects:g.added,missingInTarget:M,recordCounts:g.recordCounts,totalObjectsScanned:C.size,parentIds:g.parentIds,personAccounts:B,scope:{maxDepth:d,maxObjects:l,selected:[...D],parents:g.added.map(A=>({objectApiName:A,records:g.parentIds.get(A)?.length??0})),leftEmpty:g.leftEmpty,standardNeeded:g.standardNeeded,...g.followedByDefault.length>0?{followedByDefault:g.followedByDefault}:{},...L?{currencies:L}:{},...g.cutShort.length>0?{cutShort:g.cutShort}:{}},sourceRequests:a.requests()}}async readFitRows(e,t,r=()=>{}){let i=new Set(t.objectDescribes.keys()),n=new Map;for(let a of t.scope.selected){let s=t.objectDescribes.get(a);if(!s)continue;r(`reading the lookups of ${a} to fit it\u2026`);let d=new Set(s.fields.map(c=>c.name)),l=Xe(a,s).filter(c=>c.targets.some(f=>i.has(f))),h=["Id",...new Set(l.map(c=>c.field)),...(a===W||a===Y)&&d.has(v)?[v]:[],...a===ge&&d.has(He)?[He]:[]],R=await he(`SELECT ${h.map(_).join(", ")} FROM ${_(a)} ORDER BY Id`,async c=>(await this.readAll(e,c)).records);n.set(a,R.filter(c=>typeof c.Id=="string"))}return n}async walkFrom(e,t,r,i=()=>{}){let n=new Map(t.objectDescribes),a=new Set(n.keys()),s=new Map;for(let[l,h]of n)h.keyPrefix&&s.set(h.keyPrefix,l);let d=await this.walkRecords(e,n,new Set(t.scope.selected),{isStandard:()=>!1,includeStandardObjects:!0,leftOut:l=>!a.has(l),keyPrefixes:s,maxDepth:t.scope.maxDepth,maxObjects:a.size,say:i},r);return{added:d.added,parentIds:d.parentIds,personAccounts:d.personAccounts,leftEmpty:d.leftEmpty,namingSelected:d.namingSelected}}async personAccountsOf(e,t,r,i,n){let a=new Map;for(let s of[W,Y]){if(!t.get(s)?.fields.some(h=>h.name===v))continue;let l=`SELECT COUNT() FROM ${_(s)} WHERE ${v} = true`;try{let h=n.cutShort.find(c=>c.objectApiName===s)?.copied;if(r.has(s)&&h!==void 0){let c=n.cutAt.get(s)??await this.lastIdOfTheFirst(e,s,h);a.set(s,c!==void 0?(await e.query(`${l} AND Id <= '${U(c)}'`)).totalSize:Math.min((await e.query(l)).totalSize,h));continue}if(r.has(s)){a.set(s,(await e.query(l)).totalSize);continue}let R=0;for(let c of this.chunk([...i.get(s)??[]],K)){let f=c.map(y=>`'${U(y)}'`).join(", ");R+=(await e.query(`${l} AND Id IN (${f})`)).totalSize}a.set(s,R)}catch(h){G.warn("Autopilot could not count the person accounts it copies",{objectApiName:s,error:z(h)})}}return a}async lastIdOfTheFirst(e,t,r){let{records:i}=await this.readAll(e,`SELECT Id FROM ${_(t)} ORDER BY Id`),n=i.length>=r?i[r-1]?.Id:void 0;return typeof n=="string"?n:void 0}async currenciesOf(e,t,r){let i=[...r.values()].filter(d=>d.fields.some(l=>l.name===J)).map(d=>d.name).sort();if(i.length===0)return;let n=await Pe(async d=>(await e.query(d)).records,async d=>(await t.query(d)).records),a=n?.target.corporate;if(!n||a===void 0)return;let s=[...n.source.active].filter(d=>!n.target.active.has(d));return s.length>0?{notInTarget:s.sort(),writtenIn:a,objects:i}:void 0}async walkRecords(e,t,r,i,n){let a=new Set(r),s=new Set,d=i.maxRecords??5e4,l=i.maxObjects,h=i.maxObjects*Te,R=new Map,c=[],f=[],y=[],w=new Map,S=[],C=new Map,D=new Map,x=new Map,E=[],g=u=>{let b=t.get(u);return b?Xe(u,b).map(N=>({...N,targets:N.targets.filter(p=>!i.leftOut(p)&&!s.has(p))})).filter(N=>N.targets.length>0):[]},T=u=>["Id",...new Set(g(u).map(b=>b.field)),...n&&(u===W||u===Y)&&t.get(u)?.fields.some(b=>b.name===v)?[v]:[]].map(_).join(", "),M=(u,b,N)=>{let p=`${u.objectApiName}.${u.field}>${b}`;R.has(p)||R.set(p,{objectApiName:u.objectApiName,fieldApiName:u.field,target:b,reason:N,...u.required?{required:!0}:{}})},L=new Map,B=(u,b,N)=>{let p=g(u);for(let I of b)for(let m of p){let O=I[m.field];if(typeof O!="string"||O==="")continue;let P=at(O,m.targets,i.keyPrefixes,n!==void 0&&m.polymorphic);if(!P)continue;if(r.has(P)){n&&N>0&&E.push({objectApiName:u,field:m.field,required:m.required,target:P,id:O});continue}let k={objectApiName:u,field:m.field,required:m.required};if(N>=i.maxDepth&&!m.required){a.has(P)||M(k,P,"depth");continue}if(D.get(P)?.has(O))continue;let F=L.get(P)??{ids:new Set,required:!1,via:[]};F.ids.add(O),F.required||=m.required,F.via.some(j=>j.objectApiName===u&&j.field===m.field)||F.via.push(k),L.set(P,F)}},A=[];for(let u of r){if(n){B(u,n.get(u)??[],0);continue}let b=g(u).filter(N=>N.targets.some(p=>!r.has(p)));if(b.length===0){A.push(u);continue}i.say(`reading the lookups of ${u}\u2026`);try{let N=["Id",...new Set(b.map(m=>m.field))].map(_).join(", "),{records:p,truncated:I}=await this.readAll(e,`SELECT ${N} FROM ${_(u)} ORDER BY Id`,d);if(C.set(u,p.length),I){let m=(await this.countRecords(e,[u])).get(u);y.push({objectApiName:u,copied:p.length,...m!==void 0?{total:m}:{}});let O=p[p.length-1]?.Id;typeof O=="string"&&w.set(u,O)}B(u,p,0)}catch(N){G.warn("Autopilot could not read the lookups of a selected object",{objectApiName:u,error:z(N)}),A.push(u)}}for(let[u,b]of await this.countRecords(e,A))b>d?(C.set(u,d),y.push({objectApiName:u,copied:d,total:b})):C.set(u,b);let Ze=i.maxDepth+it;for(let u=1;L.size>0&&u<=Ze;u++){let b=L;L=new Map;let N=[];for(let[p,I]of b){if(a.has(p))continue;let m=i.isStandard(p)&&!i.includeStandardObjects,O=m&&!I.required&&rt.has(p),P;if(m&&!I.required&&!O?P="standard":a.size>=l&&(I.required&&l<h?l++:P="objects"),P){for(let k of I.via)M(k,p,P);b.delete(p);continue}if(a.add(p),N.push(p),O)f.push({objectApiName:p,referencedBy:I.via.map(k=>`${k.objectApiName}.${k.field}`)});else if(m){let k=I.via[0];c.push({objectApiName:p,neededBy:`${k.objectApiName}.${k.field}`})}}if(N.length>0){let p=N.filter(m=>!t.has(m));p.length>0&&i.say(`describing ${p.length} parent object(s) at depth ${u}\u2026`);let I=await this.describeAll(e,p);for(let m of N){let O=t.get(m)??I.get(m);O?(t.set(m,O),S.push(m)):(a.delete(m),s.add(m),b.delete(m))}}for(let[p,I]of b){let m=[...I.ids].filter(j=>!D.get(p)?.has(j));if(m.length===0)continue;i.say(`reading ${m.length} ${p} record(s) by id\u2026`);let O=D.get(p)??new Set;D.set(p,O);let P=p===te,k=P?nt(T(p),t.get(p)):T(p),F=[];for(let j of this.chunk(m,K)){let $=j.map(q=>`'${U(q)}'`).join(", "),H=(await e.query(`SELECT ${k} FROM ${_(p)} WHERE Id IN (${$})`)).records.filter(q=>typeof q.Id=="string");for(let q of H)O.add(q.Id);F.push(...H);let de=H.filter(q=>q[v]===!0).length;n&&de>0&&x.set(p,(x.get(p)??0)+de),B(p,H,u)}if(P){let j=await this.standardPricesOf(e,k,F,O);if(j.length>0){i.say(`reading ${j.length} standard price(s) the prices need\u2026`);for(let $ of j)O.add($.Id);B(p,j.map($=>({...$,[V]:void 0})),u)}}}}let le=new Map;for(let u of S){let b=[...D.get(u)??[]];le.set(u,b),C.set(u,b.length)}return{added:S,leftEmpty:[...R.values()].filter(u=>!a.has(u.target)),standardNeeded:c,followedByDefault:f.filter(u=>a.has(u.objectApiName)),cutShort:y,cutAt:w,recordCounts:C,parentIds:le,personAccounts:x,namingSelected:E}}async standardPricesOf(e,t,r,i){let n=a=>[a[X],a[J],a[oe]].map(s=>String(s??"")).join("|");try{let[a]=(await e.query(be)).records,s=a?.Id;if(typeof s!="string")return[];let d=r.filter(c=>c[V]!==s),l=[...new Set(d.flatMap(c=>{let f=c[X];return typeof f=="string"&&f!==""?[f]:[]}))];if(l.length===0)return[];let h=new Set(d.map(n)),R=[];for(let c of this.chunk(l,K)){let f=c.map(w=>`'${U(w)}'`).join(", "),y=await e.query(`SELECT ${t} FROM ${te} WHERE ${V} = '${U(s)}' AND ${X} IN (${f})`);for(let w of y.records){let S=w.Id;typeof S!="string"||i.has(S)||!h.has(n(w))||R.push(w)}}return R}catch(a){return G.warn("Autopilot could not read the standard prices its prices need",{error:z(a)}),[]}}async readAll(e,t,r=5e4){let{queryMore:i}=e;if(!i){let a=await e.query(t);return{records:a.records,truncated:a.done===!1}}let n=await Ce({query:a=>e.query(a),queryMore:a=>i.call(e,a)},t,r);return n.truncated&&G.warn("Autopilot read the lookups of a selected object to its bound only",{records:n.records.length}),{records:n.records,truncated:n.truncated}}async toolingObjects(e){if(!e.tooling)return[];try{return(await e.tooling.describeGlobal()).sobjects.map(r=>r.name)}catch(t){return G.warn("Autopilot could not ask the Tooling API which objects are metadata",{error:z(t)}),[]}}async describeAll(e,t){let r=new Map,i=this.chunk(t,this.maxConcurrent);for(let n of i){let a=await Promise.allSettled(n.map(s=>e.describe(s)));for(let s of a)s.status==="fulfilled"&&r.set(s.value.name,s.value)}return r}async countRecords(e,t){let r=new Map,i=this.chunk(t,this.maxConcurrent);for(let n of i){let a=await Promise.allSettled(n.map(async s=>{let d=await e.query(`SELECT COUNT() FROM ${_(s)}`);return{name:s,count:d.totalSize}}));for(let s of a)s.status==="fulfilled"&&r.set(s.value.name,s.value.count)}return r}chunk(e,t){let r=[];for(let i=0;i<e.length;i+=t)r.push(e.slice(i,i+t));return r}};function ce(o,e){return o!==void 0&&Number.isInteger(o)&&o>0?o:e}function Xe(o,e){return e.fields.filter(t=>t.referenceTo.length>0&&me(t)).map(t=>({field:t.name,targets:[...t.referenceTo],required:fe(o,t.name,t.nillable),polymorphic:t.referenceTo.length>1}))}function at(o,e,t,r=!1){if(e.length===1&&!r)return e[0];let i=t.get(o.slice(0,3));return i!==void 0&&e.includes(i)?i:void 0}var Ye={PII:"PII",PHI:"PHI",PCI:"PCI",Confidential:"SENSITIVE"},Qe={PII:"fake",PHI:"nullify",PCI:"mask",SENSITIVE:"hash",NONE:"fake"},st={name_pattern:"field_name",type_analysis:"field_name",content_pattern:"content_sampling"},ct=1;function lt(o,e){let t=Re({field:{name:e.name,label:e.label,type:e.type,nillable:e.nillable,updateable:e.createable},classification:"PII",detectedBy:"name",pattern:o});switch(t?.ruleType){case"fake":case"mask":case"hash":case"preserve_format":case"redact":case"nullify":return t.ruleType;default:return e.nillable?"nullify":"mask"}}var dt=.9,ut=1;function Ft(o,e,t,r=!1){let i=[];for(let[n,a]of e){let s=a.fields.filter(c=>c.createable&&Ne(c)),d=new Map(s.map(c=>[c.name,c])),l=new Map,h=o.detectPII(n,s.map(c=>({apiName:c.name,label:c.label,type:c.type})));for(let c of h.piiFields){let f=d.get(c.fieldApiName);if(!f)continue;let y=Ye[c.classification];l.set(f.name,{objectApiName:n,fieldApiName:f.name,fieldLabel:f.label,fieldType:f.type,piiCategory:y,detectionMethod:st[c.detectionMethod],confidence:c.confidence,suggestedMethod:Qe[y]})}for(let c of s)l.has(c.name)||Q(c.name,c.type)===void 0||l.set(c.name,{objectApiName:n,fieldApiName:c.name,fieldLabel:c.label,fieldType:c.type,piiCategory:"PII",detectionMethod:"field_name",confidence:dt,suggestedMethod:"fake"});let R=t?.get(n)?.fields;for(let c of s){let f=R?.get(c.name.toLowerCase());if(f===void 0||l.has(c.name))continue;let y=Ye[f.classification.classification];l.set(c.name,{objectApiName:n,fieldApiName:c.name,fieldLabel:c.label,fieldType:c.type,piiCategory:y,detectionMethod:"org_classification",confidence:ut,suggestedMethod:Qe[y]})}for(let c of r?s:[]){let f=Ee(n,c);f===void 0||l.has(c.name)||l.set(c.name,{objectApiName:n,fieldApiName:c.name,fieldLabel:c.label,fieldType:c.type,piiCategory:"PII",detectionMethod:"field_name",confidence:ct,suggestedMethod:lt(f,c)})}i.push(...l.values())}return i}function qt(o,e){let t=i=>`${i.objectApiName}.${i.fieldApiName}`,r=new Set(o.map(t));return[...o,...e.filter(i=>!r.has(t(i)))]}var pt=["Contact","Lead"];function vt(o,e,t){if(o==="none")return[];let r=new Set(e),i=[];for(let n of pt){if(!r.has(n))continue;let a=t.filter(d=>d.objectApiName===n).map(d=>d.fieldApiName),s=[];a.some(ye)||s.push("name"),a.some(d=>Q(d,"string")==="email")||s.push("email"),a.some(d=>Q(d,"string")==="phone")||s.push("phone"),s.length>0&&i.push({objectApiName:n,missing:s})}return i}function Bt(o,e,t){let r=[...e?.objects??new Map].flatMap(([a,s])=>s.refused!==void 0?[{objectApiName:a,message:s.refused}]:[]),i=Je(e,t).map(({objectApiName:a,fieldApiName:s})=>({objectApiName:a,fieldApiName:s}));if(r.length===0&&i.length===0)return o;let n=o.anonymizationSummary;return{...o,anonymizationSummary:{...n,orgClassification:{fields:n.orgClassification?.fields??0,refused:r,...i.length>0?{hidden:i}:{}}}}}function Je(o,e){if(o===void 0||e===void 0)return[];let t=[];for(let[r,i]of e){let n=o.objects.get(r);if(!(n===void 0||n.refused!==void 0))for(let a of Oe(i.fields,n.fields))t.push({objectApiName:r,fieldApiName:a.fieldApiName,classification:a.orgClassification})}return t}function Gt(o,e,t){let r=e.filter(n=>n.detectionMethod==="org_classification"),i=[`classification: ${r.length} field(s) only the source org's classification names, anonymized with the rest (${o.requests} Tooling request(s))`];for(let n of r){let a=o.objects.get(n.objectApiName)?.fields.get(n.fieldApiName.toLowerCase()),s=a?Ae(a.classification):n.piiCategory;i.push(` ${n.objectApiName}.${n.fieldApiName}: ${s}`)}for(let[n,a]of o.objects)a.refused!==void 0&&i.push(` ${n}: classification not read, its fields stand as the detector names them: ${a.refused}`);for(let n of Je(o,t))i.push(ke(n));return i}function $t(o){return o.fatalError!==void 0?"failure":o.totalFailure>0||o.failedObjects.length>0?o.totalSuccess+(o.totalLinked??0)>0?"partial":"failure":[...Object.values(o.lookups??{}),...Object.values(o.statuses??{})].some(t=>t.refusals.length>0)||o.stopped===!0?"partial":"success"}var ft=pe({name:Z().min(1),referenceTo:ue(Z()).min(1),createable:ee().optional(),updateable:ee().optional()}).loose();function Kt(o){if(!Array.isArray(o))return[];let e=[];for(let t of o){let r=ft.safeParse(t);r.success&&e.push({name:r.data.name,referenceTo:r.data.referenceTo,createable:r.data.createable??!1,updateable:r.data.updateable??!1})}return e}var Zt={STORAGE_EXCEEDED:"AUTOPILOT_STORAGE_EXCEEDED",API_BUDGET_EXCEEDED:"API_BUDGET_EXCEEDED",WRITE_DECLINED:"AUTOPILOT_WRITE_DECLINED",CONFIRMATION_UNAVAILABLE:"AUTOPILOT_CONFIRMATION_UNAVAILABLE",CHECKPOINT_REFUSED:"CHECKPOINT_REFUSED",RUN_CANCELLED:"RUN_CANCELLED",EMAILS_NOT_ACCEPTED:$e},eo={NO_PLAN:"AUTOPILOT_NO_PLAN",STORAGE_UNREAD:"AUTOPILOT_FIT_STORAGE_UNREAD",READ_REFUSED:"AUTOPILOT_FIT_READ_REFUSED",STALE:"AUTOPILOT_FIT_STALE"};function to(o,e,t=new Map){return je(o.waves.flatMap(r=>r.objects).map(r=>{let i=t.get(r);return{objectApiName:r,rows:[],counted:{rows:e.get(r)??0,...i!==void 0?{personAccounts:i}:{}}}}))}function oo(o){return[...new Set(o.waves.flatMap(e=>e.objects.map(String)))]}async function no(o){return Ge(o)}function mt(o){return o.filter(e=>e.verdict==="exceeds").map(Ue)}function gt(o){return o.filter(e=>e.verdict==="unread").map(e=>({limit:e.limit,emails:e.emails,unread:e.unread??""}))}function io(o){return o.objects.filter(({rows:e})=>e>0).length}async function bt(o,e,t,r,i={}){let n="unread"in e?await t().catch(l=>({unread:l instanceof Error?l.message:String(l)})):e.dailyApiRequests,{readBack:a=0,deliverability:s=0,mute:d=0}=i;return ae({run:_e(o.objects.map(({rows:l})=>({rows:l}))),...Le(r),...d>0?{mute:d}:{},...a>0?{readBack:a}:{},...s>0?{deliverability:s}:{}},n)}function At(o){return o.objects.reduce((e,{rows:t})=>e+Math.ceil(Math.max(0,t)/K),0)}function ro(o,e){let t={...o!==void 0&&o>0?{scan:o}:{},...e!==void 0&&e.requestsRead>0?{fit:e.requestsRead}:{}};return Object.keys(t).length>0?t:void 0}async function ht(o,e){let t=await e().catch(r=>({unread:r instanceof Error?r.message:String(r)}));return ae(At(o),t)}async function ao(o){let{plan:e}=o,t=Be(e,o.storage);if(e.totalRows===0)return{go:!0,check:t,asked:!1};let r=o.checkpointFirst?.estimate,i=Fe(r);if(i)return{go:!1,...i,check:t};let n=Ke(t,o.org);if(n)return{go:!1,code:"STORAGE_EXCEEDED",message:`${n} Nothing was written.`,check:t};let a=await bt(e,o.storage,o.readApiBudget,r,{...o.readBack!==void 0?{readBack:o.readBack}:{},...o.mute!==void 0?{mute:o.mute}:{},...ze(o.runEmails?.ofRun)}),s=xe(a,o.org,Ie);if(s)return{go:!1,code:"API_BUDGET_EXCEEDED",message:s,check:t};let d;if(o.source){let E=await ht(e,o.source.readApiBudget),g=ve(E,o.source.org);if(g!==void 0&&E.verdict==="exceeds")return{go:!1,code:"API_BUDGET_EXCEEDED",message:g,check:t,source:{estimate:E.estimate,remaining:E.remaining,max:E.max}};if(E.verdict==="near"){let{readBefore:T}=o.source;d={org:o.source.org,estimate:E.estimate,remaining:E.remaining,max:E.max,...T?{readBefore:{...T}}:{}}}}let l=o.confirmAboveRecords,h=l>0&&e.totalRows>l?l:void 0,R=mt(o.emails??[]),c=gt(o.emails??[]),f=o.emailsUncounted,y=o.runEmails?.gate,w=y?.verdict==="asks",S=async E=>{let g=re(y,E&&w),T=o.checkpointFirst;if(T===void 0)return{go:!0,check:t,asked:E,...g};let M=await qe(()=>T.take(T.estimate));return"stop"in M?{go:!1,...M.stop,check:t,...g}:{go:!0,check:t,asked:E,checkpoint:M.checkpoint,...g}};if(h===void 0&&t.verdict==="fits"&&R.length===0&&c.length===0&&f===void 0&&r===void 0&&a.verdict!=="near"&&d===void 0&&!w)return S(!1);let C=we(o.orgTier),D=await o.confirm({stage:"write",module:"autopilot",org:o.org,orgTier:o.orgTier,objects:e.objects.map(({objectApiName:E,rows:g})=>({objectApiName:E,rows:g})),total:e.totalRows,...h!==void 0?{aboveRecords:h}:{},...C!==void 0&&e.totalRows>C?{largeVolume:C}:{},storage:We(t),counted:!0,...R.length>0?{emails:R}:{},...c.length>0?{emailsUnread:c}:{},...f!==void 0?{emailsUncounted:f}:{},...Me(a),...d!==void 0?{sourceApiRequests:d}:{},...r!==void 0?{checkpoint:r}:{},...y?.confirmation});if(D==="confirmed")return S(!0);let x=re(y,!1);return D==="declined"?{go:!1,code:"WRITE_DECLINED",message:"The Autopilot run was cancelled before it wrote anything. Nothing was written.",check:t,...x}:{go:!1,code:"CONFIRMATION_UNAVAILABLE",message:"The Autopilot run needed a confirmation before it wrote, and there was no one to ask. Nothing was written: run it again from the Autopilot page, where the question is asked.",check:t,...x}}export{tt as a,ot as b,K as c,v as d,He as e,Ve as f,Xe as g,Ft as h,qt as i,vt as j,Bt as k,Gt as l,$t as m,Kt as n,Zt as o,eo as p,to as q,oo as r,no as s,io as t,bt as u,ro as v,ht as w,ao as x};
@@ -4,7 +4,7 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a as s}from"./chunk-AL4C3GFT.mjs";import{readFileSync as d}from"node:fs";import{extname as p,join as i}from"node:path";import{pathToFileURL as c}from"node:url";var r={autopilot:"run an Autopilot copy between two orgs",backup:"take and restore DataOps snapshots",checkpoint:"take a checkpoint of an org's data, and rewind the org to it",cleanup:"Bulk delete records you created on a sandbox in a time window",clone:"clone a record, or whole tables, from one org to a sandbox, or remove a run",compare:"compare two orgs the way the Compare page does, and deploy what differs",dataops:"mask an org's records, and put them back",empty:"empty objects of a sandbox, or the whole of it",env:"apply a sandforge.yaml to an org, and take it back",frozen:"build and replay a Frozen Dataset",mcp:"the MCP server: these scripts as tools for an AI agent, on stdio",monitor:"read an org the way the Monitor page does",pipeline:"plan and run an Automation pipeline exported from VS Code",seed:"fill an org from a seed template",sync:"run a Sync between two orgs",users:"set up the users of a sandbox after its refresh, and take them back"},a=o=>Object.prototype.hasOwnProperty.call(r,o);function m(o){let[e,...n]=o;if(e===void 0)return{kind:"refused",reason:"Name the command to run."};if(e==="--help"||e==="-h"||e==="help")return{kind:"help"};if(e==="--version"||e==="-v")return{kind:"version"};if(a(e))return{kind:"run",tool:e,args:n};let t=e.replace(/^sandforge-/,"");return t!==e&&a(t)?{kind:"refused",reason:`"${e}" is named ${t} here: ${s(t)} \u2026.`}:{kind:"refused",reason:e.startsWith("-")?`"${e}" is not a flag sandforge reads: name a command first.`:`"${e}" is not a command of sandforge.`}}function f(){let o=Math.max(...Object.keys(r).map(n=>n.length));return`sandforge \u2014 SandForge's command lines, without the editor: Seed, Forge's clone, Sync,
7
+ import{a as s}from"./chunk-AL4C3GFT.mjs";import{readFileSync as d}from"node:fs";import{extname as p,join as i}from"node:path";import{pathToFileURL as c}from"node:url";var r={autopilot:"run an Autopilot copy between two orgs",backup:"take and restore DataOps snapshots",checkpoint:"take a checkpoint of an org's data, and rewind the org to it",cleanup:"Bulk delete records you created on a sandbox in a time window",clone:"clone a record, or whole tables, from one org to a sandbox, or remove a run",compare:"compare two orgs the way the Compare page does, and deploy what differs",dataops:"mask an org's records and put them back, verify a masking, list templates",empty:"empty objects of a sandbox, or the whole of it",env:"apply a sandforge.yaml to an org, and take it back",frozen:"build and replay a Frozen Dataset",mcp:"the MCP server: these scripts as tools for an AI agent, on stdio",monitor:"read an org the way the Monitor page does",pipeline:"plan and run an Automation pipeline exported from VS Code",seed:"fill an org from a seed template",sync:"run a Sync between two orgs",users:"set up the users of a sandbox after its refresh, and take them back"},a=o=>Object.prototype.hasOwnProperty.call(r,o);function m(o){let[e,...n]=o;if(e===void 0)return{kind:"refused",reason:"Name the command to run."};if(e==="--help"||e==="-h"||e==="help")return{kind:"help"};if(e==="--version"||e==="-v")return{kind:"version"};if(a(e))return{kind:"run",tool:e,args:n};let t=e.replace(/^sandforge-/,"");return t!==e&&a(t)?{kind:"refused",reason:`"${e}" is named ${t} here: ${s(t)} \u2026.`}:{kind:"refused",reason:e.startsWith("-")?`"${e}" is not a flag sandforge reads: name a command first.`:`"${e}" is not a command of sandforge.`}}function l(){let o=Math.max(...Object.keys(r).map(n=>n.length));return`sandforge \u2014 SandForge's command lines, without the editor: Seed, Forge's clone, Sync,
8
8
  Checkpoints, DataOps, Frozen Dataset, the emptying of a sandbox, the users of a sandbox,
9
9
  sandforge.yaml environments, Automation pipelines, and the MCP server.
10
10
 
@@ -22,7 +22,7 @@ to it. In Claude Code:
22
22
 
23
23
  --version the version of SandForge these scripts belong to
24
24
  --help this text
25
- `}function l(o,e=__dirname,n=__filename){return i(e,`sandforge-${o}${p(n)}`)}function h(o=__dirname){let e=JSON.parse(d(i(o,"..","package.json"),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}var u=o=>import(c(o).href);async function g(o=process.argv,e=u){let n=m(o.slice(2));switch(n.kind){case"help":process.stdout.write(f());return;case"version":process.stdout.write(`${h()}
25
+ `}function f(o,e=__dirname,n=__filename){return i(e,`sandforge-${o}${p(n)}`)}function g(o=__dirname){let e=JSON.parse(d(i(o,"..","package.json"),"utf8"));return typeof e.version=="string"?e.version:"0.0.0"}var h=o=>import(c(o).href);async function u(o=process.argv,e=h){let n=m(o.slice(2));switch(n.kind){case"help":process.stdout.write(l());return;case"version":process.stdout.write(`${g()}
26
26
  `);return;case"refused":process.stderr.write(`${n.reason} Nothing was run. The commands: ${Object.keys(r).join(", ")}. Run with --help.
27
- `),process.exitCode=2;return;case"run":{let t=l(n.tool);process.argv=[o[0]??process.execPath,t,...n.args],await e(t);return}}}/(?:^|[\\/])sandforge\.[cm]?[jt]s$/.test(process.argv[1]??"")&&g().catch(o=>{process.stderr.write(`${o instanceof Error?o.message:String(o)}
28
- `),process.exit(1)});export{r as a,m as b,f as c,l as d,h as e,g as f};
27
+ `),process.exitCode=2;return;case"run":{let t=f(n.tool);process.argv=[o[0]??process.execPath,t,...n.args],await e(t);return}}}/(?:^|[\\/])sandforge\.[cm]?[jt]s$/.test(process.argv[1]??"")&&u().catch(o=>{process.stderr.write(`${o instanceof Error?o.message:String(o)}
28
+ `),process.exit(1)});export{r as a,m as b,l as c,f as d,g as e,u as f};
@@ -0,0 +1,15 @@
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 Un}from"./chunk-WJGK6VGU.mjs";import{b as bi}from"./chunk-54V4FVEY.mjs";import{a as ji,b as Ms}from"./chunk-XCA5AONB.mjs";import{a as Vt,b as Wn,c as vs}from"./chunk-66NMFCWX.mjs";import{a as Xr}from"./chunk-TZXYVMZC.mjs";import{Aa as mi,Ac as qe,Ba as gi,Bc as Ts,Cc as xt,Dc as Ns,Ea as hi,Ec as Xt,Fc as mn,Gc as gn,Ic as yi,Jc as ki,Kc as wi,Oc as Ri,Rc as $s,Tc as vi,b as un,d as ws,e as As,f as Rs,j as Ee,k as Fn,l as pn,m as Kt,n as dt,o as J,qa as ii,ra as oi,s as he,sa as ai,ta as di,ua as ci,va as li,wa as ui,xa as Hn,ya as pi,za as fi}from"./chunk-CJAWKLAL.mjs";import{d as Ai}from"./chunk-VKREON6Q.mjs";import{a as Gt,b as si}from"./chunk-CE6ZDGBB.mjs";import{a as Ti,b as Cs,c as Ni,d as Es,e as xs,f as hn,g as bn,h as Mi,i as zs,j as Ci,k as Kn,l as Ls}from"./chunk-VFKG2G37.mjs";import{a as Hr,b as Ur,c as Kr,d as Is,p as Oi,w as Ei,x as xi}from"./chunk-7O6EFNQS.mjs";import{e as qr}from"./chunk-3LRFPGYZ.mjs";import{b as Vr,d as ct,f as Qr,g as Yr,h as fn,i as Zr,j as Jr,k as ei,l as ti,n as ni}from"./chunk-NV5QA2HY.mjs";import{a as Ps}from"./chunk-YYZL7UGV.mjs";import{e as Gr,g as Ss}from"./chunk-TYUYPFDJ.mjs";import{a as Ii,c as Si}from"./chunk-DLSU66MY.mjs";import{a as Os,b as ot,c as Ke,d as qt,h as _n}from"./chunk-GP5J3DGS.mjs";import{a as mt}from"./chunk-5LFSFYFJ.mjs";import{r as Ue}from"./chunk-OT2NHL2V.mjs";import{d as js,x as Pi}from"./chunk-OLCS7JCT.mjs";import{d as Lr,g as ln,k as ve,l as Bn}from"./chunk-TQ6HEJ73.mjs";import{b as $i}from"./chunk-VV3B6IC3.mjs";import{a as Dr,d as Br,e as Fr,g as _r,h as Wr}from"./chunk-INIT2UKJ.mjs";import{B as ri}from"./chunk-4XROG5CT.mjs";import{q as de,r as cn,u as Dn}from"./chunk-SZOJ7BEJ.mjs";import{a as zr,f as dn,h as tt}from"./chunk-TZE3Y7IQ.mjs";import{b as v}from"./chunk-CA5NAXSU.mjs";import{$c as Be,Cc as bs,Sd as ks,Te as xr,a as Fe,ed as ys,ib as Pr,jb as Mr,kb as Cr,kd as Ht,ld as Ut,pd as Er,qd as Ln,tc as hs,x as $r,y as It}from"./chunk-J347SPU6.mjs";import{b as D,e as zn,f as ft,i as jr,k as Ce,l as ue,o as vr,q as Tr,s as Nr,v as an}from"./chunk-WZQEK4WT.mjs";var Xo={defaultQueryLimit:500,previewQueryLimit:200,exportQueryLimit:1e3},Qo={defaultQueryLimit:2e3,previewQueryLimit:2e3,exportQueryLimit:5e3};function qn(r){return r==="production"?{...Xo}:{...Qo}}function Gn(r){return r?"sandbox":"production"}var St="IsPersonAccount",Yo=new Set(["FirstName","LastName","MiddleName","Suffix","Salutation","Phone","Fax"]);function Zo(r){if(Yo.has(r))return r;if(r.endsWith("__c"))return`${r.slice(0,-3)}__pc`;if(/^[A-Za-z][A-Za-z0-9]*$/.test(r))return`Person${r}`}function yn(r){let e=(s,i)=>s.fieldPattern.toLowerCase().startsWith(`${i.toLowerCase()}.`)?s.fieldPattern.slice(i.length+1):void 0,t=new Set(r.flatMap(s=>{let i=e(s,de);return i===void 0?[]:[i.toLowerCase()]})),n=[];for(let s of r){let i=e(s,cn),o=i===void 0?void 0:Zo(i);o===void 0||t.has(o.toLowerCase())||(t.add(o.toLowerCase()),n.push({...s,fieldPattern:`${de}.${o}`}))}return n}function zi(r){if(r.objectApiName.toLowerCase()!==de.toLowerCase()||!r.fields.some(l=>l.name===St))return;let e=new Map(r.fields.map(l=>[l.name.toLowerCase(),l])),t=new Set(r.kept.map(l=>l.fieldApiName.toLowerCase())),n=[],s=new Set,i=[],o=(l,u)=>{t.add(u.name.toLowerCase()),s.add(u.name),n.push({...l,objectApiName:de,fieldApiName:u.name})};for(let l of r.derived){let u=e.get(l.fieldApiName.toLowerCase());if(!u){i.push(l.fieldApiName);continue}t.has(u.name.toLowerCase())||o(l,u)}let a=r.fields.filter(l=>Er(l.name)&&l.updateable===!0&&l.calculated!==!0&&!t.has(l.name.toLowerCase())),d=new Map,c=a.map(l=>{let u=Di(l.name);return d.set(u,l),{...l,name:u,label:l.label??l.name,type:l.type??"string"}});for(let l of fn(r.detector,cn,c)){let u=d.get(l.field.name);!u||t.has(u.name.toLowerCase())||o({objectApiName:de,fieldApiName:u.name,method:ni({...l.field,name:u.name}),config:{}},u)}return{rules:n,personOnly:s,unseen:i}}function Li(r,e){let t=new Set((e??[]).map(n=>n.name.toLowerCase()));return r.filter(n=>!t.has(Di(n).toLowerCase()))}function Di(r){return r.endsWith("__pc")?`${r.slice(0,-4)}__c`:r.startsWith("Person")&&!r.includes("__")?r.slice(6):r}function Bi(r,e,t,n){if(r.toLowerCase()!==de.toLowerCase())return[...t];let s=Dn(e,!1);return t.filter(i=>!Ln(de,i.fieldApiName,s)&&(s==="person"||!n.has(i.fieldApiName)))}var _s="HISTORY_NOT_DELETABLE",Jo='In Setup, turn on "Enable Delete from Field History" (User Interface), then give the user the "Delete From Field History" permission in a permission set.',Ds=2e3,kn=/^[A-Za-z][A-Za-z0-9_]{0,79}$/;function Ws(r,e=()=>{},t=n=>r.describe(n)){return{describe:t,count:async n=>{let s=await r.query(n);return e("history count"),s.totalSize},ids:async n=>{let s=await r.query(n);e("history read");let i=s.records.map(o=>o.Id);for(;!s.done&&s.nextRecordsUrl;)s=await r.queryMore(s.nextRecordsUrl),e("history read"),i.push(...s.records.map(o=>o.Id));return i.filter(Ke)},destroy:async(n,s)=>{let i=await r.destroy(n,s);return e("history delete"),i},tooling:{query:async n=>{let s=await r.tooling.query(n);return e("history fields"),s},more:async n=>{let s=await r.tooling.queryMore(n);return e("history fields"),s}}}}var wn=ue({deletable:ft().optional(),fields:Ce(ue({name:D(),compoundFieldName:D().nullish(),type:D().nullish(),length:zn().nullish(),extraTypeInfo:D().nullish()}).loose()).optional(),childRelationships:Ce(ue({childSObject:D(),field:D(),relationshipName:D().nullish()}).loose()).optional()}).loose();function Xn(r){let e=wn.safeParse(r);if(!e.success)return;let t=(e.data.childRelationships??[]).find(n=>n.relationshipName==="Histories");if(!(!t||!kn.test(t.childSObject)||!kn.test(t.field)))return{historyObject:t.childSObject,parentField:t.field}}var ea=255;function Fi(r,e){let t=wn.safeParse(e),n=t.success?t.data.fields??[]:[];return r.filter(s=>{let i=n.find(o=>o.name.toLowerCase()===s.toLowerCase());return i?.type==="textarea"&&((i.length??0)>ea||i.extraTypeInfo==="richtextarea")})}function _i(r,e,t){let n=wn.safeParse(t),s=n.success?n.data.fields??[]:[],i=new Set(Fi(e,t).map(d=>d.toLowerCase())),o=[],a=d=>{!d||!kn.test(d)||o.some(c=>c.toLowerCase()===d.toLowerCase())||o.push(d)};for(let d of e)i.has(d.toLowerCase())||(a(d),a(s.find(c=>c.name.toLowerCase()===d.toLowerCase())?.compoundFieldName));return r.toLowerCase()==="account"&&o.some(d=>d==="Name")&&a("TextName"),o}function ta(r){return r.map(e=>`'${e}'`).join(", ")}function Bs(r){return`FROM ${r.historyObject} WHERE Field IN (${ta(r.names)})`}async function Wi(r,e,t,n){if(t.names.length===0)return{rows:0};if("all"in n)return{rows:await r.count(`SELECT COUNT() ${Bs(t)}`)};let s,i=!1;if("where"in n){if(!kn.test(e))throw new Error(`Not an object name: ${e}`);s=await r.ids(`SELECT Id FROM ${e} WHERE ${n.where} ORDER BY Id LIMIT ${Ds+1}`),s.length>Ds&&(s=s.slice(0,Ds),i=!0)}else s=n.ids.filter(Ke);let o=0;for(let a of qt(s))o+=await r.count(`SELECT COUNT() ${Bs(t)} AND ${t.parentField} IN (${a})`);return i?{rows:o,atLeast:!0}:{rows:o}}async function Hi(r,e,t){let n=e.filter(c=>c.fields.length>0&&kn.test(c.objectApiName));if(n.length===0)return[];let s=c=>[...t.definitions??[]].find(([l])=>l.toLowerCase()===c.toLowerCase())?.[1],i=n.map(c=>c.objectApiName).filter(c=>s(c)===void 0),{objects:o}=i.length>0?await Ur(r.tooling,i):{objects:new Map},a=new Map(n.map(c=>[c.objectApiName,s(c.objectApiName)??o.get(c.objectApiName)])),d=[];for(let c of n){let l=a.get(c.objectApiName),u;try{u=await r.describe(c.objectApiName)}catch{continue}let f=Xn(u);if(!f)continue;let p=wn.safeParse(u),m=b=>(p.success?p.data.fields??[]:[]).find($=>$.name.toLowerCase()===b.toLowerCase())?.compoundFieldName??void 0,y=b=>b!==void 0&&l?.fields.get(b.toLowerCase())?.historyTracked===!0,k=Fi(c.fields,u),T=c.fields.filter(b=>y(b)||y(m(b))),g=T.filter(b=>!k.includes(b)),A=T.filter(b=>k.includes(b));if(l?.refused===void 0&&T.length===0)continue;let S={objectApiName:c.objectApiName,historyObject:f.historyObject,parentField:f.parentField,names:_i(c.objectApiName,c.fields,u),trackedFields:g,...A.length>0?{withoutValue:A}:{},deletable:!1,...l?.refused!==void 0?{unread:`which fields its history tracks was not read: ${l.refused}`}:{}};try{let b=wn.parse(await r.describe(f.historyObject));S.deletable=b.deletable===!0}catch(b){S.unread=`${f.historyObject} was not read: ${v(b)}`,d.push(S);continue}if(t.count)try{let b=await Wi(r,c.objectApiName,S,c.records);S.rows=b.rows,b.atLeast&&(S.atLeast=!0)}catch(b){S.unread=`its lines were not counted: ${v(b)}`}d.push(S)}return d}var na=Ce(ue({success:ft(),errors:Ce(vr([ue({message:D()}).loose(),D()])).optional()}).loose());async function sa(r,e,t,n=()=>!1){let s={deleted:0,refused:0,left:0,notReached:[],errors:[]},i=t.filter(Ke),o=a=>{!s.errors.includes(a)&&s.errors.length<5&&s.errors.push(a)};if(e.names.length===0)return s;for(let a=0;a<i.length;a+=ot){if(n()){s.notReached=i.slice(a);break}let[d]=qt(i.slice(a,a+ot)),c=`${Bs(e)} AND ${e.parentField} IN (${d})`,l;try{l=await r.ids(`SELECT Id ${c}`)}catch(u){o(v(u));continue}for(let u=0;u<l.length;u+=ot){let f=l.slice(u,u+ot);try{let p=na.safeParse(await r.destroy(e.historyObject,f)),m=p.success?p.data:[];for(let y of m){if(y.success){s.deleted++;continue}s.refused++;let k=y.errors?.[0];o(typeof k=="string"?k:k?.message??"The org gave no reason.")}s.refused+=Math.max(0,f.length-m.length)}catch(p){s.refused+=f.length,o(v(p))}}try{s.left+=await r.count(`SELECT COUNT() ${c}`)}catch(u){o(v(u))}}return s}async function Ui(r,e,t,n){try{let s=await r.describe(e),i=Xn(s);if(!i)return{none:!0};let o=_i(e,t,s),{rows:a}=await Wi(r,e,{...i,names:o},{ids:n});return{historyObject:i.historyObject,left:a}}catch(s){return{unread:v(s)}}}var Vn=class{constructor(e,t){this.org=e;this.of=t}org;of;waiting=new Map;done=new Map;historyOf(e){return this.of.find(t=>t.objectApiName.toLowerCase()===e.toLowerCase())}covers(e){return this.historyOf(e)!==void 0}add(e,t){let n=this.historyOf(e);if(!n)return;let s=this.waiting.get(n.objectApiName)??[];for(let i of t)Ke(i)&&!s.includes(i)&&s.push(i);this.waiting.set(n.objectApiName,s)}async flush(e,t=()=>!1){let n=this.historyOf(e);if(!n)return;let s=this.waiting.get(n.objectApiName)??[];if(s.length===0)return;let i=await sa(this.org,n,s,t);i.notReached.length>0?this.waiting.set(n.objectApiName,i.notReached):this.waiting.delete(n.objectApiName);let o=this.done.get(n.objectApiName)??{deleted:0,refused:0,left:0,errors:[]};o.deleted+=i.deleted,o.refused+=i.refused,o.left+=i.left;for(let a of i.errors)o.errors.includes(a)||o.errors.push(a);this.done.set(n.objectApiName,o)}async flushAll(e=()=>!1){for(let t of[...this.waiting.keys()])await this.flush(t,e)}pending(){return[...this.waiting].filter(([,e])=>e.length>0).map(([e,t])=>({objectApiName:e,ids:[...t]}))}result(){return this.of.map(e=>{let t=this.done.get(e.objectApiName)??{deleted:0,refused:0,left:0,errors:[]},n=this.waiting.get(e.objectApiName)?.length??0;return{objectApiName:e.objectApiName,historyObject:e.historyObject,trackedFields:[...e.trackedFields],deleted:t.deleted,refused:t.refused,left:t.left,...n>0?{notReached:n}:{},...t.errors.length>0?{unread:t.errors.join(" ")}:{}}})}};function Hs(r){return r.filter(e=>Ut(e)&&!e.deletable)}function Us(r){return`Nothing was written: the field history of what the run writes cannot be deleted by this user (${r.map(t=>t.historyObject||t.objectApiName).join(", ")}). ${Jo} Or run it without deleting the history.`}function Ki(r){if(r.length===0)return"";let e=i=>r.reduce((o,a)=>o+(a[i]??0),0),t=r.map(i=>`${i.historyObject} ${i.deleted??0}`).join(", "),n=e("notReached"),s=r.find(i=>i.unread!==void 0)?.unread;return`Field history: ${e("deleted")} line(s) deleted for good (${t}), ${e("refused")} refused by the org, ${e("left")} left holding a value of a masked field.`+(n>0?` The history of ${n} masked record(s) was not reached before the run stopped.`:"")+(s!==void 0?` The org said: ${s}`:"")}var qi=200,ra=48,ia=64;function Qn(r,e){return Math.max(1,Math.ceil(r/e))}function Gi(r,e,t){let n=Math.max(1,Math.ceil(r/e)),s=t.masking?Math.ceil(r/qi):0;return n+1+s+(t.duplicateRule?2:0)}function Ks(r,e,t,n){let s=0,i=0,o=0,a=0,d=[],c=[];for(let l of r){let u=Qn(l.rows,e);u>It&&c.push(l.objectApiName);let f=Math.floor(l.rows/e),p=l.rows-f*e;s+=f*Math.ceil(e/t)+Math.ceil(p/t)+1,n==="masking"&&(i+=Math.ceil(l.rows/qi)),o+=u+(l.duplicateRule&&n==="masking"?2*u:0)+2,a+=l.rows*(ra+ia*l.fields),d.push({objectApiName:l.objectApiName,size:e,slices:u,...l.approximate?{approximate:!0}:{}})}return{objects:d,requests:s+i+o,parts:{snapshots:s,updates:i,reads:o},diskBytes:a,seconds:Math.round(s*Ei+i*xi),tooMany:c}}function Yn(r){return Math.ceil(r*1.1)}function qs(r){let e=["bytes","KB","MB","GB","TB"],t=r,n=0;for(;t>=1024&&n<e.length-1;)t/=1024,n++;return n===0?`${r} bytes`:`${t.toFixed(t<10?1:0)} ${e[n]}`}import{createHash as oa}from"node:crypto";import{mkdir as aa,readFile as da,rm as ca,writeFile as la}from"node:fs/promises";import*as Gs from"node:path";function Zn(r){if(!/^[A-Za-z0-9_-]{1,200}$/.test(r))throw new Error(`Not a set id: "${r}".`);return r}var Vi=/^[0-9a-f]{64}$/;function Ld(r){return{save:async(e,t)=>{await r.storeSecret(`dataops.runKey.${Zn(e)}`,t)},load:async e=>{let t=await r.getSecret(`dataops.runKey.${Zn(e)}`);return t!==void 0&&Vi.test(t)?t:void 0},delete:async e=>{await r.deleteSecret(`dataops.runKey.${Zn(e)}`)}}}var ua=384,pa=448;function Dd(r){let e=Gs.join(r,"keys"),t=n=>Gs.join(e,`${Zn(n)}.key`);return{save:async(n,s)=>{await aa(e,{recursive:!0,mode:pa}),await la(t(n),s,{encoding:"utf8",mode:ua})},load:async n=>{try{let s=(await da(t(n),"utf8")).trim();return Vi.test(s)?s:void 0}catch{return}},delete:async n=>{await ca(t(n),{force:!0})}}}function Vs(r){return oa("sha256").update(`sandforge-slice-key:${r}`).digest("hex").slice(0,16)}import{randomBytes as Qa}from"node:crypto";import{statfs as Ya}from"node:fs/promises";import*as Do from"node:path";var Qt=[{id:"tpl-gdpr-standard",name:"GDPR Standard",description:"Standard GDPR compliance: anonymize personal data fields across common Salesforce objects.",complianceFramework:"gdpr",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace with fake first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace with fake last name."},{fieldPattern:"Contact.Email",ruleType:"fake",description:"Replace with fake email address."},{fieldPattern:"Contact.Phone",ruleType:"mask",description:"Mask phone number (keep last 4 digits).",config:{maskKeepLast:4}},{fieldPattern:"Contact.MailingStreet",ruleType:"fake",description:"Replace with fake street address."},{fieldPattern:"Contact.MailingCity",ruleType:"fake",description:"Replace with fake city."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"mask",description:"Mask postal code."},{fieldPattern:"Lead.FirstName",ruleType:"fake",description:"Replace with fake first name."},{fieldPattern:"Lead.LastName",ruleType:"fake",description:"Replace with fake last name."},{fieldPattern:"Lead.Email",ruleType:"fake",description:"Replace with fake email address."},{fieldPattern:"Lead.Phone",ruleType:"mask",description:"Mask phone number."},{fieldPattern:"Lead.Street",ruleType:"fake",description:"Replace with fake street address."},{fieldPattern:"Account.BillingStreet",ruleType:"fake",description:"Replace with fake address."},{fieldPattern:"Account.Phone",ruleType:"mask",description:"Mask phone number."}]},{id:"tpl-ccpa-california",name:"CCPA California",description:"CCPA compliance: anonymize consumer personal information per California privacy regulations.",complianceFramework:"ccpa",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace consumer first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace consumer last name."},{fieldPattern:"Contact.Email",ruleType:"hash",description:"Hash email for pseudonymization."},{fieldPattern:"Contact.Phone",ruleType:"nullify",description:"Nullify phone number."},{fieldPattern:"Contact.MailingStreet",ruleType:"nullify",description:"Nullify street address."},{fieldPattern:"Contact.MailingCity",ruleType:"nullify",description:"Nullify city."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"nullify",description:"Nullify postal code."},{fieldPattern:"Contact.Birthdate",ruleType:"nullify",description:"Remove date of birth."},{fieldPattern:"Lead.Email",ruleType:"hash",description:"Hash email for pseudonymization."},{fieldPattern:"Lead.Phone",ruleType:"nullify",description:"Nullify phone number."}]},{id:"tpl-hipaa-health",name:"HIPAA Health Data",description:"HIPAA compliance: de-identify protected health information (PHI) in healthcare Salesforce orgs.",complianceFramework:"hipaa",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace patient first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace patient last name."},{fieldPattern:"Contact.Email",ruleType:"hash",description:"Hash email address."},{fieldPattern:"Contact.Phone",ruleType:"mask",description:"Mask phone number."},{fieldPattern:"Contact.Birthdate",ruleType:"nullify",description:"Remove date of birth (PHI)."},{fieldPattern:"Contact.MailingStreet",ruleType:"nullify",description:"Remove address (PHI)."},{fieldPattern:"Contact.MailingCity",ruleType:"nullify",description:"Remove city (PHI)."},{fieldPattern:"Contact.MailingState",ruleType:"nullify",description:"Remove state (PHI)."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"truncate",description:"Truncate to first 3 digits.",config:{truncateLength:3,truncateKeep:"first"}},{fieldPattern:"Account.Name",ruleType:"fake",description:"Replace facility name."},{fieldPattern:"Account.Phone",ruleType:"mask",description:"Mask facility phone."}]},{id:"tpl-sandbox-scrub",name:"Sandbox Data Scrub",description:"General-purpose sandbox data scrubbing: mask all PII for safe development use.",complianceFramework:"custom",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Fake first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Fake last name."},{fieldPattern:"Contact.Email",ruleType:"preserve_format",description:"Replace keeping email format."},{fieldPattern:"Contact.Phone",ruleType:"preserve_format",description:"Replace keeping phone format."},{fieldPattern:"Lead.FirstName",ruleType:"fake",description:"Fake first name."},{fieldPattern:"Lead.LastName",ruleType:"fake",description:"Fake last name."},{fieldPattern:"Lead.Email",ruleType:"preserve_format",description:"Replace keeping email format."},{fieldPattern:"Lead.Company",ruleType:"fake",description:"Fake company name."},{fieldPattern:"Account.Name",ruleType:"fake",description:"Fake account name."},{fieldPattern:"Account.Website",ruleType:"constant",description:"Replace with placeholder URL.",config:{constantValue:"https://example.com"}},{fieldPattern:"Opportunity.Name",ruleType:"fake",description:"Fake opportunity name."}]},{id:"tpl-gdpr-complete",name:"GDPR Complete",description:"GDPR Standard, plus every other personal field of contacts, leads and cases: other phones, birthdate, other address, assistant, web requester, and descriptions redacted.",complianceFramework:"gdpr",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace with fake first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace with fake last name."},{fieldPattern:"Contact.Email",ruleType:"fake",description:"Replace with fake email address."},{fieldPattern:"Contact.Phone",ruleType:"mask",description:"Mask phone number (keep last 4 digits).",config:{maskKeepLast:4}},{fieldPattern:"Contact.MobilePhone",ruleType:"mask",description:"Mask mobile phone number (keep last 4 digits).",config:{maskKeepLast:4}},{fieldPattern:"Contact.HomePhone",ruleType:"mask",description:"Mask home phone number (keep last 4 digits).",config:{maskKeepLast:4}},{fieldPattern:"Contact.OtherPhone",ruleType:"mask",description:"Mask other phone number (keep last 4 digits).",config:{maskKeepLast:4}},{fieldPattern:"Contact.Birthdate",ruleType:"nullify",description:"Remove date of birth."},{fieldPattern:"Contact.MailingStreet",ruleType:"fake",description:"Replace with fake street address."},{fieldPattern:"Contact.MailingCity",ruleType:"fake",description:"Replace with fake city."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"mask",description:"Mask postal code."},{fieldPattern:"Contact.OtherStreet",ruleType:"fake",description:"Replace with fake street address."},{fieldPattern:"Contact.OtherCity",ruleType:"fake",description:"Replace with fake city."},{fieldPattern:"Contact.OtherPostalCode",ruleType:"mask",description:"Mask postal code."},{fieldPattern:"Contact.AssistantName",ruleType:"nullify",description:"Remove the assistant's name."},{fieldPattern:"Contact.AssistantPhone",ruleType:"mask",description:"Mask the assistant's phone number (keep last 4 digits).",config:{maskKeepLast:4}},{fieldPattern:"Contact.Description",ruleType:"redact",description:"Redact the personal data in the description, keep the rest of the text."},{fieldPattern:"Lead.FirstName",ruleType:"fake",description:"Replace with fake first name."},{fieldPattern:"Lead.LastName",ruleType:"fake",description:"Replace with fake last name."},{fieldPattern:"Lead.Email",ruleType:"fake",description:"Replace with fake email address."},{fieldPattern:"Lead.Phone",ruleType:"mask",description:"Mask phone number."},{fieldPattern:"Lead.MobilePhone",ruleType:"mask",description:"Mask mobile phone number."},{fieldPattern:"Lead.Street",ruleType:"fake",description:"Replace with fake street address."},{fieldPattern:"Lead.City",ruleType:"fake",description:"Replace with fake city."},{fieldPattern:"Lead.PostalCode",ruleType:"mask",description:"Mask postal code."},{fieldPattern:"Lead.Description",ruleType:"redact",description:"Redact the personal data in the description, keep the rest of the text."},{fieldPattern:"Account.BillingStreet",ruleType:"fake",description:"Replace with fake address."},{fieldPattern:"Account.Phone",ruleType:"mask",description:"Mask phone number."},{fieldPattern:"Account.Description",ruleType:"redact",description:"Redact the personal data in the description, a person account\u2019s above all, keep the rest."},{fieldPattern:"Case.SuppliedName",ruleType:"nullify",description:"Remove the name the requester gave."},{fieldPattern:"Case.SuppliedEmail",ruleType:"fake",description:"Replace with fake email address."},{fieldPattern:"Case.SuppliedPhone",ruleType:"mask",description:"Mask phone number (keep last 4 digits).",config:{maskKeepLast:4}},{fieldPattern:"Case.Description",ruleType:"redact",description:"Redact the personal data in the description, keep the rest of the text."}]}];var ma=200;function Xi(r,e){return`SELECT EntityDefinition.QualifiedApiName, QualifiedApiName, ComplianceGroup, SecurityClassification FROM FieldDefinition WHERE EntityDefinition.QualifiedApiName IN (${r.map(n=>`'${Be(n)}'`).join(", ")}) AND ${e} != null`}var ga=ue({EntityDefinition:ue({QualifiedApiName:D()}).loose(),ComplianceGroup:D().nullish(),SecurityClassification:D().nullish()}).loose();function ha(r){let e=[],t=[];for(let n of r){let s=[...t,n],i=t.length>=ma||Dr(Xi(s,"SecurityClassification"))>14e3;t.length>0&&i?(e.push(t),t=[n]):t=s}return t.length>0&&e.push(t),e}async function Qi(r,e){let t=[...new Set(e)],n=new Map(t.map(a=>[a.toLowerCase(),a])),s=new Set,i=[],o=0;for(let a of ha(t))for(let d of["ComplianceGroup","SecurityClassification"])try{o++;let c=await r.query(Xi(a,d)),l=[...c.records];for(;!c.done;){if(c.nextRecordsUrl===void 0||r.more===void 0)throw new Error("FieldDefinition answered more than one page");o++,c=await r.more(c.nextRecordsUrl),l.push(...c.records)}for(let u of l){let f=ga.safeParse(u);if(!f.success)continue;let p=n.get(f.data.EntityDefinition.QualifiedApiName.toLowerCase());if(p===void 0)continue;Hr({complianceGroups:(f.data.ComplianceGroup??"").split(";").map(y=>y.trim()).filter(y=>y!==""),...f.data.SecurityClassification?{securityClassification:f.data.SecurityClassification}:{}})!==void 0&&s.add(p)}}catch(c){let l=v(c);i.includes(l)||i.push(l)}return{objects:t.filter(a=>s.has(a)),requests:o,refused:i}}var ba=ue({sobjects:Ce(ue({name:D(),queryable:ft().optional(),updateable:ft().optional(),layoutable:ft().optional()}).loose())}).loose();function Yi(r){return ba.parse(r).sobjects.filter(e=>e.queryable===!0&&e.updateable===!0&&e.layoutable===!0).map(e=>e.name)}var Zi=100;async function ka(r,e,t){let n=new Map,s=[],i=t.map(a=>tt(a.name)).filter(a=>a!=="Id"),o=[];for(let a=0;a<i.length;a+=Zi)o.push(i.slice(a,a+Zi));o.length===0&&o.push([]);for(let a of o){let d=await r.query(`SELECT ${["Id",...a].join(", ")} FROM ${e} ORDER BY Id DESC LIMIT ${200}`);for(let c of d.records){if(typeof c!="object"||c===null)continue;let l={...c};delete l.attributes;let u=typeof l.Id=="string"?l.Id:void 0;if(!u)continue;let f=n.get(u);f?Object.assign(f,l):(n.set(u,l),s.push(u))}}return s.map(a=>n.get(a))}async function wa(r,e,t,n,s=!1){let i,o;try{if(i=qr.parse(await r.describe(tt(t))),o=tt(i.name),i.queryable===!1)throw new Error(`${o} cannot be queried.`)}catch(g){return{status:"failed",objectApiName:t,message:v(g)}}let a=fn(e,o,i.fields),d=n?.fields,c=new Set([...a.map(g=>g.field.name),...i.fields.filter(g=>d?.has(g.name.toLowerCase())).map(g=>g.name)]),l=i.fields.filter(g=>Qr(g)&&Yr(g)||c.has(g.name)),u=[],f;try{u=await ka(r,o,l)}catch(g){f=v(g)}let p=Zr(f?a:fn(e,o,i.fields,u),i.fields,d),y=(s?Vr(o,i.fields,p):p).map(g=>{let A=ei(g.field),S=u.map(I=>I[g.field.name]),b=g.detectedBy==="content"?g.pattern:void 0,$=Xr(g);return{fieldApiName:g.field.name,label:g.field.label,classification:g.classification,detectedBy:g.detectedBy,pattern:g.pattern,filled:S.filter(ct).length,...b!==void 0?{matched:S.filter(I=>typeof I=="string"&&e.contentMatches(b,I)).length}:{},...A?{searchedFor:A}:{},...g.orgClassification?{orgClassification:g.orgClassification}:{},...$?{suggestedRule:$}:{}}}).sort((g,A)=>A.filled-g.filled||g.label.localeCompare(A.label)),k=ti(i),T=Jr(i.fields,d);return{status:"scanned",objectApiName:t,label:i.label,sampled:u.length,fields:y,nameField:k?{fieldApiName:k.name,label:k.label}:null,...f!==void 0?{sampleError:f}:{},...n?.refused!==void 0?{classificationError:n.refused}:{},...T.length>0?{hiddenClassified:T}:{}}}async function Ji(r,e,t,n=()=>new Date,s){let i=n().toISOString(),o=s?await Kr(s,t.objects):void 0,a=[];for(let d of t.objects)a.push(await wa(r,e,d,o?.objects.get(d),t.everything===!0));return{orgId:t.orgId,scannedAt:i,sampleSize:200,objects:a,...o?{classificationRequests:o.requests}:{}}}var zt={id:ks,name:"Every personal field (automatic)",description:"Masks every personal field of the objects a run masks, read from the org at Preview and Apply: what the detector names by name, type or content, what the org classifies, the names of people and companies, every part of an address, the birthdates, and free text (Redact).",complianceFramework:"custom",rules:[],automatic:!0};function Yt(r){return r.id===ks}function Xs(r){let e=[];for(let t of r)for(let n of t.rules){let s=n.fieldPattern.split(".")[0];e.some(i=>i.toLowerCase()===s.toLowerCase())||e.push(s)}return e}function eo(r){return{...zt,rules:[...r]}}async function to(r,e,t,n,s){let i=t.objects===void 0||t.objects.length===0,o=i&&s?await Qs(r,s,n):void 0,a=i?o?.objects??[...n]:[...t.objects??[]],d=await Ji(r,e,{orgId:t.orgId,objects:a,everything:!0},void 0,s),c=[],l={objects:[],defaultObjects:i,rules:[],hidden:[],unwritable:[],unread:[],classificationRefused:[],toolingRequests:(d.classificationRequests??0)+(o?.requests??0),...o&&o.classified.length>0?{classifiedObjects:[...o.classified]}:{},...o?.unread!==void 0?{classifiedObjectsUnread:o.unread}:{}};for(let u of d.objects){if(u.status!=="scanned"){l.unread.push({objectApiName:u.objectApiName,message:u.message});continue}let f=u;l.objects.push(f.objectApiName),f.classificationError!==void 0&&l.classificationRefused.push({objectApiName:f.objectApiName,message:f.classificationError});for(let m of f.hiddenClassified??[])l.hidden.push({objectApiName:f.objectApiName,fieldApiName:m.fieldApiName});let p=[...f.fields].sort((m,y)=>m.fieldApiName.localeCompare(y.fieldApiName));for(let m of p){if(m.suggestedRule===void 0){l.unwritable.push({objectApiName:f.objectApiName,fieldApiName:m.fieldApiName});continue}c.push({fieldPattern:`${f.objectApiName}.${m.fieldApiName}`,ruleType:m.suggestedRule.ruleType,description:"",...m.suggestedRule.config?{config:{...m.suggestedRule.config}}:{}})}}return l.rules=c.map(u=>({fieldPattern:u.fieldPattern,ruleType:u.ruleType})),Aa(l),{template:eo(c),plan:l}}function Aa(r){let e=r.classifiedObjects??[];if(e.length===0)return;let t=new Set(r.rules.map(o=>o.fieldPattern.split(".")[0]?.toLowerCase())),n=(o,a)=>o.toLowerCase()===a.toLowerCase(),s=e.filter(o=>t.has(o.toLowerCase())),i=e.filter(o=>!t.has(o.toLowerCase())).map(o=>({objectApiName:o,reason:r.unread.some(a=>n(a.objectApiName,o))?"unread":r.hidden.some(a=>n(a.objectApiName,o))?"hidden":"unwritable"}));s.length>0?r.classifiedObjects=s:delete r.classifiedObjects,i.length>0&&(r.classifiedObjectsUnmasked=i)}async function Qs(r,e,t){let n=a=>({objects:[...t],classified:[],requests:0,unread:a});if(r.describeGlobal===void 0)return n("The session cannot list the objects of the org.");let s;try{s=Yi(await r.describeGlobal())}catch(a){return n(v(a))}let i=new Set(t.map(a=>a.toLowerCase())),o=await Qi(e,s.filter(a=>!i.has(a.toLowerCase())));return{objects:[...t,...o.objects],classified:o.objects,requests:o.requests,...o.refused.length>0?{unread:o.refused.join(" ")}:{}}}function no(r){let e=[];for(let t of r){let n=t.fieldPattern.split(".")[0];e.includes(n)||e.push(n)}return{template:eo(r),plan:{objects:e,defaultObjects:!1,rules:r.map(t=>({fieldPattern:t.fieldPattern,ruleType:t.ruleType})),hidden:[],unwritable:[],unread:[],classificationRefused:[],toolingRequests:0,frozen:!0}}}var Jn=class{constructor(e){this.reads=e}reads;kept=new Map;async plan(e,t,n){let s=this.key(e,t),i=this.kept.get(s);if(n==="kept"&&i)return i;let{session:o,tooling:a}=await this.reads.reads(e),d=await to(o,this.reads.detector(),{orgId:e,...t?{objects:t}:{}},this.reads.shippedObjects,a);return this.kept.set(s,d),d}frozen(e){let t=this.reads.keptRules(e);return t&&t.length>0?no(t):void 0}forget(e){for(let t of[...this.kept.keys()])t.startsWith(`${e}\0`)&&this.kept.delete(t)}key(e,t){let n=t&&t.length>0?t.map(s=>s.toLowerCase()):["*"];return`${e}\0${n.join(",")}`}};var es=class{operations=new Map;ttlMs;nowFn;constructor(e=36e5,t=Date.now){this.ttlMs=e,this.nowFn=t}isDuplicate(e){return this.pruneExpired(),this.operations.has(e)}register(e,t,n,s){if(this.pruneExpired(),this.operations.has(e))throw new Error(`Duplicate DML operation detected: ${e}`);let i={operationId:e,objectApiName:t,dmlType:n,recordCount:s,registeredAt:new Date(this.nowFn()).toISOString(),status:"pending"};return this.operations.set(e,i),i}markCompleted(e){let t=this.operations.get(e);t&&(t.status="completed")}markFailed(e){let t=this.operations.get(e);t&&(t.status="failed")}get(e){return this.operations.get(e)}get size(){return this.operations.size}clear(){this.operations.clear()}pruneExpired(){let e=this.nowFn()-this.ttlMs;for(let[t,n]of this.operations)new Date(n.registeredAt).getTime()<e&&this.operations.delete(t);if(this.operations.size>1e4){let t=Array.from(this.operations.entries()),n=t.length-1e4;for(let s=0;s<n;s++)this.operations.delete(t[s][0])}}};var Ra=3e3;function lt(r){return r.slice(0,15)}function ts(r,e){let t=r??null,n=e??null;return t===n?!0:t===null||n===null?!1:typeof t=="object"||typeof n=="object"?JSON.stringify(t)===JSON.stringify(n):String(t)===String(n)}function Ys(r){let e=[],t=[],n=0;for(let s of r)t.length>0&&n+s.length+2>Ra&&(e.push(t),t=[],n=0),t.push(s),n+=s.length+2;return t.length>0&&e.push(t),e}async function so(r,e,t){let n=t.map(a=>a.Id).filter(Ke),s=[...new Set(t.flatMap(a=>Object.keys(a)))].filter(a=>a.toLowerCase()!=="id");if(n.length===0||s.length===0)return{write:[...t],unchanged:0};let i=new Map;try{for(let a of Ys(s))for(let d of await _n(r,e,a,n))typeof d.Id=="string"&&i.set(lt(d.Id),{...i.get(lt(d.Id)),...d})}catch(a){return{write:[...t],unchanged:0,unread:v(a)}}let o=t.filter(a=>{let d=Ke(a.Id)?i.get(lt(a.Id)):void 0;return d?Object.keys(a).some(c=>c.toLowerCase()!=="id"&&!ts(a[c],d[c])):!0});return{write:o,unchanged:t.length-o.length}}async function ro(r,e,t,n){let s=tt(e),i=new Set,o=t.filter(Ke);for(let a=0;a<o.length;a+=ot){let d=o.slice(a,a+ot),[c]=qt(d,d.length),l=new Set,u=await r.query(`SELECT Id, LastModifiedDate FROM ${s} WHERE Id IN (${c})`);for(let y of u.records){if(typeof y.Id!="string")continue;l.add(lt(y.Id)),Date.parse(String(y.LastModifiedDate??""))<=n||i.add(lt(y.Id))}let f=d.filter(y=>!l.has(lt(y)));if(f.length===0)continue;let[p]=qt(f,f.length),m=await r.query(`SELECT Id FROM ${s} WHERE Id IN (${p}) AND IsDeleted = true`,{scanAll:!0});for(let y of m.records)typeof y.Id=="string"&&i.add(lt(y.Id))}return i}function io(r,e){return{async*[Symbol.asyncIterator](){for await(let t of r){let n=t.filter(s=>!(Ke(s.Id)&&e.has(lt(s.Id))));n.length>0&&(yield n)}}}}function Zs(r,e){let t=0;return{batches:{async*[Symbol.asyncIterator](){let n=new Map,s=[],i=0;for await(let a of r)for(let d of a){if(i++,!Ke(d.Id)){s.push({...d});continue}let c=n.get(lt(d.Id));if(!c){n.set(lt(d.Id),{...d});continue}for(let[l,u]of Object.entries(d))l in c||(c[l]=u)}t=i;let o=[...n.values(),...s];for(let a=0;a<o.length;a+=e)yield o.slice(a,a+e)}},lines:()=>t}}var Ia=1e3,Sa=50,oo=99,Oa=new Set(["string","textarea","email","phone","url","combobox","encryptedstring"]),co=new Set(["id","attributes",St.toLowerCase()]),ja="@example.invalid",ao=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,va=/[A-Za-z0-9._%+'-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+/g,Ta=/\+?\d[\d\s().\-/]*\d/g;function lo(r,e,t){let n=[];for(let s of t){if(s.fieldApiName==="Id"||n.some(o=>o.objectApiName.toLowerCase()===s.objectApiName.toLowerCase()&&o.fieldApiName.toLowerCase()===s.fieldApiName.toLowerCase()))continue;let i={...s.config};delete i.hashSalt,n.push({objectApiName:s.objectApiName,fieldApiName:s.fieldApiName,method:s.method,config:i})}return{runId:r,templateId:e.id,templateName:e.name,rules:n}}function Na(r,e){switch(r.method){case"redact":return!0;case"shuffle":{let t=String(e);return[...t].every(n=>n===t[0])}case"mask":case"truncate":case"constant":case"preserve_format":{if(r.config===void 0)return!1;let t=new bi(void 0,"verify").applyRule(e,{objectApiName:r.objectApiName,fieldApiName:r.fieldApiName,method:r.method,config:r.config});return ts(e,t)}default:return!1}}function Js(r){return r.slice(0,15)}function ns(r,e){if(e in r)return r[e];let t=e.toLowerCase(),n=Object.keys(r).find(s=>s.toLowerCase()===t);return n===void 0?void 0:r[n]}function er(r){if(typeof r=="object"&&r!==null){let{errorCode:e,code:t}=r;if(typeof e=="string"&&e!=="")return e;if(typeof t=="string"&&t!=="")return t}return/^([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+):/.exec(v(r))?.[1]??"READ_REFUSED"}function $a(r){let e=r?.fields;return Array.isArray(e)?e.flatMap(t=>{let{name:n,type:s}=t??{};return typeof n=="string"?[{name:n,type:typeof s=="string"?s:""}]:[]}):[]}function Pa(r){return Ys(r).flatMap(e=>{let t=[];for(let n=0;n<e.length;n+=oo)t.push(e.slice(n,n+oo));return t})}function Ma(r){let e=r.trim().split(/\s+/).filter(t=>t!=="").map(t=>t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));if(!(e.length<2))return new RegExp(`(?<![\\p{L}\\p{N}])${e.join("\\s+")}(?![\\p{L}\\p{N}])`,"iu")}function Ca(r,e){let t={emails:new Set,phones:new Set};for(let i of e){let o=ns(r,i.name);if(typeof o!="string"||!ct(o))continue;let a=o.trim(),d=Gr(i.name,i.type)??(ao.test(a)?"email":void 0);if(d==="email"&&ao.test(a)){let c=a.toLowerCase();c.endsWith(ja)||t.emails.add(c)}else if(d==="phone"){let c=hs(a);c.length>=8&&t.phones.add(c.slice(-8))}}let n=e.find(i=>i.name.toLowerCase()==="firstname"),s=e.find(i=>i.name.toLowerCase()==="lastname");if(n&&s){let i=ns(r,n.name),o=ns(r,s.name);if(typeof i=="string"&&typeof o=="string"&&ct(i)&&ct(o)){let a=Ma(`${i} ${o}`);a&&(t.name=a)}}return t}function Ea(r,e){let t=[];if(e.emails.size>0){for(let n of r.matchAll(va))if(e.emails.has(n[0].replace(/\.+$/,"").toLowerCase())){t.push("email");break}}if(e.phones.size>0)for(let n of r.matchAll(Ta)){let s=hs(n[0]);if(s.length>=8&&e.phones.has(s.slice(-8))){t.push("phone");break}}return e.name?.test(r)&&t.push("name"),t}async function Ic(r,e,t){let n=t.now??Date.now,s=n(),i=t.maxRequests??Ia,o=t.idsShown??Sa,a=0,d=!1,c={query:g=>(a+=1,r.query(g))},l=new Map,u=[],f=[],p=[...new Set(e.parts.map(g=>g.objectApiName))];for(let g of p){let A=e.parts.filter(F=>F.objectApiName===g),S={out:{objectApiName:g,kept:A.reduce((F,V)=>F+V.records,0),verified:0,gone:0,notRead:0,fields:[],elsewhere:[],textFields:0},fields:new Map,elsewhere:new Map};l.set(g,S);let b=(F,V)=>{S.out.notRead+=F,V!==void 0&&(S.out.notReadCode??=V)};if(a+1>i){d=!0,b(S.out.kept);continue}let $,I;try{a+=1,I=await r.describe(g),$=$a(I)}catch(F){b(S.out.kept,er(F));continue}let L=new Map($.map(F=>[F.name.toLowerCase(),F])),N=e.rules.filter(F=>F.objectApiName.toLowerCase()===g.toLowerCase());if(N.length===0){let F=new Set;for(let V of A){let U=await r.kept(V.snapshotId,g,1);if(U)for await(let ce of U){for(let xe of Object.keys(ce[0]??{}))co.has(xe.toLowerCase())||F.add(xe);break}}N=[...F].map(V=>({objectApiName:g,fieldApiName:V}))}let w=[],P=[];for(let F of N){u.push({objectApiName:g,fieldApiName:F.fieldApiName,...F.method!==void 0?{method:F.method}:{}});let V=L.get(F.fieldApiName.toLowerCase());if(!V){P.push(F.fieldApiName);continue}w.push({...V,rule:F}),S.fields.set(V.name,{fieldApiName:V.name,...F.method!==void 0?{method:F.method}:{},compared:0,left:0,asItsRuleWrites:0})}P.length>0&&(S.out.fieldsUnseen=P);let K=$.filter(F=>Oa.has(F.type.toLowerCase()));S.out.textFields=K.length;let H=[...new Set([...w.map(F=>F.name),...K.map(F=>F.name)])],Y=Pa(H),ae=Y.length>0?Y:[[]],Te=!1,pe=[];for(let F of A){let V=await r.kept(F.snapshotId,g,ot);if(!V){b(F.records,"NOT_ON_THIS_MACHINE");continue}for await(let U of V){let ce=U.map(le=>le.Id).filter(Ke);if(b(U.length-ce.length),ce.length===0)continue;if(Te||t.signal?.aborted){b(ce.length);continue}if(a+ae.length>i){d=!0,b(ce.length);continue}let xe=new Map;try{for(let le of ae)for(let be of await _n(c,g,le,ce))typeof be.Id=="string"&&xe.set(Js(be.Id),{...xe.get(Js(be.Id)),...be})}catch(le){Te=!0,b(ce.length,er(le));continue}for(let le of U){if(!Ke(le.Id))continue;let be=le.Id,pt=xe.get(Js(be));if(!pt){S.out.gone+=1;continue}S.out.verified+=1,pe.push(be);let bt=new Set;for(let Ae of w){let Ne=ns(le,Ae.name);if(!ct(Ne))continue;let _e=S.fields.get(Ae.name);if(_e.compared+=1,!!ts(Ne,pt[Ae.name])){if(Na(Ae.rule,Ne)){_e.asItsRuleWrites+=1;continue}_e.left+=1,bt.add(Ae.name),(_e.leftIds??=[]).length<o&&_e.leftIds.push(be)}}let st=Ca(le,w);if(!(st.emails.size===0&&st.phones.size===0&&!st.name))for(let Ae of K){if(bt.has(Ae.name))continue;let Ne=pt[Ae.name];if(!(typeof Ne!="string"||Ne===""))for(let _e of Ea(Ne,st)){let fe=`${Ae.name}\0${_e}`,_=S.elsewhere.get(fe)??{fieldApiName:Ae.name,as:_e,records:0};_.records+=1,(_.ids??=[]).length<o&&_.ids.push(be),S.elsewhere.set(fe,_)}}}}}r.history&&f.push(await xa(r.history,I,g,w,pe,{room:()=>i-a,sent:()=>{a+=1}}))}let m=[...l.values()].map(g=>({...g.out,fields:[...g.fields.values()],elsewhere:[...g.elsewhere.values()]})),y={kept:m.reduce((g,A)=>g+A.kept,0),verified:m.reduce((g,A)=>g+A.verified,0),valuesLeft:m.reduce((g,A)=>g+A.fields.reduce((S,b)=>S+b.left,0),0),foundElsewhere:m.reduce((g,A)=>g+A.elsewhere.reduce((S,b)=>S+b.records,0),0),gone:m.reduce((g,A)=>g+A.gone,0),notRead:m.reduce((g,A)=>g+A.notRead,0),notKept:e.slices?.notKept??0,historyLeft:f.reduce((g,A)=>g+(A.left??0),0)},k=m.some(g=>(g.fieldsUnseen??[]).length>0);f.some(g=>g.unread==="MAX_REQUESTS")&&(d=!0);let T=y.valuesLeft+y.foundElsewhere+y.historyLeft>0?"left":y.gone+y.notRead+y.notKept>0||k||f.some(g=>g.unread!==void 0)||(e.slices?.notTaken??0)>0?"incomplete":"clean";return{verificationId:t.verificationId,backupId:e.backupId,from:e.from,org:t.org,...e.template?{template:e.template}:{},rules:u,...e.keptAt!==void 0?{keptAt:e.keptAt}:{},...e.runId!==void 0?{runId:e.runId}:{},objects:m,totals:y,reads:{requests:a,maxRequests:i,stoppedAtBound:d,durationMs:Math.max(0,n()-s)},...e.slices?{slices:{read:new Set(e.parts.map(g=>g.snapshotId)).size,restored:e.slices.restored,notTaken:e.slices.notTaken}}:{},verdict:T,verifiedAt:new Date(n()).toISOString(),history:r.history?f:null}}async function xa(r,e,t,n,s,i){let o=Xn(e);if(!o)return{objectApiName:t,notTracked:!0};if(Math.ceil(s.length/ot)>i.room())return{objectApiName:t,historyObject:o.historyObject,unread:"MAX_REQUESTS"};let a=await Ui({describe:()=>Promise.resolve(e),count:d=>(i.sent(),r.count(d)),ids:d=>(i.sent(),r.ids(d))},t,n.map(d=>d.name),s);return"none"in a?{objectApiName:t,notTracked:!0}:"unread"in a?{objectApiName:t,historyObject:o.historyObject,unread:er(new Error(a.unread))}:{objectApiName:t,historyObject:a.historyObject,left:a.left}}function Sc(r){return r==="clean"?"success":r==="incomplete"?"partial":"failure"}var za="MASKING_NOT_VERIFIABLE",La="BACKUP_NOT_FOUND",uo="-snapshot";function po(r,e){return e.masking!==void 0||e.origin===void 0&&r.endsWith(uo)}function fo(r,e){if(typeof e!="object"||e===null)return{};let t=e;return po(r,t)?{masking:t.masking?{templateId:t.masking.templateId,templateName:t.masking.templateName}:{}}:{}}function Da(r,e,t){let n=`${e}.${t}`.toLowerCase(),i=(e.toLowerCase()===de.toLowerCase()?[...r.rules,...yn(r.rules)]:r.rules).find(o=>o.fieldPattern.toLowerCase()===n);return i?{objectApiName:e,fieldApiName:t,method:i.ruleType,config:{...i.config}}:{objectApiName:e,fieldApiName:t}}function Oc(r,e){let{backupId:t,orgId:n}=e,s=p=>({refused:{code:za,message:`${p} keeps no masking: only the values a masking run kept before it wrote \u2014 Keep the values first, ticked in its confirmation, or its slices \u2014 say what it masked. Leave Keep the values first ticked on the next run, then verify the backup it takes.`}}),i={refused:{code:La,message:`No backup or set of slices "${t}" of this org is kept on this machine: the retention may have removed it, or it was taken from another org.`}},o=r.meta(t);if(typeof o=="object"&&o!==null){let p=o;if(p.orgId!==n)return i;let m=p.masking;return po(t,p)?{toVerify:{from:"snapshot",backupId:t,...m?{template:{id:m.templateId,name:m.templateName}}:{},rules:m?.rules??[],...p.timestamp?{keptAt:p.timestamp}:{},runId:m?.runId??t.slice(0,-uo.length),parts:(p.objects??[]).map(y=>({objectApiName:y.objectApiName,snapshotId:t,records:y.recordCount}))}}:s(`Backup ${t}`)}let a=r.set(t);if(!a||a.orgId!==n)return i;if(a.kind!=="masking")return s(`Set ${t}, a backup in slices,`);let d=a.templateId!==void 0?r.template(a.templateId):void 0,c=[],l=[],u=0,f=0;for(let p of a.objects){let m=(p.select??"").split(",").map(y=>y.trim()).filter(y=>y!==""&&!co.has(y.toLowerCase()));for(let y of m)c.push(d?Da(d,p.objectApiName,y):{objectApiName:p.objectApiName,fieldApiName:y});for(let y of p.slices)y.state==="restored"?u+=1:y.state==="pending"?f+=1:l.push({objectApiName:p.objectApiName,snapshotId:y.snapshotId,records:y.rows})}return{toVerify:{from:"slices",backupId:t,...a.templateId!==void 0?{template:{id:a.templateId,name:d?.name??a.templateId}}:{},rules:c,keptAt:a.startedAt,parts:l,slices:{restored:u,notTaken:f,notKept:mn(a)}}}}var tr="anonymization:template:",mo="anonymizationTemplates",go=ue({id:D().min(1).max(100),name:D().trim().min(1).max(Pr),description:D().max(500),complianceFramework:an("custom"),rules:Ce(Tr(Cr,ue({description:D().max(500)}))).min(1).max(Mr),saved:an(!0),createdAt:D()}),rs=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${tr}${e.id}`,e,mo)}create(e,t,n=()=>new Date){let s={id:`tpl-saved-${crypto.randomUUID()}`,name:e.trim(),description:"",complianceFramework:"custom",rules:t.map(i=>({...i,description:""})),saved:!0,createdAt:n().toISOString()};return this.save(s),s}load(e){let t=go.safeParse(this.configStore.get(`${tr}${e}`));return t.success?t.data:void 0}list(){let e=[];for(let t of Object.values(this.configStore.getByCategory(mo))){let n=go.safeParse(t);n.success&&e.push(n.data)}return e.sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}delete(e){return this.configStore.delete(`${tr}${e}`)}};import{createHash as bo}from"node:crypto";var Ba="anonymization:checkpoint:",Fa="anonymizationCheckpoints",Lt=2e3,_a=1e4,is=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Wa=D().min(1).max(255),Ha=ue({id:D().regex(is),fields:Ce(Wa).min(1).max(800),digest:D().regex(/^[0-9a-f]{64}$/)}),Ua=ue({objectApiName:D().min(1).max(255),done:ft(),afterId:D().regex(is).optional(),refused:Ce(D().regex(is)).max(Lt),unconfirmed:Ce(Ha).max(Lt).optional(),slice:ue({setId:D().min(1).max(200),index:zn().int().positive()}).optional()}),ho=ue({id:D().min(1).max(200),orgId:D().min(1).max(200),templateId:D().min(1).max(200),fingerprint:D().regex(/^[0-9a-f]{64}$/),savedAt:D(),objects:Ce(Ua),namesGiven:D().max(6e4).regex(/^[A-Za-z0-9+/]*={0,2}$/).optional(),setId:D().min(1).max(200).optional(),rules:Ce(ue({fieldPattern:D().min(1).max(600),ruleType:D().min(1).max(40),description:D().max(500),config:Nr(D(),jr()).optional()})).max(5e3).optional(),history:ue({purge:an(!0),pending:Ce(ue({objectApiName:D().min(1).max(255),ids:Ce(D().regex(is)).max(_a)})).max(200)}).optional()});function Zt(r,e,t,n){let s=r.map(o=>[o.fieldPattern,o.ruleType,o.config??null]),i=t?.trim();return bo("sha256").update(JSON.stringify({rules:s,objects:e,...i?{where:i}:{},...n!==void 0?{slices:n}:{}})).digest("hex")}function Ka(r){return r==null||r===""?null:typeof r=="string"?r.trim():typeof r=="number"||typeof r=="boolean"?String(r):JSON.stringify(r)}function nr(r,e){let t=[...e].sort().map(n=>[n,Ka(r[n])]);return bo("sha256").update(JSON.stringify(t)).digest("hex")}function An(r){return r.reduce((e,t)=>e+t.refused.length,0)}var ut=class{constructor(e){this.configStore=e}configStore;load(e,t,n){let s=ho.safeParse(this.configStore.get(this.key(e,t)));if(!s.success)return;let i=s.data;if(!(i.orgId!==e||i.templateId!==t||i.fingerprint!==n))return i}keptRules(e,t){let n=ho.safeParse(this.configStore.get(this.key(e,t)));if(!n.success)return;let{rules:s}=n.data;if(!(n.data.orgId!==e||n.data.templateId!==t||!s))return s.map(i=>({fieldPattern:i.fieldPattern,ruleType:i.ruleType,description:i.description,...i.config?{config:i.config}:{}}))}save(e){if(An(e.objects)>Lt)throw new Error(`A checkpoint keeps at most ${Lt} refused records; this run left ${An(e.objects)}.`);this.configStore.set(this.key(e.orgId,e.templateId),e,Fa)}clear(e,t){this.configStore.delete(this.key(e,t))}key(e,t){return`${Ba}${e}:${t}`}};async function qa(r){let{open:e,rename:t,rm:n}=await import("node:fs/promises"),{randomBytes:s}=await import("node:crypto"),i=`${r}.${s(4).toString("hex")}.partial`,o=await e(i,"w"),a=!1;return{write:async d=>{let c=Buffer.from(d,"utf8");for(let l=0;l<c.length;){let{bytesWritten:u}=await o.write(c,l,c.length-l,null);l+=u}},close:async()=>{a=!0,await o.close(),await t(i,r)},abort:async()=>{a||await o.close().catch(()=>{}),a=!0,await n(i,{force:!0})}}}function Ga(r){let e=[];return{write:async t=>{e.push(t)},close:async()=>{await r(new TextEncoder().encode(e.join("")))},abort:async()=>{e.length=0}}}var os=class r{host;constructor(e){this.host=e??null}async defaultHost(){let e=await import("vscode");return{showSaveDialog:t=>e.window.showSaveDialog(t),writeFile:(t,n)=>e.workspace.fs.writeFile(t,n),fileUri:t=>e.Uri.file(t),openFile:async t=>t.scheme==="file"?qa(t.fsPath):Ga(n=>e.workspace.fs.writeFile(t,n))}}static filtersOf(e,t){let n=e.includes(".")?e.split(".").pop():void 0;return t?.length?{[t.join("/").toUpperCase()]:t}:n?{[n.toUpperCase()]:[n]}:void 0}static ask(e,t,n){let s=r.filtersOf(t,n);return e.showSaveDialog({saveLabel:"Save",defaultUri:e.fileUri(t),...s?{filters:s}:{}})}async save(e,t,n){let s=this.host??await this.defaultHost();try{let i=await r.ask(s,e,n);return i?(await s.writeFile(i,new TextEncoder().encode(t)),{status:"saved",path:i.fsPath}):{status:"cancelled"}}catch(i){return{status:"error",message:i instanceof Error?i.message:String(i)}}}async saveStream(e,t,n){let s=this.host??await this.defaultHost(),i;try{let o=await r.ask(s,e,n);if(!o)return{status:"cancelled"};let a=await s.openFile(o);i=a;let d=await t(c=>a.write(c));return await a.close(),i=void 0,{status:"saved",path:o.fsPath,result:d}}catch(o){return await i?.abort().catch(()=>{}),{status:"error",message:o instanceof Error?o.message:String(o)}}}};function Rn(r,e,t,n,s=0){r?.register(e,t,n,s);let i=!1,o=a=>{i||(i=!0,a())};return{progress:(a,d,c,l)=>{i||r?.updateProgress(e,a,d,c,l)},complete:()=>o(()=>r?.complete(e)),partial:()=>o(()=>r?.partial(e)),fail:a=>o(()=>r?.fail(e,a)),cancel:()=>o(()=>r?.cancel(e))}}var nt={orgUnknown:"ORG_NOT_FOUND",production:"PIPELINE_WRITE_REFUSED",needsApproval:"PIPELINE_WRITE_NEEDS_APPROVAL",retries:"PIPELINE_WRITE_NO_RETRIES",filterNeedsObject:"MASKING_FILTER_NEEDS_OBJECT",invalid:"INVALID_PAYLOAD",templateMissing:"TEMPLATE_NOT_FOUND",fieldsUnseen:"MASKING_FIELDS_UNSEEN",masksNothing:"MASKING_MASKS_NOTHING"};function gt(r,e){return Object.assign(new Error(e),{code:r})}function yo(r,e,t){let n=xr(r);if(n==="refused")return gt(nt.production,`${t} is a production org, or one SandForge cannot tell is not: a pipeline never masks one, whatever an Approval step answers. Mask a sandbox, a scratch org or a Developer Edition org. Nothing was masked.`);if(n==="needsApproval"&&!e.approved)return gt(nt.needsApproval,`${t} is a sandbox marked Staging, which a pipeline masks only once an Approval step before the masking has approved the run, and none did: put an Approval step before it. Nothing was masked.`)}function sr(r,e){if(r.retries!==void 0&&r.retries>0)return{refusal:gt(nt.retries,"A masking step is never tried again: a second try masks again what the first one masked \u2014 an address it hashed is hashed once more, and no longer gives the same pseudonym on Contact and on Lead. Set its retries to 0. Nothing was masked.")};let t=r.where?.trim();if(t&&r.object===void 0)return{refusal:gt(nt.filterNeedsObject,"A masking condition filters the rows of one object: name the object it holds, or remove the condition. Nothing was masked.")};let n=Hn.safeParse({orgId:r.orgId,templateId:r.templateId,...r.object!==void 0?{objects:[r.object]}:{},...t?{where:t}:{},snapshot:!0,...r.purgeHistory===!0?{purgeHistory:!0}:{}});if(!n.success){let s=n.error.issues[0];return{refusal:gt(nt.invalid,`The masking step is not one the DataOps page would run (${s.path.join(".")}: ${s.message}). Nothing was masked.`)}}return e(n.data.templateId)?{asked:n.data}:{refusal:gt(nt.templateMissing,`No masking template is shipped or saved under ${n.data.templateId}: it was deleted on the DataOps page. Choose another. Nothing was masked.`)}}function as(r,e){return`${r} ${e}${r===1?"":"s"}`}function xc(r,e,t){return(r??[]).map(n=>{let s=`${n.objectApiName}'s field history (${n.historyObject})`,i=n.rows===void 0?"":`, ${n.atLeast?"at least ":""}${n.rows} line(s) already holding their values for these records`,o=n.withoutValue??[],a=o.length>0?` ${o.join(", ")} ${o.length>1?"are":"is"} tracked without ${o.length>1?"their":"its"} value: those lines hold none.`:"",d=n.trackedFields.length>0?`${s} keeps ${n.trackedFields.join(", ")}${i}: the masking adds a line per record and field it changes, the original value with it.${a}`:`${s}${i}.${a}`,c=n.unread!==void 0?` Not read: ${n.unread}`:"";if(!Ut(n))return`${d}${c}`;let l=n.deletable?e?" The step deletes those lines of the records it masks, for good, as it goes.":" purgeHistory would delete those lines of the records it masks, for good.":` They cannot be deleted by this user: ${t}`;return`${d}${c}${l}`}).join(" ")}function zc(r){if(r?.purge!==!0)return;let e=o=>r.objects.reduce((a,d)=>a+(d[o]??0),0),t=e("refused"),n=e("left"),s=e("notReached"),i=r.objects.find(o=>o.unread!==void 0)?.unread;if(!(t+n+s===0&&i===void 0))return`its field history still holds values it masked: ${t} refused by the org, ${n} left`+(s>0?`, the history of ${s} masked record(s) not reached`:"")+(i!==void 0?`; the org said: ${i}`:"")}var Va={email:"an email address",phone:"a phone number",name:"a full name"};function Lc(r){let{totals:e}=r,t=`Verified against the ${r.from==="slices"?"set of slices":"snapshot"} `+r.backupId,n=`${e.verified} of ${as(e.kept,"record")}`,s=(r.history??[]).filter(o=>o.notTracked!==!0&&o.unread===void 0);if(r.verdict==="clean")return`${t}: no value left, ${n} read again`+(s.length>0?", and no line of field history holds one.":".");if(r.verdict==="left"){let o=[...r.objects.flatMap(a=>a.fields.filter(d=>d.left>0).map(d=>`${a.objectApiName}.${d.fieldApiName} on ${as(d.left,"record")}`)),...r.objects.flatMap(a=>a.elsewhere.map(d=>`${Va[d.as]??d.as} kept from a masked field in ${a.objectApiName}.${d.fieldApiName} on ${as(d.records,"record")}`)),...s.filter(a=>(a.left??0)>0).map(a=>`${as(a.left??0,"line")} of ${a.historyObject??`${a.objectApiName}'s history`} still hold a value of a masked field`)];return`${t}: values left \u2014 ${o.join("; ")}. The DataOps page's Backups tab verifies ${r.backupId} again and opens those records.`}let i=[...e.gone>0?[`${e.gone} gone since`]:[],...e.notRead>0?[`${e.notRead} not read`+(r.reads.stoppedAtBound?` (the bound of ${r.reads.maxRequests} requests came first)`:"")]:[],...e.notKept>0?[`${e.notKept} no slice kept`]:[],...(r.history??[]).filter(o=>o.unread!==void 0).map(o=>`the field history of ${o.objectApiName} not read (${o.unread})`)];return`${t}: no value found left, but ${n} were read again`+(i.length>0?` \u2014 ${i.join(", ")}.`:".")}var Xa=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function ko(r){if(!Xa.test(r))throw new Error(`Not a record id: "${r}".`);return r}function rr(r,e){let t=r?.trim();return[...t?[`(${dn(t)})`]:[],...e.createdSince!==void 0?[`CreatedDate >= ${ri(e.createdSince)}`]:[],...e.afterId!==void 0?[`Id > '${ko(e.afterId)}'`]:[],...e.untilId!==void 0?[`Id <= '${ko(e.untilId)}'`]:[]]}function ir(r){return r.length===0?"":` WHERE ${r.join(" AND ")}`}function wo(r,e,t,n,s){if(!Number.isInteger(s)||s<=0)throw new Error(`Not a slice size: ${s}.`);return`SELECT ${e} FROM ${tt(r)}${ir(rr(t,n))} ORDER BY Id LIMIT ${s}`}function or(r,e,t,n){return`SELECT COUNT() FROM ${tt(r)}`+ir(rr(e,{...n,createdSince:t}))}function Ao(r,e,t){return`SELECT COUNT() FROM ${tt(r)}`+ir(rr(e,{afterId:t}))}function Bo(r){let e=r.fields;return{name:r.name,label:r.label,labelPlural:r.labelPlural??"",keyPrefix:r.keyPrefix??null,custom:r.custom??!1,createable:r.createable,updateable:r.updateable,deletable:r.deletable,queryable:r.queryable,fields:e.map(t=>({name:t.name,label:t.label,type:t.type,length:t.length??0,nillable:t.nillable??!1,createable:t.createable,updateable:t.updateable,externalId:t.externalId??!1,referenceTo:t.referenceTo??[],relationshipName:t.relationshipName??null,picklistValues:t.picklistValues??[],defaultValue:t.defaultValue??null,calculated:t.calculated??!1,autoNumber:t.autoNumber??!1,unique:t.unique??!1,permissionable:t.permissionable??!0})),recordTypeInfos:r.recordTypeInfos??[],childRelationships:r.childRelationships??[]}}var Za=new Set(["backup:execute","backup:list","backup:objects","backup:export","backup:delete","dataops:rollback","dataops:anonymize","dataops:anonymization-templates","dataops:anonymization-template:save","dataops:anonymization-template:delete","dataops:anonymize:coverage","dataops:anonymize:preview","dataops:automation","precheck:pii-scan"]),Ja=6e4,ed=10,td=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function nd(r,e){return r.slice(0,15)===e.slice(0,15)}var Ro="ORG_REPLACED_SINCE_BACKUP",sd="Backup was cancelled before it finished. Nothing was saved \u2014 run it again to take a complete snapshot.",Dt=class extends Error{constructor(){super(sd),this.name="BackupCancelledError"}},Tn=class extends Error{constructor(e){super(`The backup could not be written to disk: ${v(e)}`),this.name="BackupWriteError"}},nn=class extends Error{constructor(t,n){super(t);this.retryable=n;this.name="BackupNotWholeError"}retryable},br="IsDeleted = false",rd="SystemModstamp",Fo=5e4,id=100,vn=$r;function od(r){return typeof r!="number"||!Number.isFinite(r)?Fo:Math.min(vn,Math.max(id,Math.floor(r)))}var Jt=200,ad=1440*6e4,dd=1440*6e4,Io="backupRetention:since",ar="BACKUP_BUSY";function cd(r,e){return e===0?"success":r===0?"failure":"partial"}function dr(r){return ys(r)}function So(r,e,t){r.length>=ed||r.push({objectApiName:e,message:t?.[0]?.message??"Unknown DML error"})}function In(r,e,t=!1){let n=(e?.rules??[]).map(i=>i.fieldPattern.split(".")[0]).filter((i,o,a)=>a.findIndex(d=>Nn(d,i))===o);if(r.objects)return r.objects.map(i=>n.find(o=>Nn(o,i))??(Nn(i,de)?de:i));if(!e)return[];let s=[...n];return t&&$n(r,e,de)&&s.push(de),s}function Nn(r,e){return r.toLowerCase()===e.toLowerCase()}var ld=`${St} = true`;function $n(r,e,t){return r.objects===void 0&&t.toLowerCase()===de.toLowerCase()&&Bt(e,de).length===0&&yn(e.rules).length>0}function Sn(r,e,t){return $n(r,e,t)?ld:us(r)}async function cr(r,e){try{return(await r.describe(de)).fields.some(t=>t.name===St)}catch(t){return e(`[WARN] dataops: whether the org has person accounts was not read: ${v(t)}`),!1}}function Bt(r,e){let t=`${e.toLowerCase()}.`;return r.rules.filter(n=>n.fieldPattern.toLowerCase().startsWith(t)||n.fieldPattern==="*")}function en(r,e){return e.toLowerCase()===de.toLowerCase()?yn(r.rules):[]}function On(r){let e=new Map;return{describe:t=>{let n=e.get(t)??r.describe(t);return e.set(t,n),n}}}async function lr(r,e){return new vs(async n=>Bo(await r.describe(n))).deniedOf(e.map(({objectApiName:n,rules:s})=>({objectApiName:n,operation:"update",fieldNames:s.map(i=>i.fieldPattern.includes(".")?i.fieldPattern.split(".")[1]:i.fieldPattern).filter(i=>i!=="*")})))}function Oo(r){return{objectApiName:r.objectApiName,historyObject:r.historyObject,trackedFields:[...r.trackedFields],...r.withoutValue?{withoutValue:[...r.withoutValue]}:{},...r.rows!==void 0?{rows:r.rows}:{},...r.atLeast?{atLeast:!0}:{},deletable:r.deletable,...r.unread!==void 0?{unread:r.unread}:{}}}function ur(r,e){return Bt(r,e).length>0||en(r,e).length>0}function pr(r){return{objectApiName:r.objectApiName,recordCount:r.recordCount,truncated:r.truncated===!0,...r.orgCount!==void 0?{orgCount:r.orgCount}:{},...r.stoppedAt?{stoppedAt:r.stoppedAt}:{},...r.notKept&&r.notKept.length>0?{notKept:[...r.notKept]}:{},...r.where?{where:r.where}:{}}}function fr(r,e){return r.flatMap(t=>{let n=e?.get(t.objectApiName);if(n!==void 0&&n<t.recordCount)return[`${t.objectApiName} ${n} of the ${t.recordCount} it listed (not found on disk)`];if(!t.truncated)return[];if(t.stoppedAt==="not_reached")return[`${t.objectApiName} none (the backup stopped before it)`];let s=t.orgCount!==void 0?` of ${t.orgCount}`:"",i=t.stoppedAt==="cap"?" (stopped at the cap)":t.stoppedAt==="failure"?" (the read failed)":"";return[`${t.objectApiName} ${t.recordCount}${s}${i}`]}).join(", ")}var ht=200,mr=95,Pn=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ud="NOTHING_TO_RESUME",jo="TEMPLATE_NOT_FOUND";function gr(r){return new Error(`Template "${r}" not found.`)}function pd(r){let e=r.Id;if(typeof e!="string"||!Pn.test(e))return[];let t=Object.keys(r).filter(n=>n!=="Id");return t.length>0?[{id:e,fields:t,digest:nr(r,t)}]:[]}var fd="COUNT_FAILED",jn="SNAPSHOT_NOT_TAKEN",hr=new Set(["QUERY_TIMEOUT","OPERATION_TOO_LARGE"]),md=/^([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+):/;function ds(r){if(typeof r=="object"&&r!==null){let{errorCode:e,code:t}=r;if(typeof e=="string"&&e!=="")return e;if(typeof t=="string"&&t!=="")return t}return md.exec(v(r))?.[1]??"UNKNOWN"}var vo=5;function To(r){return r==null?null:typeof r=="string"||typeof r=="number"||typeof r=="boolean"?r:JSON.stringify(r)}function _o(r){return r.done?0:Math.max(0,r.total-r.masked-r.nothingToMask-r.refused-r.unanswered-(r.deletedSince??0))}function ps(r){return r.refused+r.unanswered+_o(r)+(r.late??0)}function tn(r){return r.reduce((e,t)=>({recordsProcessed:e.recordsProcessed+t.masked+t.nothingToMask,recordsFailed:e.recordsFailed+t.refused,recordsNotMasked:e.recordsNotMasked+ps(t)}),{recordsProcessed:0,recordsFailed:0,recordsNotMasked:0})}function gd(r,e){let{recordsProcessed:t,recordsFailed:n,recordsNotMasked:s}=tn(r);return s===0?"success":t>0||e&&n===0?"partial":"failure"}function hd(r,e,t){if(!t||e==="success")return{outcome:e};let{recordsProcessed:n,recordsFailed:s}=tn(r);return n+s>0?{outcome:"cancelled"}:{outcome:"stopped",code:js}}function No(r){return r.filter(e=>ps(e)>0).map(e=>`${e.objectApiName} ${ps(e)}`).join(", ")}function $o(r){return r.map(e=>({objectApiName:e.objectApiName,total:e.total,processed:e.masked+e.nothingToMask,failed:e.refused,notMasked:ps(e)}))}function Po(r){return r.filter(e=>e.total>0||e.masked+e.refused>0).map(e=>{let t=_o(e);return{...Bn(e.objectApiName),updated:e.masked,failed:e.refused+e.unanswered,...e.unanswered>0?{mayHaveBeenWritten:e.unanswered}:{},...t>0?{notSent:t}:{}}})}async function Mo(r,e,t,n,s,i){return si(r,`SELECT ${t} FROM ${e}${ls(i,s)} ORDER BY Id LIMIT ${n}`,n)}function ls(r,e){let t=r?.trim(),n=[...t?[`(${dn(t)})`]:[],...e===void 0?[]:[`Id > '${e}'`]];return n.length===0?"":` WHERE ${n.join(" AND ")}`}function us(r){let e=r.where?.trim();return e||void 0}function bd(r){let e=r?.trim();return e?`(${dn(e)}) AND ${br}`:br}function yd(r){let e=new Map;for(let[t,n]of r){if(n.length===0)throw new Error(`No field of ${t} was named for the snapshot to read.`);e.set(t,n.map(s=>tt(s)).join(", "))}return e}function Co(r,e,t){let n=e===void 0?"more records":`${e} records`;return new nn(`${r} holds ${n}, past the ${t} a snapshot reads of one object: no snapshot was kept, as one holding part of the object would be taken for all of it.`,!1)}function Wo(r,e){return`The org stopped answering the read of ${r} after ${e} record(s), before it said the read was done: no snapshot was kept.`}async function kd(r,e,t,n){let s={headers:{},maxFetch:1e4,autoFetch:!1,scanAll:t,responseTarget:"QueryResult"},i=await r.query(e,s),o=[...i.records];for(;!i.done;){if(!i.nextRecordsUrl)throw new nn(Wo(n,o.length),!0);i=await r.queryMore(i.nextRecordsUrl,s),o.push(...i.records)}return o}function wd(r,e,t){let n=r[r.length-1]?.Id;if(typeof n!="string"||!Pn.test(n)||n===e)throw new Error(`The org answered a page of ${t} that does not end past the page before it: masking stopped there rather than write the same rows again.`);return n}function Ad(r){let e=r?.[0];return e?.statusCode==="ENTITY_IS_DELETED"||e?.errorCode==="ENTITY_IS_DELETED"}function cs(r){return r.slices.filter(e=>!e.late&&e.state!=="pending"&&e.lastId!==void 0).at(-1)?.lastId}function Rd(r){return r.slices.reduce((e,t)=>{let n=t.state==="masking"?Math.max(0,t.rows-t.masked-t.nothingToMask-t.refused-t.deletedSince-(t.unanswered??0)):0;return e+n+t.refused+(t.lateLeft??0)},0)}var Eo=100,xo=3;function zo(r){return`_refused_${r}`}var Lo=class{constructor(e,t){this.deps=e;this.saveDialog=t??new os}deps;activeOrgOperations=new Set;writing=new ji;dmlTracker=new es;backupRecords;syncRuns;expiryListener;sweeping;liveTracker;backupsWriting=new Set;maskingKey=Qa(32).toString("hex");runKeys;freeBytes=async()=>{let e=this.backupRecords?.directory;if(e!==void 0)for(let t of[e,Do.dirname(e)])try{let n=await Ya(t);return Number(n.bavail)*Number(n.bsize)}catch{}};sliceRunsOn=new Map;saveDialog;get savedTemplates(){return new rs(this.deps.configStore)}findTemplate(e){return e===zt.id?zt:Qt.find(t=>t.id===e)??this.savedTemplates.load(e)??this.heldTemplates.get(e)}automaticPlansKept;get automaticPlans(){return this.automaticPlansKept??=new Jn({reads:async e=>{let t=await Ue(e,this.deps.orgRegistry,this.deps.orgManager);return{session:Os(t,"dataops:anonymize"),tooling:Is(t)}},detector:()=>this.deps.infraServices?.piiDetector??new Ss,shippedObjects:Xs(Qt),keptRules:e=>new ut(this.deps.configStore).keptRules(e,zt.id)}),this.automaticPlansKept}async automaticTemplateOf(e,t,n){let s=this.automaticPlans.frozen(e);return s&&(t===void 0||t.every(i=>s.plan.objects.some(o=>Nn(o,i))))?s:this.automaticPlans.plan(e,t,n)}heldTemplates=new Map;holdTemplate(e){this.heldTemplates.set(e.id,e)}ruleConfig(e,t=this.maskingKey){let n={...e.config};return e.ruleType==="hash"&&(n.hashSalt=t),n}maskingRules(e,t,n=this.maskingKey){return t.map(s=>({objectApiName:e,fieldApiName:s.fieldPattern.includes(".")?s.fieldPattern.split(".")[1]:s.fieldPattern,method:s.ruleType,config:this.ruleConfig(s,n)}))}refuseUnknownTemplate(e,t,n){J(this.deps,e,"dataops:error",t,gr(n),{code:jo})}setLiveOperationTracker(e){this.liveTracker=e}setSyncRuns(e){this.syncRuns=e}setRunKeyStore(e){this.runKeys=e}setFreeBytes(e){this.freeBytes=e}get sliceSets(){return new wi(this.deps.configStore)}busyMessage(e,t){let n=this.sliceRunsOn.get(e);if(n===void 0)return t;let s=this.onCommandLine?"the same line with --resume masks the rest, and --abandon gives the set up":"Resume masks the rest, and Abandon gives the set up";return`A masking run in slices (set ${n}) writes to org ${e} now, and holds its backups and restores until it ends: wait for it, or stop it; once stopped, ${s}.`}targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;muteLeases={};setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}setMuteOffered(e){this.muteOffered=e}muteOffered=!0;setOnCommandLine(e){this.onCommandLine=e}onCommandLine=!1;countGaveUp(e,t){if(!hr.has(ds(e)))return e;let n=this.onCommandLine?"give --slices, which reads the object a slice at a time by Id and plans on the org's own figure when no count comes, or narrow --where to an indexed field, such as a range of CreatedDate":`mask in slices, which reads the object a slice at a time by Id and plans on the org's own figure when no count comes, or narrow the run from the command line with sandforge dataops anonymize --object ${t} --where on an indexed field, such as a range of CreatedDate`;return new Error(`${v(e)} The org gave up counting the ${t} records the run would mask: ${n}. Nothing was masked.`)}duplicatesSettleMs=Ti;setDuplicatesSettle(e){this.duplicatesSettleMs=e}duplicatesWatchOf(e,t){return Ni({query:async n=>e.query(n),serverTime:async()=>(await e.soap.getServerTimestamp()).timestamp},t,{settleMs:this.duplicatesSettleMs})}ownReader(){return this.reader??=import("./chunk-UK3QLBHW.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(n=>Ue(n,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}orgNameOf(e){return Ht(this.deps.orgManager.getOrg(e),e)}readAct(e,t,n,s,i,o){let a=this.targetAutomation;return Ci({act:n,target:this.orgNameOf(t),objects:s,org:Mi(e,d=>new $i(Ja).withTimeout("dataops automation",()=>a.read(t,d)),ys(this.deps.orgManager.getOrg(t))==="production"),accord:i,mayMute:this.muteOffered,muteLeases:this.muteLeases,...o?{voice:o}:{}})}async releaseMute(e,t){if(!e)return;let n=await e.release();for(let s of Pi(n,this.orgNameOf(t)))this.deps.log(`[INFO] ${s}`);return n}async handleAutomation(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=qe(ui,e,"dataops:error",this.deps);if(t)try{let n=await Ue(t.orgId,this.deps.orgRegistry,this.deps.orgManager),s=await this.readAct(n,t.orgId,t.act,t.objects,t,bn(t)),i=Ee(this.deps,e,"dataops:automation:response",{...s.answer});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} refusals=${s.answer.refusals.length}`)}catch(n){J(this.deps,"dataops:automation","dataops:error",e,n)}}setExpiryListener(e){this.expiryListener=e}setBackupRecordStore(e){this.backupRecords=e,this.sweeping=this.sweepBackupFiles()}swept(){return this.sweeping??Promise.resolve()}async sweepBackupFiles(e=Date.now()){await this.expireBackups(e);let t=this.backupRecords;if(t)try{let n=new Set(this.backupsWriting);for(let i of this.deps.configStore.getKeysByPrefix("backup:"))n.add(i.slice(7).split(":")[0]);let s=await t.sweep(n,ad,e);s.length>0&&this.deps.log(`[INFO] Removed ${s.length} backup file(s) whose backup never saved its metadata: `+s.join(", "))}catch(n){this.deps.log("[WARN] the files of backups that never saved their metadata were not removed: "+v(n))}}isWritingTo(e){return this.writing.has(e)}async handle(e){if(!Za.has(e.type))return!1;switch(e.type){case"backup:execute":return await this.handleBackup(e),!0;case"backup:list":return this.handleBackupList(e),!0;case"backup:objects":return await this.handleBackupObjects(e),!0;case"backup:export":return await this.handleBackupExport(e),!0;case"backup:delete":return await this.handleBackupDelete(e),!0;case"dataops:rollback":return await this.writing.during(Ms(e,"orgId"),()=>this.handleRollback(e)),!0;case"dataops:anonymize":return await this.writing.during(Ms(e,"orgId"),()=>this.handleAnonymize(e)),!0;case"dataops:anonymization-templates":return this.handleAnonymizationTemplates(e),!0;case"dataops:anonymization-template:save":return this.handleTemplateSave(e),!0;case"dataops:anonymization-template:delete":return this.handleTemplateDelete(e),!0;case"dataops:anonymize:coverage":return await this.handleAnonymizeCoverage(e),!0;case"dataops:anonymize:preview":return await this.handleAnonymizePreview(e),!0;case"dataops:automation":return await this.handleAutomation(e),!0;case"precheck:pii-scan":return await this.handlePIIScan(e),!0;default:return!1}}async selectAllFields(e,t,n){let s=await e.describe(t),i=s.fields.filter(d=>d.type===Ii).map(d=>d.name),o=i.length>0&&n&&!await n()?i:[];return{select:s.fields.filter(d=>!o.includes(d.name)).map(d=>d.name).join(", "),notKept:o}}async maskedFields(e,t,n,s=[]){let i=(await e.describe(t)).fields,o=new Map(i.map(p=>[p.name.toLowerCase(),p.name])),a=[],d=[];for(let p of n){let m=o.get(p.fieldApiName.toLowerCase());m!==void 0?a.push({...p,fieldApiName:m}):p.fieldApiName!=="*"&&!d.includes(p.fieldApiName)&&d.push(p.fieldApiName)}let c=zi({objectApiName:t,fields:i,kept:a,derived:s,detector:this.deps.infraServices?.piiDetector??new Ss});if(c&&c.unseen.length>0){let p=await e.describe(cn).then(m=>m.fields,()=>{});for(let m of Li(c.unseen,p))d.includes(m)||d.push(m)}let l=c?[...a,...c.rules]:a,u=l.map(p=>p.fieldApiName).filter((p,m,y)=>p!=="Id"&&y.indexOf(p)===m),f=c&&u.length>0&&!u.includes(St);return{rules:l,select:["Id",...u,...f?[St]:[]].join(", "),missing:d,rulesOf:c?p=>Bi(t,p,l,c.personOnly):()=>l}}async countRows(e,t,n,s){let o=(await e.query(`SELECT COUNT() FROM ${t}${ls(s,n)}`)).totalSize;if(typeof o!="number"||!Number.isInteger(o)||o<0)throw new Error(`The org did not say how many records ${t} holds.`);return o}async organizationIdOf(e){try{let n=(await Gt(e,"SELECT Id FROM Organization"))[0]?.Id;return typeof n=="string"&&td.test(n)?n:void 0}catch(t){this.deps.log(`[WARN] dataops: the org did not say which org it is: ${v(t)}`);return}}async handleBackup(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=qe(ii,e,"dataops:error",this.deps);if(!t)return;let n=e.id,s=new Map;for(let[a,d]of Object.entries(t.wheres??{})){let c=t.objects.find(l=>Nn(l,a));c!==void 0&&d.trim()!==""&&s.set(Be(c),d.trim())}if(t.slices===!0){await this.backupInSlices(e,{orgId:t.orgId,objects:t.objects,wheres:s});return}let i=await this.takeBackup(n,{orgId:t.orgId,objects:t.objects,...s.size>0?{wheres:s}:{}},e.type);if("error"in i){J(this.deps,"backup:execute","dataops:error",e,i.error),this.endBackupNotTaken(n,i);return}let o=Ee(this.deps,e,"dataops:backup:response",{operationId:n,status:"completed",objects:i.objects.map(pr),totalRecords:i.totalRecords,...i.partial?{partial:!0}:{},timestamp:i.timestamp});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}async backupInSlices(e,t){let n=e.id,s={module:"dataops",operation:e.type},i=(f,p)=>{J(this.deps,"backup:execute","dataops:error",e,new Error(p),{...f?{code:f}:{}}),he(this.deps,n,p,!1,{context:s,authored:!0})};if(!this.backupRecords){i(Fe.needsStore,"A backup in slices writes each slice to the backup files, and this host keeps none.");return}let o=`backup:${t.orgId}`;if(this.activeOrgOperations.has(o)){i(void 0,this.busyMessage(t.orgId,`A backup or rollback operation is already running for org ${t.orgId}. Please wait for it to complete.`));return}this.activeOrgOperations.add(o);let a=new AbortController,d=()=>{},c,l,u=`Backup ${t.objects.length} object(s) in slices`;try{let f=await Ue(t.orgId,this.deps.orgRegistry,this.deps.orgManager);pn(this.deps,n,"dataops",u),this.deps.infraServices?.backgroundRegistry?.register(n,"dataops",u,new Promise((N,w)=>{d=P=>{P===void 0?N():w(P instanceof Error?P:new Error(String(P)))}}),a),c=Rn(this.liveTracker,n,"dataops",u,t.objects.length);let p=0,m=new Date().toISOString(),y=await this.organizationIdOf(f),k={setId:n,kind:"backup",orgId:t.orgId,...y!==void 0?{organizationId:y}:{},size:this.backupCap(),state:"open",startedAt:m,lastActivityAt:m,requestsSpent:0,objects:t.objects.map(N=>{let w=Be(N),P=t.wheres.get(w);return{objectApiName:w,...P?{where:P}:{},done:!1,slices:[]}})},T=this.sliceSets,g=()=>{k.lastActivityAt=new Date().toISOString(),k.requestsSpent=p,T.save(k)};g();let A,S=!1;e:for(let N of k.objects)for(s.objectName=N.objectApiName;;){if(a.signal.aborted){S=!0;break e}let w=N.slices.filter(Te=>!Te.late);if(w.length>=It){A=`${N.objectApiName} holds more rows than ${It} slices of ${k.size} do: the backup stopped there.`;break e}let P=Ns(k),K=cs(N),H={index:P,...K!==void 0?{afterId:K}:{},rows:0,snapshotId:Ts(k.setId,P),state:"pending",masked:0,refused:0,deletedSince:0,nothingToMask:0,sizeUsed:w.at(-1)?.sizeUsed??k.size};N.slices.push(H),g();let Y=await this.snapshotSlice(f,t.orgId,k,N,H,{bounds:K!==void 0?{afterId:K}:{},stop:a.signal,onRequest:()=>{p++},origin:e.type,clock:!1});if("failed"in Y){N.slices=N.slices.filter(Te=>Te!==H),g(),Y.cancelled?S=!0:A=this.sliceNotTakenMessage(N.objectApiName,Y);break e}if(Y.lastId===void 0){await this.removeBackup(`backup:${H.snapshotId}`),N.slices=N.slices.filter(Te=>Te!==H),N.done=!0,g();break}H.rows=Y.rows,H.lastId=Y.lastId,H.sizeUsed=Y.sizeUsed,H.takenAt=new Date().toISOString(),H.state="snapshotted",g();let ae=`Backed up ${N.objectApiName} slice ${P} (${Y.rows} records)`;Kt(this.deps,n,0,P,P,ae),c.progress(0,P,P,ae)}k.objects.every(N=>N.done)&&(k.state="done"),g();let b=k.objects.map(N=>({objectApiName:N.objectApiName,recordCount:N.slices.reduce((w,P)=>w+P.rows,0),truncated:!N.done,...N.done?{}:{stoppedAt:"failure"},...N.where?{where:N.where}:{}})),$=b.reduce((N,w)=>N+w.recordCount,0),I=k.state!=="done";S?(this.deps.infraServices?.backgroundRegistry?.abort(n),dt(this.deps,n,{aborted:!0,totalRecords:$}),c.cancel()):(dt(this.deps,n,{objects:b.map(N=>({objectApiName:N.objectApiName,recordCount:N.recordCount})),totalRecords:$,...I?{status:"partial"}:{}}),I?c.partial():c.complete()),A&&this.deps.log(`[WARN] backup ${n}: ${A}`);let L=Ee(this.deps,e,"dataops:backup:response",{operationId:n,status:I?"partial":"completed",objects:b,totalRecords:$,...I?{partial:!0}:{},timestamp:k.lastActivityAt,slices:gn(k,{requestsSpent:p})});this.deps.broker.postToWebview(L),this.deps.log(`[TX] ${L.type} id=${L.id} slices=${xt(k).length}`),(A||S)&&Fn(this.deps,"warning","Backup",`${S?"The backup in slices was cancelled":A}: set ${k.setId} holds ${$} record(s) in ${xt(k).length} slice(s), listed as partial.`)}catch(f){l=f,J(this.deps,"backup:execute","dataops:error",e,f),he(this.deps,n,v(f),!0,{context:s}),c?.fail(v(f))}finally{this.activeOrgOperations.delete(o),d(l)}}restoreOfSet(e,t){let n=t===void 0?e.operationId:t.origin==="slice"?t.setId:void 0;if(n===void 0)return e.slices?{refused:{code:"NOT_A_SLICE_SET",message:`Backup ${e.operationId} holds no slices: restore it whole, without naming a slice.`}}:{};let s=this.sliceSets.get(n);if(!s||s.orgId!==e.orgId)return{};if(s.kind==="masking"&&s.state==="open"){let p=this.sliceWays(this.onCommandLine?void 0:"page");return{refused:{code:Fe.runOpen,message:`Set ${s.setId} is still open: its masking run stopped part way, and resumed it would mask again over what a restore puts back. Give it up first (${p.abandon}), then restore it; or resume it to its end (${p.resume}). Nothing was written.`}}}let i=e.slices??(t?.slice?[t.slice.index]:void 0),o=s.objects.flatMap(p=>p.slices.filter(m=>m.state!=="pending").map(m=>({objectApiName:p.objectApiName,slice:m})));o.sort((p,m)=>p.slice.index-m.slice.index);let a=(i??[]).filter(p=>!o.some(m=>m.slice.index===p));if(a.length>0)return{refused:{code:"SLICE_NOT_FOUND",message:`Set ${s.setId} holds no slice ${a.join(", ")}: its slices are ${o.map(p=>p.slice.index).join(", ")||"none"}. Nothing was written.`}};let d=i?o.filter(p=>i.includes(p.slice.index)):o,c=p=>i!==void 0||e.rewriteAll===!0||p.slice.restoredAt===void 0,l=d.filter(c).map(p=>({snapshotId:p.slice.snapshotId,objectApiName:p.objectApiName,recordCount:p.slice.rows,slice:p.slice})),u=d.filter(p=>!c(p)).map(p=>({index:p.slice.index,objectApiName:p.objectApiName,restored:0,failed:0,unchanged:0,skipped:!0}));if(l.length===0&&u.length>0){let p=u.map(y=>o.find(k=>k.slice.index===y.index)?.slice.restoredAt??"").sort().at(-1),m=this.onCommandLine?"--rewrite-all":"Write every row back";return{refused:{code:"NOTHING_TO_RESTORE",message:`Every slice of set ${s.setId} was restored already (the last on ${p}): nothing was written. ${m} restores them again.`}}}let f=s.objects.map(p=>({objectApiName:p.objectApiName,recordCount:l.filter(m=>m.objectApiName===p.objectApiName).reduce((m,y)=>m+y.recordCount,0)})).filter(p=>l.some(m=>m.objectApiName===p.objectApiName));return{set:s,meta:{orgId:s.orgId,...s.organizationId!==void 0?{organizationId:s.organizationId}:{},timestamp:s.startedAt,totalRecords:f.reduce((p,m)=>p+m.recordCount,0),objects:f},parts:l,skipped:u}}async backupForPipeline(e,t){let n=e.fields?yd(e.fields):void 0,s=await this.takeBackup(e.operationId,{orgId:e.orgId,objects:e.objects,...n?{fields:n}:{},...e.scanAll?{scanAll:new Set(e.scanAll)}:{},...e.origin?{origin:e.origin}:{},...e.failWhenTruncated===!0?{failWhenTruncated:!0}:{},...e.onConnection?{onConnection:e.onConnection}:{}},e.origin==="checkpoint"?"checkpoint:take":"pipeline:execute",t);if("error"in s){let i=v(s.error);throw this.endBackupNotTaken(e.operationId,s),s.cancelled?new Un(i):s.error instanceof Error?s.error:new Error(i)}return s}endBackupNotTaken(e,t){if(t.cancelled){dt(this.deps,e,{aborted:!0});return}he(this.deps,e,v(t.error),t.retryable,{context:t.context})}async takeBackup(e,t,n,s){let i={module:"dataops",operation:n},o=t.slice,a=`backup:${t.orgId}`;if(!o&&this.activeOrgOperations.has(a)){let A=`A backup or rollback operation is already running for org ${t.orgId}. Please wait for it to complete.`;return this.deps.log(`[WARN] ${A}`),{error:new Error(this.busyMessage(t.orgId,A)),retryable:!1,context:i}}o||this.activeOrgOperations.add(a);let d=()=>{},c,l=new AbortController,u=()=>l.abort();s?.aborted&&l.abort(),s?.addEventListener("abort",u,{once:!0});let f=this.backupCap(),p=this.backupWriter(e);this.backupsWriting.add(e);let m=[],y,k,T,g=(A,S,b,$)=>{o||(Kt(this.deps,e,A,S,b,$),T?.progress(A,S,b,$))};try{if(!o&&this.dmlTracker.isDuplicate(e))return this.deps.log(`[WARN] Duplicate backup operation detected: ${e}`),{error:new Error(`Duplicate operation: ${e}`),retryable:!1,context:i};o||this.dmlTracker.register(e,"backup","insert",t.objects.length);let A=await Ue(t.orgId,this.deps.orgRegistry,this.deps.orgManager);k=A,t.onConnection?.(A);let S=Si(async P=>(await A.query(P)).records),b=this.deps.orgManager.getOrg(t.orgId),$=Gn(b?.orgType==="Sandbox"||b?.orgType==="Scratch"),I=qn($).defaultQueryLimit,L=`Backup ${t.objects.length} object(s)`;o||(pn(this.deps,e,"dataops",L),this.deps.infraServices?.backgroundRegistry?.register(e,"dataops",L,new Promise((P,K)=>{d=H=>{H===void 0?P():K(H instanceof Error?H:new Error(String(H)))}}),l),T=Rn(this.liveTracker,e,"dataops",L,t.objects.length));for(let P of t.objects){if(l.signal.aborted)throw new Dt;let K=Be(P);i.objectName=K;let H=t.wheres?.get(K),Y={objectApiName:P,recordCount:0,truncated:!1,...H!==void 0?{where:H}:{}};y=Y,await this.readIntoBackup(A,K,Y,p,{pageSize:I,cap:o?.size??f,select:t.fields?.get(K),where:H,scanAll:t.scanAll?.has(K)===!0,...t.origin==="checkpoint"?{stamp:rd}:{},whole:t.failWhenTruncated===!0||o!==void 0,viewsEncrypted:S,...o?{slice:{bounds:o.bounds,size:o.size,...o.skip?{skip:o.skip}:{}},onRequest:o.onRequest}:{}},l.signal,()=>{let ae=Math.max(1,Math.min(Y.orgCount??f,f));g(Math.round((m.length+Y.recordCount/ae)/t.objects.length*100),m.length,t.objects.length,`Reading ${P} (${Y.recordCount} of ${ae} records)`)}),y=void 0,m.push(Y),Y.stoppedAt==="cap"&&this.deps.log(`[WARN] backup of ${K} stopped at the cap of ${f} record(s): the object holds ${Y.orgCount??"more"}.`),g(Math.round(m.length/t.objects.length*100),m.length,t.objects.length,`Exported ${P} (${Y.recordCount} records)`)}let N=o?void 0:await this.organizationIdOf(A);if(l.signal.aborted)throw new Dt;let w=this.saveBackupMeta({operationId:e,orgId:t.orgId,organizationId:N,cap:o?.size??f,...t.origin?{origin:t.origin}:{},...o?{origin:"slice",setId:o.setId,slice:{index:o.index,...o.bounds.afterId!==void 0?{afterId:o.bounds.afterId}:{},...m[0]?.lastId!==void 0?{lastId:m[0].lastId}:{},size:o.size}}:{}},m,p,!1);return o?{operationId:e,objects:m,totalRecords:w.totalRecords,partial:!1,timestamp:w.timestamp}:(this.pruneAfterBackup(t.orgId),dt(this.deps,e,{objects:m.map(P=>({objectApiName:P.objectApiName,recordCount:P.recordCount})),totalRecords:w.totalRecords,...w.partial?{status:"partial"}:{}}),this.dmlTracker.markCompleted(e),w.partial?T?.partial():T?.complete(),{operationId:e,objects:m,totalRecords:w.totalRecords,partial:w.partial,timestamp:w.timestamp})}catch(A){o||this.dmlTracker.markFailed(e);let S=A instanceof Dt,b=S||A instanceof Tn||t.failWhenTruncated===!0||o!==void 0?void 0:await this.keepFailedBackup({operationId:e,orgId:t.orgId,cap:f,...t.origin?{origin:t.origin}:{}},k,{taken:m,reading:y,planned:t.objects},p);b===void 0&&await p.discard().catch(L=>{this.deps.log(`[WARN] backup ${e}: what it wrote before it stopped was not removed: `+v(L))});let $=b===void 0?A:new Error(`${v(A)} \u2014 the backup keeps the ${b.totalRecords} record(s) read before it stopped, listed as partial: ${fr(b.objects)}.`);c=$,S&&!o&&this.deps.infraServices?.backgroundRegistry?.abort(e),S?T?.cancel():T?.fail(v($));let I=!(A instanceof nn)||A.retryable;return{error:$,retryable:I,context:i,cancelled:S}}finally{s?.removeEventListener("abort",u),d(c),o||this.activeOrgOperations.delete(a),this.backupsWriting.delete(e)}}backupCap(){return od(this.deps.services?.getSandforgeSetting?.("backup.maxRecordsPerObject",Fo))}snapshotCapWay(e,t){let n=this.backupCap(),s=e.filter(d=>d.tally.total>n),i=s.length>0?s.map(d=>d.tally.objectApiName).join(", "):"the object",o=s.reduce((d,c)=>Math.max(d,Qn(c.tally.total,n)),1),a=n<vn&&s.every(d=>d.tally.total<=vn);return t==="step"?`A pipeline's step masks no slices: mask ${i} from the DataOps panel, in slices each backed up just before it is masked, or with sandforge dataops anonymize --slices.`:t===void 0&&this.onCommandLine?`Give --slices to mask ${i} in ${o} slices, each with its own snapshot (the same line with --dry-run shows the plan)`+(a?`, --max-records up to ${vn} (this run held ${n})`:"")+", or narrow the run with --where.":`Tick "Mask in slices" in the confirmation: ${i} is then masked in ${o} slices, each backed up just before it is masked`+(a?`; or raise sandforge.backup.maxRecordsPerObject in Settings (this run held ${n}, 1,000,000 at most)`:"")+"."}backupWriter(e){let t=this.backupRecords;if(t){let s=new Set;return{begin:async i=>{s.add(i),await t.begin(e,i).catch(o=>{throw new Tn(o)})},append:async(i,o)=>{await t.append(e,i,o).catch(a=>{throw new Tn(a)})},keep:()=>{},discard:async()=>{for(let i of s)await t.delete(e,i)}}}let n=new Map;return{begin:async s=>{n.set(s,[])},append:async(s,i)=>{n.get(s)?.push(...i)},keep:()=>{for(let[s,i]of n)this.deps.configStore.set(`backup:${e}:${s}`,i,"backups")},discard:async()=>{n.clear()}}}async readIntoBackup(e,t,n,s,i,o,a){let d=i.scanAll===!0,c=()=>i.onRequest?.(),l={headers:{"Sforce-Query-Options":`batchSize=${i.pageSize}`},maxFetch:1e4,autoFetch:!1,scanAll:d,responseTarget:"QueryResult"},u=i.select;if(u===void 0){let A=await this.selectAllFields(e,t,i.viewsEncrypted);u=A.select,A.notKept.length>0&&(n.notKept=A.notKept)}let f=d?bd(i.where):i.where,p=i.slice,m=p?wo(t,u,f,p.bounds,p.size):`SELECT ${u} FROM ${t}${ls(f,void 0)}`,y=i.stamp??Br(m)?.stamp,k=Fr(m,y===void 0?void 0:["Id",y]),T=d||i.whole===!0?A=>(c(),kd(e,A,d,t)):A=>(c(),Gt(e,A)),g=await e.query(k?.first??m,l);if(c(),mt(e.limitInfo,`dataops:backup query ${t}`),!p&&typeof g.totalSize=="number"&&Number.isInteger(g.totalSize)&&(n.orgCount=g.totalSize),!p&&i.whole===!0&&n.orgCount!==void 0&&n.orgCount>i.cap)throw Co(t,n.orgCount,i.cap);for(await s.begin(n.objectApiName);;){let A=i.cap-n.recordCount,S=g.records.length>A,b=S?g.records.slice(0,A):g.records,$=b;k&&y!==void 0?$=await Wr(b,k,T,{stamp:y,...d?{idsWhere:br}:{}}):k&&await _r(b,k,T);let I=g.done?void 0:g.nextRecordsUrl;if(i.whole===!0&&!g.done&&I===void 0)throw new nn(Wo(t,n.recordCount+$.length),!0);let L=S||I!==void 0&&n.recordCount+$.length>=i.cap;if(p){let N=$.at(-1)?.Id;typeof N=="string"&&(n.lastId=N);let w=p.skip?$.filter(P=>!p.skip?.(P)):$;if(await s.append(n.objectApiName,w),n.recordCount+=w.length,n.readCount=(n.readCount??0)+$.length,L||I===void 0)return;if(a(),o.aborted)throw new Dt;g=await e.queryMore(I,l),c(),mt(e.limitInfo,`dataops:backup query ${t}`);continue}if(L&&i.whole===!0)throw Co(t,n.orgCount,i.cap);if(await s.append(n.objectApiName,$),n.recordCount+=$.length,L){n.truncated=!0,n.stoppedAt="cap";return}if(I===void 0)return;if(a(),o.aborted)throw new Dt;g=await e.queryMore(I,l),c(),mt(e.limitInfo,`dataops:backup query ${t}`)}}saveBackupMeta(e,t,n,s){let i={operationId:e.operationId,orgId:e.orgId,...e.organizationId!==void 0?{organizationId:e.organizationId}:{},...e.origin!==void 0?{origin:e.origin}:{},...e.setId!==void 0?{setId:e.setId}:{},...e.slice!==void 0?{slice:e.slice}:{},objects:t.map(pr),partial:t.some(o=>o.truncated),...s?{status:"failed"}:{},cap:e.cap,timestamp:new Date().toISOString(),totalRecords:t.reduce((o,a)=>o+a.recordCount,0)};return this.deps.configStore.set(`backup:${e.operationId}`,i,"backups"),n.keep(),i}async keepFailedBackup(e,t,n,s){let{taken:i,reading:o}=n,a=o?[...i,{...o,truncated:!0,stoppedAt:"failure"}]:[...i],d=new Set(a.map(u=>u.objectApiName.toLowerCase())),c=n.planned.filter(u=>!d.has(u.toLowerCase())).map(u=>({objectApiName:u,recordCount:0,truncated:!0,stoppedAt:"not_reached"})),l=[...a,...c];if(!l.every(u=>u.recordCount===0))try{let u=t?await this.organizationIdOf(t):void 0,f=this.saveBackupMeta({...e,organizationId:u},l,s,!0);return this.pruneAfterBackup(e.orgId),{...f,objects:l}}catch(u){this.deps.log(`[WARN] backup ${e.operationId}: the rows read before it failed were not kept: `+v(u));try{this.deps.configStore.delete(`backup:${e.operationId}`)}catch{}return}}async expireBackups(e){let t=vi(this.deps.services);if(t<=0)return;let n=e-t*dd;try{let s=this.retentionSince(e);for(let i of this.backupMetaKeys()){let o=this.deps.configStore.get(i),a=Date.parse(o?.timestamp??"");if(!Number.isFinite(a)||a>=n||a<s||o?.origin==="checkpoint"||o?.origin==="slice"||o?.orgId!==void 0&&this.backupBusy(o.orgId))continue;await this.removeBackup(i);let d=o?.origin==="sync"?` \u2014 the values the Sync run ${o.runId??"(unknown)"} wrote over, which removing that run no longer puts back`:"";this.deps.log(`[INFO] Removed backup ${i}: taken more than ${t} day(s) ago${d}`),this.expiryListener?.({operationId:i.slice(7),days:t,...o?.timestamp!==void 0?{takenAt:o.timestamp}:{},...o?.origin==="sync"?{syncRunId:o.runId??""}:{}})}for(let i of this.sliceSets.list()){let o=Date.parse(i.lastActivityAt);!Number.isFinite(o)||o>=n||o<s||this.backupBusy(i.orgId)||(await this.removeSliceSet(i),this.deps.log(`[INFO] Removed set of slices ${i.setId}: last moved more than ${t} day(s) ago`+(i.state==="open"?", its run left open and now over":"")),this.expiryListener?.({operationId:i.setId,days:t,takenAt:i.startedAt}))}}catch(s){this.deps.log(`[WARN] the backups past their age were not removed: ${v(s)}`)}}async removeSliceSet(e){for(let t of e.objects)for(let n of t.slices)await this.removeBackup(`backup:${n.snapshotId}`),await this.backupRecords?.delete(n.snapshotId,zo(t.objectApiName));this.sliceSets.delete(e.setId),e.kind==="masking"&&e.state==="open"&&e.templateId!==void 0&&new ut(this.deps.configStore).clear(e.orgId,e.templateId),await this.runKeys?.delete(e.setId).catch(t=>{this.deps.log(`[WARN] the key of set ${e.setId} was not removed: ${v(t)}`)})}retentionSince(e){let t=Date.parse(this.deps.configStore.get(Io)??"");return Number.isFinite(t)?t:(this.deps.configStore.set(Io,new Date(e).toISOString()),e)}backupMetaKeys(){return this.deps.configStore.getKeysByPrefix("backup:").filter(e=>!e.slice(7).includes(":"))}backupBusy(e){return this.activeOrgOperations.has(`backup:${e}`)}async removeBackup(e){let n=this.deps.configStore.get(e)?.objects??[];for(let i of n)this.deps.configStore.delete(`${e}:${i.objectApiName}`);this.deps.configStore.delete(e);let s=e.slice(7);for(let i of n)await this.backupRecords?.delete(s,i.objectApiName)}async handleBackupDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=qe(ci,e,"dataops:error",this.deps);if(!t)return;if(this.backupBusy(t.orgId)){J(this.deps,"backup:delete","dataops:error",e,new Error(this.busyMessage(t.orgId,`A backup or rollback operation is already running for org ${t.orgId}. Delete its backups once it has ended.`)),{code:ar});return}let n=t.operationIds?new Set(t.operationIds):void 0;for(let o of n??[]){let a=this.deps.configStore.get(`backup:${o}`);if(!(a?.origin!=="slice"||a.orgId!==t.orgId)){J(this.deps,"backup:delete","dataops:error",e,new Error(`Backup ${o} is slice ${a.slice?.index??"?"} of set ${a.setId??"?"}: a slice is deleted with its set, which holds the way back of every slice. Delete set ${a.setId??"?"} to delete it. Nothing was deleted.`),{code:Fe.deleteAlone});return}}let s=[];try{for(let o of this.backupMetaKeys()){let a=this.deps.configStore.get(o);if(a?.orgId!==t.orgId||a.origin==="slice")continue;let d=a.operationId??o.slice(7);n&&!n.has(d)||(await this.removeBackup(o),s.push(d))}for(let o of this.sliceSets.list(t.orgId))n&&!n.has(o.setId)||(await this.removeSliceSet(o),s.push(o.setId))}catch(o){J(this.deps,"backup:delete","dataops:error",e,o);return}this.deps.log(`[INFO] Deleted ${s.length} backup(s) of org ${t.orgId}`);let i=Ee(this.deps,e,"backup:delete:result",{orgId:t.orgId,deleted:s});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} deleted=${s.length}`)}pruneAfterBackup(e){try{this.pruneBackups(e)}catch(t){this.deps.log(`[WARN] backup retention failed after the snapshot was written: ${v(t)}`)}this.sweepBackupFiles()}handleBackupList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=qe(oi,e,"dataops:error",this.deps);if(!t)return;let n=[];for(let o of this.deps.configStore.getKeysByPrefix("backup:")){if(o.slice(7).includes(":"))continue;let a=this.deps.configStore.get(o);!a||a.orgId!==t.orgId||a.origin!=="slice"&&n.push({operationId:a.operationId??o.slice(7),orgId:a.orgId,timestamp:a.timestamp??"",totalRecords:a.totalRecords??0,totalSize:0,status:a.status==="failed"?"failed":"completed",objectResults:(a.objects??[]).map(pr),...a.partial?{partial:!0}:{},...a.origin==="sync"?{origin:"sync"}:{},...fo(o.slice(7),a)})}n.sort((o,a)=>a.timestamp.localeCompare(o.timestamp));let s=this.sliceSets.list(t.orgId).map(yi).sort((o,a)=>a.lastActivityAt.localeCompare(o.lastActivityAt)),i=Ee(this.deps,e,"backup:list:result",{backups:n,...s.length>0?{sets:s}:{}});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} count=${n.length}`)}async handleBackupExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=qe(di,e,"dataops:error",this.deps);if(!t)return;let n=`backup:${t.operationId}`,s=this.deps.configStore.get(n);if(!s||s.orgId!==t.orgId){J(this.deps,"backup:export","dataops:error",e,new Error(`Backup not found: ${t.operationId}`),{code:"BACKUP_NOT_FOUND"});return}let i=await this.saveDialog.saveStream(`sandforge-backup-${t.operationId}.json`,a=>this.writeBackupDocument(t,s,a),["json"]);if(i.status==="error"){J(this.deps,"backup:export","dataops:error",e,new Error(i.message));return}let o=Ee(this.deps,e,"backup:export:result",i.status==="saved"?{operationId:t.operationId,status:"saved",path:i.path,objects:i.result}:{operationId:t.operationId,status:"cancelled"});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} ${i.status}`)}async writeBackupDocument(e,t,n){let{operationId:s}=e,o=[["sandforgeBackupVersion",1],["operationId",s],["orgId",e.orgId],["timestamp",t.timestamp??""],["totalRecords",t.totalRecords??0]].map(([d,c])=>` "${d}": ${JSON.stringify(c)},
8
+ `);await n(`{
9
+ ${o.join("")} "objects": {`);let a=[];for(let{objectApiName:d}of t.objects??[]){if(a.some(l=>l.objectApiName===d))continue;await n(`${a.length>0?",":""}
10
+ ${JSON.stringify(d)}: [`);let c=0;for await(let l of await this.backupBatches(s,d))l.length!==0&&(await n(l.map((u,f)=>`${c+f>0?",":""}
11
+ ${JSON.stringify(u)}`).join("")),c+=l.length);await n(c>0?`
12
+ ]`:"]"),a.push({objectApiName:d,records:c})}return await n(`${a.length>0?`
13
+ `:""}}
14
+ }
15
+ `),a}async backupBatches(e,t){let n=await this.backupRecords?.batches(e,t,Jt);if(n)return n;let s=this.deps.configStore.get(`backup:${e}:${t}`),i=Array.isArray(s)?s:[];return{async*[Symbol.asyncIterator](){for(let o=0;o<i.length;o+=Jt)yield i.slice(o,o+Jt)}}}async firstBackupRecord(e,t,n){let s=await this.backupBatches(e,t),i=n.origin==="sync"?Zs(s,Jt).batches:s;for await(let o of i)if(o[0]!==void 0)return o[0]}pruneBackups(e){let t=this.deps.services?.getSandforgeSetting?.("backup.maxCount",10)??10,n=[];for(let s of this.deps.configStore.getKeysByPrefix("backup:")){if(s.slice(7).includes(":"))continue;let o=this.deps.configStore.get(s);o?.orgId===e&&o.origin!=="sync"&&o.origin!=="checkpoint"&&o.origin!=="slice"&&n.push({key:s,timestamp:o.timestamp??""})}if(!(n.length<=t)){n.sort((s,i)=>s.timestamp.localeCompare(i.timestamp));for(let{key:s}of n.slice(0,n.length-t))this.removeBackup(s),this.deps.log(`[INFO] Pruned backup ${s} (retention: ${t} per org)`)}}async undeleteFromRecycleBin(e,t,n){let s=[];for await(let o of n){let a=o.map(c=>c.Id).filter(c=>typeof c=="string");if(a.length===0)continue;let d=a.map(c=>`'${zr(c)}'`).join(", ");try{let c=await e.query(`SELECT Id FROM ${t} WHERE Id IN (${d}) AND IsDeleted = true`,{scanAll:!0});s.push(...c.records.map(l=>l.Id))}catch(c){return this.deps.log(`[WARN] Rollback on ${t}: could not look for deleted records \u2014 ${v(c)}`),{undeleted:0}}}let i=0;for(let o=0;o<s.length;o+=200){let a=await e.soap.undelete(s.slice(o,o+200));i+=a.filter(d=>d.success).length}return{undeleted:i}}refuseWithoutGuard(e,t,n,s){ve(this.deps,{...s,outcome:"stopped",source:void 0,code:un.code}),e(new Error(un.message),{code:un.code}),he(this.deps,t,un.message,!1,{context:n,authored:!0})}async handleRollback(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=qe(li,e,"dataops:error",this.deps);if(!t)return;let n=t,s=e.id,i={module:"dataops",operation:e.type},o=`backup:${n.orgId}`;if(this.activeOrgOperations.has(o)){let k=this.busyMessage(n.orgId,`A backup or rollback operation is already running for org ${n.orgId}. Please wait for it to complete.`);this.deps.log(`[WARN] ${k}`),J(this.deps,"dataops:rollback","dataops:error",e,new Error(k)),he(this.deps,s,k,!1,{context:i,authored:!0});return}this.activeOrgOperations.add(o);let a,d,c=[],l=!1,u=new AbortController,f=()=>{},p,m,y;try{if(this.dmlTracker.isDuplicate(s)){this.deps.log(`[WARN] Duplicate rollback operation detected: ${s}`),J(this.deps,"dataops:rollback","dataops:error",e,new Error(`Duplicate operation: ${s}`)),he(this.deps,s,`Duplicate operation: ${s}`,!1,{context:i,authored:!0});return}this.dmlTracker.register(s,"rollback","upsert",0);let k=await Ue(n.orgId,this.deps.orgRegistry,this.deps.orgManager),T=new vs(async M=>{let B=await k.describe(M);return Bo(B)}),g=`backup:${n.operationId}`,A=this.deps.configStore.get(g),S=this.restoreOfSet(n,A);if("refused"in S){J(this.deps,"dataops:rollback","dataops:error",e,new Error(S.refused.message),{code:S.refused.code}),he(this.deps,s,S.refused.message,!1,{context:i,authored:!0});return}d=S.set;let b=S.meta??A;if(!b)throw new Error(`No backup found for operation ${n.operationId}. Cannot rollback.`);let $=S.parts??b.objects.map(M=>({snapshotId:n.operationId,objectApiName:M.objectApiName,recordCount:M.recordCount}));if(b.orgId!==n.orgId){let M=Ht(this.deps.orgManager.getOrg(b.orgId),b.orgId),B=Ht(this.deps.orgManager.getOrg(n.orgId),n.orgId);throw new Error(`Backup ${n.operationId} was taken from org ${b.orgId} and cannot be restored into org ${n.orgId}. A restore writes back by record Id, and an Id belongs to the org that holds it: to bring these records from ${M} into ${B}, copy them with Forge or Sync.`)}a={action:"backup_restore",module:"dataops",operationId:s,orgId:n.orgId,outcome:"failure",source:{origin:"backup",label:b.timestamp?.slice(0,16).replace("T"," ")??n.operationId}};let I=this.deps.infraServices?.productionGuard;if(!I){this.refuseWithoutGuard((M,B)=>J(this.deps,"dataops:rollback","dataops:error",e,M,B),s,i,a);return}let L=[],N=new Set;for(let M of $){if(N.has(M.objectApiName.toLowerCase()))continue;let B=await this.firstBackupRecord(M.snapshotId,M.objectApiName,b);if(B===void 0)continue;N.add(M.objectApiName.toLowerCase());let C=Be(M.objectApiName);if(!(await T.checkCrudPermission(C,"upsert")).allowed){L.push({objectApiName:C,operation:"upsert",deniedFields:[]});continue}let{denied:Me}=await T.partitionWritableFields(C,"upsert",Object.keys(B).filter(ee=>ee!=="attributes"));Me.length>0&&L.push({objectApiName:C,operation:"upsert",deniedFields:Me})}if(L.length>0){let M=Wn(L);this.deps.log(`[WARN] CRUD/FLS check failed for rollback ${s}: ${M}`),ve(this.deps,{...a,outcome:"stopped",source:void 0,code:Vt}),J(this.deps,"dataops:rollback","dataops:error",e,new Error(M),{code:Vt}),he(this.deps,s,M,!1,{context:i,authored:!0});return}let w=(M,B,C,Pe=[])=>{ve(this.deps,{...C,outcome:"stopped",source:void 0,code:M}),J(this.deps,"dataops:rollback","dataops:error",e,new Error(B),{code:M,...Ls({alsoRefused:Pe})}),he(this.deps,s,B,!1,{context:i,authored:!0})},P=await this.readAct(k,n.orgId,"restore",b.objects.map(M=>({objectApiName:M.objectApiName,records:M.recordCount})),n,bn(n)),K=Kn(P.answer);if(K){w(K.code,K.message,a,K.alsoRefused);return}y=this.duplicatesWatchOf(k,Cs(P.answer.automation,b.objects.filter(M=>M.recordCount>0).map(M=>M.objectApiName)));let H=this.deps.orgManager.getOrg(n.orgId),Y={orgId:n.orgId,orgTier:dr(H),operation:"upsert",objectName:b.objects.map(M=>M.objectApiName).join(", ")||"RollbackData",recordCount:b.totalRecords??0,module:"dataops"},{check:ae,decision:Te}=await $s(I,Y);if(a.guard=Te,(Te==="refused"||Te==="declined")&&ve(this.deps,{...a,outcome:"stopped",source:void 0}),Te==="refused")throw As(ae.blockedReason??ae.impactSummary);if(Te==="declined"){let M="Operation cancelled by user (confirmation declined).";J(this.deps,"dataops:rollback","dataops:error",e,new Error(M),{code:ws.declined}),he(this.deps,s,M,!1,{context:i,authored:!0});return}if(b.organizationId!==void 0){let M=await this.organizationIdOf(k);if(M!==void 0&&!nd(b.organizationId,M)){let B=Ht(H,n.orgId),C=this.deps.infraServices?.confirmRestoreIntoReplacedOrg;if(!(C?await C({alias:B,backedUpFrom:b.organizationId,now:M}):!1)){ve(this.deps,{...a,outcome:"stopped",source:void 0,code:Ro});let Me=`Restore not run: ${B} answers as org ${M}, not as org ${b.organizationId}, which backup ${n.operationId} was taken from, `+(C?"and the restore into the org it is now was not confirmed.":"and nothing here can ask whether to restore into the org it is now.");J(this.deps,"dataops:rollback","dataops:error",e,new Error(Me),{code:Ro}),he(this.deps,s,Me,!1,{context:i,authored:!0});return}}}let pe=await zs(P,s,n.acceptEmails===!0,bn(n));if("refused"in pe){w(pe.refused.code,pe.refused.message,a);return}m=pe.held,pn(this.deps,s,"dataops",`Rollback ${b.objects.length} object(s)`);let F=S.skipped??[];l=!0,this.deps.infraServices?.backgroundRegistry?.register(s,"dataops",`Rollback ${b.objects.length} object(s)`,new Promise((M,B)=>{f=C=>{C===void 0?M():B(C instanceof Error?C:new Error(String(C)))}}),u),p=Rn(this.liveTracker,s,"dataops",`Rollback ${b.objects.length} object(s)`,b.objects.length);let V=!1,U=0,ce=0,xe=0,le=[],be=new Map,pt=b.origin==="sync"&&n.includeChanged!==!0,bt=Number.NEGATIVE_INFINITY,st=!1;if(pt){let M=b.runId!==void 0?await this.syncRuns?.get(b.runId).catch(C=>{this.deps.log(`[WARN] Rollback: the Sync run of backup ${n.operationId} could not be read \u2014 ${v(C)}`)}):void 0,B=M?Ri(M):void 0;st=B===void 0,bt=await Ai({serverTime:async()=>(await k.soap.getServerTimestamp()).timestamp},B)}let Ae=[];for(let M=0;M<$.length;M++){if(u.signal.aborted){V=!0;break}let B=$[M],C=Be(B.objectApiName);i.objectName=C;let Pe=await this.backupBatches(B.snapshotId,B.objectApiName),Me=b.origin==="sync"?Zs(Pe,Jt):void 0,ee=Me?.batches??Pe,We;for await(let Ie of ee)if(We=Ie[0],We!==void 0)break;if(pt&&We!==void 0){let Ie=[];for await(let Ge of ee)for(let it of Ge)typeof it.Id=="string"&&Ie.push(it.Id);let ze=await ro({query:async(Ge,it)=>({records:(await k.query(Ge,it)).records})},C,Ie,bt);ze.size>0&&(Ae.push({objectApiName:C,count:ze.size}),ee=io(ee,ze))}if(We===void 0){be.set(B.objectApiName,be.get(B.objectApiName)??0),this.deps.log(`[WARN] No backup records for ${B.objectApiName}, skipping.`);continue}let Mn=Object.keys(We).filter(Ie=>Ie!=="attributes"),{skipped:at}=await T.partitionWritableFields(C,"upsert",Mn),ke=new Set(at.filter(Ie=>Ie.toLowerCase()!=="id").map(Ie=>Ie.toLowerCase()));ke.size>0&&this.deps.log(`[INFO] Rollback on ${C}: ${ke.size} non-writable field(s) excluded from the payload \u2014 ${[...ke].sort().join(", ")}`);let sn=await this.undeleteFromRecycleBin(k,C,ee);sn.undeleted>0&&(this.deps.log(`[INFO] Rollback on ${C}: ${sn.undeleted} record(s) brought back from the recycle bin`),Lr(n.orgId,{[C]:sn.undeleted})),i.batchSize=Jt;let Ye=0,Ze=0,kt=0,rt=0;for await(let Ie of ee){if(u.signal.aborted){V=!0;break}rt+=Ie.length;let ze=Ie.map(me=>{let Ve=C===de?Dn(me,!1):void 0,Nt={};for(let[$t,rn]of Object.entries(me))$t!=="attributes"&&(ke.has($t.toLowerCase())||Ve!==void 0&&Ln(de,$t,Ve)||(Nt[$t]=rn));return Nt}),Ge=ze;if(n.rewriteAll!==!0){let me=await so({query:async Ve=>{let Nt=await k.query(Ve);return{totalSize:Nt.totalSize,records:Nt.records}}},C,ze);me.unread!==void 0&&this.deps.log(`[WARN] Rollback on ${C}: the org's values could not be read, so ${ze.length} row(s) are written back without comparing \u2014 ${me.unread}`),Ge=me.write,kt+=me.unchanged}if(Ge.length===0)continue;y.beforeWrite(C);let it;try{it=await k.sobject(C).upsert(Ge,"Id",{headers:bs()})}catch(me){throw Ps(me)==="may-have-written"&&y.wrote(C,Ge.map(Ve=>Ve.Id)),me}let Tt=Array.isArray(it)?it:[it];y.wrote(C,Tt.flatMap((me,Ve)=>me.success?[Ge[Ve]?.Id]:[]));for(let me of Tt){if(me.success){Ye++;continue}Ze++,So(le,C,me.errors)}}mt(k.limitInfo,`dataops:rollback upsert ${C}`),be.set(B.objectApiName,(be.get(B.objectApiName)??0)+(Me&&!V?Me.lines():rt)),U+=Ye,ce+=Ze,xe+=kt;let jt=c.find(Ie=>Ie.objectApiName===C);if(jt?(jt.updated+=Ye,jt.failed+=Ze):c.push({...Bn(C),updated:Ye,failed:Ze}),B.slice&&(F.push({index:B.slice.index,objectApiName:C,restored:Ye,failed:Ze,unchanged:kt}),!V&&d&&(B.slice.restoredAt=new Date().toISOString(),B.slice.state="restored",d.lastActivityAt=B.slice.restoredAt,this.sliceSets.save(d))),V)break;let vt=`Restored ${C}${B.slice?` slice ${B.slice.index}`:""} (${Ye}/${rt}${kt>0?`, ${kt} unchanged`:""})`,Cn=Math.round((M+1)/$.length*100);Kt(this.deps,s,Cn,M+1,$.length,vt),p.progress(Cn,M+1,$.length,vt)}let Ne=Ae.reduce((M,B)=>M+B.count,0),_e=cd(U,ce),fe=V&&ce===0||Ne>0&&_e==="success"?"partial":_e;a&&(l=!1,ve(this.deps,{...a,...V?U+ce>0?{outcome:"cancelled"}:{outcome:"stopped",code:js}:{outcome:fe},objects:c}));let _=await this.releaseMute(m,n.orgId);m=void 0;let Z=await y.read();V?(this.deps.infraServices?.backgroundRegistry?.abort(s),dt(this.deps,s,{aborted:!0,totalRestored:U,totalFailed:ce,totalUnchanged:xe})):dt(this.deps,s,{status:fe,totalRestored:U,totalFailed:ce,totalUnchanged:xe}),this.dmlTracker.markCompleted(s),V?p.cancel():fe==="failure"?p.fail(`The org refused the ${ce} record(s)`):fe==="partial"?p.partial():p.complete();let ye=fr(b.objects,be),ne=(V?`Rollback cancelled: ${U} records restored before the cancel; the rest still hold the values they had, and the same restore puts them back`:ce>0?`Rollback ${fe}: ${U} restored, ${ce} rejected by the org`:Ne>0?`Rollback partial: ${U} records restored`:`Rollback completed: ${U} records restored`)+(xe>0?`; ${xe} already held the backup's values and were not written`:"")+(Ne>0?`; ${Ne} changed or deleted since the Sync run were left as they are `+(st?"(the run is no longer kept here, so every record reads as changed since it) ":"")+"unless the restore includes them":""),$e=hn(Z,this.orgNameOf(n.orgId),"restore"),Re=ye===""?ne:`${ne}. The backup held only part of the org's records, and the rest were left as they are: ${ye}`,Ot=$e?`${Re}. ${$e}`:ye===""?Re:`${Re}.`,yt=Ee(this.deps,e,"dataops:rollback:response",{operationId:n.operationId,status:fe,message:Ot,totalRestored:U,totalFailed:ce,totalUnchanged:xe,...n.rewriteAll===!0?{rewriteAll:!0}:{},...n.includeChanged===!0?{includeChanged:!0}:{},...Ne>0?{keptChanged:{total:Ne,objects:Ae,...st?{runNotKept:!0}:{}}}:{},errors:le,...ye!==""?{partial:!0}:{},...V?{cancelled:!0}:{},..._?{mutedAutomation:_}:{},...Z?{duplicates:Z}:{},...d?{slices:F}:{}});this.deps.broker.postToWebview(yt),this.deps.log(`[TX] ${yt.type} id=${yt.id} status=${fe}`),(ce>0||ye!==""||V||Ne>0||xs(Z))&&Fn(this.deps,fe==="failure"?"error":"warning","Restore",`${Ot}${le[0]?` \u2014 e.g. ${le[0].message}`:""}`)}catch(k){this.dmlTracker.markFailed(s),await this.releaseMute(m,n.orgId),m=void 0;let T=await y?.read(),g=hn(T,this.orgNameOf(n.orgId),"restore");J(this.deps,"dataops:rollback","dataops:error",e,g?new Error(`${v(k)} ${g}`):k,{code:Rs(k),...T?{extraPayload:{duplicates:T}}:{}}),he(this.deps,s,v(k),!0,{context:i}),p?.fail(v(k))}finally{await this.releaseMute(m,n.orgId),this.activeOrgOperations.delete(o),f(),l&&a&&ve(this.deps,{...a,outcome:"failure",objects:c})}}async snapshotBeforeMasking(e,t,n,s,i){let o=new Map,a=[],d=new Map;try{for(let u of s){if(u.tally.total===0)continue;u.where!==void 0&&d.set(u.tally.objectApiName,u.where);let{select:f,rules:p}=await this.maskedFields(e,u.tally.objectApiName,this.maskingRules(u.objectName,u.objectRules),this.maskingRules(u.objectName,u.personRules));f!=="Id"&&o.set(u.tally.objectApiName,f),a.push(...p.map(m=>({...m,objectApiName:u.tally.objectApiName})))}}catch(u){return{refused:`No snapshot was taken, so nothing was masked: ${v(u)}`,retryable:!0}}if(o.size===0)return{};let c=`${t}-snapshot`,l=await this.takeBackup(c,{orgId:n,objects:[...o.keys()],...d.size>0?{wheres:d}:{},fields:o},i.origin,i.stop);return"error"in l?(this.endBackupNotTaken(c,l),{refused:`No snapshot was taken, so nothing was masked: ${v(l.error)}`,retryable:l.retryable&&l.cancelled!==!0}):l.partial?{refused:`Snapshot ${c} holds only part of the records the run would mask, so nothing was masked: a restore could not put back the rest (${fr(l.objects)}). `+this.snapshotCapWay(s),retryable:!1}:(this.keepMaskingOf(c,lo(t,i.template,a)),{taken:{operationId:c,totalRecords:l.totalRecords}})}keepMaskingOf(e,t){try{let n=this.deps.configStore.get(`backup:${e}`);n&&this.deps.configStore.set(`backup:${e}`,{...n,masking:t},"backups")}catch(n){this.deps.log(`[WARN] dataops:anonymize: what snapshot ${e} masks was not kept with it: `+v(n))}}async maskingNotCovered(e,t,n,s){if(s.length===0)return{code:nt.masksNothing,message:`The template "${t.name}" has no rule for ${n.join(", ")}: the run would mask nothing. Choose an object its rules name, or another template. Nothing was masked.`,gaps:{fieldsNotFound:[],objectsNotCovered:[...n]}};let i=[],o=[];for(let d of s){if(d.tally.total===0)continue;let{objectApiName:c}=d.tally,{rules:l,missing:u}=await this.maskedFields(e,c,this.maskingRules(d.objectName,d.objectRules),this.maskingRules(d.objectName,d.personRules));i.push(...u.map(f=>({objectApiName:c,fieldApiName:f}))),l.length===0&&o.push(c)}let a={fieldsNotFound:i,objectsNotCovered:o};if(i.length>0){let d=i.map(c=>`${c.objectApiName}.${c.fieldApiName}`).join(", ");return{code:nt.fieldsUnseen,message:`The template "${t.name}" masks ${d}, which the org does not show the user SandForge connects as: it has no such field, or field-level security hides it. `+(o.length>0?`No field of ${o.join(", ")} can be masked. `:"")+"A run masks every field its template names, or nothing: give that user read and edit access to the field, or take the field out of the template. Nothing was masked.",gaps:a}}if(o.length>0)return{code:nt.masksNothing,message:`The template "${t.name}" masks no field of ${o.join(", ")} in this org: the run would write nothing over its records. Choose an object its rules name, or another template. Nothing was masked.`,gaps:a}}async anonymizeForPipeline(e,t){let n=this.deps.orgManager.getOrg(e.orgId);if(!n)throw gt(nt.orgUnknown,`The org the masking writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was masked.`);let s=yo(dr(n),e.answer,Ht(n,e.orgId));if(s)throw s;let i=sr(e,m=>this.findTemplate(m)!==void 0);if("refusal"in i)throw i.refusal;let o=crypto.randomUUID(),a,d,c,l={origin:"pipeline:execute",pipeline:e.pipeline,accord:e.accord??{},voice:"step",muted:m=>{c=m},refused:(m,y)=>{a??={err:m,...y},this.deps.log(`[ERR] dataops:anonymize ${o} for the pipeline "${e.pipeline.name}": `+v(m))},ended:m=>{d=m}};await this.writing.during(e.orgId,()=>Oi(e.answer,()=>this.mask(i.asked,o,l,t)));let u=a,f=c;if(u){let m=v(u.err),y=u.err,k=u.code??(typeof y?.code=="string"?y.code:void 0),T=u.extraPayload?.snapshot,g={...k!==void 0?{code:k}:{},...T!==void 0?{snapshot:T}:{},...f?{mutedAutomation:f}:{}};throw Object.assign(k===ln?new Un(m):new Error(m),g)}let p=d;if(p===void 0)throw new Error("The masking run ended without a result.");return{operationId:o,result:f?{...p,mutedAutomation:f}:p}}async previewMaskingForPipeline(e,t){let n=(I,L)=>gt(I,L),s=()=>new Un("The simulation of the masking was stopped: nothing was masked.");if(!this.deps.orgManager.getOrg(e.orgId))throw n(nt.orgUnknown,`The org the masking writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was masked.`);let i=sr(e,I=>this.findTemplate(I)!==void 0);if("refusal"in i)throw i.refusal;let o=i.asked,a=this.findTemplate(o.templateId);if(!a)throw gr(o.templateId);let d=Yt(a)?(await this.automaticTemplateOf(o.orgId,o.objects,"again")).template:a,c=this.sliceSets.openFor(o.orgId,o.templateId);if(c)throw n(Fe.runOpen,this.sliceRunOpenMessage(c,"step"));let l=await Ue(o.orgId,this.deps.orgRegistry,this.deps.orgManager),u=On(l),f=await this.plannedObjectsIn(u,o,d),p=[];for(let I of f){if(t?.aborted)throw s();let L=Bt(d,I),N=en(d,I);if(L.length===0&&N.length===0)continue;let w=Be(I),P=Sn(o,d,I),K;try{K=await this.countRows(l,w,void 0,P)}catch(H){throw this.countGaveUp(H,w)}p.push({objectName:I,...P!==void 0?{where:P}:{},objectRules:L,personRules:N,tally:{objectApiName:w,total:K,masked:0,nothingToMask:0,refused:0,unanswered:0,done:K===0},progress:{objectApiName:w,done:K===0,refused:[]}})}let m=await this.maskingNotCovered(u,d,f,p);if(m)throw n(m.code,m.message);let y=p.filter(I=>I.tally.total>0),k=await lr(u,y.map(I=>({objectApiName:I.tally.objectApiName,rules:[...I.objectRules,...I.personRules]})));if(k.length>0)throw n(Vt,Wn(k));let T=await this.maskingHistoryOf(l,u,p,{count:!0}),g=o.purgeHistory===!0?Hs(T):[];if(g.length>0)throw n(_s,Us(g));let A=this.backupCap();if(p.some(I=>I.tally.total>A))throw n(jn,`Nothing was masked: ${p.filter(I=>I.tally.total>A).map(I=>`${I.tally.objectApiName} holds ${I.tally.total} record(s)`).join(", ")}, more than the ${A} a snapshot holds of one object. `+this.snapshotCapWay(p,"step"));if(t?.aborted)throw s();let S=await this.readAct(l,o.orgId,"masking",p.map(I=>({objectApiName:I.tally.objectApiName,records:I.tally.total})),e.accord??{},"step"),b=Kn(S.answer);if(b)throw n(b.code,b.message);let $=[];for(let I of p){let{rules:L}=await this.maskedFields(u,I.tally.objectApiName,this.maskingRules(I.objectName,I.objectRules),this.maskingRules(I.objectName,I.personRules));$.push({objectApiName:I.tally.objectApiName,records:I.tally.total,fields:[...new Set(L.map(N=>N.fieldApiName))].filter(N=>N!=="Id")})}return{objects:$,records:$.reduce((I,L)=>I+L.records,0),...T.length>0?{history:T.map(Oo)}:{}}}async handleAnonymize(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=qe(Hn,e,"dataops:error",this.deps);if(!t)return;let n=bn(t);await this.mask(t,e.id,{...this.pageMaskingReplies(e),accord:{acceptAutomation:t.acceptAutomation===!0,acceptEmails:t.acceptEmails===!0,muteAutomation:t.muteAutomation===!0},...n?{voice:n}:{}})}pageMaskingReplies(e){return{origin:e.type,refused:(t,n)=>J(this.deps,"dataops:anonymize","dataops:error",e,t,n),ended:t=>{let n=Ee(this.deps,e,"dataops:anonymize:response",t);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} status=${t.status}`),(t.recordsNotMasked>0||xs(t.duplicates))&&Fn(this.deps,t.status==="failure"?"error":"warning","Anonymize",`${t.message}${t.errors[0]?` \u2014 e.g. ${t.errors[0].message}`:""}`)}}}pageSizeFor(e){let t=this.deps.orgManager.getOrg(e);return qn(Gn(t?.orgType==="Sandbox"||t?.orgType==="Scratch")).defaultQueryLimit}sliceWays(e){return e==="page"?{resume:"Resume",abandon:"Abandon",restore:()=>"Restore lists the set and puts its values back"}:e===void 0&&this.onCommandLine?{resume:"the same line with --resume",abandon:"--abandon",restore:t=>`the same command with --restore ${t} puts its values back`}:{resume:"Resume on the DataOps panel, or sandforge dataops anonymize --resume",abandon:"Abandon on the DataOps panel, or sandforge dataops anonymize --abandon",restore:()=>"the Backups tab of the DataOps panel lists the set and puts its values back"}}async approximateCount(e,t,n){if(hr.has(ds(n)))try{let s=await e.request(`/services/data/v${e.version}/limits/recordCount?sObjects=${t}`),{recordCountsOf:i}=await import("./chunk-EIYMQPMG.mjs"),o=i(s)?.get(t);return o!==void 0&&this.deps.log(`[INFO] dataops:anonymize: the org gave up counting ${t}; its own figure, ${o}, plans the slices, approximate.`),o}catch(s){this.deps.log(`[WARN] dataops:anonymize: the org's figure of ${t} was not read: `+v(s));return}}async apiBudgetFor(e,t){let{apiBudgetCheckOf:n,readApiBudget:s}=await import("./chunk-Y37ED7AS.mjs"),i=await s(e).catch(a=>({unread:v(a)})),o=n(t,i);return o.verdict==="unread"?{verdict:"unread",unread:o.unread}:{verdict:o.verdict,remaining:o.remaining,max:o.max}}async sliceRunPlan(e,t,n,s){let i=[];for(let o of t){if(o.tally.total===0)continue;let{select:a}=await this.maskedFields(e,o.tally.objectApiName,this.maskingRules(o.objectName,o.objectRules),this.maskingRules(o.objectName,o.personRules));i.push({objectApiName:o.tally.objectApiName,rows:o.tally.total,fields:a.split(",").length})}return Ks(i,n,s,"masking")}tooManySlicesMessage(e,t){let n=e.objects.filter(i=>e.tooMany.includes(i.objectApiName)).map(i=>`${i.objectApiName} (${i.slices} slices)`).join(", "),s=this.onCommandLine?`Give --max-records up to ${vn}, so that a slice holds more, or narrow the run with --where.`:"Raise sandforge.backup.maxRecordsPerObject in Settings, up to 1,000,000, so that a slice holds more.";return`Nothing was masked: ${n} would take more than the ${It} slices a set holds, at ${t} records a slice. ${s}`}diskShortMessage(e,t,n=!1){let s=this.backupRecords?.directory??"the backups folder",i=this.onCommandLine?"give --store a folder on another disk, delete the backups no longer needed (sandforge backup --list, then delete them), or keep backups fewer days (--max-age-days)":"delete the backups no longer needed in the Backups tab, or keep backups fewer days (sandforge.backup.maxAgeDays)";return`${n?"Nothing was masked":"The run stopped between two slices"}: the slices' snapshots take about ${qs(e)}, and ${s} has ${qs(t)} free. To make room, ${i}.`}sliceBudgetStop(e,t,n,s,i){if(t!==void 0&&n+s>t)return`Stopped between slices: the run sent ${n} request(s), and the next slice takes about ${s} more, past the ${t} of ${i==="page"?"the requests it was given":"--max-requests"}.`;let o=mt(e.limitInfo,"dataops:anonymize slices");if(o&&o.apiLimit>0&&(o.apiUsage+s)/o.apiLimit*100>=mr)return`Stopped between slices: the org used ${o.apiUsage} of its ${o.apiLimit} daily API requests, and the next slice takes about ${s} more, past the ${mr}% the run leaves the org's integrations below.`}sliceNotTakenMessage(e,t){if(t.code===Fe.readTooHeavy){let n=this.onCommandLine?"narrow --where to an indexed field, such as a range of CreatedDate, or give a lower --max-records":"mask it from the command line with --where on an indexed field, such as a range of CreatedDate, or lower sandforge.backup.maxRecordsPerObject";return`The org would not read a slice of ${e} in time, even halved ${xo} times (${v(t.failed)}): the run stopped there, and nothing of that slice was masked. To go on, ${n}.`}return`The snapshot of the next slice of ${e} was not taken (${v(t.failed)}): the run stopped there, and nothing of that slice was masked.`}sliceRunOpenMessage(e,t){let n=xt(e),s=this.sliceWays(t);return`A masking run of this template in slices is still open on ${this.orgNameOf(e.orgId)} (set ${e.setId}, ${n.filter(Xt).length} of ${n.length} slice(s) masked, last moved ${e.lastActivityAt}): a new run would mask its rows again and write over where it stopped. Resume it (${s.resume}), or give it up (${s.abandon}), which masks nothing more and keeps its slices to restore. Nothing was masked.`}sliceKeyLostMessage(e,t){let n=this.sliceWays(t);return`The key set ${e.setId} was masked with is not kept where this run reads it: masked with another, the same address would get another digest and the same record another person. Give the set up (${n.abandon}); ${n.restore(e.setId)} if its values are wanted back, and a new run masks again. Nothing was masked.`}slicesSentence(e,t,n,s,i=[]){let o=this.sliceWays(n),a=xt(e),d=mn(e);return[...t?[t.message]:[],`Set ${e.setId}: ${a.filter(Xt).length} of ${a.length} slice(s) of up to ${e.size} records masked, each backed up just before it was masked; ${o.restore(e.setId)}.`,...d>0?[`${d} record(s) were created during the run in a range a slice had masked, or past its last slice: no snapshot holds them, and they were not masked.`]:[],...i.length>0?[`Whether records were created during the run in a range a slice had masked could not be read for ${i.join(", ")}: any such record was not masked.`]:[],...e.state==="open"&&s?[`${o.resume[0].toUpperCase()}${o.resume.slice(1)} masks the rest, each slice backed up first.`]:[]].join(" ")}async snapshotSlice(e,t,n,s,i,o){let a;try{o.clock!==!1&&(a=new Date((await e.soap.getServerTimestamp()).timestamp).toISOString(),o.onRequest())}catch(c){this.deps.log(`[WARN] dataops: the org's clock before slice ${i.index} was not read: `+v(c))}let d=i.sizeUsed;for(let c=0;;c++){let l=await this.takeBackup(i.snapshotId,{orgId:t,objects:[s.objectApiName],...s.where!==void 0?{wheres:new Map([[s.objectApiName,s.where]])}:{},...o.select!==void 0?{fields:new Map([[s.objectApiName,o.select]])}:{},slice:{setId:n.setId,index:i.index,bounds:o.bounds,size:d,...o.skip?{skip:o.skip}:{},onRequest:o.onRequest}},o.origin,o.stop);if(!("error"in l)){let f=l.objects[0];return{rows:f?.recordCount??0,read:f?.readCount??f?.recordCount??0,...f?.lastId!==void 0?{lastId:f.lastId}:{},sizeUsed:d,...a!==void 0?{readSince:a}:{}}}if(l.cancelled)return{failed:l.error,code:ln,cancelled:!0};if(!hr.has(ds(l.error)))return{failed:l.error,code:jn};if(c>=xo||d<=Eo)return{failed:l.error,code:Fe.readTooHeavy};d=Math.max(Eo,Math.floor(d/2)),this.deps.log(`[INFO] dataops: the org would not read slice ${i.index} of ${s.objectApiName} in time; read again in ${d} records.`)}}async countLateRows(e,t,n){let s=[],i=async o=>{let a=await e.query(o);return n(),typeof a.totalSize=="number"?a.totalSize:0};for(let o of t.objects)try{let a=o.slices.filter(f=>!f.late&&f.lastId!==void 0),d=a.at(-1)?.lastId,c=await i(d!==void 0?Ao(o.objectApiName,o.where,d):`SELECT COUNT() FROM ${o.objectApiName}${ls(o.where,void 0)}`);c>0?(o.tailLeft=c,o.done=!1):delete o.tailLeft;let l=t.serverStartedAt;if(d===void 0||l===void 0||await i(or(o.objectApiName,o.where,l,{untilId:d}))===0)continue;for(let f of a){if(f.lastId===void 0)continue;let p=await i(or(o.objectApiName,o.where,f.readSince??l,{...f.afterId!==void 0?{afterId:f.afterId}:{},untilId:f.lastId}));p>0?f.lateLeft=p:delete f.lateLeft}}catch(a){this.deps.log(`[WARN] dataops: the ${o.objectApiName} records created during set ${t.setId} were not counted: ${v(a)}`),s.push(`${o.objectApiName} (${v(a)})`)}return s}async abandonSliceSet(e,t,n){if(!e){n.refused(new Error(`No masking run of this template in slices is open on ${this.orgNameOf(t.orgId)}: there is nothing to give up.`),{code:Fe.nothingToAbandon});return}if(this.sliceRunsOn.get(t.orgId)===e.setId){n.refused(new Error(this.busyMessage(t.orgId,"")),{code:ar});return}e.state="abandoned",e.lastActivityAt=new Date().toISOString(),this.sliceSets.save(e),new ut(this.deps.configStore).clear(t.orgId,t.templateId),await this.runKeys?.delete(e.setId).catch(a=>{this.deps.log(`[WARN] dataops: the key of set ${e.setId} was not removed: ${v(a)}`)});let i=xt(e).filter(Xt).length,o=this.sliceWays(n.voice);this.deps.log(`[INFO] dataops: set ${e.setId} given up, ${i} slice(s) masked`),n.ended({templateId:t.templateId,status:"success",recordsProcessed:0,recordsFailed:0,recordsNotMasked:0,objects:[],message:`Set ${e.setId} given up: nothing more is masked. Its ${i} masked slice(s) stay masked, each with its snapshot; ${o.restore(e.setId)} until the retention removes them. The records no slice reached keep their values.`,errors:[],abandoned:!0,slices:gn(e,{requestsSpent:0})})}async mask(e,t,n,s){let i,o={},a,d=async()=>(a??={released:await this.releaseMute(i,e.orgId)},a.released),c={...n,refused:(_,Z)=>{if(!i){n.refused(_,Z);return}o.answer??=ye=>n.refused(_,ye?{...Z,extraPayload:{...Z.extraPayload,mutedAutomation:ye}}:Z)},ended:_=>{if(!i){n.ended(_);return}o.answer??=Z=>n.ended(Z?{..._,mutedAutomation:Z}:_)}},l={module:"dataops",operation:c.origin},u=this.findTemplate(e.templateId),f,p=()=>u!==void 0&&f!==void 0?{rules:[...u.rules]}:{},m=In(e,u),y={action:"anonymize_execute",module:"dataops",operationId:t,orgId:e.orgId,outcome:"failure",source:{origin:"org",orgId:e.orgId}},k=[],T=[],g=us(e),A=u?Zt(u.rules,m,g):"",S=!1,b=!1,$=!1,I=!1,L,N,w,P=0,K=0,H,Y,ae=!1,Te=[],pe,F=()=>pe?{history:{purge:!0,objects:pe.result()}}:{},V=()=>pe?{history:{purge:!0,pending:pe.pending()}}:{},U=new AbortController,ce=()=>{},xe,le,be,pt=async()=>Es(Y,await be?.read()),bt=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(t);bt?.signal.addEventListener("abort",()=>U.abort(),{once:!0});let st=()=>U.abort();s?.aborted&&U.abort(),s?.addEventListener("abort",st,{once:!0});let Ae=async()=>{ve(this.deps,{...y,outcome:"stopped",source:void 0,code:ln});let _="The masking run was cancelled before it wrote anything.";c.refused(new Error(_),{code:ln,...N?{extraPayload:{snapshot:N}}:{}}),await d(),dt(this.deps,t,{aborted:!0})},Ne=(_,Z,ye)=>{xe=_;let ne=v(_),$e=tn(k),Re=S&&$e.recordsNotMasked>0,Ot=hn(ye,this.orgNameOf(e.orgId)),yt={...S?{...$e,objects:$o(k)}:{},...N?{snapshot:N}:{},...ye?{duplicates:ye}:{},...F(),...w?{slices:gn(w,{requestsSpent:P})}:{}},M=Re?`${ne} \u2014 ${$e.recordsProcessed} masked before it stopped; ${$e.recordsNotMasked} still hold their original values (${No(k)}).`:ne;c.refused(Re||Ot?new Error(Ot?`${M} ${Ot}`:M):_,{code:Rs(_),extraPayload:yt}),he(this.deps,t,ne,Z,{context:l,extraPayload:yt}),le?.fail(ne)},_e=()=>{I=!0;let _=new ut(this.deps.configStore),{recordsNotMasked:Z}=tn(k),ye=k.reduce(($e,Re)=>$e+Re.masked+Re.nothingToMask+Re.refused+Re.unanswered,0),ne=(pe?.pending().length??0)>0;try{if(Z===0&&w?.state!=="open"&&!ne||w!==void 0&&w.state!=="open")return _.clear(e.orgId,e.templateId),!1;if(ye===0&&w===void 0&&!pe)return _.load(e.orgId,e.templateId,A)!==void 0;let $e=T.map(Re=>Re.progress);return An($e)>Lt?(this.deps.log(`[WARN] dataops:anonymize ${t}: the org refused ${An($e)} record(s), more than a resume retries (${Lt}): only a full run masks them.`),_.clear(e.orgId,e.templateId),!1):(_.save({id:t,orgId:e.orgId,templateId:e.templateId,fingerprint:A,savedAt:new Date().toISOString(),objects:$e,...L?{namesGiven:L.namesGiven()}:{},...w?{setId:w.setId}:{},...V(),...p()}),!0)}catch($e){return this.deps.log(`[WARN] dataops:anonymize ${t}: where the run stopped was not kept: `+v($e)),!1}},fe=()=>{if(w){w.lastActivityAt=new Date().toISOString(),w.requestsSpent=K+P,this.sliceSets.save(w);try{new ut(this.deps.configStore).save({id:t,orgId:e.orgId,templateId:e.templateId,fingerprint:A,savedAt:new Date().toISOString(),objects:T.map(_=>_.progress),...L?{namesGiven:L.namesGiven()}:{},setId:w.setId,...V(),...p()})}catch(_){this.deps.log(`[WARN] dataops:anonymize ${t}: where the run is in set ${w.setId} was not kept: ${v(_)}`)}}};try{let _=this.deps.infraServices?.productionGuard;if(!_){this.refuseWithoutGuard((h,O)=>c.refused(h,O),t,l,y);return}if(u!==void 0&&Yt(u)){let h=await this.automaticTemplateOf(e.orgId,e.objects,"kept");this.automaticPlans.forget(e.orgId),u=h.template,f=h.plan,m=In(e,u),A=Zt(u.rules,m,g),y.details={...y.details,anonymizeEverything:!0}}if(!u){c.refused(gr(e.templateId),{code:jo});return}let Z=$n(e,u,de)?In(e,u,!0):void 0,ye=this.sliceSets,ne=ye.openFor(e.orgId,e.templateId);if(e.abandon===!0){await this.abandonSliceSet(ne,e,c);return}let $e=u.rules,Re=(h,O)=>Zt($e,h,g,O),yt=(Z?[m,Z]:[m]).flatMap(h=>[Re(h),...ne?[Re(h,ne.size)]:[]]),M=h=>c.refused(new Error(h??"There is nothing to resume: the run has finished since, another run of this template has stopped since, its rules have changed, or the slices it masked expired. Apply masks every record of its objects."),{code:ud}),B=(h,O)=>{ve(this.deps,{...y,outcome:"stopped",source:void 0,code:h}),c.refused(new Error(O),{code:h}),he(this.deps,t,O,!1,{context:l,authored:!0})},C;if(e.resumeFrom!==void 0){let h=new ut(this.deps.configStore);if(C=yt.map(O=>h.load(e.orgId,e.templateId,O)).find(O=>O?.id===e.resumeFrom),!C){M();return}if(C.setId!==void 0&&C.setId!==ne?.setId||C.setId===void 0&&e.slices===!0){M(C.setId===void 0?"The run this one resumes was not in slices: it resumes as it ran, without slices, or Apply masks every record of its objects in slices. Nothing was masked.":void 0);return}}if(ne&&C?.setId!==ne.setId){B(Fe.runOpen,this.sliceRunOpenMessage(ne,c.voice));return}let Pe=C?.setId!==void 0?ne?.size:e.slices===!0?this.backupCap():void 0;if(A=Re(m,Pe),Pe!==void 0&&!this.backupRecords){B(Fe.needsStore,"A run in slices writes each slice to the backup files, and this host keeps none. Nothing was masked.");return}let Me=this.maskingKey;if(C?.setId!==void 0&&ne){if(Me=await this.runKeys?.load(ne.setId).catch(O=>{this.deps.log(`[WARN] dataops:anonymize: the key of set ${ne.setId} was not read: `+v(O))})??this.maskingKey,ne.keyCheck!==void 0&&Vs(Me)!==ne.keyCheck){B(Fe.keyLost,this.sliceKeyLostMessage(ne,c.voice));return}w=ne,K=ne.requestsSpent}let ee=await Ue(e.orgId,this.deps.orgRegistry,this.deps.orgManager),We=On(ee);if(Z&&await cr(We,this.deps.log)&&(m=Z,A=Re(Z,Pe)),C&&C.fingerprint!==A){M();return}let Mn,at=h=>{P++;let O=mt(ee.limitInfo,h);O&&O.usagePercent>=mr&&(Mn??=O)},ke=()=>Mn,sn=new Set;for(let h of m){let O=Bt(u,h),q=en(u,h);if(O.length===0&&q.length===0)continue;let G=Be(h),W=Sn(e,u,h);l.objectName=G;let x=C?.objects.find(Xe=>Xe.objectApiName===G),z={objectApiName:G,done:x?.done??!1,...x?.afterId!==void 0?{afterId:x.afterId}:{},refused:[...x?.refused??[]],...x?.unconfirmed?.length?{unconfirmed:[...x.unconfirmed]}:{},...x?.slice?{slice:{...x.slice}}:{}},Le=0,se=async Xe=>{try{let te=await this.countRows(ee,G,Xe,W);return at(`dataops:anonymize count ${G}`),te}catch(te){let Se=Pe!==void 0&&Xe===void 0&&W===void 0?await this.approximateCount(ee,G,te):void 0;if(Se!==void 0)return sn.add(G),Se;throw ve(this.deps,{...y,outcome:"failure",source:void 0,objects:[Bn(G)],code:fd,details:{reason:ds(te)}}),this.countGaveUp(te,G)}},He=w?.objects.find(Xe=>Xe.objectApiName===G);He?(Le=Rd(He),He.done||(Le+=await se(cs(He))),z.done=Le===0):z.done||(Le=await se(z.afterId),Le===0&&(z.done=!0));let Et=Le+z.refused.length+(z.unconfirmed?.length??0),Rt={objectApiName:G,total:Et,masked:0,nothingToMask:0,refused:0,unanswered:0,done:Et===0};k.push(Rt),T.push({objectName:h,...W!==void 0?{where:W}:{},objectRules:O,personRules:q,tally:Rt,progress:z})}let Ye=k.reduce((h,O)=>h+O.total,0),Ze=await this.maskingNotCovered(We,u,m,T);if(Ze){ve(this.deps,{...y,outcome:"stopped",source:void 0,code:Ze.code}),c.refused(new Error(Ze.message),{code:Ze.code,extraPayload:{...Ze.gaps}}),he(this.deps,t,Ze.message,!1,{context:l,authored:!0});return}let kt=await lr(We,T.filter(h=>h.tally.total>0).map(h=>({objectApiName:h.tally.objectApiName,rules:[...h.objectRules,...h.personRules]})));if(kt.length>0){let h=Wn(kt);this.deps.log(`[WARN] CRUD/FLS check failed for anonymize ${t}: ${h}`),ve(this.deps,{...y,outcome:"stopped",source:void 0,code:Vt}),c.refused(new Error(h),{code:Vt}),he(this.deps,t,h,!1,{context:l,authored:!0});return}let rt=(h,O,q=[])=>{ve(this.deps,{...y,outcome:"stopped",source:void 0,code:h}),c.refused(new Error(O),{code:h,...Ls({alsoRefused:q})}),he(this.deps,t,O,!1,{context:l,authored:!0})};if(e.purgeHistory===!0||C?.history?.purge===!0){let h=await this.maskingHistoryOf(ee,We,T,{count:!1,onRequest:q=>at(`dataops:anonymize ${q}`)}),O=Hs(h);if(O.length>0){rt(_s,Us(O));return}pe=new Vn(Ws(ee,q=>at(`dataops:anonymize ${q}`),q=>We.describe(q)),h.filter(Ut));for(let q of C?.history?.pending??[])pe.add(q.objectApiName,q.ids)}if(e.snapshot===!0&&Pe===void 0){let h=this.backupCap();if(T.some(O=>O.tally.total>h)){rt(jn,`Nothing was masked: ${T.filter(O=>O.tally.total>h).map(O=>`${O.tally.objectApiName} holds ${O.tally.total} record(s)`).join(", ")}, more than the ${h} a snapshot holds of one object. `+this.snapshotCapWay(T,c.voice));return}}if(Pe!==void 0){let h=await this.sliceRunPlan(We,T,Pe,this.pageSizeFor(e.orgId));if(h.tooMany.length>0){rt(Fe.tooMany,this.tooManySlicesMessage(h,Pe));return}let O=await this.freeBytes();if(O!==void 0&&Yn(h.diskBytes)>O){rt(Fe.diskShort,this.diskShortMessage(Yn(h.diskBytes),O,!0));return}}let jt=await this.readAct(ee,e.orgId,"masking",k.map(h=>({objectApiName:h.objectApiName,records:h.total})),c.accord,c.voice),vt=Kn(jt.answer);if(vt){rt(vt.code,vt.message,vt.alsoRefused);return}let Cn=Cs(jt.answer.automation,k.filter(h=>h.total>0).map(h=>h.objectApiName)),Ie=()=>this.duplicatesWatchOf(ee,Cn),ze=Ie();be=ze;let Ge=this.deps.orgManager.getOrg(e.orgId),it={orgId:e.orgId,orgTier:dr(Ge),operation:"update",objectName:m.join(", ")||"AnonymizeData",recordCount:Ye,module:"dataops"},{check:Tt,decision:me}=await $s(_,it);if(y.guard=me,(me==="refused"||me==="declined")&&ve(this.deps,{...y,outcome:"stopped",source:void 0}),me==="refused")throw As(Tt.blockedReason??Tt.impactSummary);if(me==="declined"){let h="Operation cancelled by user (confirmation declined).";c.refused(new Error(h),{code:ws.declined}),he(this.deps,t,h,!1,{context:l,authored:!0});return}for(let h of Tt.warnings)this.deps.log(`[WARN] dataops:anonymize ${t}: ${h}`);if(U.signal.aborted){await Ae();return}let Ve=await zs(jt,t,c.accord.acceptEmails===!0,c.voice);if("refused"in Ve){rt(Ve.refused.code,Ve.refused.message);return}if(i=Ve.held,S=!0,Pe!==void 0){let h=`backup:${e.orgId}`;if(this.activeOrgOperations.has(h)){rt(ar,this.busyMessage(e.orgId,`A backup or rollback operation is already running for org ${e.orgId}. Mask once it has ended.`));return}if(this.activeOrgOperations.add(h),ae=!0,!w){let O=new Date().toISOString(),q=await ee.soap.getServerTimestamp().then(W=>new Date(W.timestamp).toISOString()).catch(()=>O);P++;let G=await this.organizationIdOf(ee);P++,w={setId:t,kind:"masking",orgId:e.orgId,...G!==void 0?{organizationId:G}:{},templateId:e.templateId,fingerprint:A,size:Pe,state:"open",startedAt:O,serverStartedAt:q,lastActivityAt:O,requestsSpent:0,keyCheck:Vs(Me),objects:T.map(W=>({objectApiName:W.tally.objectApiName,...W.where!==void 0?{where:W.where}:{},done:W.tally.total===0,slices:[]}))},ye.save(w),await this.runKeys?.save(w.setId,Me).catch(W=>{this.deps.log(`[WARN] dataops:anonymize ${t}: the key of set ${t} was not kept, so only this window resumes it: ${v(W)}`)})}this.sliceRunsOn.set(e.orgId,w.setId)}let Nt=Gn(Ge?.orgType==="Sandbox"||Ge?.orgType==="Scratch"),$t=qn(Nt).defaultQueryLimit;if(e.snapshot===!0&&w===void 0){let h=await this.snapshotBeforeMasking(We,t,e.orgId,T,{origin:c.origin,stop:U.signal,template:{id:u.id,name:u.name}});if("refused"in h&&U.signal.aborted){await Ae();return}if("refused"in h){ve(this.deps,{...y,outcome:"stopped",source:void 0,code:jn}),c.refused(new Error(h.refused),{code:jn}),await d(),he(this.deps,t,h.refused,h.retryable,{context:l,authored:!0});return}if(N=h.taken,U.signal.aborted){await Ae();return}}let rn=c.pipeline?`Pipeline anonymization with ${u.name}`:`Anonymizing with ${u.name}`;pn(this.deps,t,"dataops",rn),b=!0,$=!0,this.deps.infraServices?.backgroundRegistry?.register(t,"dataops",rn,new Promise((h,O)=>{ce=q=>{q===void 0?h():O(q instanceof Error?q:new Error(String(q)))}}),U),le=Rn(this.liveTracker,t,"dataops",rn,Ye);let{AnonymizationEngine:Ho}=await import("./chunk-HGVPBJR6.mjs"),En=new Ho(void 0,Me);L=En,C&&!(C.namesGiven!==void 0&&En.continueFrom(C.namesGiven))&&this.deps.log(`[INFO] dataops:anonymize ${t}: the run it resumes kept no record of the names it made up, so this one may give again a name or an address that run gave.`);let yr=[],ge=!1,kr=()=>U.signal.aborted||ke()!==void 0,Ft=h=>h.masked+h.nothingToMask+h.refused+(h.deletedSince??0),_t,wr=(h,O)=>{let q=k.reduce((z,Le)=>z+Ft(Le),0),G=Math.max(Ye,q),W=Math.round(q/G*100),x=`Anonymized ${h}${_t?` ${_t}`:""} (${Ft(O)}/${Math.max(O.total,Ft(O))})`;Kt(this.deps,t,W,q,G,x),le?.progress(W,q,G,x)},fs=[],Uo=async h=>{let O=w,q=this.backupRecords,{safeObj:G,fields:W,tally:x,progress:z,writeBack:Le}=h,se=O?.objects.find(R=>R.objectApiName===G);if(!O||!q||!se)throw new Error(`The set of slices holds no ${G}: nothing more was masked.`);let He=zo(G),Et=W.split(",").length,Rt=()=>({masked:x.masked,nothing:x.nothingToMask,refused:x.refused,gone:x.deletedSince??0}),Xe=(R,j)=>{R.masked+=x.masked-j.masked,R.nothingToMask+=x.nothingToMask-j.nothing,R.deletedSince+=(x.deletedSince??0)-j.gone;let E=z.unconfirmed?.length??0;E>0?R.unanswered=E:delete R.unanswered},te=async R=>{let j=[];for await(let E of await this.backupBatches(R.snapshotId,He))for(let X of E)typeof X.Id=="string"&&j.push(X.Id);return j},Se=async(R,j)=>{j.length===0?await q.delete(R.snapshotId,He):(await q.begin(R.snapshotId,He),await q.append(R.snapshotId,He,j.map(E=>({Id:E})))),R.refused=j.length},Je=async(R,j)=>{j.length!==0&&(await q.append(R.snapshotId,He,j.map(E=>({Id:E}))),R.refused+=j.length)},De=se.slices.find(R=>R.state==="masking")??se.slices.at(-1);if(De){De.masked+=x.masked,De.nothingToMask+=x.nothingToMask,De.deletedSince+=x.deletedSince??0,await Je(De,z.refused),z.refused=[];let R=z.unconfirmed?.length??0;R>0?De.unanswered=R:delete De.unanswered}for(let R of se.slices){if(R.refused===0)continue;let j=await te(R),E=[...j],X=[];for(let re=0;re<j.length;re+=ht){if(U.signal.aborted)return ge=!0,"stopped";if(ke())return"stopped";let ie=j.slice(re,re+ht),Oe=await Gt(ee,`SELECT ${W} FROM ${G} WHERE Id IN (${ie.map(on=>`'${on}'`).join(", ")})`);at(`dataops:anonymize query ${G}`);let je=ie.length-Oe.length;R.deletedSince+=je,x.deletedSince=(x.deletedSince??0)+je;let et=Rt(),Q=[],oe=!1;try{oe=await Le(Oe,(on,gs)=>Q.push(...gs),(on,gs)=>{z.unconfirmed=[...z.unconfirmed??[],...gs]})}finally{Xe(R,et),E=E.slice(ie.length),X.push(...Q),await Se(R,[...X,...oe?ie:[],...E]),fe()}if(oe)return"stopped"}}let Qe=async R=>{let j=new Set;for(let E of se.slices)if(!(E!==R&&E.lateOf!==R.index)&&E.state!=="pending")for await(let X of await this.backupBatches(E.snapshotId,G))for(let re of X)typeof re.Id=="string"&&j.add(re.Id);return j},we=async R=>{let j=z.slice?.index===R.index?z.afterId:void 0,E=j===void 0;for await(let X of await this.backupBatches(R.snapshotId,G)){let re=X;if(!E){let Q=re.findIndex(oe=>oe.Id===j);if(Q<0)continue;E=!0,re=re.slice(Q+1)}if(re.length===0)continue;if(U.signal.aborted)return ge=!0,!0;if(ke())return!0;let ie=Rt(),Oe=[],je=Q=>{let oe=Q[Q.length-1]?.Id;typeof oe=="string"&&Pn.test(oe)&&(z.afterId=oe)},et=!0;try{et=await Le(re,(Q,oe)=>{Oe.push(...oe),je(Q)},(Q,oe)=>{z.unconfirmed=[...z.unconfirmed??[],...oe],je(Q)}),et||je(re)}finally{Xe(R,ie),await Je(R,Oe)}if(et)return!0}if(!E)throw new Error(`The snapshot of slice ${R.index} of ${G} no longer holds the row the run stopped at: it is not the file the slice was masked from, and nothing more of it was masked.`);return!1};for(;;){if(U.signal.aborted)return ge=!0,"stopped";if(ke())return"stopped";let R=se.slices.find(j=>!Xt(j));if(!R){let j=se.slices.find(et=>!et.late&&(et.lateLeft??0)>0);if(!j&&se.done)break;let E=se.slices.filter(et=>!et.late),X=E.at(-1)?.sizeUsed??O.size,re=Math.max(1,Math.min(X,x.total-Ft(x))),ie=Gi(re,$t,{masking:!0,duplicateRule:ze.covers(G)}),Oe=this.sliceBudgetStop(ee,e.maxRequests,P,ie,c.voice);if(Oe)return H={budget:!0,message:Oe},"stopped";if(!j&&E.length>=It)return H={code:Fe.tooMany,message:`${G} holds more rows than ${It} slices of ${X} do, as it grew during the run: the run stopped between two slices.`},"stopped";let je=Ns(O);R={index:je,...j?{late:!0,lateOf:j.index,...(j.lateAfterId??j.afterId)!==void 0?{afterId:j.lateAfterId??j.afterId}:{}}:cs(se)!==void 0?{afterId:cs(se)}:{},rows:0,snapshotId:Ts(O.setId,je),state:"pending",masked:0,refused:0,deletedSince:0,nothingToMask:0,sizeUsed:X},se.slices.push(R),fe()}if(R.state==="pending"){let j=R.late===!0?se.slices.find(oe=>oe.index===R?.lateOf):void 0,E=await this.freeBytes(),X=Yn(R.sizeUsed*(48+64*Et));if(E!==void 0&&X>E)return se.slices=se.slices.filter(oe=>oe!==R),fe(),H={code:Fe.diskShort,message:this.diskShortMessage(X,E)},"stopped";let re=j?{...R.afterId!==void 0?{afterId:R.afterId}:{},...j.lastId!==void 0?{untilId:j.lastId}:{},createdSince:j.readSince??O.serverStartedAt??O.startedAt}:R.afterId!==void 0?{afterId:R.afterId}:{},ie=j?await Qe(j):void 0,Oe=Qn(Math.max(x.total,Ft(x)),R.sizeUsed);_t=`slice ${R.index} of about ${Math.max(Oe,R.index)}`;let je=k.reduce((oe,on)=>oe+Ft(on),0),et=`Backing up ${G} ${_t}`;Kt(this.deps,t,Math.round(je/Math.max(Ye,je,1)*100),je,Math.max(Ye,je),et);let Q=await this.snapshotSlice(ee,e.orgId,O,se,R,{select:W,bounds:re,...ie?{skip:oe=>ie.has(String(oe.Id))}:{},stop:U.signal,onRequest:()=>{P++},origin:c.origin});if("failed"in Q)return se.slices=se.slices.filter(oe=>oe!==R),fe(),Q.cancelled?(ge=!0,"stopped"):(H={code:Q.code,message:this.sliceNotTakenMessage(G,Q)},"stopped");if(Q.lastId===void 0){await this.removeBackup(`backup:${R.snapshotId}`),se.slices=se.slices.filter(oe=>oe!==R),j?(delete j.lateLeft,delete j.lateAfterId,Q.readSince&&(j.readSince=Q.readSince)):se.done=!0,fe();continue}R.rows=Q.rows,R.lastId=Q.lastId,R.sizeUsed=Q.sizeUsed,R.takenAt=new Date().toISOString(),Q.readSince&&(R.readSince=Q.readSince),j&&(Q.read<Q.sizeUsed?(delete j.lateLeft,delete j.lateAfterId,Q.readSince&&(j.readSince=Q.readSince)):j.lateAfterId=Q.lastId),R.state="masking",z.slice={setId:O.setId,index:R.index},delete z.afterId,fe()}if(_t??=`slice ${R.index}`,await we(R))return"stopped";fs.push(R.index),_t=void 0,R.state="masked",delete R.unanswered,Y=Es(Y,await ze.read()),ze=Ie(),be=ze,En.forgetRecords(),delete z.slice,delete z.afterId,fe()}return x.done=!0,z.done=!0,"done"};for(let{objectName:h,where:O,objectRules:q,personRules:G,tally:W,progress:x}of T){if(W.total===0)continue;if(U.signal.aborted){ge=!0;break}if(ke())break;let z=W.objectApiName;l.objectName=z;let{select:Le,rulesOf:se}=await this.maskedFields(We,z,this.maskingRules(h,q,Me),this.maskingRules(h,G,Me));l.batchSize=ht;let He=async(te,Se,Je)=>{let De=te.map(se),Qe=te.map((R,j)=>En.anonymize([R],De[j])[0]),we=[];te.forEach((R,j)=>{let E={Id:R.Id};for(let X of De[j]){let re=R[X.fieldApiName],ie=Qe[j][X.fieldApiName];!ct(re)||X.method==="redact"&&ie===re||(E[X.fieldApiName]=ie)}Object.keys(E).length>1?we.push(E):W.nothingToMask++});for(let R=0;R<we.length;R+=ht){if(U.signal.aborted)return ge=!0,!0;if(ke())return!0;let j=we.slice(R,R+ht),E;ze.beforeWrite(z);try{E=await ee.sobject(h).update(j,{headers:bs()})}catch(ie){throw Ps(ie)==="may-have-written"&&(W.unanswered+=j.length,Je(j,j.flatMap(pd)),ze.wrote(z,j.map(Oe=>Oe.Id))),ie}at(`dataops:anonymize update ${z}`);let X=[],re=Array.isArray(E)?E:[E];ze.wrote(z,re.flatMap((ie,Oe)=>ie.success?[j[Oe]?.Id]:[])),re.forEach((ie,Oe)=>{if(ie.success){W.masked++;return}if(w&&Ad(ie.errors)){W.deletedSince=(W.deletedSince??0)+1;return}W.refused++;let je=j[Oe]?.Id;typeof je=="string"&&Pn.test(je)&&X.push(je),So(yr,z,ie.errors)}),pe?.add(z,re.flatMap((ie,Oe)=>ie.success?[String(j[Oe]?.Id)]:[])),Se(j,X),wr(h,W)}return we.length===0&&wr(h,W),await pe?.flush(z,kr),!1},Et=x.unconfirmed??[];for(let te=0;te<Et.length;te+=ht){if(U.signal.aborted){ge=!0;break}if(ke())break;let Se=Et.slice(te,te+ht),Je=Se.map(E=>`'${E.id}'`).join(", "),De=await Gt(ee,`SELECT ${Le} FROM ${z} WHERE Id IN (${Je})`);at(`dataops:anonymize query ${z}`);let Qe=new Map(De.map(E=>[String(E.Id),E])),we=[];for(let E of Se){let X=Qe.get(E.id);X===void 0?W.total-=1:nr(X,E.fields)===E.digest?(W.nothingToMask++,pe?.add(z,[E.id])):we.push(E.id)}let R=new Set(Se.map(E=>E.id)),j=(x.unconfirmed??[]).filter(E=>!R.has(E.id));j.length>0?x.unconfirmed=j:delete x.unconfirmed,x.refused.push(...we)}if(ge||ke())break;let Rt=[...x.refused];for(let te=0;te<Rt.length;te+=ht){if(U.signal.aborted){ge=!0;break}if(ke())break;let Se=Rt.slice(te,te+ht),Je=await Gt(ee,`SELECT ${Le} FROM ${z} WHERE Id IN (${Se.map(R=>`'${R}'`).join(", ")})`);at(`dataops:anonymize query ${z}`),W.total-=Se.length-Je.length;let De=[];if(await He(Je,(R,j)=>De.push(...j),(R,j)=>{let E=new Set(j.map(X=>X.id));x.refused=x.refused.filter(X=>!E.has(X)),x.unconfirmed=[...x.unconfirmed??[],...j]}))break;let we=new Set(Se);x.refused=[...x.refused.filter(R=>!we.has(R)),...De]}if(ge||ke())break;if(w){if(await Uo({objectName:h,safeObj:z,fields:Le,tally:W,progress:x,writeBack:He})!=="done")break;continue}if(x.done){W.done=!0;continue}let Xe=x.afterId;for(;;){if(U.signal.aborted){ge=!0;break}if(ke())break;let te=await Mo(ee,z,Le,$t,Xe,O);if(at(`dataops:anonymize query ${z}`),te.records.length===0){W.done=!0,x.done=!0;break}let Se=te.truncated?wd(te.records,Xe,z):void 0;if(U.signal.aborted){ge=!0;break}let Je=Qe=>{let we=Qe[Qe.length-1]?.Id;typeof we=="string"&&Pn.test(we)&&(x.afterId=we)};if(await He(te.records,(Qe,we)=>{x.refused.push(...we),Je(Qe)},(Qe,we)=>{x.unconfirmed=[...x.unconfirmed??[],...we],Je(Qe)}))break;if(Se===void 0){W.done=!0,x.done=!0;break}Xe=Se,x.afterId=Se}if(ge||ke())break}if(await pe?.flushAll(kr),w){!ge&&!ke()&&!H&&(Te=await this.countLateRows(ee,w,()=>{P++}));for(let h of k){let O=w.objects.find(G=>G.objectApiName===h.objectApiName),q=h.done&&O?mn({objects:[O]}):0;q>0&&(h.late=q)}if(tn(k).recordsNotMasked===0&&w.objects.every(h=>h.done&&(h.tailLeft??0)===0&&h.slices.every(O=>Xt(O)&&O.refused===0&&(O.lateLeft??0)===0))&&(w.state="done"),xt(w).length===0&&w.state==="open"?(w.state="abandoned",this.sliceSets.delete(w.setId)):fe(),w.state!=="open"){let h=w.setId;await this.runKeys?.delete(h).catch(O=>{this.deps.log(`[WARN] dataops:anonymize ${t}: the key of set ${h} was not removed: ${v(O)}`)})}}let Pt=ke(),wt=gd(k,ge),{recordsProcessed:Mt,recordsFailed:Wt,recordsNotMasked:At}=tn(k),Ar=No(k);b=!1;let Ct=pe?.result(),Ko=Ct?{historyDeleted:Ct.reduce((h,O)=>h+(O.deleted??0),0),historyRefused:Ct.reduce((h,O)=>h+(O.refused??0),0),historyLeft:Ct.reduce((h,O)=>h+(O.left??0),0)}:{};ve(this.deps,{...y,...hd(k,wt,ge),objects:Po(k),...w||Ct?{details:{...w?{setId:w.setId,sliceSize:w.size,...fs.length>0?{slices:fs.join(",")}:{}}:{},...Ko}}:{}});let xn=Ct?Ki(Ct):"";xn&&this.deps.log(`[INFO] dataops:anonymize ${t}: ${xn}`);let Rr=_e();if(At>0){let h=ge?"cancelled":Pt?`stopped at ${Pt.usagePercent}% of the org's API requests`:"refused by the org";this.deps.log(`[WARN] dataops:anonymize ${t} ${h}: ${At} record(s) not masked \u2014 ${Ar}`)}await d();let ms=await pt();ge?(this.deps.infraServices?.backgroundRegistry?.abort(t),dt(this.deps,t,{aborted:!0,totalProcessed:Mt,totalFailed:Wt,totalNotMasked:At}),le?.cancel()):(dt(this.deps,t,{status:wt,totalProcessed:Mt,totalFailed:Wt,totalNotMasked:At}),wt==="failure"?le?.fail(`The org refused the ${Wt} record(s)`):wt==="partial"?le?.partial():le?.complete());let Ir=`${At} still hold their original values (${Ar})`,qo=ge?`Anonymization cancelled: ${Mt} masked before the cancel \u2014 ${Ir}.`:Pt?`Anonymization stopped at ${Pt.usagePercent}% of the org's daily API requests (${Pt.apiUsage} of ${Pt.apiLimit}): ${Mt} masked \u2014 ${Ir}. ${Rr?"Resume it":"Run it again"} once the org has requests to spare.`:Wt===0?`Anonymization ${wt==="success"?"completed":wt}: ${Mt} records processed.`:`Anonymization ${wt}: ${Mt} masked, ${Wt} rejected by the org \u2014 those records still hold their original values.`,Go=Rr&&At>0?" Resume masks only what this run left.":"",Sr=hn(ms,this.orgNameOf(e.orgId)),Or=w?this.slicesSentence(w,H,c.voice,At>0,Te):"",Vo=qo+(Or?` ${Or}`:Go)+(Sr?` ${Sr}`:"")+(xn?` ${xn}`:"");c.ended({templateId:e.templateId,anonymizationMode:f?"everything":"standard",...f?{automatic:f}:{},status:wt,recordsProcessed:Mt,recordsFailed:Wt,recordsNotMasked:At,objects:$o(k),message:Vo,errors:yr,...ge?{cancelled:!0}:{},...Pt?{stoppedAtApiLimit:!0}:{},...N?{snapshot:N}:{},...i?{mutedAutomation:i.outcome}:{},...ms?{duplicates:ms}:{},...w?{slices:gn(w,{requestsSpent:P,stoppedOnBudget:H?.budget===!0})}:{},...F()})}catch(_){await d();let Z=await pt().catch(()=>{});Ne(_,!0,Z)}finally{let _=await d();if(_&&c.muted?.(_),b){let Z=k.some(ye=>ye.masked>0);ve(this.deps,{...y,outcome:Z?"partial":"failure",objects:S?Po(k):[]})}if($&&!I){try{fe()}catch(Z){this.deps.log(`[WARN] dataops:anonymize ${t}: its set of slices was not kept: `+v(Z))}_e()}ae&&(this.activeOrgOperations.delete(`backup:${e.orgId}`),this.sliceRunsOn.delete(e.orgId)),ce(xe),bt?.release(),s?.removeEventListener("abort",st),o.answer?.(_)}}handleAnonymizationTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.listedTemplates(),n=Ee(this.deps,e,"dataops:anonymization-templates:response",{templates:t});this.deps.broker.postToWebview(n),this.deps.log("[TX] dataops:anonymization-templates:response")}listedTemplates(){return[...Qt,zt,...this.savedTemplates.list()]}async handleBackupObjects(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=qe(ai,e,"dataops:error",this.deps);if(!t)return;let n=t.templateId!==void 0?this.findTemplate(t.templateId):void 0;if(t.templateId!==void 0&&!n){this.refuseUnknownTemplate("backup:objects",e,t.templateId);return}try{let s,i=()=>s??=Ue(t.orgId,this.deps.orgRegistry,this.deps.orgManager).then(l=>cr(l,this.deps.log)),o,a=()=>o??=Ue(t.orgId,this.deps.orgRegistry,this.deps.orgManager).then(async l=>(await Qs(Os(l,"backup:objects"),Is(l),Xs(Qt))).objects),d=[];for(let l of n?[n]:this.listedTemplates()){let u=$n({},l,de)&&await i(),f=Yt(l)?await a():In({},l,u);for(let p of f)p!==""&&p!=="*"&&!d.includes(p)&&d.push(p)}let c=Ee(this.deps,e,"backup:objects:response",{objects:d});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id} objects=${d.length}`)}catch(s){J(this.deps,"backup:objects","dataops:error",e,s)}}async plannedObjectsIn(e,t,n){let s=$n(t,n,de)&&await cr(e,this.deps.log);return In(t,n,s)}async handleAnonymizeCoverage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=qe(pi,e,"dataops:error",this.deps);if(!t)return;let n=this.findTemplate(t.templateId);if(!n){this.refuseUnknownTemplate("dataops:anonymize:coverage",e,t.templateId);return}try{let s=this.latestBackup(t.orgId),i=await Ue(t.orgId,this.deps.orgRegistry,this.deps.orgManager),o;if(Yt(n)){let T=await this.automaticTemplateOf(t.orgId,t.objects,"kept");n=T.template,o=T.plan}let a=[],d=await this.plannedObjectsIn(i,t,n),c=[];for(let T of d){if(!ur(n,T))continue;let g=Be(T),A=Sn(t,n,T),S=null,b;try{S=await this.countRows(i,g,void 0,A)}catch(L){this.deps.log(`[WARN] dataops:anonymize:coverage: ${g} not counted: ${v(L)}`),b=await this.approximateCount(i,g,L)}c.push({objectName:T,...S!==null?{rows:S}:b!==void 0?{rows:b}:{},...S===null&&b!==void 0?{approximate:!0}:{}});let $=s?.objects.find(L=>L.objectApiName.toLowerCase()===g.toLowerCase()),I=$?.where!==void 0&&$.where!==A;a.push({objectApiName:g,count:S,backedUp:I?0:$?.recordCount??0,truncated:!I&&$?.truncated===!0,...$?.stoppedAt&&!I?{stoppedAt:$.stoppedAt}:{},...I?{filtered:!0}:{}})}let l=this.sliceSets.openFor(t.orgId,t.templateId),u=l?.size??this.backupCap(),f;if(t.slices===!0||l!==void 0||c.some(T=>(T.rows??0)>this.backupCap())){let T=On(i),g=[];for(let b of c){if(b.rows===void 0)continue;let $=Bt(n,b.objectName),I=en(n,b.objectName),L=await this.maskedFields(T,Be(b.objectName),this.maskingRules(b.objectName,$),this.maskingRules(b.objectName,I)).then(({select:N})=>N.split(",").length,()=>$.length+I.length+1);g.push({objectApiName:Be(b.objectName),rows:b.rows,fields:L,...b.approximate?{approximate:!0}:{}})}let A=Ks(g,u,this.pageSizeFor(t.orgId),"masking");for(let b of a){let $=A.objects.find(I=>I.objectApiName===b.objectApiName);$&&(b.slicePlan=$)}let S=await this.freeBytes();f={requests:A.requests,parts:A.parts,bulkBatches:0,diskBytes:A.diskBytes,...S!==void 0?{diskFree:S}:{},seconds:A.seconds,apiBudget:await this.apiBudgetFor(i,A.requests)}}let p=new ut(this.deps.configStore),m=(l?p.load(t.orgId,t.templateId,Zt(n.rules,d,us(t),l.size)):void 0)??p.load(t.orgId,t.templateId,Zt(n.rules,d,us(t))),y=await this.maskingHistoryOf(i,On(i),this.historyWork(t,n,d),{count:!0}),k=Ee(this.deps,e,"dataops:anonymize:coverage:response",{templateId:t.templateId,...s?{backup:{operationId:s.operationId,timestamp:s.timestamp}}:{},objects:a,...m?{checkpoint:{id:m.id,savedAt:m.savedAt}}:{},...f?{plan:f}:{},...l?{sliceSet:ki(l)}:{},...y.length>0?{history:y.map(Oo)}:{},...o?{automatic:o}:{}});this.deps.broker.postToWebview(k),this.deps.log(`[TX] ${k.type} id=${k.id} objects=${a.length}`)}catch(s){J(this.deps,"dataops:anonymize:coverage","dataops:error",e,s)}}historyWork(e,t,n){return n.filter(s=>ur(t,s)).map(s=>{let i=Sn(e,t,s);return{objectName:s,...i!==void 0?{where:i}:{},objectRules:Bt(t,s),personRules:en(t,s)}})}async maskingHistoryOf(e,t,n,s){let i=[];for(let o of n){if(o.objectRules.length===0&&o.personRules.length===0)continue;let a=Be(o.objectName),d=await this.maskedFields(t,a,this.maskingRules(o.objectName,o.objectRules),this.maskingRules(o.objectName,o.personRules)).then(({rules:c})=>c.map(l=>l.fieldApiName).filter((l,u,f)=>l!=="Id"&&l!=="*"&&f.indexOf(l)===u),()=>[]);i.push({objectApiName:a,fields:d,records:o.where!==void 0?{where:o.where}:{all:!0}})}try{return await Hi(Ws(e,s.onRequest,o=>t.describe(o)),i,s)}catch(o){return this.deps.log("[WARN] dataops:anonymize: the field history of what it writes was not read: "+v(o)),[]}}async handleAnonymizePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=qe(fi,e,"dataops:error",this.deps);if(!t)return;let n=this.findTemplate(t.templateId);if(!n){this.refuseUnknownTemplate("dataops:anonymize:preview",e,t.templateId);return}try{let s=await Ue(t.orgId,this.deps.orgRegistry,this.deps.orgManager),i;if(Yt(n)){let f=await this.automaticTemplateOf(t.orgId,t.objects,"again");n=f.template,i=f.plan}let{AnonymizationEngine:o}=await import("./chunk-HGVPBJR6.mjs"),a=new o(void 0,this.maskingKey),d=[],c=[],l=On(s);for(let f of await this.plannedObjectsIn(s,t,n)){if(!ur(n,f))continue;let p=Be(f);try{let m=Bt(n,f),y=en(n,f),{rules:k,select:T,missing:g,rulesOf:A}=await this.maskedFields(l,p,this.maskingRules(f,m),this.maskingRules(f,y)),S=await Mo(s,p,T,vo,void 0,Sn(t,n,f));mt(s.limitInfo,`dataops:anonymize:preview ${p}`);let b=S.records.length>0;b&&c.push(...g.map(w=>({objectApiName:p,fieldApiName:w})));let[$]=b?await lr(l,[{objectApiName:p,rules:[...m,...y]}]):[],I=S.records.map(A),L=S.records.map((w,P)=>a.anonymize([w],I[P])[0]),N=k.map(w=>w.fieldApiName).filter((w,P,K)=>w!=="Id"&&K.indexOf(w)===P);d.push({objectApiName:p,fields:N,...b&&k.length===0?{notCovered:!0}:{},...$?{writeDenied:{deniedFields:[...$.deniedFields]}}:{},methods:Object.fromEntries(k.map(w=>[w.fieldApiName,w.method])),rows:S.records.slice(0,vo).map((w,P)=>{let K={},H={},Y=new Set(I[P].map(ae=>ae.fieldApiName));for(let ae of N)K[ae]=To(w[ae]),H[ae]=ct(w[ae])&&Y.has(ae)?To(L[P][ae]):K[ae];return{id:String(w.Id??""),before:K,after:H}})})}catch(m){let y=v(m);this.deps.log(`[WARN] dataops:anonymize:preview: ${p} not read: ${y}`),d.push({objectApiName:p,fields:[],rows:[],error:y})}}let u=Ee(this.deps,e,"dataops:anonymize:preview:response",{templateId:t.templateId,objects:d,fieldsNotFound:c,...i?{automatic:i}:{}});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id} objects=${d.length}`)}catch(s){J(this.deps,"dataops:anonymize:preview","dataops:error",e,s)}}latestBackup(e){let t;for(let n of this.deps.configStore.getKeysByPrefix("backup:")){let s=n.slice(7);if(s.includes(":"))continue;let i=this.deps.configStore.get(n);if(i?.orgId!==e||i.origin==="slice")continue;let o=i.timestamp??"";t&&t.timestamp.localeCompare(o)>=0||(t={operationId:s,timestamp:o,objects:i.objects??[]})}return t}handleTemplateSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=qe(mi,e,"dataops:error",this.deps);if(t)try{let n=t.name.trim();if(this.listedTemplates().some(a=>a.name.trim().toLowerCase()===n.toLowerCase())){J(this.deps,"dataops:anonymization-template:save","dataops:error",e,new Error(`A template named "${n}" already exists. Pick another name.`),{code:"DUPLICATE_NAME"});return}let i=this.savedTemplates.create(n,t.rules),o=Ee(this.deps,e,"dataops:anonymization-template:save:response",{template:i});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(n){J(this.deps,"dataops:anonymization-template:save","dataops:error",e,n)}}handleTemplateDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=qe(gi,e,"dataops:error",this.deps);if(!t)return;let{templateId:n}=t;if([...Qt,zt].some(s=>s.id===n)){J(this.deps,"dataops:anonymization-template:delete","dataops:error",e,new Error(`Template "${n}" ships with SandForge and cannot be deleted.`),{code:"BUILT_IN"});return}try{let s=this.savedTemplates.delete(n),i=Ee(this.deps,e,"dataops:anonymization-template:delete:response",{templateId:n,deleted:s});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(s){J(this.deps,"dataops:anonymization-template:delete","dataops:error",e,s)}}async handlePIIScan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=qe(hi,e,"dataops:error",this.deps);if(!t)return;let{orgId:n,objectNames:s}=t;try{if(!this.deps.infraServices?.piiDetector)throw new Error("PII Detector not available.");let i=await Ue(n,this.deps.orgRegistry,this.deps.orgManager),o=await Promise.all(s.map(async d=>{let c=Be(d),l=await i.describe(c);mt(i.limitInfo,`precheck:pii-scan describe ${c}`);let u=l.fields.map(p=>({apiName:p.name,label:p.label,type:p.type,length:p.length})),f=this.deps.infraServices.piiDetector.detectPII(d,u);return{objectName:d,piiFields:f.piiFields.map(p=>({fieldName:p.fieldApiName,piiType:p.classification,confidence:p.confidence}))}})),a=Ee(this.deps,e,"precheck:pii-scan:response",{success:!0,results:o});this.deps.broker.postToWebview(a)}catch(i){this.deps.log(`[ERR] precheck:pii-scan: ${v(i)}`);let o=Ee(this.deps,e,"precheck:pii-scan:response",{success:!1,error:v(i)});this.deps.broker.postToWebview(o)}}};export{Qt as a,Ji as b,zt as c,es as d,qn as e,Gn as f,St as g,yn as h,_s as i,Jo as j,Ws as k,Hi as l,Vn as m,Hs as n,Us as o,Ki as p,Ia as q,Ic as r,Sc as s,Oc as t,rs as u,os as v,Rn as w,sr as x,xc as y,zc as z,Lc as A,Yn as B,qs as C,Ld as D,Dd as E,id as F,vn as G,Lo as H};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a,b}from"./chunk-A7YP27GQ.mjs";import"./chunk-CRPLDXJU.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as describedFieldsOf,b as requiredForAccountKinds};
7
+ import{a,b}from"./chunk-BNHJCJJM.mjs";import"./chunk-J347SPU6.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as describedFieldsOf,b as requiredForAccountKinds};
@@ -4,6 +4,6 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{e as k,f as w}from"./chunk-QBYK5XIT.mjs";import{g as A,k as S}from"./chunk-H4OBZIX3.mjs";import{Sb as T,Tb as h}from"./chunk-CRPLDXJU.mjs";import{mkdir as v,rename as D,writeFile as x}from"node:fs/promises";import*as f from"node:path";var y="CaseId",O=80;function $(e){let t=T.safeParse(e.choice);if(!t.success)return{ok:!1,refusals:t.error.issues.map(a=>({code:"choice-invalid",name:a.path.join("."),message:a.message}))};let n=t.data,s=A(e.catalog,n.agent);if(!s)return{ok:!1,refusals:[{code:"agent-absent",name:n.agent,message:`"${n.agent}" is not one of this org's agents`}]};let r=P(n,s,E(e.compiled.tests));if(r.length>0)return{ok:!1,refusals:r};let i=new Map(n.topics.map(a=>[a.packTopic,a])),c=S(s,y)?y:void 0,g=[],o=[];for(let a of e.compiled.tests){if(a.topicKey===null){if(n.guardTopic===null){o.push({test:a.key,reason:"no-guard-topic",message:`"${a.utterance}" is on no topic of the scenario, and no topic of the agent is chosen to decline it: the test is left out`});continue}g.push({key:a.key,utterance:a.utterance,expectedTopic:n.guardTopic,expectedActions:[],expectedOutcome:a.expectedOutcome,contextVariables:[]});continue}let u=i.get(a.topicKey),p=[];if(a.openCase){let m=e.openCaseIds[a.openCase.caseKey];if(m===void 0){o.push({test:a.key,reason:"case-not-written",message:`The case ${a.openCase.caseKey} the test is about was not written by the run: the test is left out`});continue}c!==void 0&&p.push({name:c,value:m})}g.push({key:a.key,utterance:a.utterance,expectedTopic:u.agentTopic,expectedActions:[...u.actions],expectedOutcome:j(a),contextVariables:p})}return g.length===0?{ok:!1,refusals:[{code:"no-test-left",name:e.compiled.packId,message:"No test of the scenario is left to write: "+o.map(a=>a.message).join("; ")}]}:{ok:!0,spec:{name:M(e.compiled.template.name),description:F(e.compiled.packId,e.compiled.seed,e.runId),subjectName:s.name,testCases:g},choice:n,leftOut:o,...c!==void 0?{contextVariable:c}:{}}}function E(e){return[...new Set(e.flatMap(t=>t.topicKey===null?[]:[t.topicKey]))]}function P(e,t,n){let s=[],r=new Map(t.topics.map(o=>[o.name,o])),i=new Set(t.topics.flatMap(o=>o.actions.map(a=>a.name))),c=o=>({code:"topic-absent",name:o,message:`"${o}" is not a topic of the agent ${t.name}`});for(let o of e.topics){n.includes(o.packTopic)||s.push({code:"pack-topic-unknown",name:o.packTopic,message:`"${o.packTopic}" is not a topic of the scenario`});let a=r.get(o.agentTopic);if(!a){s.push(c(o.agentTopic));continue}let u=new Set(a.actions.map(p=>p.name));for(let p of o.actions)u.has(p)||s.push(i.has(p)?{code:"action-not-of-topic",name:p,message:`"${p}" is not an action of the topic ${a.name}, which the agent answers "${o.packTopic}" from`}:{code:"action-absent",name:p,message:`"${p}" is not an action of the agent ${t.name}`})}let g=new Set(e.topics.map(o=>o.packTopic));for(let o of n)g.has(o)||s.push({code:"pack-topic-unmatched",name:o,message:`The topic "${o}" of the scenario is matched to no topic of the agent`});return e.guardTopic!==null&&!r.has(e.guardTopic)&&s.push(c(e.guardTopic)),s}function j(e){if(!e.article)return e.expectedOutcome;let t=e.article.facts.length>0?`, which states: ${e.article.facts.join("; ")}`:"";return`${e.expectedOutcome} The answer draws on the article "${e.article.title}"${t}.`}function M(e){let t=" (SandForge)",n=O-t.length;return`${e.length>n?e.slice(0,n).trimEnd():e}${t}`}function F(e,t,n){let s=n!==void 0?`, written by the seed run ${n}`:"";return`SandForge scenario ${e}, seed ${t}${s}. Its cases are about the records that run wrote: once it is removed, they are about none.`}var C="specs",L=80,V=10;function K(e,t){return G(h(e,t))}function W(e,t,n){let s=n==="agentforce-studio"?"ngtTestSpec":"testSpec";return`${b(e)}-${b(t)}-sandforge-${s}.yaml`}function z(e,t){let n=c=>c.replace(/[^A-Za-z0-9]+/g,"_").replace(/^_+|_+$/g,""),s=`${n(t)}_SandForge`,r=n(e);/^[A-Za-z]/.test(r)||(r=`Agent_${r}`.replace(/_+$/,""));let i=L-s.length-1;return r=r.slice(0,i).replace(/_+$/,""),`${r}_${s}`}function Z(e){let t=e.runner==="agentforce-studio"?["--test-runner","agentforce-studio"]:[],n=["sf","agent","test","create","--spec",e.specPath,"--api-name",e.apiName,...t,"-o",e.alias],s=["sf","agent","test","run","--api-name",e.apiName,"--wait",String(V),...t,"-o",e.alias];return{create:{argv:n,line:R(n)},run:{argv:s,line:R(s)}}}function te(){return{mkdir:async e=>{await v(e,{recursive:!0})},writeNew:async(e,t)=>{try{return await x(e,t,{encoding:"utf8",flag:"wx"}),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}},replace:async(e,t)=>{let n=`${e}.${process.pid}.tmp`;await x(n,t,"utf8"),await D(n,e)}}}async function X(e,t){let n=W(t.model.subjectName,t.packId,t.runner),s=`${C}/${n}`,r=f.join(t.projectDir,C,n),i=K(t.model,t.runner);if(await e.mkdir(f.dirname(r)),t.overwrite===!0)await e.replace(r,i);else if(!await e.writeNew(r,i))return{kind:"exists",path:r,specPath:s};let c=z(t.model.subjectName,t.packId);return{kind:"written",path:r,specPath:s,apiName:c,commands:Z({specPath:s,apiName:c,alias:t.alias,runner:t.runner})}}async function ne(e,t){let n=w(t.sidecar,t.pack);if(!n.ok)return{kind:"refused",refusals:[{code:"pack-changed",name:t.pack.id,message:n.message}]};let s=$({compiled:n.compiled,catalog:t.catalog,choice:t.choice,openCaseIds:t.sidecar.openCases,runId:t.sidecar.runId});if(!s.ok)return{kind:"refused",refusals:s.refusals};let{choice:r}=s,i=await X(e,{projectDir:t.projectDir,model:s.spec,runner:r.runner,packId:t.pack.id,alias:t.alias,...t.overwrite!==void 0?{overwrite:t.overwrite}:{}});return i.kind==="exists"?i:{...i,leftOut:s.leftOut,sidecar:k(t.sidecar,r)}}function G(e){return`${l(e,0).join(`
7
+ import{e as k,f as w}from"./chunk-QACFTHJM.mjs";import{g as A,k as S}from"./chunk-H4OBZIX3.mjs";import{Vb as T,Wb as h}from"./chunk-J347SPU6.mjs";import{mkdir as v,rename as D,writeFile as x}from"node:fs/promises";import*as f from"node:path";var y="CaseId",O=80;function $(e){let t=T.safeParse(e.choice);if(!t.success)return{ok:!1,refusals:t.error.issues.map(a=>({code:"choice-invalid",name:a.path.join("."),message:a.message}))};let n=t.data,s=A(e.catalog,n.agent);if(!s)return{ok:!1,refusals:[{code:"agent-absent",name:n.agent,message:`"${n.agent}" is not one of this org's agents`}]};let r=P(n,s,E(e.compiled.tests));if(r.length>0)return{ok:!1,refusals:r};let i=new Map(n.topics.map(a=>[a.packTopic,a])),c=S(s,y)?y:void 0,g=[],o=[];for(let a of e.compiled.tests){if(a.topicKey===null){if(n.guardTopic===null){o.push({test:a.key,reason:"no-guard-topic",message:`"${a.utterance}" is on no topic of the scenario, and no topic of the agent is chosen to decline it: the test is left out`});continue}g.push({key:a.key,utterance:a.utterance,expectedTopic:n.guardTopic,expectedActions:[],expectedOutcome:a.expectedOutcome,contextVariables:[]});continue}let u=i.get(a.topicKey),p=[];if(a.openCase){let m=e.openCaseIds[a.openCase.caseKey];if(m===void 0){o.push({test:a.key,reason:"case-not-written",message:`The case ${a.openCase.caseKey} the test is about was not written by the run: the test is left out`});continue}c!==void 0&&p.push({name:c,value:m})}g.push({key:a.key,utterance:a.utterance,expectedTopic:u.agentTopic,expectedActions:[...u.actions],expectedOutcome:j(a),contextVariables:p})}return g.length===0?{ok:!1,refusals:[{code:"no-test-left",name:e.compiled.packId,message:"No test of the scenario is left to write: "+o.map(a=>a.message).join("; ")}]}:{ok:!0,spec:{name:M(e.compiled.template.name),description:F(e.compiled.packId,e.compiled.seed,e.runId),subjectName:s.name,testCases:g},choice:n,leftOut:o,...c!==void 0?{contextVariable:c}:{}}}function E(e){return[...new Set(e.flatMap(t=>t.topicKey===null?[]:[t.topicKey]))]}function P(e,t,n){let s=[],r=new Map(t.topics.map(o=>[o.name,o])),i=new Set(t.topics.flatMap(o=>o.actions.map(a=>a.name))),c=o=>({code:"topic-absent",name:o,message:`"${o}" is not a topic of the agent ${t.name}`});for(let o of e.topics){n.includes(o.packTopic)||s.push({code:"pack-topic-unknown",name:o.packTopic,message:`"${o.packTopic}" is not a topic of the scenario`});let a=r.get(o.agentTopic);if(!a){s.push(c(o.agentTopic));continue}let u=new Set(a.actions.map(p=>p.name));for(let p of o.actions)u.has(p)||s.push(i.has(p)?{code:"action-not-of-topic",name:p,message:`"${p}" is not an action of the topic ${a.name}, which the agent answers "${o.packTopic}" from`}:{code:"action-absent",name:p,message:`"${p}" is not an action of the agent ${t.name}`})}let g=new Set(e.topics.map(o=>o.packTopic));for(let o of n)g.has(o)||s.push({code:"pack-topic-unmatched",name:o,message:`The topic "${o}" of the scenario is matched to no topic of the agent`});return e.guardTopic!==null&&!r.has(e.guardTopic)&&s.push(c(e.guardTopic)),s}function j(e){if(!e.article)return e.expectedOutcome;let t=e.article.facts.length>0?`, which states: ${e.article.facts.join("; ")}`:"";return`${e.expectedOutcome} The answer draws on the article "${e.article.title}"${t}.`}function M(e){let t=" (SandForge)",n=O-t.length;return`${e.length>n?e.slice(0,n).trimEnd():e}${t}`}function F(e,t,n){let s=n!==void 0?`, written by the seed run ${n}`:"";return`SandForge scenario ${e}, seed ${t}${s}. Its cases are about the records that run wrote: once it is removed, they are about none.`}var C="specs",L=80,V=10;function K(e,t){return G(h(e,t))}function W(e,t,n){let s=n==="agentforce-studio"?"ngtTestSpec":"testSpec";return`${b(e)}-${b(t)}-sandforge-${s}.yaml`}function z(e,t){let n=c=>c.replace(/[^A-Za-z0-9]+/g,"_").replace(/^_+|_+$/g,""),s=`${n(t)}_SandForge`,r=n(e);/^[A-Za-z]/.test(r)||(r=`Agent_${r}`.replace(/_+$/,""));let i=L-s.length-1;return r=r.slice(0,i).replace(/_+$/,""),`${r}_${s}`}function Z(e){let t=e.runner==="agentforce-studio"?["--test-runner","agentforce-studio"]:[],n=["sf","agent","test","create","--spec",e.specPath,"--api-name",e.apiName,...t,"-o",e.alias],s=["sf","agent","test","run","--api-name",e.apiName,"--wait",String(V),...t,"-o",e.alias];return{create:{argv:n,line:R(n)},run:{argv:s,line:R(s)}}}function te(){return{mkdir:async e=>{await v(e,{recursive:!0})},writeNew:async(e,t)=>{try{return await x(e,t,{encoding:"utf8",flag:"wx"}),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}},replace:async(e,t)=>{let n=`${e}.${process.pid}.tmp`;await x(n,t,"utf8"),await D(n,e)}}}async function X(e,t){let n=W(t.model.subjectName,t.packId,t.runner),s=`${C}/${n}`,r=f.join(t.projectDir,C,n),i=K(t.model,t.runner);if(await e.mkdir(f.dirname(r)),t.overwrite===!0)await e.replace(r,i);else if(!await e.writeNew(r,i))return{kind:"exists",path:r,specPath:s};let c=z(t.model.subjectName,t.packId);return{kind:"written",path:r,specPath:s,apiName:c,commands:Z({specPath:s,apiName:c,alias:t.alias,runner:t.runner})}}async function ne(e,t){let n=w(t.sidecar,t.pack);if(!n.ok)return{kind:"refused",refusals:[{code:"pack-changed",name:t.pack.id,message:n.message}]};let s=$({compiled:n.compiled,catalog:t.catalog,choice:t.choice,openCaseIds:t.sidecar.openCases,runId:t.sidecar.runId});if(!s.ok)return{kind:"refused",refusals:s.refusals};let{choice:r}=s,i=await X(e,{projectDir:t.projectDir,model:s.spec,runner:r.runner,packId:t.pack.id,alias:t.alias,...t.overwrite!==void 0?{overwrite:t.overwrite}:{}});return i.kind==="exists"?i:{...i,leftOut:s.leftOut,sidecar:k(t.sidecar,r)}}function G(e){return`${l(e,0).join(`
8
8
  `)}
9
9
  `}function l(e,t){let n=" ".repeat(t),s=[];for(let[r,i]of Object.entries(e)){if(i===void 0)continue;let c=`${n}${J(r)}:`;Array.isArray(i)?i.length===0?s.push(`${c} []`):s.push(c,...I(i,t+2)):d(i)?Object.values(i).every(g=>g===void 0)?s.push(`${c} {}`):s.push(c,...l(i,t+2)):s.push(`${c} ${_(i)}`)}return s}function I(e,t){let n=" ".repeat(t),s=[];for(let r of e){let i=Array.isArray(r)?r.length===0?void 0:I(r,t+2):d(r)&&Object.values(r).some(c=>c!==void 0)?l(r,t+2):void 0;if(i===void 0){s.push(`${n}- ${Array.isArray(r)?"[]":d(r)?"{}":_(r)}`);continue}s.push(`${n}- ${i[0].slice(t+2)}`,...i.slice(1))}return s}function d(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function J(e){return/^[A-Za-z_][A-Za-z0-9_]*$/.test(e)?e:N(e)}function _(e){if(typeof e=="string")return N(e);if(typeof e=="boolean"||typeof e=="number"&&Number.isFinite(e))return String(e);if(e===null)return"null";throw new TypeError(`No YAML scalar for ${typeof e}`)}function N(e){return JSON.stringify(e).replace(/[\u007f-\u009f\u2028\u2029\ufeff\ufffe\uffff]/g,t=>`\\u${t.charCodeAt(0).toString(16).padStart(4,"0")}`)}function b(e){return e.replace(/[^A-Za-z0-9_-]/g,"_")}function R(e){return e.map(t=>/^[A-Za-z0-9_./:@=+,-]+$/.test(t)?t:`"${t.replace(/(["\\])/g,"\\$1")}"`).join(" ")}export{C as a,V as b,K as c,W as d,z as e,Z as f,te as g,X as h,ne as i,G as j};
@@ -4,6 +4,6 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a as d,b as g,c as f}from"./chunk-CI2O7WBH.mjs";import{a as s,b as a}from"./chunk-Q7TLC3I2.mjs";function c(n,t,e){if(!g(t))return;let o=t.edition?`IsSandbox false, edition ${t.edition}`:"IsSandbox false, and no edition",r=e.action==="write"?`${e.tool} writes to sandboxes and Developer Edition orgs only. Nothing was written`:`${e.tool} deletes from sandboxes and Developer Edition orgs only. Nothing was deleted`;return`${n} is a production org (its Organization record says ${o}): ${r}; ${e.readOnly}, which only reads, runs against it.`}function p(n,t,e){let o=t instanceof Error?t.message:String(t),r=`Nothing was ${e.action==="write"?"written":"deleted"}.`,i=`${e.tool} ${e.action==="write"?"writes to":"deletes from"} no org it cannot tell from a production one`;return s(t)?`${n} refused the session sf gave for it (${o}), and ${i}. "sf org display --target-org ${n}" says what sf holds for it; "sf org login web --alias ${n}" signs in again (in a CI job, "sf org login jwt" or "sf org login sfdx-url"); then run the command again. ${r}`:a(t)?`${n} did not answer (${o}), and ${i}. Run the command again once it answers. ${r}`:f(t)?`${n} would not show its Organization record (${o}), and ${i}. Reading it takes the View Setup and Configuration permission: give it to the user the alias signs in as, or name an alias of a user who has it. ${r}`:`${n} did not say what org it is (${o}), and ${i}. ${r}`}var u=1;async function y(n,t,e){let o;try{o=await d(n)}catch(i){process.stderr.write(`${p(t,i,e)}
7
+ import{a as d,b as g,c as f}from"./chunk-65AMXOQU.mjs";import{a as s,b as a}from"./chunk-Q7TLC3I2.mjs";function c(n,t,e){if(!g(t))return;let o=t.edition?`IsSandbox false, edition ${t.edition}`:"IsSandbox false, and no edition",r=e.action==="write"?`${e.tool} writes to sandboxes and Developer Edition orgs only. Nothing was written`:`${e.tool} deletes from sandboxes and Developer Edition orgs only. Nothing was deleted`;return`${n} is a production org (its Organization record says ${o}): ${r}; ${e.readOnly}, which only reads, runs against it.`}function p(n,t,e){let o=t instanceof Error?t.message:String(t),r=`Nothing was ${e.action==="write"?"written":"deleted"}.`,i=`${e.tool} ${e.action==="write"?"writes to":"deletes from"} no org it cannot tell from a production one`;return s(t)?`${n} refused the session sf gave for it (${o}), and ${i}. "sf org display --target-org ${n}" says what sf holds for it; "sf org login web --alias ${n}" signs in again (in a CI job, "sf org login jwt" or "sf org login sfdx-url"); then run the command again. ${r}`:a(t)?`${n} did not answer (${o}), and ${i}. Run the command again once it answers. ${r}`:f(t)?`${n} would not show its Organization record (${o}), and ${i}. Reading it takes the View Setup and Configuration permission: give it to the user the alias signs in as, or name an alias of a user who has it. ${r}`:`${n} did not say what org it is (${o}), and ${i}. ${r}`}var u=1;async function y(n,t,e){let o;try{o=await d(n)}catch(i){process.stderr.write(`${p(t,i,e)}
8
8
  `),process.exit(u)}let r=c(t,o,e);return r!==void 0&&(process.stderr.write(`${r}
9
9
  `),process.exit(u)),o}export{c as a,p as b,y as c};
@@ -4,4 +4,4 @@ import { dirname as __sandforgeDirname } from 'node:path';
4
4
  const require = __sandforgeRequire(import.meta.url);
5
5
  const __filename = __sandforgePath(import.meta.url);
6
6
  const __dirname = __sandforgeDirname(__filename);
7
- import{a,b,c,d,e,f,g,h,i,j}from"./chunk-IZ2M2RGO.mjs";import"./chunk-S6BMJSLD.mjs";import"./chunk-H33DVU3D.mjs";import"./chunk-ROTDZKOE.mjs";import"./chunk-YTBM3TSW.mjs";import"./chunk-SF52ZSIV.mjs";import"./chunk-CI2O7WBH.mjs";import"./chunk-VV3B6IC3.mjs";import"./chunk-Q7TLC3I2.mjs";import"./chunk-FG4Y4ZVL.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-THYQOG24.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-CRPLDXJU.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as RECOVERY_HANDOFF_DIR_MODE,b as RECOVERY_HANDOFF_FILE_MODE,c as RECOVERY_HANDOFF_FOLDER,d as journalDirOf,h as lastHandoffOf,g as newestHandoffOf,e as recoveryHandoffFolderOf,i as recoveryHandoffNoteOf,f as recoveryHandoffPathOf,j as writeRecoveryHandoff};
7
+ import{a,b,c,d,e,f,g,h,i,j}from"./chunk-JANBNTR5.mjs";import"./chunk-CT324C7I.mjs";import"./chunk-H33DVU3D.mjs";import"./chunk-DUBECLZV.mjs";import"./chunk-LHNAR6FC.mjs";import"./chunk-4CSBZZAL.mjs";import"./chunk-65AMXOQU.mjs";import"./chunk-VV3B6IC3.mjs";import"./chunk-Q7TLC3I2.mjs";import"./chunk-DAUX63UB.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-22L43JMK.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-J347SPU6.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{a as RECOVERY_HANDOFF_DIR_MODE,b as RECOVERY_HANDOFF_FILE_MODE,c as RECOVERY_HANDOFF_FOLDER,d as journalDirOf,h as lastHandoffOf,g as newestHandoffOf,e as recoveryHandoffFolderOf,i as recoveryHandoffNoteOf,f as recoveryHandoffPathOf,j as writeRecoveryHandoff};