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,21 @@
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 XS,b as Rd,c as KS,d as YS}from"./chunk-BXZ73A5M.mjs";import{b as WS}from"./chunk-XV4CVZYD.mjs";import{a as RR}from"./chunk-BLMJ4WVI.mjs";import{c as wR,d as bR}from"./chunk-4NSXPONF.mjs";import{d as QS,m as ZS}from"./chunk-TAN2CIRI.mjs";import{a as zS,b as co,c as ei,d as dp,e as cp,f as up,g as GS,h as lp}from"./chunk-LHNAR6FC.mjs";import{a as _l,b as mR,c as yR,d as za,f as Xs}from"./chunk-4VLP6RHC.mjs";import{h as XR,k as Vl,m as rv,n as nv,o as Ys,p as qo,q as Xl,r as Qs,s as ov,t as sv,u as iv,v as av,w as dv,x as cv}from"./chunk-YRULC27A.mjs";import{a as Zv,b as sp,c as DS,d as NS,e as jS,h as MS,i as LS,j as FS,k as _S,n as US,o as HS,p as yd,q as ip,r as wd,s as ap}from"./chunk-GYDTM62J.mjs";import{b as $S,e as xS}from"./chunk-HLROVOR6.mjs";import{A as lS,B as pS,C as fS,D as gS,E as fd,F as hS,G as mS,H as gd,I as hd,J as md,K as Nn,L as yS,M as wS,P as bS,Q as RS,R as vS,S as SS,T as kS,V as OS,W as op,X as IS,Y as AS,Z as TS,a as nd,c as od,ca as ES,d as sd,e as eS,ea as PS,f as tS,fa as CS,g as rS,h as Pt,j as Vo,k as id,l as Xo,o as ad,p as tn,q as Ko,r as Yo,s as Qo,t as nS,u as oS,v as sS,w as dd,x as cd,y as ud,z as iS}from"./chunk-WF5S4FW5.mjs";import{b as ld,g as pd}from"./chunk-FV6MOSHD.mjs";import{e as Ar,g as aS,i as dS,k as cS,l as Zo,m as uS}from"./chunk-FYG47CNA.mjs";import{a as qS,d as es,e as jn,f as bd,g as JS,h as VS}from"./chunk-ON7Y63FK.mjs";import{a as BS}from"./chunk-7KHA5UIQ.mjs";import{A as eR,D as oR,H as hR,a as em,b as hm,d as ba,i as Pl,j as Qw,k as Cl,l as Zw,m as eb,n as tb,o as rb,p as nb,u as Na,v as An,w as sr,x as Yb,y as Qb,z as Zb}from"./chunk-YTOTMJTY.mjs";import{a as Rt,b as Pb}from"./chunk-WJGK6VGU.mjs";import{b as Yw}from"./chunk-54V4FVEY.mjs";import{a as jb,b as Mb}from"./chunk-XCA5AONB.mjs";import{$ as Do,$b as Aw,A as Fm,Ab as ew,Ac as x,B as Sn,Bb as tw,C as Sl,Cb as rw,D as _m,Db as nw,E as Um,Eb as ow,F as va,Fa as Ry,Fb as sw,G as Hm,Ga as vy,Gb as iw,H as Bm,Ha as Sy,Hb as aw,I as qm,Ia as ky,Ib as dw,J as Wm,Ja as Oy,Jb as ka,K as zm,Ka as Iy,Kb as cw,L as Gm,La as Ay,Lb as uw,M as kl,Ma as Ty,Mb as lw,Mc as Da,N as Jm,Na as Ey,Nb as pw,O as Vm,Oa as Py,Ob as fw,P as Xm,Pa as Cy,Pb as gw,Q as Km,Qa as $y,Qb as hw,R as Ym,Ra as xy,Rb as mw,Rc as et,S as Qm,Sa as Yr,Sb as yw,Sc as oo,T as Zm,Ta as Dy,Tb as ww,Tc as Lb,U as ey,Ua as Tl,Ub as bw,Uc as Fb,V as ty,Va as Sa,Vb as Rw,W as ry,Wa as Bs,Wb as vw,X as ny,Xa as Ny,Xb as Sw,Y as oy,Ya as jy,Yb as kw,Z as sy,Zb as Ow,_ as iy,_b as Iw,a as Gr,aa as ay,ac as Tw,b as ve,ba as dy,bc as Ew,c as ua,ca as cy,cc as Pw,d as Dt,da as uy,dc as Cw,e as bn,ea as Ol,ec as $w,f as xo,fa as ly,fc as xw,g as ut,ga as py,gc as Dw,h as yr,ha as fy,hc as Nw,i as Rn,ia as gy,ib as My,ic as jw,j as A,ja as hy,jb as Ly,jc as Mw,k as Ae,ka as my,kb as Fy,kc as Lw,l as Ge,la as yy,lb as _y,lc as Fw,m as _e,ma as wy,mb as Uy,mc as _w,n as me,na as by,nb as Hy,nc as Uw,o as T,oa as Il,ob as By,oc as Hw,p as la,pa as Al,pb as qy,pc as Oa,q as js,qa as Hs,qb as Wy,qc as Bw,r as Jr,rb as zy,rc as qw,s as Le,sb as Gy,sc as Ww,t as Dm,tb as Jy,tc as zw,u as Nm,ub as Vy,uc as Gw,v as jm,vb as Xy,vc as Jw,w as Mm,wb as Ky,wc as Vw,x as Ra,xb as Yy,xc as Xw,yb as Qy,yc as Kw,z as Lm,zb as Zy,zc as El}from"./chunk-CJAWKLAL.mjs";import{c as km}from"./chunk-PE7CHD2W.mjs";import{g as xa}from"./chunk-VKREON6Q.mjs";import{a as Ft,b as _s,c as vm,d as Sm}from"./chunk-CE6ZDGBB.mjs";import{a as _b,b as Ub,c as Hb,e as Bb,f as qb,g as Ma,h as Fo,i as io,j as Qr,k as Tn,l as La}from"./chunk-VFKG2G37.mjs";import{b as so,c as Kb}from"./chunk-BOGNK4LV.mjs";import{$a as Fv,A as lv,Aa as Ev,Ca as Pv,Da as Cv,E as pv,Ea as $v,Fa as xv,Ga as Dv,Ia as Nv,Ja as jv,Ka as tp,Ma as Wo,Oa as Mv,T as fv,Xa as Lv,Za as zo,a as sa,aa as Za,ab as Go,b as Nh,ba as Sv,bb as Jo,fb as _v,ga as Yl,gb as Ir,h as VR,ha as Ql,hb as rp,i as Jl,ib as Bv,ja as Zl,jb as qv,kb as Wv,lb as zv,mb as Gv,n as uv,na as ed,nb as td,ob as rd,pa as kv,ra as ep,rb as Jv,sa as Ov,sb as Vv,ua as Iv,ub as np,vb as Xv,wa as Av,wb as Kv,xb as Yv,ya as Tv,yb as Qv,za as Zs}from"./chunk-C5AUNG6T.mjs";import{c as pa,d as fa,e as Sb,f as No,g as jo,h as In,i as kb,j as Ob,k as Dl,n as Cb,o as $b,p as ja,q as xb,r as Db,u as Ll,v as Vs,w as ao,x as qa}from"./chunk-7O6EFNQS.mjs";import{A as wb,B as or,C as Ea,D as Pa,E as Ca,G as On,J as bb,K as $l,L as xl,M as Wt,N as Rb,O as vb,P as $a,a as Yh,b as tm,c as rm,d as nm,e as Vr,f as yl,g as wl,h as om,i as sm,j as im,k as am,l as to,n as qs,o as ub,p as lb,r as pb,s as fb,t as Ws,v as gb,w as hb,x as mb,y as yb}from"./chunk-3LRFPGYZ.mjs";import{b as Uv,c as Hv}from"./chunk-34SMB5PA.mjs";import{i as KR}from"./chunk-AVY742BJ.mjs";import{a as YR,b as QR,f as ZR,g as ev,h as tv}from"./chunk-BWWQXU2B.mjs";import{b as Ib,f as Ab,p as Nt,q as zs,r as Nl,s as Lo,t as jl,u as Gs,x as Tb,y as Eb}from"./chunk-KWUS7UAV.mjs";import{a as lR,b as Wa,c as pR,m as fR,r as gR}from"./chunk-HZCS6EED.mjs";import{d as dm,e as cm,h as um,i as lm,j as pm,m as fm,o as gm}from"./chunk-NV5QA2HY.mjs";import{a as Nb}from"./chunk-YYZL7UGV.mjs";import{a as Ia,c as Aa}from"./chunk-YDXMTWAT.mjs";import{g as ga}from"./chunk-TYUYPFDJ.mjs";import{b as gv,c as hv,d as mv,e as Qa,f as Kl,h as yv,i as wv,j as bv,k as Rv,n as vv}from"./chunk-TICZXC53.mjs";import{c as wr,d as no}from"./chunk-DLSU66MY.mjs";import{b as Ha,f as Ba}from"./chunk-ATQML7ZK.mjs";import{L as nR,d as Fa,h as _a,i as tR,k as rR,z as Ua}from"./chunk-4CSBZZAL.mjs";import{a as ha,b as qt,c as Xr,d as Ls,e as ma,f as Fs,g as ya,h as vn,i as mm,j as wa,k as bl}from"./chunk-GP5J3DGS.mjs";import{a as $e}from"./chunk-5LFSFYFJ.mjs";import{b as Dh}from"./chunk-WQCXOZEJ.mjs";import{a as ll,c as Eo,d as pl,e as Ih,f as Ds,g as fl,h as Ah,j as Th,k as Eh,l as Po,m as Ph,n as gl,o as Ch,p as $h,q as xh,r as B}from"./chunk-OT2NHL2V.mjs";import{a as Wb,b as Gt,c as Jt,g as ir}from"./chunk-ZVU7MD2S.mjs";import{$a as SR,Bc as Dn,Cc as Ks,Ec as ql,Fc as Wl,Gc as zl,Hc as qR,Ic as WR,Jc as zR,Kb as ER,Kc as Gl,L as sR,Lb as PR,Mb as CR,N as iR,Nb as Sr,Nc as gt,Ob as kr,Oc as Ya,P as aR,Pb as Ka,Pc as GR,Qb as $R,Qc as JR,S as dR,Sb as Bl,T as cR,U as Fl,Va as en,Wb as xR,X as uR,Xa as Ul,Ya as vR,ac as DR,b as ym,bb as En,bc as NR,c as wm,cb as Ga,cc as jR,d as ot,db as Hl,dc as Or,e as bm,eb as kR,f as Rl,fb as OR,g as Rm,h as Kr,hb as IR,i as vl,ib as AR,j as _t,jb as TR,jc as MR,k as jt,kb as Vt,lc as LR,m as Jb,mb as vr,mc as FR,nb as ar,nc as _R,o as Ml,oc as UR,p as br,pc as HR,q as Vb,rb as Pn,s as Et,sb as Uo,sc as BR,t as Xb,tb as Ja,ub as Ho,uc as $n,vb as Cn,vc as xn,w as Js,wb as Bo,x as Qt,xb as Va,zb as Xa}from"./chunk-OLCS7JCT.mjs";import{a as Qh,f as $o,g as ht,h as Zh,j as Tt,k as Y,l as bt}from"./chunk-TQ6HEJ73.mjs";import{a as na,f as oa}from"./chunk-65AMXOQU.mjs";import{q as Rr,r as Zr,s as _o}from"./chunk-6HHSAPIM.mjs";import{a as zt,b as pe}from"./chunk-VV3B6IC3.mjs";import{a as ie}from"./chunk-4TLYUZD5.mjs";import{i as Ms}from"./chunk-INIT2UKJ.mjs";import{a as Oh,b as xs,c as ul}from"./chunk-Q7TLC3I2.mjs";import{e as ib,h as kn,k as ab,l as db,m as cb}from"./chunk-ATBQIE2V.mjs";import{b as Ta}from"./chunk-UCUFLFNK.mjs";import{D as Us,F as xm,p as Em}from"./chunk-4XROG5CT.mjs";import{b as Om,e as Im,k as Am,m as Tm}from"./chunk-HFSBDM7B.mjs";import{a as nr}from"./chunk-EADHKH3A.mjs";import{c as zh,f as ca,g as Gh,j as Jh,l as Vh,r as Xh,s as Kh}from"./chunk-DAUX63UB.mjs";import{$ as Wh,F as mr,G as Ns,N as Uh,P as Hh,Y as Bh,Z as qh,a as ia,b as rr,c as aa,f as Mh,j as Lh,m as da,n as ml,o as Fh,p as _h,q as Co,r as hr}from"./chunk-SZOJ7BEJ.mjs";import{a as tr,d as hl,f as jh,h as Xe}from"./chunk-TZE3Y7IQ.mjs";import{a as kh,b as I}from"./chunk-CA5NAXSU.mjs";import{a as zb,b as Gb}from"./chunk-PC247GKX.mjs";import{f as ob,j as sb}from"./chunk-22L43JMK.mjs";import{a as Mo,d as ro}from"./chunk-TUACWKIH.mjs";import{a as Cm,d as $m}from"./chunk-3KJCSYXY.mjs";import{a as Pm}from"./chunk-HDDJ3CVN.mjs";import{$ as Wi,$c as St,$e as cl,A as Is,Aa as Ng,Bd as eh,Be as uh,Cc as Vi,Cd as th,Ce as lh,Da as Hr,Dd as ol,De as Ps,Ea as zi,Ec as Xi,Ed as qr,Fa as jg,Ga as Xu,Gc as As,Gd as rh,Ha as Ku,Hd as Ts,He as ph,I as Eg,Ia as Mg,Id as Qi,Ie as fh,Ja as Yu,Jd as sl,Je as gh,Kd as yn,Ke as hh,Ld as nh,Le as mh,Md as Wr,Nd as oh,Ob as Ug,Od as il,Oe as wn,Pa as Lg,Pb as Zn,Pd as sh,Pe as xt,Qa as Fg,Qb as Zu,Qe as Zi,Rb as el,Re as Cs,Sb as Hg,Se as $s,Tb as Bg,Td as ih,Te as ea,Ud as ah,Ue as al,Ve as yh,We as dl,X as Pg,Xb as qg,Y as qi,Ye as wh,Z as Cg,_e as bh,aa as Gu,af as ta,b as yg,ba as $g,bd as eo,bf as Rh,c as wg,cc as Wg,cd as Ki,ce as dh,cf as vh,d as kg,dc as zg,df as Sh,ec as Gg,ed as Pe,ef as ra,fc as Gi,fd as Io,gc as Jg,gd as rl,hc as Vg,hd as Br,ic as Ji,jd as nl,je as Es,k as ko,ka as Ju,kc as Xg,kd as we,l as Oo,lc as Kg,ld as Zg,le as zr,mc as Yg,o as mn,oa as xg,p as Os,pe as ch,q as Og,qb as _g,r as Ig,rb as Qu,s as Ag,sc as Qg,tc as tl,te as gr,ue as ft,xd as Yi,ya as Dg,yd as Ao,z as Tg,za as Vu,zd as To}from"./chunk-J347SPU6.mjs";import{a as bg,b as L,e as Te,f as Ve,i as hn,k as Re,l as K,o as Rg,p as Hi,s as Bi,u as Be,v as vt,x as vg,y as Sg,z as Qn}from"./chunk-WZQEK4WT.mjs";var ek="pipeline-rewind-grants",rk="pipeline:rewind-grant:",tk="pipeline:saved:",pp=K({pipelineId:L().min(1).max(200),stepId:L().min(1).max(200),organizationId:L().min(1).max(18),checkpointId:L().min(1).max(200),digest:L().regex(/^sha256:[0-9a-f]{64}$/),grantedAt:Qn.datetime(),grantedBy:L().max(80).optional(),takenBackAt:Qn.datetime().optional()}).strict();function Mn(s,e){return`Rewind step "${s}" has `+(e==="changed"?"not been confirmed since it was changed":"never been confirmed")+": open it and type the org's alias, or, for an org that has none, its name or Organization Id. No record was written."}function fp(s,e){return`${rk}${s}:${e}`}var ti=class{constructor(e){this.store=e}store;all(){return Object.values(this.store.getByCategory(ek)).flatMap(e=>{let t=pp.safeParse(e);return t.success?[t.data]:[]})}get(e,t){let r=pp.safeParse(this.store.get(fp(e,t)));return r.success?r.data:void 0}write(e){this.store.set(fp(e.pipelineId,e.stepId),pp.parse(e),ek)}revoke(e,t){return this.store.delete(fp(e,t))}revokePipeline(e){let t=`${rk}${e}:`,r=[];for(let n of this.store.getKeysByPrefix(t))this.store.delete(n)&&r.push(n.slice(t.length));return r}revokeChanged(e,t,r=()=>new Date){let n=[];for(let o of this.all().filter(i=>i.pipelineId===e)){let i=t.find(d=>d.id===o.stepId),a=i?.type==="rewind";a&&o.takenBackAt!==void 0||a&&ri(i.config)===o.digest||(a?(this.write({...o,takenBackAt:r().toISOString()}),n.push(o.stepId)):this.revoke(o.pipelineId,o.stepId)&&o.takenBackAt===void 0&&n.push(o.stepId))}return n}async revokeVoid(e){let t=[],r=new Map;for(let n of this.all()){let i=!this.store.has(`${tk}${n.pipelineId}`);if(!i&&e){let a=r.get(n.checkpointId);a||(a=e(n.checkpointId),r.set(n.checkpointId,a)),i=!await a}i&&this.revoke(n.pipelineId,n.stepId)&&t.push(n)}return t}verify(e,t){let r=this.get(e,t.id);return!r||!this.store.has(`${tk}${e}`)?{refusal:"never"}:r.takenBackAt!==void 0||ri(t.config)!==r.digest?{refusal:"changed"}:{grant:{organizationId:r.organizationId,checkpointId:r.checkpointId,digest:r.digest,grantedAt:r.grantedAt}}}};function ri(s){let e=xt.safeParse(s??{});return e.success?$s(e.data):void 0}function nk(s,e){return new ti(s).revokePipeline(e)}var FE="/lightning/setup/AsyncApexJobs/home";function ok(s){let e=es(s);return e.ok?{ok:!0,url:new URL(FE,e.url.origin).toString()}:e}import{randomBytes as _E}from"node:crypto";import{createReadStream as UE}from"node:fs";import{open as HE,readdir as BE,rm as qE,stat as WE}from"node:fs/promises";import{homedir as zE}from"node:os";import{join as dr,resolve as GE}from"node:path";import{createInterface as JE}from"node:readline";var gp="journal.ndjson",vd=2e3,ck=/^em-\d{8}-\d{6}-[a-z0-9]{4}$/,sk="abcdefghijklmnopqrstuvwxyz0123456789";function mp(s=new Date){let e=s.toISOString(),t=`${e.slice(0,4)}${e.slice(5,7)}${e.slice(8,10)}`,r=`${e.slice(11,13)}${e.slice(14,16)}${e.slice(17,19)}`,n=Array.from(_E(4),o=>sk[o%sk.length]).join("");return`em-${t}-${r}-${n}`}function hp(s){return ck.test(s)}function yp(s=process.env){let e=s.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?GE(e):dr(zE(),".sandforge");return dr(t,"empty")}var VE=L().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),rn=L().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Not an API name").max(80),ni=Qn.datetime({offset:!0}),ik=Re(VE).max(vd),uk=Be(["success","partial","failure","cancelled"]),lk=K({v:vt(1),kind:vt("head"),runId:L().regex(ck),organizationId:L().min(15).max(18),orgName:L(),startedAt:ni,readAt:ni,previewId:L(),mode:Be(["objects","org"]),deleteMode:Be(["recycle","hard"]),request:K({mode:Be(["objects","org"]),objects:Re(L()).optional(),excluded:Re(L()).optional(),customSettings:Ve().optional(),files:Ve().optional(),managedPackages:Ve().optional(),unrestorable:Ve().optional()}).strict(),passes:Re(K({objectApiName:rn,records:Te().int().nonnegative().optional(),sent:Te().int().nonnegative().optional(),rows:L().max(200).optional()})),toDraftAlong:Re(K({objectApiName:rn,condition:L().optional()})),beforeParent:Re(K({objectApiName:rn,field:L(),parent:rn,reason:Be(["restricted","customPrices"])})),undoLost:Re(K({objectApiName:rn,field:L().optional(),parent:rn.optional(),reason:Be(["restricted","unordered","notRestorable"]),records:Te().int().nonnegative().optional(),atLeast:vt(!0).optional()})).optional()}),XE=K({kind:vt("attempt"),at:ni,resumed:Ve()}),pk=K({kind:vt("spooled"),objectApiName:rn,place:Te().int().nonnegative(),count:Te().int().nonnegative(),sinceRead:Ve()}),KE=K({kind:vt("settled"),objectApiName:rn,deleted:ik,gone:ik}),YE=K({objectApiName:rn,planned:Te().int().nonnegative(),deleted:Te().int().nonnegative(),gone:Te().int().nonnegative(),refused:Te().int().nonnegative(),notReached:Te().int().nonnegative().optional(),madeSince:Te().int().nonnegative().optional(),reasons:Re(L())}),fk=K({kind:vt("end"),at:ni,status:uk,hardRefused:L().optional(),passes:Re(YE)}),QE=K({kind:vt("undo"),at:ni,status:uk}),ak=Hi("kind",[lk,XE,pk,KE,fk,QE]),Tr=class extends Error{constructor(e){super(e),this.name="EmptyJournalDamaged"}};function ZE(s){return s==="success"||s==="partial"}var Sd=class s{constructor(e,t){this.dir=e;this.head=t}dir;head;static async begin(e,t){let r=lk.parse({v:1,kind:"head",...t});await Ua(e);let n=new s(e,r);return await n.write(r,"wx"),n}static async open(e){let t;for await(let r of dk(dr(e,gp))){r.kind==="head"&&(t=r);break}if(t===void 0)throw new Tr("The journal of this emptying names nothing it was to do.");return new s(e,t)}idsDirOf(e,t){return dr(this.dir,"ids",`${e}-${St(t)}`)}async write(e,t="a"){let r=dr(this.dir,gp),n=await HE(r,t,Fa);try{await n.appendFile(`${JSON.stringify(e)}
8
+ `,"utf8"),await n.sync()}finally{await n.close()}}attempt(e,t){return this.write({kind:"attempt",at:t.toISOString(),resumed:e})}spooled(e){return this.write(pk.parse({kind:"spooled",...e}))}async settled(e,t,r){for(let n=0;n<Math.max(t.length,r.length);n+=vd)await this.write({kind:"settled",objectApiName:e,deleted:t.slice(n,n+vd),gone:r.slice(n,n+vd)})}ended(e,t,r,n){return this.write(fk.parse({kind:"end",at:r.toISOString(),status:e,...n!==void 0?{hardRefused:n}:{},passes:t}))}undone(e,t){return this.write({kind:"undo",at:t.toISOString(),status:e})}lines(){return dk(dr(this.dir,gp))}async state(){let e=0,t,r,n=!1,o=!1,i=new Map;for await(let a of this.lines())switch(a.kind){case"attempt":e++,r=void 0;break;case"spooled":i.set(a.objectApiName,a);break;case"settled":a.deleted.length>0&&(o=!0);break;case"end":t=a,r=a;break;case"undo":ZE(a.status)&&(n=!0);break;default:break}return{head:this.head,attempts:e,...t?{lastEnd:t}:{},open:e>0&&!n&&(r===void 0||r.status==="cancelled"||r.status==="failure"&&o),undone:n,spooled:i,deletedAny:o}}async*settledOf(e){for await(let t of this.lines())t.kind==="settled"&&t.objectApiName===e&&(yield t)}};async function*dk(s){let e=UE(s,{encoding:"utf8"}),t=JE({input:e,crlfDelay:1/0}),r,n=0,o=(i,a)=>{try{return ak.parse(JSON.parse(i))}catch{throw new Tr(`Line ${a} of the journal of this emptying does not read: the journal is not used.`)}};try{for await(let i of t)n++,i.trim()!==""&&(r&&(yield o(r.raw,r.number)),r={raw:i,number:n})}catch(i){throw i.code==="ENOENT"?new Tr("The journal of this emptying is not on this machine."):i}finally{t.close(),e.destroy()}if(r)try{yield ak.parse(JSON.parse(r.raw))}catch{return}}var kd=class{constructor(e){this.root=e}root;orgDir(e){return dr(this.root,rR(e))}begin(e,t){return Sd.begin(dr(this.orgDir(e),t.runId),{...t,organizationId:e})}async runsOf(e){let t=this.orgDir(e),r;try{r=await BE(t)}catch(n){if(n.code==="ENOENT")return[];throw n}return r.filter(hp).sort().map(n=>({runId:n,dir:dr(t,n)}))}async lastOf(e){return(await this.runsOf(e)).at(-1)}async open(e,t){if(!hp(t))throw new Tr(`Not an emptying's id: ${t}`);let r=dr(this.orgDir(e),t);try{await WE(r)}catch{throw new Tr(`No journal of the emptying ${t} is on this machine.`)}return Sd.open(r)}async remove(e,t){hp(t)&&await qE(dr(this.orgDir(e),t),{recursive:!0,force:!0})}};import{createHash as eP}from"node:crypto";import{readFileSync as tP}from"node:fs";import{homedir as rP}from"node:os";import{join as Od,resolve as nP}from"node:path";var gk=K({...zb,pipelineId:L().min(1).max(200),pipelineName:L().max(200).optional(),ranFrom:Be(["editor","commandLine"]),triggeredBy:Be(["manual","schedule","event","webhook","sandbox_refresh","deployment_complete"]),dryRun:Ve().optional()}),wp=Gb(s=>{let e=gk.safeParse(s);return e.success?e.data:void 0}),oP="run.lock",sP=/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;function hk(s=process.env){let e=s.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?nP(e):Od(rP(),".sandforge");return Od(t,"pipelines")}function oi(s){return sP.test(s)&&!s.includes("..")?s:`p-${eP("sha256").update(s).digest("hex").slice(0,32)}`}function Id(s,e){return Od(s,oi(e))}function mk(s,e){return Od(Id(s,e),oP)}function iP(s){try{let e=gk.safeParse(JSON.parse(tP(s,"utf8")));return e.success?e.data:void 0}catch{return}}function bp({version:s,token:e,...t}){return t}function yk(s,e,t,r={}){let n=mk(s,e),o=iP(n),i=o!==void 0&&wp.holder(n,r)===void 0,a=wp.acquire(n,d=>({...d,pipelineId:e,...t.pipelineName!==void 0?{pipelineName:t.pipelineName.slice(0,200)}:{},ranFrom:t.ranFrom,triggeredBy:t.triggeredBy,...t.dryRun?{dryRun:!0}:{}}),r);return"busy"in a?{busy:bp(a.busy)}:{lock:{pipelineId:e,release:a.lock.release},...i&&o!==void 0?{tookOver:bp(o)}:{}}}function CF(s,e,t={}){let r=wp.holder(mk(s,e),t);return r!==void 0?bp(r):void 0}function wk(s){let e=s.dryRun?"a simulation":"a run";return s.ranFrom==="commandLine"?`${e} from the command line (sandforge pipeline run)`:`${e} in VS Code`}function Rp(s,e){return`Pipeline "${e}" is already running on this machine: ${wk(s)} started at ${s.acquiredAt} (process ${s.pid} on ${s.host}) has not ended. A pipeline runs once at a time: run it again once that run ends.`}function bk(s){return`The run lock of pipeline "${s.pipelineName??s.pipelineId}" was left by ${wk(s)} started at ${s.acquiredAt} (process ${s.pid} on ${s.host}), whose process has ended: taken over.`}import{randomBytes as aP}from"node:crypto";import{mkdirSync as dP,readFileSync as Sk,readdirSync as cP,renameSync as Rk,statSync as uP,unlinkSync as lP,writeFileSync as pP}from"node:fs";import{join as Sp}from"node:path";var kp=50,Op="history.json",Ip=1,vk=4*1024*1024,fP=448,gP=384,hP=K({decision:Be(["approved","rejected","timedOut","cancelled"]),via:Be(["notification","page","terminal","commandLine"]).optional(),at:L().max(64),by:L().max(64).optional()}),mP=K({stepName:L().max(200),stepType:L().max(80),status:Be(["pending","running","completed","failed","skipped","stopped"]),duration:Te().nonnegative().optional(),summary:L().max(8e3).optional(),error:L().max(8e3).optional(),approval:hP.optional()}),vp=K({runId:L().min(1).max(200),pipelineId:L().min(1).max(200),pipelineName:L().max(200),status:Be(["idle","queued","running","completed","completed_with_warnings","failed","cancelled"]),triggeredBy:Be(["manual","schedule","event","webhook","sandbox_refresh","deployment_complete"]),startTime:Qn.datetime({offset:!0}),duration:Te().nonnegative(),stepCount:Te().int().nonnegative(),errorCount:Te().int().nonnegative(),steps:Re(mP).max(200).optional()}),yP=K({sandforgePipelineHistory:vt(Ip),entries:Re(hn()).max(kp*4)});function MF(s,e){return Sp(Id(s,e),Op)}function wP(s){let e=Date.parse(s.startTime);return{...s,ranFrom:"commandLine",timestamp:Number.isNaN(e)?0:e}}function kk(s){let e;try{e=JSON.parse(s)}catch{return{why:"it is not JSON"}}let t=yP.safeParse(e);if(!t.success){let o=e?.sandforgePipelineHistory;return{why:typeof o=="number"&&o>Ip?`a later release of SandForge wrote it (version ${o})`:"it is not a pipeline history"}}let r=[],n=0;for(let o of t.data.entries){let i=vp.safeParse(o);i.success?r.push(wP(i.data)):n+=1}return{entries:r,skipped:n}}function Ok(s,e){let t=new Map,r=(n,o,i)=>{t.get(n)!==o&&(t.set(n,o),e(i))};return{read(){let n;try{n=cP(s,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name)}catch{return[]}let o=[];for(let i of n.sort()){let a=Sp(s,i,Op),d,c;try{let l=uP(a);if(d=`${l.size}:${l.mtimeMs}`,l.size>vk){r(a,d,`[WARN] pipeline history ${a} is not listed: at ${l.size} bytes it is past the ${vk} a history of ${kp} runs takes.`);continue}c=Sk(a,"utf8")}catch{continue}let u=kk(c);if("why"in u){r(a,d,`[WARN] pipeline history ${a} is not listed: ${u.why}. The runs it held are not shown in History; the next run from the command line starts it again.`);continue}u.skipped>0&&r(a,d,`[WARN] pipeline history ${a}: ${u.skipped} of its runs do not read and are not listed.`),o.push(...u.entries)}return o.sort((i,a)=>a.timestamp-i.timestamp)}}}function LF(s,e,t){let r=vp.safeParse(t);if(!r.success)throw new Error(`The run was not recorded: ${r.error.issues.slice(0,3).map(l=>`${l.path.join(".")||"(entry)"}: ${l.message}`).join("; ")}`);let n=Id(s,e);dP(n,{recursive:!0,mode:fP});let o=Sp(n,Op),i=[],a,d;try{d=Sk(o,"utf8")}catch{d=void 0}if(d!==void 0){let l=kk(d);"why"in l?(a=`${o}.unreadable-${Date.now()}`,Rk(o,a)):i=l.entries.map(({ranFrom:p,timestamp:f,...g})=>vp.parse(g))}let c=[r.data,...i.filter(l=>l.runId!==r.data.runId)].sort((l,p)=>Date.parse(p.startTime)-Date.parse(l.startTime)).slice(0,kp),u=`${o}.${process.pid}-${aP(4).toString("hex")}.tmp`;pP(u,`${JSON.stringify({sandforgePipelineHistory:Ip,entries:c},null,2)}
9
+ `,{encoding:"utf8",mode:gP,flag:"wx"});try{Rk(u,o)}catch(l){try{lP(u)}catch{}throw l}return{kept:c.length,...a!==void 0?{setAside:a}:{}}}var Ht={major:20,minor:19},Ik=5,bP=12,RP=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function mt(s){return s.replace(/\s*[\r\n\u2028\u2029]+\s*/g," ").trim()}function Ut(s){return`'${s.replace(/'/g,"'\\''")}'`}function Zt(s){return`'${s.replace(/['\u2018\u2019\u201a\u201b]/g,e=>e+e)}'`}function ts(s){return JSON.stringify(s)}function Ap(s){return s.endsWith(al)?s.slice(0,-al.length):s.replace(/\.json$/,"")}function vP(s){return`SFDX_AUTH_URL_${s.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")}`}function Tp(s){return"refused"in s?{kind:"refused",code:s.refused,reason:s.reason}:{kind:"line",text:s.cron,timezone:s.timezone,offsetMinutes:s.offsetMinutes,offsetChanges:s.offsetChanges}}function Ak(s){return s.offsetChanges.map(e=>{let t=s.offsetMinutes-e.offsetMinutes,r=new Date(e.at).toISOString();return t===0?`From ${r}, it runs at the pipeline's times again.`:`From ${r}, it runs ${Math.abs(t)} minutes ${t>0?"later":"earlier"} than the pipeline's schedule says: export it again then.`})}function SP(s){return`npx -y sandforge@${s.sandforgeVersion} pipeline run --file ${s.fileName}`}function Ep(s,e){return[`SandForge pipeline "${mt(s.pipelineName)}", run from its file with VS Code closed.`,`Exported by SandForge ${s.sandforgeVersion} on ${s.exportedAt}.`,"",...e,"",`It runs: ${SP(s)}`,"Exit code: the run's. 0 completed; 1 failed; 2 refused before its first step, nothing","ran; 3 completed with a step that failed; 129, 130 or 143 stopped by a signal; and 127","when Node.js or the Salesforce CLI is not found."]}function Pp(s,e,t){let r=[];if(s.approvals.length>0){r.push(`${e} An Approval step asks a person. Run with no one at a terminal, the run is`,`${e} refused before its first step unless the step is answered here, ahead:`,`${e} remove the "${e}" of its line to answer it yes on every run.`);for(let n of s.approvals)n.staging?r.push(`${e} "${mt(n.name)}" stands before a write to a sandbox marked Staging:`,`${e} only a person at a terminal answers it, never a line here.`):r.push(`${e} ${t("--approve",n.name)}`)}if(s.rewinds.length>0){r.push(`${e} A Rewind step runs once its org's alias is confirmed: by`,`${e} "npx -y sandforge@${s.sandforgeVersion} pipeline confirm --file ${s.fileName}"`,`${e} at a terminal of this machine, or here. Its checkpoint must be kept on this machine.`);for(let n of s.rewinds)r.push(n.alias!==void 0?`${e} ${t("--confirm-rewind",n.alias)}`:`${e} "${mt(n.name)}" rewinds an org with no alias: confirm it with pipeline confirm.`)}return r}function rs(s){for(let e of s){let t=e.codePointAt(0)??0;if(t<32||t===127||t===8232||t===8233)return!1}return!0}function kP({alias:s,...e}){return e}function Cp(s){if(!rs(s.fileName))throw new Error("A pipeline file name is one line of text.");let e=[],t=s.orgs.flatMap(i=>rs(i.key)?i.alias===void 0||rs(i.alias)?[i]:(e.push(`The alias of org "${mt(i.label)}" holds a line break: it is asked below as an alias of this machine.`),[kP(i)]):(e.push(`Org "${mt(i.label)}" is named by a key no line can hold: run it from a terminal.`),[])),r=s.variables.filter(i=>rs(i.name)?!0:(e.push(`Variable "${mt(i.name)}" holds a line break in its name, which no line gives: rename it.`),!1)),n=s.approvals.filter(i=>rs(i.name)?!0:(e.push(`Approval step "${mt(i.name)}" holds a line break in its name: only a terminal answers it.`),!1)),o=s.rewinds.map(i=>i.alias===void 0||rs(i.alias)?i:{name:i.name});return{input:{...s,orgs:t,variables:r,approvals:n,rewinds:o},leftOut:e}}function Tk(s){return s.orgs.filter(e=>e.alias===void 0).map((e,t)=>({...e,slot:`org_alias_${t+1}`}))}function OP(s){let{input:e,leftOut:t}=Cp(s),n=`${Ap(e.fileName)}.sh`,o=oi(e.pipelineId),i=e.schedule===null?void 0:Tp(ta(e.schedule.cron,e.schedule.timezone,e.machineTimezone,e.now)),a=i===void 0?["This pipeline has no schedule: run this script by hand, or from a scheduler of your own."]:i.kind==="line"?[`Its schedule, as a line of this machine's crontab (crontab -e), read in ${i.timezone}:`,` ${i.text} /bin/bash /path/to/${n}`,...i.offsetMinutes!==0?[`The pipeline's schedule, ${e.schedule?.cron} in ${e.schedule?.timezone}, moved by ${i.offsetMinutes} minutes: Ubuntu's cron reads no zone of its own.`]:[],...Ak(i)]:["Its schedule cannot be written as a line of this machine's crontab:",mt(i.reason)],d=[`Keep it beside ${e.fileName}. It needs Node.js ${Ht.major}.${Ht.minor} or later`,"and the Salesforce CLI (sf), signed in to each org of the pipeline under its alias.","Each run is appended to runs.log, in the pipeline's folder below.","",...a,...t.length>0?["",...t]:[]],c=Tk(e),u=["#!/usr/bin/env bash",...Ep(e,d).map(l=>l===""?"#":`# ${l}`),"set -u","",'here="$(cd "$(dirname "$0")" && pwd)"',`file="$here/"${Ut(e.fileName)}`,`store="\${SANDFORGE_JOURNAL_DIR:-$HOME/.sandforge}/pipelines/"${Ut(o)}`,'mkdir -p "$store" && chmod 700 "$store"','log="$store/runs.log"',"","# cron starts a script with little more than /usr/bin and /bin on its PATH:","# the usual places of node and sf are added, then the default Node.js of nvm.",'PATH="$PATH:/usr/local/bin:$HOME/.local/bin"',"node_ok() {"," command -v node >/dev/null 2>&1 &&",` node -e 'const [a, b] = process.versions.node.split(".").map(Number); process.exit(a > ${Ht.major} || (a === ${Ht.major} && b >= ${Ht.minor}) ? 0 : 1)'`,"}","if ! node_ok || ! command -v sf >/dev/null 2>&1; then",' nvm_sh="${NVM_DIR:-$HOME/.nvm}/nvm.sh"',' if [ -s "$nvm_sh" ]; then',' . "$nvm_sh" >/dev/null 2>&1'," nvm use --silent default >/dev/null 2>&1 || true"," fi","fi",`say() { printf '%s %s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" | tee -a "$log" >&2; }`,"if ! node_ok; then",` say "Node.js ${Ht.major}.${Ht.minor} or later is not found on this PATH ($PATH), nor through nvm: nothing ran. Install it, or add its folder to PATH at the top of this script."`," exit 127","fi","if ! command -v sf >/dev/null 2>&1; then",' say "The Salesforce CLI (sf) is not found on this PATH ($PATH): nothing ran. Install it (npm install -g @salesforce/cli), or add its folder to PATH at the top of this script."'," exit 127","fi",""];if(c.length>0||e.variables.length>0){u.push("# What the pipeline file does not hold, read from here or from the environment.",'# cron gives a script no environment of yours: set values in "$store/env",',"# one `export NAME='value'` a line, in a file only you can read (chmod 600).",'if [ -f "$store/env" ]; then . "$store/env"; fi');for(let l of c)u.push(`# The alias, on this machine, of org "${mt(l.label)}", which has none of its own`,"# (sf alias set <alias>=<its username>).",`${l.slot}="\${${l.slot.toUpperCase()}:-}"`);u.push("missing=()");for(let l of c)u.push(`[ -n "$${l.slot}" ] || missing+=(${Ut(`${l.slot} (the alias of org "${mt(l.label)}")`)})`);for(let l of e.variables)u.push(`[ -n "\${${l.env}:-}" ] || missing+=(${Ut(`${l.env} (variable "${mt(l.name)}"${l.secret?", a secret":""})`)})`);u.push('if [ "${#missing[@]}" -gt 0 ]; then',' say "Not set, so nothing ran: ${missing[*]}. Set each in this script or in $store/env."'," exit 2","fi","")}return u.push('args=(pipeline run --file "$file" --triggered-by schedule --fail-on-partial)',...c.map(l=>`args+=(--org ${Ut(`${l.key}=`)}"$${l.slot}")`),...e.variables.map(l=>`args+=(--var-env ${Ut(`${l.name}=${l.env}`)})`),...Pp(e,"#",(l,p)=>`args+=(${l} ${Ut(p)})`),"",'say "start"',`npx -y ${Ut(`sandforge@${e.sandforgeVersion}`)} "\${args[@]}" >>"$log" 2>&1`,"code=$?",'say "exit $code"','exit "$code"',""),{runner:"cron",fileName:n,text:u.join(`
10
+ `),...i!==void 0?{schedule:i.kind==="line"?{...i,text:`${i.text} /bin/bash /path/to/${n}`}:i}:{}}}function IP(s){let e=cl(s);if("refused"in e)return e.reason;if(e.daysOfMonth!=="*"||e.months!=="*")return"It names days of the month or months, which a daily or weekly trigger does not: create the task in Task Scheduler by hand.";let t=e.hours.flatMap(n=>e.minutes.map(o=>`${String(n).padStart(2,"0")}:${String(o).padStart(2,"0")}`));if(t.length>bP)return`It starts ${t.length} times a day; a task of that many daily triggers is better made with a repetition: create the task in Task Scheduler by hand.`;let r=e.daysOfWeek==="*"?void 0:e.daysOfWeek.map(n=>RP[n]).join(",");return t.map(n=>r===void 0?`New-ScheduledTaskTrigger -Daily -At ${Zt(n)}`:`New-ScheduledTaskTrigger -Weekly -DaysOfWeek ${r} -At ${Zt(n)}`)}function AP(s){let{input:e,leftOut:t}=Cp(s),r=Ap(e.fileName),n=`${r}.ps1`,o=oi(e.pipelineId),i;if(e.schedule!==null){let l=Tp(ta(e.schedule.cron,e.schedule.timezone,e.machineTimezone,e.now));if(l.kind!=="line")i=l;else{let p=IP(l.text);i=typeof p=="string"?{kind:"manual",reason:p}:{...l,text:[`# In PowerShell, from the folder that holds ${n}, once:`,`$action = New-ScheduledTaskAction -Execute 'pwsh' -Argument ('-NoProfile -File "{0}"' -f (Join-Path $PWD ${Zt(n)}))`,"$triggers = @(",...p.map(f=>` ${f}`),")",`Register-ScheduledTask -TaskName ${Zt(`SandForge ${r}`)} -Action $action -Trigger $triggers`].join(`
11
+ `)}}}let a=i===void 0?["This pipeline has no schedule: run this script by hand, or from a scheduler of your own."]:i.kind==="line"?[`Its schedule, as Task Scheduler reads it, in ${i.timezone}:`,...i.text.split(`
12
+ `).map(l=>` ${l}`),...Ak(i)]:i.kind==="manual"?[`Its schedule, ${e.schedule?.cron} in ${e.schedule?.timezone}, as Task Scheduler reads it:`,mt(i.reason)]:["Its schedule cannot be written for this machine's clock:",mt(i.reason)],d=[`Keep it beside ${e.fileName}. It needs PowerShell 7 (pwsh), Node.js`,`${Ht.major}.${Ht.minor} or later and the Salesforce CLI (sf), signed in to each org of the`,"pipeline under its alias. Each run is appended to runs.log, in the pipeline's folder below.","",...a,...t.length>0?["",...t]:[]],c=Tk(e),u=[...Ep(e,d).map(l=>l===""?"#":`# ${l}`),"$ErrorActionPreference = 'Continue'","","$here = Split-Path -Parent $MyInvocation.MyCommand.Path",`$file = Join-Path $here ${Zt(e.fileName)}`,"$journal = if ($env:SANDFORGE_JOURNAL_DIR) { $env:SANDFORGE_JOURNAL_DIR } else { Join-Path $HOME '.sandforge' }",`$store = Join-Path (Join-Path $journal 'pipelines') ${Zt(o)}`,"New-Item -ItemType Directory -Force -Path $store | Out-Null","$log = Join-Path $store 'runs.log'","function Say([string] $line) {"," $stamped = '{0} {1}' -f ([DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ')), $line"," Add-Content -Path $log -Value $stamped"," [Console]::Error.WriteLine($stamped)","}","","if ($PSVersionTable.PSVersion.Major -lt 7) {",' Say ("PowerShell 7 (pwsh) runs this script, not PowerShell {0}: nothing ran. Start it with pwsh." -f $PSVersionTable.PSVersion)'," exit 127","}","$node = Get-Command node -ErrorAction SilentlyContinue","$nodeOk = $false","if ($node -and ((& node --version) -match '^v(\\d+)\\.(\\d+)')) {"," $major = [int] $Matches[1]",` $nodeOk = ($major -gt ${Ht.major}) -or ($major -eq ${Ht.major} -and [int] $Matches[2] -ge ${Ht.minor})`,"}","if (-not $nodeOk) {",` Say "Node.js ${Ht.major}.${Ht.minor} or later is not found on this PATH: nothing ran. Install it, or add its folder to PATH."`," exit 127","}","if (-not (Get-Command sf -ErrorAction SilentlyContinue)) {",' Say "The Salesforce CLI (sf) is not found on this PATH: nothing ran. Install it (npm install -g @salesforce/cli), or add its folder to PATH."'," exit 127","}",""];if(c.length>0||e.variables.length>0){u.push("# What the pipeline file does not hold, set here or in the environment.");for(let l of c)u.push(`# The alias, on this machine, of org "${mt(l.label)}", which has none of its own.`,`$${l.slot} = $env:${l.slot.toUpperCase()}`);u.push("$missing = @()");for(let l of c)u.push(`if (-not $${l.slot}) { $missing += ${Zt(`${l.slot} (the alias of org "${mt(l.label)}")`)} }`);for(let l of e.variables)u.push(`if (-not $env:${l.env}) { $missing += ${Zt(`${l.env} (variable "${mt(l.name)}"${l.secret?", a secret":""})`)} }`);u.push("if ($missing.Count -gt 0) {"," Say ('Not set, so nothing ran: {0}. Set each in this script or in the environment.' -f ($missing -join ', '))"," exit 2","}","")}return u.push("$runArgs = @('pipeline', 'run', '--file', $file, '--triggered-by', 'schedule', '--fail-on-partial')",...c.map(l=>`$runArgs += @('--org', (${Zt(`${l.key}={0}`)} -f $${l.slot}))`),...e.variables.map(l=>`$runArgs += @('--var-env', ${Zt(`${l.name}=${l.env}`)})`),...Pp(e,"#",(l,p)=>`$runArgs += @('${l}', ${Zt(p)})`),"","Say 'start'",`& npx -y ${Zt(`sandforge@${e.sandforgeVersion}`)} @runArgs *>> $log`,"$code = $LASTEXITCODE",'Say "exit $code"',"exit $code",""),{runner:"taskScheduler",fileName:n,text:u.join(`
13
+ `),...i!==void 0?{schedule:i}:{}}}function TP(s){let e=cl(s);if("refused"in e)return!1;let t=e.minutes;if(t.length===1)return!1;for(let r=0;r<t.length;r+=1)if((r+1<t.length?t[r+1]:t[0]+60)-t[r]<Ik)return!0;return!1}function EP(s){let{input:e,leftOut:t}=Cp(s),n=`${Ap(e.fileName)}.yml`,o=oi(e.pipelineId),i=e.schedule===null?void 0:Tp(ta(e.schedule.cron,e.schedule.timezone,e.schedule.timezone,e.now)),a=e.orgs.map((l,p)=>{let f=l.alias??`pipeline-org-${p+1}`;return{...l,ciAlias:f,secret:vP(f)}}),d=l=>l===""?"#":`# ${l}`,c=[...Ep(e,[`Save it as .github/workflows/${n} of a private repository, and commit`,`${e.fileName} at the repository's root. Each org signs in from a repository secret:`,...a.map(l=>` ${l.secret}: the sfdx auth URL of "${mt(l.label)}" (sf org auth show-sfdx-auth-url --target-org ${l.alias??"<its username>"} --json, its result.sfdxAuthUrl)`),...e.variables.map(l=>` ${l.env}: variable "${mt(l.name)}"${l.secret?" (a secret)":""}`),"","GitHub starts a schedule late when its runners are busy, the start of each hour most of","all, and may drop it under heavy load; it disables the schedules of a public repository",'after 60 days without activity (docs.github.com, "Events that trigger workflows").',...i?.kind==="refused"?["","The pipeline's schedule cannot be written for GitHub:",mt(i.reason)]:[],...i?.kind==="line"&&TP(i.text)?["",`GitHub starts a schedule every ${Ik} minutes at most, whatever its line says.`]:[],...t.length>0?["",...t]:[]]).map(d),`name: ${ts(`SandForge pipeline: ${mt(e.pipelineName)}`)}`,"","on:"];i?.kind==="line"&&c.push(" schedule:",` - cron: ${ts(i.text)}`,` timezone: ${ts(i.timezone)}`),c.push(" workflow_dispatch:","","# One run of the pipeline at a time: a run lock keeps one machine to one run, not two jobs.","concurrency:",` group: ${ts(`sandforge-pipeline-${o}`)}`," cancel-in-progress: false","","permissions:"," contents: read","","jobs:"," run:"," runs-on: ubuntu-latest"," steps:"," - uses: actions/checkout@v4"," - uses: actions/setup-node@v4"," with:"," node-version: 22"," - name: Install the Salesforce CLI"," run: npm install -g @salesforce/cli"),a.length>0&&c.push(" - name: Sign in to the pipeline's orgs"," env:",...a.map(l=>` ${l.secret}: \${{ secrets.${l.secret} }}`)," # The URLs go to a private folder removed when this shell exits, a failed sign-in too."," run: |"," umask 077"," auth_dir=$(mktemp -d)",` trap 'rm -rf "$auth_dir"' EXIT`,...a.flatMap((l,p)=>[` printf '%s' "$${l.secret}" > "$auth_dir/org-${p+1}.txt"`,` sf org login sfdx-url --sfdx-url-file "$auth_dir/org-${p+1}.txt" --alias ${Ut(l.ciAlias)}`])),c.push(" # The Sync watermarks, the confirmations and the history of earlier runs."," - uses: actions/cache@v4"," with:"," path: .sandforge",` key: ${ts(`sandforge-pipeline-${o}-\${{ github.run_id }}`)}`,` restore-keys: ${ts(`sandforge-pipeline-${o}-`)}`),e.rewinds.length>0&&c.push(" # A Rewind step rewinds to a checkpoint kept on the machine of the run: import it"," # here first (sandforge checkpoint import), from a file you keep apart, with its key."," # - name: Import the checkpoint a Rewind step names",` # run: npx -y sandforge@${e.sandforgeVersion} checkpoint import --file <checkpoint file>`);let u=[`args=(pipeline run --file ${Ut(e.fileName)} --triggered-by "$TRIGGERED_BY" --fail-on-partial)`,...a.filter(l=>l.alias===void 0).map(l=>`args+=(--org ${Ut(`${l.key}=${l.ciAlias}`)})`),...e.variables.map(l=>`args+=(--var-env ${Ut(`${l.name}=${l.env}`)})`),...Pp(e,"#",(l,p)=>`args+=(${l} ${Ut(p)})`),`npx -y ${Ut(`sandforge@${e.sandforgeVersion}`)} "\${args[@]}"`];return c.push(" - name: Run the pipeline"," env:"," SANDFORGE_JOURNAL_DIR: ${{ github.workspace }}/.sandforge"," TRIGGERED_BY: ${{ github.event_name == 'schedule' && 'schedule' || 'manual' }}",...e.variables.map(l=>` ${l.env}: \${{ secrets.${l.env} }}`)," run: |",...u.map(l=>` ${l}`),""),{runner:"githubActions",fileName:n,text:c.join(`
14
+ `),...i!==void 0?{schedule:i}:{}}}function Ek(s){return{cron:OP(s),taskScheduler:AP(s),githubActions:EP(s)}}var PP={"pipeline.timeout":3e5,"sync.maxRecordsPerObject":5e4,"sync.defaultBatchSize":200,"seed.defaultBatchSize":200,"backup.maxRecordsPerObject":5e4,"backup.maxCount":10,"backup.maxAgeDays":30,"safety.auditLogging":!0,"safety.confirmAboveRecords":2e3,"grappe.enabled":!1,"grappe.autoActivateThreshold":1e4,"grappe.grappeSize":5e3},CP=new Set(["seed","anonymize","rewind","restore","delete"]),$P={sandbox_refresh:"sandbox refresh",event:"event",webhook:"webhook",deployment_complete:"deployment"},xP="prebuilt-",DP="tpl-";function ii(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)?s:void 0}function Er(s){return typeof s=="string"&&s.trim()!==""?s:void 0}function Td(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function ai(s,e){return Td(s,e)?s[e]:void 0}function si(s){return JSON.parse(JSON.stringify(s))}function NP(s){switch(Ki(s.orgType??"",s.metadata?.edition)){case"Sandbox":return"sandbox";case"Scratch":return"scratch";case"Developer":return"developer";default:return"production"}}function jP(s){let e=NP(s),t=nl(s.alias,s.username)?s.alias?.trim():void 0,r=s.organizationName?.trim();return{...t!==void 0?{alias:t}:{},organizationId:s.orgId??"",kind:e,staging:s.staging===!0&&e==="sandbox",...r&&nl(r,s.username)?{name:r}:{}}}function $p(s,e){return e.alias??e.name??s}function Ad(s,e,t,r){return{exported:!1,pipelineId:s,code:e,message:t,...r?{issues:r}:{}}}function MP(s,e){let t=[];return s.forEach((r,n)=>{let o=ii(r.config)??{};if(r.type==="sync"){let a=e.get(Er(o.configId)??""),d=Er(a?.sourceOrgId),c=Er(a?.targetOrgId);d!==void 0&&t.push({orgId:d,stepIndex:n,stepName:r.name,writes:!1}),c!==void 0&&t.push({orgId:c,stepIndex:n,stepName:r.name,writes:!0});return}let i=Td(dl,r.type)?dl[r.type]??[]:[];for(let a of i){let d=Er(o[a]);d!==void 0&&t.push({orgId:d,stepIndex:n,stepName:r.name,writes:CP.has(r.type)})}}),t}function LP({defaultValue:s,...e}){return e}function FP(s){let e=new Set,t=new Map;for(let r of s){let n=`SANDFORGE_VAR_${r.name.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")||"VALUE"}`,o=n;for(let i=2;e.has(o);i+=1)o=`${n}_${i}`;e.add(o),t.set(r.name,o)}return t}function _P(s,e){let t=(s.triggers??[]).filter(n=>n.type==="schedule"&&(n.enabled||s.runsOutside!==void 0)&&Er(n.config?.cron)!==void 0);if(t.length>1)return{many:t.length};let[r]=t;return r?{cron:(r.config.cron??"").trim(),timezone:Er(r.config.timezone)?.trim()??e}:null}function UP(s){let e={};for(let t of Object.keys(yh)){let r=PP[t],n=s.setting(t,r);n===r||n===void 0||n===null||(e[t]=n)}return e}function di(s,e,t={}){return{code:s,text:e,...t}}function Pk(s){let{pipeline:e}=s,t=e.id,r=si(e.steps??[]).map(f=>({...f,config:ii(f.config)??{}})),n=_P(e,s.machineTimezone);if(n!==null&&"many"in n)return Ad(t,"SCHEDULES_MANY",`Pipeline "${e.name}" has ${n.many} schedules, and a pipeline file carries one: keep one schedule, save, and export again.`);let o={},i={},a={};for(let f of r){let g=f.config;if(f.type==="sync"){let m=Er(g.configId);if(m===void 0||Td(o,m))continue;let y=ii(s.syncConfig(m));if(!y)return Ad(t,"SYNC_CONFIG_UNKNOWN",`Sync step "${f.name}" runs the configuration "${m}", which is no longer saved: pick a saved configuration in the step, save the pipeline, and export again.`);o[m]={...si(y),id:m}}let h=Er(g.templateId);if(f.type==="seed"&&h&&!h.startsWith(xP)){let m=ii(s.seedTemplate(h));m&&(i[h]={...si(m),id:h})}if(f.type==="anonymize"&&h&&!h.startsWith(DP)){let m=ii(s.maskingTemplate(h));m&&(a[h]={...si(m),id:h})}}let d=MP(r,new Map(Object.entries(o))),c={},u=new Map;for(let f of d){if(Td(c,f.orgId))continue;let g=s.org(f.orgId);if(!g)return Ad(t,"ORG_UNKNOWN",`Step "${f.stepName}" names an org that is no longer registered in SandForge: pick an org in the step, or in its Sync configuration, save, and export again.`);c[f.orgId]=jP(g),u.set(f.orgId,g.authMethod!=="usernamePassword")}let l=FP(e.variables??[]),p=si(e.variables??[]).map(f=>f.type==="secret"?LP(f):f);return{pipelineId:t,fileName:bh(e.name),schedule:n,orgs:c,cliHolds:u,uses:d,syncConfigs:o,seedTemplates:i,maskingTemplates:a,settings:UP(s),steps:r,variables:p,envs:l}}function Ck(s,e,t){return s.checkedWhereItRuns!==!0&&e.type==="rewind"&&t!==void 0&&(t===Mn(e.name,"never")||t===Mn(e.name,"changed"))}function HP(s,e){let t=[],r=[],n=o=>e.uses.filter(i=>i.stepIndex===o&&i.writes).map(i=>i.orgId);return e.steps.forEach((o,i)=>{let a=[],d=(g,h)=>{a.push(g),t.push(di(g,h,{step:o.name}))},c=s.stepRefusal?.(o,i),u=Ck(s,o,c)?void 0:c,l=n(i).find(g=>ai(e.orgs,g)?.kind==="production"),p="runs",f;if(u!==void 0)p="refused",f=u,d("STEP_REFUSED",u);else if(l!==void 0){p="refused";let g=ai(e.orgs,l);f=`Step "${o.name}" writes to "${g?$p(l,g):l}", a production org: the command line never writes to a production org, whatever an Approval answers.`,d("STEP_REFUSED",f)}else if(o.type==="approval")p="asks",e.uses.some(h=>h.stepIndex>i&&h.writes&&ai(e.orgs,h.orgId)?.staging===!0)?d("STAGING_NEEDS_PERSON",`Approval step "${o.name}" stands before a write to a sandbox marked Staging: only a person at a terminal answers it, never --approve.`):d("APPROVAL_NEEDS_PERSON",`Approval step "${o.name}" asks a person: at the terminal of the run, or answered ahead with --approve "${o.name}" for a run with no one at a terminal.`);else if(o.type==="rewind"){p="asks";let g=Er(o.config.orgId),h=g!==void 0?ai(e.orgs,g):void 0;d("REWIND_NEEDS_CONFIRMATION",`Rewind step "${o.name}" runs once its org's alias is confirmed on the machine of the run: by "sandforge pipeline confirm" at a terminal, or with --confirm-rewind ${h?.alias??"<alias>"}.`),d("REWIND_CHECKPOINT_ELSEWHERE",`Rewind step "${o.name}" rewinds to a checkpoint kept on this machine: on another, import it first (sandforge checkpoint import).`)}else o.type==="notification"&&d("NOTIFICATION_PRINTED",`Notification step "${o.name}" prints its message in the run's output: there is no VS Code window to show it in.`);r.push({stepId:o.id,name:o.name,type:o.type,fate:p,notes:a,...f!==void 0?{refusal:f}:{}})}),{steps:r,notes:t}}function BP(s,e){let t=[];for(let[r,n]of Object.entries(e.orgs))if(n.alias===void 0&&t.push(di("ORG_NO_ALIAS",`Org "${$p(r,n)}" has no alias of its own: give it one with "sf alias set <alias>=<its username>", then run with --org ${r}=<alias>.`,{org:r})),e.cliHolds.get(r)===!1){let o=n.kind==="sandbox"?" --instance-url https://test.salesforce.com":"";t.push(di("ORG_NOT_SIGNED_IN",`The Salesforce CLI of this machine does not hold org "${$p(r,n)}": SandForge connected it with a username and password. Sign in to it on the machine of the run: "sf org login web --alias ${n.alias??"<alias>"}${o}".`,{org:r}))}for(let r of s.pipeline.variables??[])r.type==="secret"&&t.push(di("SECRET_NOT_EXPORTED",`Variable "${r.name}" is a secret: its value is not in this file. Give it as the run starts with --var-env ${r.name}=${e.envs.get(r.name)}.`));for(let r of s.pipeline.triggers??[]){let n=$P[r.type];!r.enabled||n===void 0||t.push(di("TRIGGER_NOT_EXPORTED",`Its ${n} trigger starts it in the editor alone: a run of this file starts on its schedule, or by hand.`))}return t}function qP(s){return Object.entries(s.orgs).map(([e,t])=>{let r=s.uses.filter(a=>a.orgId===e),n=new Set(r.filter(a=>a.writes).map(a=>a.stepIndex)),o=[...new Set(r.filter(a=>a.writes).map(a=>a.stepName))],i=[...new Set(r.filter(a=>!n.has(a.stepIndex)).map(a=>a.stepName))];return{key:e,...t.alias!==void 0?{alias:t.alias}:{},...t.name!==void 0?{name:t.name}:{},kind:t.kind,staging:t.staging,cliHolds:s.cliHolds.get(e)??!1,writtenBy:o,readBy:i}})}function WP(s){return s.variables.map(e=>{let t=e.type!=="secret"&&e.defaultValue!==void 0,r=e.type==="secret"||e.required&&!t,n=s.envs.get(e.name);return{name:e.name,type:e.type,required:e.required,valued:t,...r&&n!==void 0?{env:n}:{}}})}function $k(s,e,t){let{pipeline:r}=s;return wh({exportedAt:s.exportedAt,sandforgeVersion:s.sandforgeVersion,pipeline:{id:r.id,name:r.name,description:r.description??"",steps:e.steps.map(n=>({...n})),variables:e.variables,tags:r.tags??[]},schedule:e.schedule,orgs:e.orgs,syncConfigs:e.syncConfigs,seedTemplates:e.seedTemplates,maskingTemplates:e.maskingTemplates,settings:e.settings,notes:t})}function xk(s){let e=s.pipeline.id,t=Pk(s);if("exported"in t)return t;let{steps:r,notes:n}=HP(s,t),o=[...n,...BP(s,t)],i=$k(s,t,o);if(!i.ok)return Ad(e,"FILE_INVALID",`The pipeline file would not read: ${i.issues.length} ${i.issues.length===1?"issue":"issues"}. Fix each where the pipeline, its orgs or the settings hold it, and export again.`,i.issues);let a=qP(t),d=WP(t),c=a.map(p=>({key:p.key,...p.alias!==void 0?{alias:p.alias}:{},label:p.alias??p.name??p.key})),u=d.flatMap(p=>p.env!==void 0?[{name:p.name,env:p.env,secret:p.type==="secret"}]:[]),l={fileName:t.fileName,text:i.text,digest:i.file.digest,schedule:t.schedule,steps:r,orgs:a,variables:d,launchers:Ek({pipelineId:e,pipelineName:s.pipeline.name,fileName:t.fileName,sandforgeVersion:s.sandforgeVersion,exportedAt:s.exportedAt,schedule:t.schedule,machineTimezone:s.machineTimezone,now:s.now,orgs:c,variables:u,approvals:r.filter(p=>p.type==="approval"&&p.fate==="asks").map(p=>({name:p.name,staging:p.notes.includes("STAGING_NEEDS_PERSON")})),rewinds:t.steps.filter(p=>p.type==="rewind").map(p=>{let f=Er(p.config.orgId),g=f!==void 0?ai(t.orgs,f)?.alias:void 0;return{name:p.name,...g!==void 0?{alias:g}:{}}})}),notes:o,problems:(s.problems??[]).filter(p=>!t.steps.some(f=>Ck(s,f,p)))};return{exported:!0,pipelineId:e,...l}}function Dk(s){let e=Pk(s);if("exported"in e)return;let t=$k(s,e,[]);return t.ok?t.file.digest:void 0}import{randomUUID as sF}from"node:crypto";import{join as iF}from"node:path";import{randomBytes as zP,randomUUID as ns}from"node:crypto";import{lstat as GP,rename as JP,rm as VP,stat as XP}from"node:fs/promises";import{hostname as KP}from"node:os";import{basename as ui,dirname as Lk,join as YP,sep as QP}from"node:path";var ZP=new Set(["checkpoint:list","checkpoint:scope","checkpoint:take","checkpoint:preview","checkpoint:plan-selection","checkpoint:rewind","checkpoint:undo","checkpoint:delete","checkpoint:keep","checkpoint:rename","checkpoint:ignore-fields","checkpoint:rewinds","checkpoint:export","checkpoint:import-read","checkpoint:import"]),Pr="checkpoint",eC=8,tC=6e4,cr="CANCELLED",rC={success:"success",partial:"partial",unstable:"partial",failure:"failure",cancelled:"cancelled"},nC={preview:"previewed",rewind:"rewound to",undo:"used",export:"exported"};function xp(s){let{result:e,notes:t,deliverability:r}=s;return{done:!0,result:e,notes:t,...r!==void 0?{deliverability:r}:{}}}var oC=/\s*\b(?:No record was (?:read or )?written|Nothing was written)\./g;function Dp(s,e,t,r){let n=t(s),o=(e??[]).map(t);return o.length===0?{done:!1,refusal:n}:r?{done:!1,refusal:{code:n.code,message:Fk([n,...o])},alsoRefused:o}:{done:!1,refusal:n,alsoRefused:o}}function Fk(s){let e=!1;return s.map(({message:t})=>{let r=t.replace(oC,"").trim();return e?r:(e=r!==t.trim(),t)}).join(" ")}var sC=new Set(["RUN_WRITING","API_BUDGET","EMAILS"]),Cr=class extends Error{constructor(t,r,n,o=[]){super(r);this.code=t;this.result=n;this.alsoRefused=o;this.name="CheckpointStepRefused"}code;result;alsoRefused};function Nk(s){return s.deleted.some(e=>e.deleted>0)||s.restored.some(e=>e.restored+(e.restoredWithout??0)>0)||s.undeleted.some(e=>e.undeleted>0)||(s.recreated??[]).some(e=>e.created>0)}async function iC(){let[s,e,t,r,n,o,i,a,d,c,u,l,p]=await Promise.all([import("./chunk-YGTOX7IL.mjs"),import("./chunk-TTU5EQZ6.mjs"),import("./chunk-55OJJT2Q.mjs"),import("./chunk-V3AXSKSU.mjs"),import("./chunk-BIDXK7KA.mjs"),import("./chunk-A2CH2QGX.mjs"),import("./chunk-RPTEEI4R.mjs"),import("./chunk-UZFTTNOP.mjs"),import("./chunk-GZW2GNFK.mjs"),import("./chunk-OO2WY3UB.mjs"),import("./chunk-JTNJKSAA.mjs"),import("./chunk-GYFIXUJG.mjs"),import("./chunk-O7YIEFG7.mjs")]);return{pageEmailsRefusal:u.pageEmailsRefusal,planSelection:a.planSelection,snapshotRowsOf:a.snapshotRowsOf,rewindWriters:a.rewindWriters,boundsRefusals:d.boundsRefusals,selectionDiff:d.selectionDiff,rewindStepsOf:d.rewindStepsOf,notConfirmedRefusal:d.notConfirmedRefusal,undeletableUnattendedRefusal:d.undeletableUnattendedRefusal,REWIND_STEP_WORDS:d.REWIND_STEP_WORDS,REWIND_MUTING_STEP_WORDS:d.REWIND_MUTING_STEP_WORDS,guardCheckpoint:o.guardCheckpoint,newArchiveKey:i.newArchiveKey,archiveKeyText:i.archiveKeyText,parseArchiveKey:i.parseArchiveKey,ARCHIVE_EXTENSION:i.ARCHIVE_EXTENSION,exportCheckpointArchive:i.exportCheckpointArchive,CheckpointExportError:i.CheckpointExportError,readArchiveHeader:i.readArchiveHeader,importCheckpointArchive:i.importCheckpointArchive,DEFAULT_KEEP_DAYS:s.DEFAULT_KEEP_DAYS,openCheckpointStore:s.openCheckpointStore,defaultCheckpointStoreRoot:s.defaultCheckpointStoreRoot,scratchOrgExpired:s.scratchOrgExpired,previewDirOf:s.previewDirOf,CheckpointStoreError:s.CheckpointStoreError,takeCheckpoint:e.takeCheckpoint,scopeCheckpoint:e.scopeCheckpoint,takeOrgOf:e.takeOrgOf,CheckpointTakeStopped:e.CheckpointTakeStopped,previewCheckpoint:t.previewCheckpoint,rewindOrg:r.rewindOrg,rewindOrgOf:r.rewindOrgOf,addedStorageMB:r.addedStorageMB,RewindStopped:r.RewindStopped,undoCheckpoint:n.undoCheckpoint,UndoStopped:n.UndoStopped,beforeRunScopeOf:c.beforeRunScopeOf,beforeRunAskedOf:c.beforeRunAskedOf,beforeRunKeepDaysOf:c.beforeRunKeepDaysOf,beforeRunDiskRefusal:c.beforeRunDiskRefusal,beforeRunOutcomeOf:c.beforeRunOutcomeOf,freeBytesOf:c.freeBytesOf,scopeBeforeRun:c.scopeBeforeRun,settleBeforeRun:c.settleBeforeRun,ReplayStore:l.ReplayStore,defaultReplayStoreRoot:l.defaultReplayStoreRoot,loadToRemove:p.loadToRemove,loadRecordsInfo:p.loadRecordsInfo}}var Ie=class extends Error{constructor(t,r,n=!1,o,i,a=[]){super(r);this.code=t;this.retryable=n;this.result=o;this.refusal=i;this.alsoRefused=a;this.name="Refused"}code;retryable;result;refusal;alsoRefused};function Ed(s){return s instanceof Rt?s:s instanceof Ie?s.code===cr?new Rt(s.message):new Cr(s.code,s.alsoRefused.length>0?Fk([s,...s.alsoRefused]):s.message,s.result,s.alsoRefused):s}async function jk(s){try{return(await XP(s)).isDirectory()}catch{return!1}}function Mt(s,e){return s!==void 0&&e!==void 0&&s.length>=15&&s.slice(0,15)===e.slice(0,15)}var Mk=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function ci(s,e){if(e===void 0)return;let t=new Map(s.objects.map(({objectApiName:n})=>[n.toLowerCase(),n])),r=e.filter(n=>!t.has(n.toLowerCase()));if(r.length>0)throw new Ie("NOT_HELD",`The checkpoint '${s.name}' holds no ${r.join(", ")}: a rewind is limited to objects it holds. No record was read or written.`);return[...new Set(e.flatMap(n=>t.get(n.toLowerCase())??[]))]}function yt(s){return we(s)}function aC(s,e){let t=[...e].sort((n,o)=>o.length-n.length),r=s;for(let n of t)r=r.replaceAll(n,ui(n));for(let n of t){let o=Lk(n);o===n||o.length<=1||(r=r.replaceAll(`${o}${QP}`,"").replaceAll(o,ui(o)))}return r}function dC(s){return{formatVersion:s.formatVersion,checkpointFormat:s.checkpointFormat,sandforgeVersion:s.sandforgeVersion,organizationId:s.organizationId,orgTier:s.orgTier,checkpointId:s.checkpointId,takenAt:s.takenAt,records:s.records,objects:s.objects,files:s.files,bytes:s.bytes,...s.dataStorageMaxMB!==void 0?{dataStorageMaxMB:s.dataStorageMaxMB}:{},...s.staging===!0?{staging:s.staging}:{}}}function cC(s){let e=s.reason==="notAFolder"?"it is a file, not a folder":s.reason==="otherOwner"?"another user of this machine owns it, and could read and replace the checkpoints in it":`it could not be made${s.detail!==void 0?` (${s.detail})`:""}`;return`The checkpoints cannot be kept in ${s.path}: ${e}.`}function Np(s){return`${s.operation==="take"?"a checkpoint is being taken":s.operation==="rewind"?"a rewind is writing":s.operation==="undo"?"an undo is writing":s.operation==="empty"?"an emptying of its objects is writing":"SandForge is deleting checkpoints"} (process ${s.pid} on ${s.host})`}var Pd=class{constructor(e,t={},r=Mo){this.deps=e;this.writers=t;this.self=r}deps;writers;self;loaded;store;replays;liveTracker;syncRuns;seedRuns;targetAutomation={read:async(e,t,r)=>(await this.ownReader()).read(e,t,r)};reader;previewsAnswered;previewReads=new Map;changeListeners=new Set;importFiles=new Map;muteLeases={};freeBytes;setLiveOperationTracker(e){this.liveTracker=e}setRunFiles(e,t){e==="sync"?this.syncRuns=t:this.seedRuns=t}setStore(e){this.store=Promise.resolve(e)}setReplayStore(e){this.replays=e}setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}setFreeBytes(e){this.freeBytes=e}rewindFromPreviewsAnswered(){this.previewsAnswered??=new Map}async handle(e){if(!ZP.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"checkpoint:list":return await this.handleList(e),!0;case"checkpoint:scope":return await this.handleScope(e),!0;case"checkpoint:take":return await this.handleTake(e),!0;case"checkpoint:preview":return await this.handlePreview(e),!0;case"checkpoint:plan-selection":return await this.handlePlanSelection(e),!0;case"checkpoint:rewind":return await this.handleRewind(e),!0;case"checkpoint:undo":return await this.handleUndo(e),!0;case"checkpoint:delete":return await this.handleDelete(e),!0;case"checkpoint:keep":return await this.handleKeep(e),!0;case"checkpoint:rename":return await this.handleRename(e),!0;case"checkpoint:ignore-fields":return await this.handleIgnoreFields(e),!0;case"checkpoint:rewinds":return await this.handleRewinds(e),!0;case"checkpoint:export":return await this.handleExport(e),!0;case"checkpoint:import-read":return await this.handleImportRead(e),!0;case"checkpoint:import":return await this.handleImport(e),!0;default:return!1}}async sweep(){try{let t=await(await this.openedStore()).sweep();for(let r of t.checkpoints)this.deps.log(`[INFO] Removed checkpoint '${r.name}' of ${r.alias??r.organizationId}, taken ${r.takenAt}: kept until ${r.expiresAt}`+(r.undoUntil!==void 0?`; the undo of its last rewind, open until ${r.undoUntil}, went with it`:""));for(let r of t.journals)this.deps.log(`[INFO] Removed the journal of rewind ${r.rewindId} of checkpoint '${r.name}': it could be undone until ${r.undoUntil}`);for(let r of t.skipped)this.deps.log(`[INFO] Checkpoints of ${r} not swept: a take, a rewind or an undo runs`);t.checkpoints.length>0&&this.checkpointsChanged()}catch(e){this.deps.log(`[WARN] Expired checkpoints were not removed: ${I(e)}`)}}async keptBefore(e){let t=e.previousOrganizationId??this.deps.sandboxRefreshes?.organizationIdOf(e.orgId);return t===void 0||!Mk.test(t)?0:(await(await this.openedStore()).list({organizationId:t})).length}async latestUsableOf(e){let t=this.deps.orgManager.getOrg(e);if(!t||!Io(t))return;let r=await this.openedStore(),n=(await this.listOfOrg(r,e)).find(o=>o.valid&&o.checkpoint!==void 0)?.checkpoint;return n?{checkpointId:n.checkpointId,name:n.name,takenAt:n.takenAt}:void 0}onCheckpointsChanged(e){return this.changeListeners.add(e),()=>{this.changeListeners.delete(e)}}async scopeBeforeRun(e,t={}){let r=this.registeredOrg(e.orgId),n=await this.modules(),o=await this.openedStore(),i=await this.connect(r);return n.scopeBeforeRun({org:n.takeOrgOf(i),store:o,handler:this.deps,runWriting:this.beforeRunWriting(r,t),...this.freeBytes?{freeBytes:this.freeBytes}:{}},this.takeRequestOf(r,{mode:"picked"}),this.beforeRunRequestOf(n,e))}async takeBeforeRun(e,t={},r={}){let n=`checkpoint:before-run:${ns()}`,o=this.registeredOrg(e.orgId),i=await this.modules(),a=await this.openedStore(),d=this.beforeRunRequestOf(i,e),c=i.beforeRunScopeOf(d),u=(g,h={})=>{let{taken:m}=h;Y(this.deps,{action:"checkpoint_take",module:Pr,operationId:n,orgId:o.id,outcome:g,beforeRun:{module:e.module,operationId:e.operationId},...h.code!==void 0?{code:h.code}:{},details:m?{checkpointId:m.checkpointId,records:m.records,objects:m.objects.length,bytes:m.bytes}:{}})};if(r.planned!==void 0){let g=i.beforeRunDiskRefusal(r.planned.estimate.bytes,await(this.freeBytes??i.freeBytesOf)(a.root));if(g!==void 0)return u("stopped",{code:g.code}),{taken:!1,refusal:g}}let l=await this.connect(o);if(r.signal?.aborted)return u("cancelled"),{taken:!1,stopped:!0};let p;try{p=await this.take(n,i,a,l,o,i.beforeRunAskedOf(c,d),{description:`Checkpoint first: taking a checkpoint of ${yt(o)} before the run`,runWriting:this.beforeRunWriting(o,t),...r.signal?{signal:r.signal}:{},...r.onProgress?{onProgress:r.onProgress}:{}})}catch(g){if(g instanceof Ie&&g.code===cr)return u("cancelled"),{taken:!1,stopped:!0};if(g instanceof Ie&&g.refusal!==void 0)return u("stopped",{code:g.refusal.code}),{taken:!1,refusal:g.refusal};throw u("failure"),g}let f=await i.beforeRunOutcomeOf(a,c,p);return f.taken?u("success",{taken:f.checkpoint}):(this.checkpointsChanged(),u("stopped",{..."refusal"in f?{code:f.refusal.code}:{}})),f}async settleBeforeRun(e,t){let r=await this.modules(),n=await this.openedStore(),o=await r.settleBeforeRun(n,e,t);return o.notDeleted!==void 0&&this.deps.log(`[WARN] ${o.notDeleted}`),o.info.state==="deleted"&&(this.deps.log(`[INFO] Deleted checkpoint '${e.name}', taken before a run that wrote nothing`),this.checkpointsChanged()),o.info}beforeRunRequestOf(e,t){let r=this.deps.services?.getSandforgeSetting?.("checkpoint.beforeRunKeepDays",Tg.default);return{module:t.module,written:t.written,running:t.running,request:t.request,operationId:t.operationId,tool:"panel",keepDays:e.beforeRunKeepDaysOf(t.request.keepDays,r)}}beforeRunWriting(e,t){return this.runWriting(e.id,yt(e),"start this run","No record was read.",t)}async takeForPipeline(e,t){let r=`checkpoint:pipeline:${ns()}`;try{let n=wn.safeParse(e.config);if(!n.success)throw new Ie("CONFIG_INVALID",`The Checkpoint step "${e.origin.step}" does not read: ${n.error.issues[0]?.message??"its configuration is not one"}. Nothing was read.`);let o=n.data,i=this.registeredOrg(o.orgId),a=await this.modules(),d=await this.openedStore(),c=await this.connect(i);if(t?.aborted)throw new Ie(cr,new a.CheckpointTakeStopped().message);let{checkpoint:u}=await this.take(r,a,d,c,i,{...o.name!==void 0?{nameWithDate:o.name}:{},mode:o.mode,...o.objects!==void 0?{objects:o.objects}:{},...o.excluded!==void 0?{excluded:o.excluded}:{},...o.maxTotal!==void 0?{maxTotal:o.maxTotal}:{},keepDays:o.keepDays,...o.ignoredFields!==void 0?{ignoredFields:o.ignoredFields}:{}},{description:`Pipeline '${e.origin.pipeline}': taking a checkpoint of ${yt(i)}`,...t?{signal:t}:{}});return{operationId:r,checkpointId:u.checkpointId,name:u.name,records:u.objects.reduce((l,p)=>l+p.records,0),objects:u.objects.length,bytes:u.bytes,movedWhileTaken:u.movedWhileTaken}}catch(n){throw Ed(n)}}async rewindForPipeline(e,t){let r=`checkpoint:pipeline:${ns()}`,{grant:n,origin:o}=e;try{let i=await this.modules(),a=xt.safeParse(e.config);if(!a.success)throw new Ie("CONFIG_INVALID",`The Rewind step "${o.step}" does not read: ${a.error.issues[0]?.message??"its configuration is not one"}. No record was read or written.`);let d=a.data;if(n.digest!==$s(d)||n.checkpointId!==d.checkpointId)throw this.refusalOf(i.notConfirmedRefusal(o.step,!0));let c=await this.openedStore(),{folder:u,checkpoint:l}=await this.checkpointOf(c,d.checkpointId);if(!Mt(n.organizationId,l.org.organizationId))throw this.refusalOf(i.notConfirmedRefusal(o.step,!0));this.usable(i,l,"rewind");let p=this.registeredOrg(d.orgId);if(!Mt(p.orgId,l.org.organizationId)&&!Mt(this.deps.sandboxRefreshes?.organizationIdOf(p.id),l.org.organizationId))throw new Ie("OTHER_ORG",`The checkpoint '${l.name}' is not of ${yt(p)}, the org the Rewind step "${o.step}" names. No record was read or written.`);let f=ci(l,d.objects),g=await this.connect(p),h=yt(p),m={operationId:r,pipeline:{origin:o,grantedAt:n.grantedAt}},y=()=>(this.audit(m,"rewind",p,l,"stopped",{code:ht}),new Rt(new i.RewindStopped().message)),v=($,H=[])=>(this.audit(m,"rewind",p,l,"stopped",{code:$.code}),this.refusalOf($,H));if(t?.aborted)throw y();let b;try{b=await i.previewCheckpoint({org:i.takeOrgOf(g),store:c,readAutomation:$=>this.readAutomation(p.id,$),runWriting:this.runWriting(p.id,h,"rewind","No record would be read or written."),...t?{signal:t}:{}},{checkpoint:l,folder:u,orgName:h,registered:p,username:p.username,...f!==void 0?{objects:f}:{},reusesPreview:!0,...d.muteAutomation?{muteAutomation:!0}:{},acceptOutside:d.acceptOutside})}catch($){throw t?.aborted?y():$}if(!b.previewed)throw v(b.refusal);let k=f!==void 0?i.selectionDiff(b.diff,await i.planSelection({checkpoint:l,previewDir:i.previewDirOf(u,b.diff.previewId),readAt:b.diff.readAt,objects:new Set(f),acceptOutside:d.acceptOutside,heldRows:i.snapshotRowsOf(l,u),...t?{signal:t}:{}})):b.diff,S=d.muteAutomation&&b.automation?Ml(b.automation,zr(i.rewindStepsOf(k))).automation:b.automation,C=await i.boundsRefusals({orgName:h,preview:{diff:k,...S?{automation:S}:{},...b.emails?{emails:b.emails}:{},...b.emailsUncounted!==void 0?{emailsUncounted:b.emailsUncounted}:{},...b.deliverability?{deliverability:b.deliverability}:{}},bounds:{maxRecords:d.maxRecords,refuseWhenActive:d.refuseWhenActive},accepted:d,writers:async()=>i.rewindWriters(l.takenBy,await i.takeOrgOf(g).userId()),words:d.muteAutomation?i.REWIND_MUTING_STEP_WORDS:i.REWIND_STEP_WORDS,user:p.username}),[R,...w]=[...b.refusal!==void 0?[b.refusal]:[],...C.filter($=>$.code!==b.refusal?.code)];if(R!==void 0)throw v(R,w);if(t?.aborted)throw y();let P=[],O=[],E=await this.writeAct(m,"rewind",p,l,`Pipeline '${o.pipeline}': rewinding ${h} to '${l.name}'`,async($,H)=>{let J=await i.rewindOrg({org:i.rewindOrgOf(g),undelete:W=>g.soap.undelete(W),store:c,readAutomation:W=>this.readAutomation(p.id,W),runWriting:this.runWriting(p.id,h,"rewind","No record was read or written."),onUndeletable:W=>(P.push(...W),this.deps.log(`[WARN] checkpoint:rewind ${r}: the user may not delete ${W.map(Z=>`${Z.objectApiName} (${Z.records})`).join(", ")} in the target, and nobody runs the pipeline to be asked: the deletion is left untouched`),Promise.resolve(!1)),onWriting:W=>Tt({action:"checkpoint_rewind",orgId:p.id,operationId:m.operationId},i.addedStorageMB(W)),onProgress:({percentage:W,step:Z})=>H(W,Z),signal:$,...d.muteAutomation?{mute:this.muteOf(g)}:{}},{checkpoint:l,folder:u,orgName:h,registered:p,username:p.username,previewId:b.diff.previewId,reusesPreview:b.diff,...f!==void 0?{objects:f}:{},acceptAutomation:d.acceptAutomation,acceptEmails:d.acceptEmails,acceptNoUndo:d.acceptNoUndo,acceptRecreate:d.acceptRecreate,acceptOutside:d.acceptOutside,acceptUnseen:d.acceptUnseen});return J.rewound?(O=J.notes,xp(J)):Dp(J.refusal,J.alsoRefused,W=>W,!1)},$=>$ instanceof i.RewindStopped,{...t?{signal:t}:{},acceptEmails:d.acceptEmails,refusalOf:$=>P.length>0?i.undeletableUnattendedRefusal(h,P,Nk($)):void 0});return{operationId:r,checkpointId:l.checkpointId,result:E,notes:O,estimate:b.estimate}}catch(i){throw Ed(i)}}async estimateTakeForPipeline(e,t){try{let r=wn.safeParse(e.config);if(!r.success)throw new Ie("CONFIG_INVALID",`The Checkpoint step "${e.origin.step}" does not read: ${r.error.issues[0]?.message??"its configuration is not one"}. Nothing was read.`);let n=r.data,o=this.registeredOrg(n.orgId),i=await this.modules(),a=await this.openedStore(),d=await this.connect(o);if(t?.aborted)throw new Ie(cr,new i.CheckpointTakeStopped().message);let c=await i.scopeCheckpoint({org:i.takeOrgOf(d),store:a,handler:this.deps,runWriting:this.runWriting(o.id,yt(o),"take the checkpoint","No record was read."),...t?{signal:t}:{}},this.takeRequestOf(o,{mode:n.mode,...n.objects!==void 0?{objects:n.objects}:{},...n.excluded!==void 0?{excluded:n.excluded}:{},...n.maxTotal!==void 0?{maxTotal:n.maxTotal}:{}}));if(c.refusal)throw this.refusalOf(c.refusal);return{objects:c.objects.length,records:c.objects.reduce((u,l)=>u+l.records,0),leftOut:c.leftOut.length,estimate:c.estimate}}catch(r){throw Ed(r)}}async previewRewindForPipeline(e,t){let{grant:r,origin:n}=e;try{let o=await this.modules(),i=xt.safeParse(e.config);if(!i.success)throw new Ie("CONFIG_INVALID",`The Rewind step "${n.step}" does not read: ${i.error.issues[0]?.message??"its configuration is not one"}. No record was read or written.`);let a=i.data;if(r.digest!==$s(a)||r.checkpointId!==a.checkpointId)throw this.refusalOf(o.notConfirmedRefusal(n.step,!0));let d=await this.openedStore(),{folder:c,checkpoint:u}=await this.checkpointOf(d,a.checkpointId);if(!Mt(r.organizationId,u.org.organizationId))throw this.refusalOf(o.notConfirmedRefusal(n.step,!0));this.usable(o,u,"rewind");let l=this.registeredOrg(a.orgId);if(!Mt(l.orgId,u.org.organizationId)&&!Mt(this.deps.sandboxRefreshes?.organizationIdOf(l.id),u.org.organizationId))throw new Ie("OTHER_ORG",`The checkpoint '${u.name}' is not of ${yt(l)}, the org the Rewind step "${n.step}" names. No record was read or written.`);let p=ci(u,a.objects),f=await this.connect(l),g=yt(l);if(t?.aborted)throw new Ie(cr,new o.RewindStopped().message);let h=await o.previewCheckpoint({org:o.takeOrgOf(f),store:d,readAutomation:C=>this.readAutomation(l.id,C),runWriting:this.runWriting(l.id,g,"rewind","No record would be read or written."),...t?{signal:t}:{}},{checkpoint:u,folder:c,orgName:g,registered:l,username:l.username,...p!==void 0?{objects:p}:{},reusesPreview:!0,...a.muteAutomation?{muteAutomation:!0}:{},acceptOutside:a.acceptOutside});if(!h.previewed)throw this.refusalOf(h.refusal);let m=p!==void 0?o.selectionDiff(h.diff,await o.planSelection({checkpoint:u,previewDir:o.previewDirOf(c,h.diff.previewId),readAt:h.diff.readAt,objects:new Set(p),acceptOutside:a.acceptOutside,heldRows:o.snapshotRowsOf(u,c),...t?{signal:t}:{}})):h.diff,y=a.muteAutomation&&h.automation?Ml(h.automation,zr(o.rewindStepsOf(m))).automation:h.automation,v=await o.boundsRefusals({orgName:g,preview:{diff:m,...y?{automation:y}:{},...h.emails?{emails:h.emails}:{},...h.emailsUncounted!==void 0?{emailsUncounted:h.emailsUncounted}:{},...h.deliverability?{deliverability:h.deliverability}:{}},bounds:{maxRecords:a.maxRecords,refuseWhenActive:a.refuseWhenActive},accepted:a,writers:async()=>o.rewindWriters(u.takenBy,await o.takeOrgOf(f).userId()),words:a.muteAutomation?o.REWIND_MUTING_STEP_WORDS:o.REWIND_STEP_WORDS,user:l.username}),[b,...k]=[...h.refusal!==void 0?[h.refusal]:[],...v.filter(C=>C.code!==h.refusal?.code)];if(b!==void 0)throw this.refusalOf(b,k);let S=C=>m.objects.reduce((R,w)=>R+C(w),0);return{checkpointId:u.checkpointId,toDelete:S(({toDelete:C})=>C.createdSince+C.broughtBackSince+C.comesBackWithParent),toGiveBack:S(({toGiveBack:C})=>C.records),toBringBack:S(({toBringBack:C})=>C.inBin+C.withParent+C.deletedWhileTaken),toRecreate:S(({toRecreate:C})=>C??0),estimate:h.estimate}}catch(o){throw Ed(o)}}async exportCheckpoint(e){try{let t=await this.modules(),r=await this.openedStore(),{folder:n,checkpoint:o}=await this.checkpointOf(r,e.checkpointId);this.usable(t,o,"export");let i=e.key??t.newArchiveKey(),a=await t.exportCheckpointArchive({folder:n,checkpoint:o,out:e.out,key:i,sandforgeVersion:e.sandforgeVersion}),{header:d}=a;return Y(this.deps,{action:"checkpoint_export",module:Pr,operationId:ns(),orgId:this.orgOfCheckpoint(o)?.id??o.org.organizationId,outcome:"success",details:{checkpointId:o.checkpointId,records:d.records,objects:d.objects,files:d.files,bytes:a.bytes}}),{exported:!0,checkpoint:o,header:d,bytes:a.bytes,sha256:a.sha256,...e.key===void 0?{key:t.archiveKeyText(i)}:{}}}catch(t){return{exported:!1,refusal:await this.transferRefusalOf(t,"EXPORT_ERROR")}}}async readImport(e){let t=await this.importChecked(e);return"refusal"in t?{allowed:!1,...t}:{allowed:!0,header:t.read.header}}async importCheckpoint(e){let t=await this.importChecked(e),r=(d,c,u,l={})=>{Y(this.deps,{action:"checkpoint_import",module:Pr,operationId:ns(),orgId:d,outcome:c,...l.code!==void 0?{code:l.code}:{},details:{...u?{checkpointId:u.checkpointId,records:u.records,objects:u.objects}:{},...l.alreadyKept?{alreadyKept:!0}:{}}})};if("refusal"in t)return t.orgId!==void 0&&r(t.orgId,"stopped",t.header,{code:t.refusal.code}),{imported:!1,refusal:t.refusal,...t.header?{header:t.header}:{}};let{m:n,store:o,org:i,read:a}=t;try{let d=await n.importCheckpointArchive({store:o,file:e.file,read:a,key:e.key,...i.alias?{alias:i.alias}:{},keepDays:e.keepDays??n.DEFAULT_KEEP_DAYS,takenOn:{host:KP(),pid:process.pid}});if(!d.imported)return r(i.id,"stopped",a.header,{code:d.refusal.code}),{imported:!1,header:a.header,refusal:d.refusal};r(i.id,"success",a.header,d.outcome==="alreadyKept"?{alreadyKept:!0}:{}),d.outcome==="imported"&&this.checkpointsChanged();let c=yt(i);return{imported:!0,outcome:d.outcome,checkpoint:d.checkpoint,warnings:[`Rewinds of ${c} from two machines at once fight each other: the lock is per machine. Agree on who rewinds.`,"A field your user cannot see is neither compared nor written back by a rewind from this machine, and its preview names it.","The rewinds made from the machine it came from, and their Undo, stayed there."]}}catch(d){return r(i.id,"failure",a.header),{imported:!1,header:a.header,refusal:await this.transferRefusalOf(d,"IMPORT_ERROR")}}}async importChecked(e){let t,r;try{let n=await this.modules(),o=await this.openedStore(),i=this.registeredOrg(e.orgId);r=i.id;let a=await n.readArchiveHeader(e.file);if("refusal"in a)return{refusal:a.refusal,orgId:r};t=a.read.header;let d=await this.connect(i),c=await n.guardCheckpoint(d,{act:"import",orgName:yt(i),registered:i,username:i.username,organizationId:t.organizationId});if(!c.allowed){let u=c.refusal.code==="OTHER_ORG"?this.refreshedAt(t.organizationId):void 0;return{refusal:u!==void 0?{code:"OTHER_ORG",message:`The sandbox this file's checkpoint was taken of was refreshed on ${u.slice(0,10)}: ${yt(i)} is another org now, and the checkpoint can no longer be rewound to. ${Is} Nothing was imported.`}:c.refusal,header:t,orgId:r}}return{m:n,store:o,org:i,read:a.read}}catch(n){return{refusal:await this.transferRefusalOf(n,"IMPORT_ERROR"),...t?{header:t}:{},...r!==void 0?{orgId:r}:{}}}}async transferRefusalOf(e,t){if(e instanceof Ie)return{code:e.code,message:e.message};let r=await this.modules().catch(()=>{});return r!==void 0&&e instanceof r.CheckpointExportError?{code:e.code,message:e.message}:{code:t,message:I(e)}}async handleExport(e){let t=x(By,e,"checkpoint:error",this.deps);if(!t)return;let r=[];try{let n=this.fileDialogs("export"),o=await this.modules(),i=await this.openedStore();r.push(i.root);let{checkpoint:a}=await this.checkpointOf(i,t.checkpointId);this.usable(o,a,"export");let{checkpointId:d}=a,c=await n.pickExportFile(`${d}${o.ARCHIVE_EXTENSION}`);if(c===void 0){this.respond(e,"checkpoint:export:response",{status:"cancelled",checkpointId:d});return}r.push(c);let u=await GP(c).then(()=>!0,()=>!1),l=u?YP(Lk(c),`.${ui(c)}.${zP(4).toString("hex")}.export`):c;r.push(l);let p=await this.exportCheckpoint({checkpointId:d,out:l,sandforgeVersion:n.sandforgeVersion});if(!p.exported)throw new Ie(p.refusal.code,p.refusal.message);if(u)try{await JP(l,c)}catch(f){throw await VP(l,{force:!0}),f}this.respond(e,"checkpoint:export:response",{status:"saved",checkpointId:d,fileName:ui(c),key:p.key,records:p.header.records,objects:p.header.objects,bytes:p.bytes})}catch(n){this.fail(e,this.pathless(n,r,"EXPORT_ERROR"),"EXPORT_ERROR")}}async handleImportRead(e){let t=[];try{let r=this.fileDialogs("import"),n=await this.modules(),o=await this.openedStore();t.push(o.root);let i=await r.pickImportFile();if(i===void 0){this.respond(e,"checkpoint:import-read:response",{status:"cancelled"});return}t.push(i);let a=await n.readArchiveHeader(i);if("refusal"in a)throw this.refusalOf(a.refusal);let{header:d}=a.read,c=[],u;for(let p of this.deps.orgManager.getAllOrgs()){if(!this.organizationIdsOf(p.id).some(h=>Mt(h,d.organizationId)))continue;let g=await this.readImport({orgId:p.id,file:i});g.allowed?c.push(p.id):u??=g.refusal}if(c.length===0&&u!==void 0)throw new Ie(u.code,u.message);let l=await o.read(d.checkpointId)!==void 0;this.respond(e,"checkpoint:import-read:response",{status:"read",token:this.keepImportFile(i),fileName:ui(i),summary:dC(d),orgIds:c,...l?{keptHere:!0}:{}})}catch(r){this.fail(e,this.pathless(r,t,"IMPORT_ERROR"),"IMPORT_ERROR")}}async handleImport(e){let t=x(qy,e,"checkpoint:error",this.deps);if(!t)return;let r=this.importFiles.get(t.token),n=r!==void 0?[r]:[];try{if(r===void 0)throw new Ie("IMPORT_FILE_GONE","This window no longer knows the file to import: choose it again with Import\u2026. Nothing was imported.");let o=await this.modules();n.push((await this.openedStore()).root);let i=o.parseArchiveKey(t.key);if(i===void 0){let d=await this.readImport({orgId:t.orgId,file:r});throw d.allowed?new Ie("IMPORT_KEY","That is not a key SandForge draws: 52 letters and digits, in groups of four as the export showed it. Nothing was imported."):new Ie(d.refusal.code,d.refusal.message)}let a=await this.importCheckpoint({orgId:t.orgId,file:r,key:i,keepDays:t.keepDays});if(!a.imported)throw new Ie(a.refusal.code,a.refusal.message);this.importFiles.delete(t.token),this.respond(e,"checkpoint:import:response",{checkpoint:a.checkpoint,outcome:a.outcome})}catch(o){this.fail(e,this.pathless(o,n,"IMPORT_ERROR"),"IMPORT_ERROR")}}fileDialogs(e){let t=this.deps.infraServices?.checkpointFiles;if(!t)throw new Ie("NO_FILE_DIALOG",e==="export"?"This window has no dialog to ask where the file goes: export the checkpoint with npx sandforge checkpoint export. Nothing was written.":"This window has no dialog to ask which file to read: import it with npx sandforge checkpoint import. Nothing was imported.");return t}keepImportFile(e){let t=ns();this.importFiles.set(t,e);for(let r of this.importFiles.keys()){if(this.importFiles.size<=eC)break;this.importFiles.delete(r)}return t}pathless(e,t,r){let n=e instanceof Ie?e:new Ie(r,I(e));return new Ie(n.code,aC(n.message,t),n.retryable)}checkpointsChanged(){for(let e of this.changeListeners)try{e()}catch(t){this.deps.log(`[WARN] A listener of the checkpoints failed: ${I(t)}`)}}modules(){return this.loaded??=iC(),this.loaded}async openedStore(){this.store??=this.modules().then(t=>{let r=t.openCheckpointStore({root:t.defaultCheckpointStoreRoot()});return"store"in r?r.store:r.refusal});let e=await this.store;if("reason"in e)throw this.store=void 0,new Ie("STORE_REFUSED",cC(e));return e}respond(e,t,r){let n=A(this.deps,e,t,r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}fail(e,t,r,n=!0){if(t instanceof Ie){let o=t.refusal?.holdingLimit,i={...t.alsoRefused.length>0?{alsoRefused:[...t.alsoRefused]}:{},...o!==void 0?{holdingLimit:o}:{}};T(this.deps,e.type,"checkpoint:error",e,t,{code:t.code,retryable:t.retryable,...Object.keys(i).length>0?{extraPayload:i}:{}});return}T(this.deps,e.type,"checkpoint:error",e,t,{code:r,retryable:n})}refusalOf(e,t=[]){return new Ie(e.code,e.message,sC.has(e.code),void 0,e,t)}registeredOrg(e){let t=this.deps.orgManager.getOrg(e);if(!t)throw new Ie("ORG_NOT_FOUND","SandForge has no connected org of this id: connect it first.");return t}async connect(e){try{return await B(e.id,this.deps.orgRegistry,this.deps.orgManager)}catch(t){throw t instanceof Eo&&t.code==="SCRATCH_ORG_EXPIRED"?new Ie("SCRATCH_EXPIRED",`${yt(e)} is a scratch org that has expired: its checkpoints no longer rewind it. `+Is):t}}takeRequestOf(e,t){let r=e.metadata?.expirationDate,{mode:n,objects:o,excluded:i,customSettings:a,maxTotal:d}=t;return{orgId:e.id,orgName:yt(e),...e.alias?{alias:e.alias}:{},username:e.username,instanceUrl:e.instanceUrl,registered:e,...e.orgType==="Scratch"&&r!==void 0&&/^\d{4}-\d{2}-\d{2}$/.test(r)?{scratchExpiresAt:r}:{},mode:n,...o!==void 0?{objects:o}:{},...i!==void 0?{excluded:i}:{},...a!==void 0?{customSettings:a}:{},...d!==void 0?{maxTotal:d}:{}}}writingTo(e,t,r,n,o={}){return this.runWriting(e,t,r,n,o)}runWriting(e,t,r,n,o={}){let i=`A SandForge run is writing to ${t}: ${r} once it has ended. ${n}`;return async a=>{if(this.writers.writingTo?.(e,o.operationId)===!0)return i;for(let d of[this.syncRuns,this.seedRuns])if(d){for(let c of await d.list())if(!(c.end!==void 0||!this.writesTo(c,e,a))&&!(o.runId!==void 0&&c.runId===o.runId&&this.writtenHere(c))&&(this.writers.isRunning?.(c.runId)===!0||ro(c,this.self)))return i}}}writtenHere(e){let t=e.writer;return t!==void 0&&t.pid===this.self.pid&&Date.parse(t.hostStartedAt)===Date.parse(this.self.startedAt)}writesTo(e,t,r){return e.targetOrgId===t||Mt(e.targetOrganizationId,r)||Mt(this.deps.orgManager.getOrg(e.targetOrgId)?.orgId,r)}refreshedAt(e){let t=this.deps.sandboxRefreshes;if(t)for(let r of this.deps.orgManager.getAllOrgs())for(let n of t.refreshesOf(r.id)){let o=n.previousOrganizationId??(n.organizationId===void 0?t.organizationIdOf(r.id):void 0);if(Mt(o,e))return n.detectedAt}}organizationIdsOf(e){let t=this.deps.sandboxRefreshes,r=[this.deps.orgManager.getOrg(e)?.orgId,t?.organizationIdOf(e),...t?.refreshesOf(e).map(o=>o.previousOrganizationId)??[]],n=[];for(let o of r)o===void 0||!Mk.test(o)||n.some(i=>Mt(i,o))||n.push(o);return n}async listOfOrg(e,t){let r=o=>this.refreshedAt(o);return(await Promise.all(this.organizationIdsOf(t).map(o=>e.list({organizationId:o,refreshedAt:r})))).flat().sort((o,i)=>o.checkpointId<i.checkpointId?1:o.checkpointId>i.checkpointId?-1:0)}async withReplays(e){if(e.length===0)return e;try{let t=await this.modules();this.replays??=new t.ReplayStore({root:t.defaultReplayStoreRoot()});let r=this.replays,n=this.deps.orgManager.getAllOrgs(),o=new Map;for(let a of e)o.has(a.organizationId)||o.set(a.organizationId,await r.list({sourceOrganizationId:a.organizationId}));let i=[];for(let a of e){let d=(o.get(a.organizationId)??[]).filter(u=>u.checkpointId===a.checkpointId),c=[];for(let u of d){let l=n.find(g=>Mt(g.orgId,u.target.organizationId)),p=await r.mappingStoreOf(r.folderOf(u.sourceOrganizationId,u.checkpointId),u.target.organizationId).recordedLoads(),f=t.loadToRemove(p);c.push({target:{organizationId:u.target.organizationId,...u.target.name!==void 0?{name:u.target.name}:{},...l?{orgId:l.id}:{}},...u.replayedAt!==void 0?{replayedAt:u.replayedAt}:{},inPlace:u.inPlace,...u.removed?{removed:!0}:{},...u.choices?{choices:u.choices}:{},...l&&f?{records:{...t.loadRecordsInfo(f),orgId:l.id}}:{}})}i.push(c.length>0?{...a,replays:c}:a)}return i}catch(t){return this.deps.log(`[WARN] The replays of the checkpoints could not be read: ${I(t)}`),e}}orgOfCheckpoint(e){let t=e.org.organizationId,r=this.deps.orgManager.getAllOrgs(),n=r.filter(a=>Mt(a.orgId,t)),o=n.find(a=>a.alias===e.org.alias)??n[0];if(o)return o;let i=this.deps.sandboxRefreshes;return r.find(a=>Mt(i?.organizationIdOf(a.id),t))}async checkpointOf(e,t){let r=await e.read(t);if(r===void 0)throw new Ie("NOT_FOUND",`No checkpoint ${t} is kept on this machine.`,!1);if(r.checkpoint===void 0)throw new Ie("DAMAGED",`The file of checkpoint ${t} cannot be read: it can only be deleted.`);return{folder:r.folder,checkpoint:r.checkpoint}}usable(e,t,r){let n=we(t.org);if(t.status!=="ready")throw new Ie(t.status==="taking"?"TAKING":"FAILED",t.status==="taking"?`The checkpoint '${t.name}' is being taken, or its take never ended: it can be ${nC[r]} once taken, or deleted.`:`The take of checkpoint '${t.name}' failed: it can only be deleted.`);if(r==="export")return;let o=this.refreshedAt(t.org.organizationId);if(o!==void 0)throw new Ie("OTHER_ORG",`This sandbox was refreshed on ${o.slice(0,10)}: ${n} is another org now, and this checkpoint is of the org before it, which it no longer rewinds. `+Is);if(e.scratchOrgExpired(t.org,Date.now()))throw new Ie("SCRATCH_EXPIRED",`${n} is a scratch org that has expired: its checkpoints no longer rewind it. `+Is)}connectedOrgOf(e,t){let r=this.orgOfCheckpoint(e);if(!r){let n=we(e.org);throw new Ie("ORG_NOT_FOUND",`${n} is not connected in SandForge: connect it to ${t}.`)}return r}async undoOffered(e,t,r,n){if((await e.list({organizationId:t.organizationId,refreshedAt:d=>this.refreshedAt(d)})).find(d=>d.checkpointId===r.checkpointId)?.undo?.rewindId===n)return;let i=r.lastRewind,a=i?.rewindId!==n?`the rewind ${n} is not the last rewind to '${r.name}'`:i.undoneAt!==void 0?`it was undone on ${i.undoneAt.slice(0,10)}, and there is nothing left to undo`:i.undoUntil!==void 0&&Date.parse(i.undoUntil)<=Date.now()?`its 15 days ended on ${i.undoUntil.slice(0,10)}, and what it deleted may have left the recycle bin`:"Undo is offered for the last rewind of an org only, while its journal is kept on this machine";throw new Ie("UNDO_CLOSED",`This rewind can no longer be undone: ${a}. No record was read or written.`)}audit(e,t,r,n,o,i={}){let{result:a,code:d,deliverability:c}=i,u=a?.mutedAutomation??i.muted,l=a?.rewindId??i.rewindId,p=e.pipeline;Y(this.deps,{action:t==="rewind"?"checkpoint_rewind":"checkpoint_undo",module:Pr,operationId:e.operationId,orgId:r.id,outcome:o,...a?{objects:xa(In(a.deleted),a.restored,a.undeleted)}:{},...d!==void 0?{code:d}:{},...u?{muted:ft(u)}:{},details:{checkpointId:n.checkpointId,...l!==void 0?{rewindId:l}:{},...a?{status:a.status,passes:a.passes}:{},...a?.scope?{limitedTo:a.scope.objects.join(", ")}:{},...c!==void 0?{deliverability:c}:{},...c!==void 0&&c!=="withheld"&&i.acceptEmails===!0?{confirmed:"emails"}:{},...p?{pipeline:p.origin.pipeline,step:p.origin.step,trigger:p.origin.trigger,grantedAt:p.grantedAt}:{}}})}async handleList(e){let t=x(My,e,"checkpoint:error",this.deps);if(t!==null)try{let r=await this.openedStore(),n=t?.orgId===void 0?await r.list({refreshedAt:i=>this.refreshedAt(i)}):await this.listOfOrg(r,t.orgId),o=await this.withReplays(n);this.respond(e,"checkpoint:list:response",{checkpoints:o})}catch(r){this.fail(e,r,"LIST_ERROR")}}async handleScope(e){let t=x(Ly,e,"checkpoint:error",this.deps);if(t)try{let r=this.registeredOrg(t.orgId),n=await this.modules(),o=await this.openedStore(),i=await this.connect(r),a=await n.scopeCheckpoint({org:n.takeOrgOf(i),store:o,handler:this.deps,runWriting:this.runWriting(r.id,yt(r),"take the checkpoint","No record was read.")},this.takeRequestOf(r,t));this.respond(e,"checkpoint:scope:response",{orgId:t.orgId,mode:a.mode,objects:a.objects,leftOut:a.leftOut,estimate:a.estimate,...a.refusal?{refusal:a.refusal}:{},...a.files?{files:a.files}:{},...a.customSettings?{customSettings:a.customSettings}:{}})}catch(r){this.fail(e,r,"SCOPE_ERROR")}}async handleTake(e){let t=x(Fy,e,"checkpoint:error",this.deps);if(!t)return;let r=e.id,o=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(r);try{let i=this.registeredOrg(t.orgId),a=await this.modules(),d=await this.openedStore(),c=await this.connect(i);if(o?.signal.aborted)throw new Ie(cr,new a.CheckpointTakeStopped().message,!0);await this.take(e.id,a,d,c,i,t,{kept:({checkpoint:u,requests:l,estimate:p})=>this.respond(e,"checkpoint:take:response",{checkpoint:u,operationId:e.id,...l?{requests:l}:{},estimate:p})})}catch(i){this.fail(e,i,"TAKE_ERROR")}finally{o?.release()}}async take(e,t,r,n,o,i,a={}){let d=yt(o),c=a.description??`Taking a checkpoint of ${d}`,u=this.deps.infraServices?.backgroundRegistry,l=new AbortController,p=()=>{},f=new Promise((y,v)=>{p=b=>b===void 0?y():v(b)});f.catch(()=>{}),Ge(this.deps,e,Pr,c),u?.register(e,Pr,c,f,l);let g=sr(this.liveTracker,e,Pr,c),h=y=>{let{percentage:v,processedObjects:b,totalObjects:k,step:S}=y;_e(this.deps,e,v,b,k,S),l.signal.aborted||u?.updateProgress(e,v),g.progress(v,b,k,S),a.onProgress?.(y)},m=()=>{u?u.abort(e):l.abort()};a.signal?.addEventListener("abort",m,{once:!0}),a.signal?.aborted&&m();try{let y=await t.takeCheckpoint({org:t.takeOrgOf(n),store:r,handler:this.deps,signal:l.signal,onProgress:h,runWriting:a.runWriting??this.runWriting(o.id,d,"take the checkpoint","No record was read.")},{...this.takeRequestOf(o,i),...i.name!==void 0?{name:i.name}:{},...i.nameWithDate!==void 0?{nameWithDate:i.nameWithDate}:{},keepDays:i.keepDays,...i.ignoredFields?{ignoredFields:i.ignoredFields}:{},...i.unprovenLeftOut===!0?{unprovenLeftOut:!0}:{},...i.beforeRun!==void 0?{beforeRun:i.beforeRun}:{}});if(!y.taken)throw me(this.deps,e,{status:"refused",code:y.refusal.code}),g.fail(y.refusal.message),p(new Error(y.refusal.message)),this.refusalOf(y.refusal);for(let{objectApiName:k,reason:S}of y.notChecked)this.deps.log(`[WARN] checkpoint:take ${e}: what moved in ${k} while it was read was not checked: ${S}`);let{checkpoint:v}=y,b={checkpoint:v,...y.requests?{requests:y.requests}:{},estimate:y.estimate};return a.kept?.(b),this.checkpointsChanged(),me(this.deps,e,{status:"success",objects:v.objects.length,records:v.objects.reduce((k,S)=>k+S.records,0)}),g.complete(),p(),b}catch(y){throw y instanceof Ie?y:y instanceof t.CheckpointTakeStopped?(u?.abort(e),me(this.deps,e,{aborted:!0}),g.cancel(),p(),new Ie(cr,y.message,!0)):(me(this.deps,e,{status:"failure"}),g.fail(I(y)),p(y),y)}finally{a.signal?.removeEventListener("abort",m)}}async handlePreview(e){let t=x(_y,e,"checkpoint:error",this.deps);if(t)try{let r=await this.modules(),n=await this.openedStore(),{folder:o,checkpoint:i}=await this.checkpointOf(n,t.checkpointId);this.usable(r,i,"preview");let a=ci(i,t.objects),d=this.connectedOrgOf(i,`preview the checkpoint '${i.name}'`),c=await this.connect(d),u=await r.previewCheckpoint({org:r.takeOrgOf(c),store:n,readAutomation:l=>this.readAutomation(d.id,l),runWriting:this.runWriting(d.id,yt(d),"rewind","No record would be read or written."),...t.muteAutomation===!0?{mute:this.muteOf(c)}:{}},{checkpoint:i,folder:o,orgName:yt(d),registered:d,username:d.username,...a!==void 0?{objects:a}:{},...this.previewsAnswered!==void 0?{reusesPreview:!0}:{},...t.muteAutomation===!0?{muteAutomation:!0}:{},...t.acceptOutside!==void 0?{acceptOutside:t.acceptOutside}:{}});if(!u.previewed)throw this.refusalOf(u.refusal);this.previewsAnswered?.set(u.diff.previewId,u.diff),this.previewReads.set(u.diff.previewId,{checkpointId:i.checkpointId,readAt:u.diff.readAt}),this.respond(e,"checkpoint:preview:response",{diff:u.diff,...u.automation?{automation:u.automation}:{},...u.emails?{emails:u.emails}:{},...u.emailsKeepingOutside?{emailsKeepingOutside:u.emailsKeepingOutside}:{},...u.emailsUncounted!==void 0?{emailsUncounted:u.emailsUncounted}:{},...u.deliverability?{deliverability:u.deliverability}:{},estimate:u.estimate,...u.refusal?{refusal:u.refusal}:{}})}catch(r){this.fail(e,r,"PREVIEW_ERROR")}}async handlePlanSelection(e){let t=x(Hy,e,"checkpoint:error",this.deps);if(t)try{let r=await this.modules(),n=await this.openedStore(),{folder:o,checkpoint:i}=await this.checkpointOf(n,t.checkpointId);this.usable(r,i,"preview");let a=ci(i,t.objects)??[],d=r.previewDirOf(o,t.previewId),c=this.previewReads.get(t.previewId);if(c?.checkpointId!==i.checkpointId||!await jk(d))throw new Ie("PREVIEW_GONE",`The preview to plan this selection from is no longer kept on this machine: preview the rewind to '${i.name}' again. No record was read or written.`);let u=await r.planSelection({checkpoint:i,previewDir:d,readAt:c.readAt,objects:new Set(a),acceptOutside:t.acceptOutside,heldRows:r.snapshotRowsOf(i,o)});this.respond(e,"checkpoint:plan-selection:response",{checkpointId:i.checkpointId,previewId:t.previewId,plan:u})}catch(r){this.fail(e,r,"PLAN_SELECTION_ERROR")}}async handleRewind(e){let t=x(Uy,e,"checkpoint:error",this.deps);if(!t)return;let n=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(e.id);try{let o=await this.modules(),i=await this.openedStore(),{folder:a,checkpoint:d}=await this.checkpointOf(i,t.checkpointId);this.usable(o,d,"rewind");let c=ci(d,t.objects);if(!await jk(o.previewDirOf(a,t.previewId)))throw new Ie("PREVIEW_GONE",`The preview this rewind was confirmed on is no longer kept on this machine: preview the rewind to '${d.name}' again, then rewind. No record was read or written.`);let u=this.connectedOrgOf(d,`rewind it to the checkpoint '${d.name}'`),l=await this.connect(u),p=this.pageAt(e);if(n?.signal.aborted)throw this.audit(p,"rewind",u,d,"stopped",{code:ht}),new Ie(cr,new o.RewindStopped().message,!0);let f=this.previewsAnswered?.get(t.previewId);this.previewsAnswered?.delete(t.previewId);let g=f?.checkpointId===d.checkpointId?f:void 0,h=yt(u);await this.writeAct(p,"rewind",u,d,`Rewinding ${h} to '${d.name}'`,async(m,y)=>{let v=await o.rewindOrg({org:o.rewindOrgOf(l),undelete:k=>l.soap.undelete(k),store:i,readAutomation:k=>this.readAutomation(u.id,k),runWriting:this.runWriting(u.id,h,"rewind","No record was read or written."),onUndeletable:Gr(this.deps,u.id,"checkpoint:rewind"),onWriting:k=>Tt({action:"checkpoint_rewind",orgId:u.id,operationId:p.operationId},o.addedStorageMB(k)),onProgress:({percentage:k,step:S})=>y(k,S),signal:m,...t.muteAutomation===!0?{mute:this.muteOf(l)}:{}},{checkpoint:d,folder:a,orgName:h,registered:u,username:u.username,previewId:t.previewId,...g?{reusesPreview:g}:{},...c!==void 0?{objects:c}:{},acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails===!0,canMute:!0,acceptNoUndo:t.acceptNoUndo,acceptRecreate:t.acceptRecreate,acceptOutside:t.acceptOutside,acceptUnseen:t.acceptUnseen});if(v.rewound)return xp(v);let b=t.fromPage===!0;return Dp(v.refusal,v.alsoRefused,k=>b?o.pageEmailsRefusal(k,"rewind",h):k,b)},m=>m instanceof o.RewindStopped,{acceptEmails:t.acceptEmails===!0})}catch(o){this.fail(e,o,"REWIND_ERROR")}finally{n?.release()}}async handleUndo(e){let t=x(Wy,e,"checkpoint:error",this.deps);if(!t)return;let n=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(e.id);try{let o=await this.modules(),i=await this.openedStore(),{folder:a,checkpoint:d}=await this.checkpointOf(i,t.checkpointId);this.usable(o,d,"undo"),await this.undoOffered(i,a,d,t.rewindId);let c=this.connectedOrgOf(d,`undo its rewind to '${d.name}'`),u=await this.connect(c),l=this.pageAt(e);if(n?.signal.aborted)throw this.audit(l,"undo",c,d,"stopped",{code:ht,rewindId:t.rewindId}),new Ie(cr,new o.UndoStopped().message,!0);let p=yt(c);await this.writeAct(l,"undo",c,d,`Undoing the rewind of ${p} to '${d.name}'`,async(f,g)=>{let h=await o.undoCheckpoint({org:o.rewindOrgOf(u),undelete:y=>u.soap.undelete(y),store:i,readAutomation:y=>this.readAutomation(c.id,y),runWriting:this.runWriting(c.id,p,"undo the rewind","No record was read or written."),onUndeletable:Gr(this.deps,c.id,"checkpoint:undo"),onWriting:y=>Tt({action:"checkpoint_undo",orgId:c.id,operationId:l.operationId},o.addedStorageMB(y)),onProgress:({percentage:y,step:v})=>g(y,v),signal:f,...t.muteAutomation===!0?{mute:this.muteOf(u)}:{}},{checkpoint:d,folder:a,orgName:p,registered:c,username:c.username,rewindId:t.rewindId,acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails===!0,canMute:!0});if(h.undone)return xp(h);let m=t.fromPage===!0;return Dp(h.refusal,h.alsoRefused,y=>m?o.pageEmailsRefusal(y,"undo",p):y,m)},f=>f instanceof o.UndoStopped,{rewindId:t.rewindId,acceptEmails:t.acceptEmails===!0})}catch(o){this.fail(e,o,"UNDO_ERROR")}finally{n?.release()}}muteOf(e){return(t,r)=>Et(async()=>_t(e),t,{...this.muteLeases,writes:r})}pageAt(e){return{operationId:e.id,respond:(t,r)=>this.respond(e,t,r)}}async writeAct(e,t,r,n,o,i,a,d={}){let{operationId:c}=e,{rewindId:u}=d,l=this.deps.infraServices?.backgroundRegistry,p=new AbortController,f=()=>{},g=new Promise((b,k)=>{f=S=>S===void 0?b():k(S)});g.catch(()=>{}),Ge(this.deps,c,Pr,o),l?.register(c,Pr,o,g,p);let h=sr(this.liveTracker,c,Pr,o),m=u!==void 0?{rewindId:u}:{},y=(b,k)=>{_e(this.deps,c,b,0,0,k),p.signal.aborted||l?.updateProgress(c,b),h.progress(b,0,0,k)},v=()=>{l?l.abort(c):p.abort()};d.signal?.addEventListener("abort",v,{once:!0}),d.signal?.aborted&&v();try{let b=await i(p.signal,y);if(!b.done)throw this.audit(e,t,r,n,"stopped",{code:b.refusal.code,...m}),me(this.deps,c,{status:"refused",code:b.refusal.code}),h.fail(b.refusal.message),f(new Error(b.refusal.message)),this.refusalOf(b.refusal,b.alsoRefused);let{result:k,notes:S,deliverability:C}=b,R={...C!==void 0?{deliverability:C}:{},...d.acceptEmails===!0?{acceptEmails:!0}:{}};for(let P of S)this.deps.log(`[WARN] checkpoint:${t} ${c}: ${P}`);for(let P of k.removedJournals??[])this.deps.log(`[INFO] Removed the journal of rewind ${P.rewindId} of checkpoint '${P.name}': Undo reaches the last rewind of the org alone`);let w=d.refusalOf?.(k);if(w!==void 0)throw this.audit(e,t,r,n,Nk(k)?"partial":"stopped",{result:k,code:w.code,...R}),me(this.deps,c,{status:"refused",code:w.code}),h.fail(w.message),f(new Error(w.message)),new Ie(w.code,w.message,!1,k);if(this.audit(e,t,r,n,rC[k.status],{result:k,...R}),e.respond?.(`checkpoint:${t}:response`,{result:k,operationId:c}),k.status==="cancelled")l?.abort(c),me(this.deps,c,{aborted:!0}),h.cancel(),f();else if(k.status==="failure"){let P=`Nothing the ${t} set out to write went through: its result says why.`;me(this.deps,c,{status:k.status}),h.fail(P),f(new Error(P))}else me(this.deps,c,{status:k.status}),k.status==="success"?h.complete():h.partial(),f();return k}catch(b){if(b instanceof Ie)throw b;if(a(b))throw l?.abort(c),me(this.deps,c,{aborted:!0}),h.cancel(),f(),this.audit(e,t,r,n,"stopped",{code:cr,...m}),new Ie(cr,I(b),!0);let k=Js(b);throw this.audit(e,t,r,n,"failure",{...m,...k?{muted:k}:{}}),this.unreleased(e,t,r,k),me(this.deps,c,{status:"failure"}),h.fail(I(b)),f(b),b}finally{d.signal?.removeEventListener("abort",v)}}unreleased(e,t,r,n){n?.released===!1&&this.deps.log(`[WARN] checkpoint:${t} ${e.operationId}: `+Qt(n,yt(r)).map(o=>o.trim()).join("; "))}readAutomation(e,t){let r=this.targetAutomation;return new pe(tC).withTimeout("checkpoint:preview automation",()=>r.read(e,t,{undeletes:!0}))}ownReader(){return this.reader??=import("./chunk-UK3QLBHW.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async handleDelete(e){let t=x(zy,e,"checkpoint:error",this.deps);if(t)try{let r=await this.openedStore(),n=[],o=[];for(let i of t.checkpointIds){let a=await r.delete(i);a.outcome==="deleted"?n.push(i):a.outcome==="busy"&&o.push(a.holder)}for(let i of o)this.deps.log(`[WARN] checkpoint:delete: kept while ${Np(i)}`);if(n.length===0&&o.length>0)throw new Ie("RUN_WRITING",`The checkpoint was not deleted: ${Np(o[0])}. Delete it once that has ended.`,!0);this.respond(e,"checkpoint:delete:response",{deleted:n}),n.length>0&&this.checkpointsChanged()}catch(r){this.fail(e,r,"DELETE_ERROR")}}async handleKeep(e){let t=x(Gy,e,"checkpoint:error",this.deps);t&&await this.change(e,t.checkpointId,"keep",r=>r.keep(t.checkpointId,t.keep))}async handleRename(e){let t=x(Jy,e,"checkpoint:error",this.deps);t&&await this.change(e,t.checkpointId,"rename",r=>r.update(t.checkpointId,n=>({...n,name:t.name})))}async handleIgnoreFields(e){let t=x(Vy,e,"checkpoint:error",this.deps);t&&await this.change(e,t.checkpointId,"ignore-fields",r=>r.update(t.checkpointId,n=>({...n,ignoredFields:t.fields})))}async handleRewinds(e){let t=x(Xy,e,"checkpoint:error",this.deps);if(t!==null)try{let r=await this.openedStore(),{readRewindLedgers:n}=await import("./chunk-GIFQXB2Q.mjs"),i=(t?.orgIds??this.deps.orgManager.getAllOrgs().map(c=>c.id)).map(c=>({orgId:c,ids:this.organizationIdsOf(c)})),a=await n(r.root,i.flatMap(({ids:c})=>c)),d=[];for(let[c,u]of a){for(let l of u.unreadable)this.deps.log(`[WARN] Line ${l} of the rewind ledger of ${c} does not parse: left out`);for(let l of u.records){let p=i.filter(({ids:f})=>f.some(g=>Mt(g,l.organizationId)));d.push({...l,orgIds:p.map(({orgId:f})=>f)})}}this.respond(e,"checkpoint:rewinds:response",{rewinds:d})}catch(r){this.fail(e,r,"REWINDS_ERROR")}}async change(e,t,r,n){try{let o=await this.modules(),i=await this.openedStore(),{folder:a}=await this.checkpointOf(i,t),d=i.heldBy(a.organizationId);if(d!==void 0&&(d.checkpointId===void 0||d.checkpointId===t))throw new Ie("RUN_WRITING",`The checkpoint was not changed: ${Np(d)}. Change it once that has ended.`,!0);let c;try{c=await n(i)}catch(u){throw u instanceof o.CheckpointStoreError?new Ie(u.code==="notFound"?"NOT_FOUND":u.code==="damaged"?"DAMAGED":"INVALID",u.message):u}this.respond(e,`checkpoint:${r}:response`,{checkpoint:c}),this.checkpointsChanged()}catch(o){this.fail(e,o,"CHANGE_ERROR")}}};var kt={orgUnknown:"ORG_NOT_FOUND",production:"PIPELINE_WRITE_REFUSED",needsApproval:"PIPELINE_WRITE_NEEDS_APPROVAL",templateMissing:"SEED_TEMPLATE_MISSING",templateInvalid:"SEED_TEMPLATE_INVALID",templateUsesAi:"SEED_TEMPLATE_USES_AI",unanswered:"SEED_CONFIRMATION_UNAVAILABLE"};function ur(s,e){return Object.assign(new Error(e),{code:s})}function _k(s,e,t){let r=ea(s);if(r==="refused")return ur(kt.production,`${t} is a production org, or one SandForge cannot tell is not: a pipeline never seeds one, whatever an Approval step answers. Seed a sandbox, a scratch org or a Developer Edition org. Nothing was written.`);if(r==="needsApproval"&&!e.approved)return ur(kt.needsApproval,`${t} is a sandbox marked Staging, which a pipeline seeds only once an Approval step before the seed has approved the run, and none did: put an Approval step before it. Nothing was written.`)}function jp(s){return s.objects.flatMap(e=>e.fieldRules.filter(t=>t.ruleType==="ai_generate").map(t=>`${e.objectApiName}.${t.fieldApiName}`))}function os(s,e,t){let r=t(e)??Ji.find(d=>d.id===e);if(r==null)return{refusal:ur(kt.templateMissing,`No Seed template is saved under ${e}, and SandForge ships none: it was deleted on the Seed page. Choose another. Nothing was written.`)};let n=r.name,o=typeof n=="string"&&n!==""?n:e,i=Do.safeParse(r);if(!i.success){let d=i.error.issues[0];return{refusal:ur(kt.templateInvalid,`The Seed template "${o}" no longer validates (${d.path.join(".")}: ${d.message}): open it on the Seed page and save it again. Nothing was written.`)}}let a=jp(i.data);return a.length>0?{refusal:ur(kt.templateUsesAi,`The Seed template "${o}" fills ${a.join(", ")} with AI rules: a pipeline runs where nobody watches, and an AI rule sends field names to Anthropic on each run. Give ${a.length===1?"it a Faker rule":"them Faker rules"} on the Seed page. Nothing was written.`)}:{asked:{orgId:s,template:i.data}}}var zk={apiLimits:"apiLimits",storage:"storage",recentErrors:"recentErrors",failedJobs:"activeJobs"},Mp=Object.keys(zk),Uk={apiLimits:{variable:Ps.apiLimits,read:s=>s.percent},storage:{variable:Ps.storage,read:s=>s.percent},recentErrors:{variable:Ps.recentErrors,read:s=>s.count},failedJobs:{variable:Ps.failedJobs,read:s=>s.count}},Gk=500,Jk=K({orgId:Dm,checks:Re(Be(["apiLimits","storage","recentErrors","failedJobs"])).min(1).refine(s=>new Set(s).size===s.length)}),Vk=K({message:L().trim().min(1).max(Gk)});function Ot(s,e){return`${s} ${e}${s===1?"":"s"}`}function xr(s,e,t,r){let n=new Date().toISOString();return{stepId:s.id,stepName:s.name,stepType:s.type,status:"completed",output:t,summary:r,startTime:e,endTime:n,duration:new Date(n).getTime()-new Date(e).getTime()}}function It(s,e,t,r){let n=new Date().toISOString();return{stepId:s.id,stepName:s.name,stepType:s.type,status:"failed",output:t,error:r,startTime:e,endTime:n,duration:new Date(n).getTime()-new Date(e).getTime()}}function $r(s,e,t,r){if(typeof t!="string"||t.trim()==="")return`${e} names no org: choose ${r}.`;if(s.orgName(t)===void 0)return`${e} names an org SandForge does not know (${t}): connect it, or choose ${r} again.`}function Up(s){return Array.isArray(s)&&s.length>0?s:void 0}function uC(s){return e=>{let t=`Backup step "${e.name}"`,r=e.config??{},n=$r(s,t,r.orgId,"the org it backs up");if(n)return n;let o=Up(r.objects);if(!o)return`${t} names no object: list the API names of the objects it backs up.`;let i=o.filter(a=>!Nm.safeParse(a).success);if(i.length>0)return`${t} names what is not an object API name: ${i.map(String).join(", ")}.`;if(!Hs.safeParse({orgId:r.orgId,objects:o}).success)return`${t} backs up more objects than one backup takes: at most 100.`}}function lC(s){return e=>{let t=`Compare step "${e.name}"`,r=e.config??{},n=$r(s,t,r.sourceOrgId,"the org it compares from")??$r(s,t,r.targetOrgId,"the org it compares with");if(n)return n;if(r.sourceOrgId===r.targetOrgId)return`${t} compares an org with itself: choose two different orgs.`;let o=Up(r.types);if(!o)return`${t} names no component type: choose what it compares.`;if(!Bs.safeParse({sourceOrgId:r.sourceOrgId,targetOrgId:r.targetOrgId,types:o}).success)return`${t} names component types the Compare page would not send: at most 50, each a type name.`}}function pC(s){return e=>{let t=`Pre-check step "${e.name}"`,r=e.config??{},n=$r(s,t,r.orgId,"the org it checks");if(n)return n;let o=Up(r.checks);if(!o)return`${t} names no check: choose what it checks (${Mp.join(", ")}).`;let i=o.filter(a=>typeof a!="string"||!Mp.includes(a));if(i.length>0)return`${t} names checks SandForge does not have: ${i.map(String).join(", ")}. It can check ${Mp.join(", ")}.`;if(!Jk.safeParse({orgId:r.orgId,checks:o}).success)return`${t} names the same check twice.`}}function fC(s){return e=>{let t=`Notification step "${e.name}"`;if(!s.notify)return`${t} cannot show a notification: there is no VS Code window to show it in.`;let r=(e.config??{}).message;if(typeof r!="string"||r.trim()==="")return`${t} has no message: write what the notification says.`;if(!Vk.safeParse({message:r}).success)return`${t} has a message longer than ${Gk} characters.`}}function gC(s){return async(e,t)=>{let r=new Date().toISOString(),{orgId:n,objects:o}=Hs.parse({orgId:e.config.orgId,objects:e.config.objects}),i=await s.backup({operationId:s.newId(),orgId:n,objects:o},t.signal),a=s.orgName(n)??n,d=i.objects.filter(u=>u.truncated).map(u=>u.objectApiName),c=`Backed up ${Ot(i.totalRecords,"record")} of ${Ot(i.objects.length,"object")} from ${a}`+(d.length>0?`; only part of ${d.join(", ")}: the org holds more rows than one backup reads.`:".");return xr(e,r,{operationId:i.operationId,orgId:n,objects:i.objects,totalRecords:i.totalRecords,partial:i.partial},c)}}function hC(s){return async(e,t)=>{let r=new Date().toISOString(),{sourceOrgId:n,targetOrgId:o,types:i}=Bs.parse({sourceOrgId:e.config.sourceOrgId,targetOrgId:e.config.targetOrgId,types:e.config.types}),a=await s.compare({sourceOrgId:n,targetOrgId:o,types:i},t.signal),{added:d,removed:c,modified:u,unchanged:l,notCompared:p}=a.summary,f=s.orgName(n)??n,g=s.orgName(o)??o;return xr(e,r,{sourceOrgId:n,targetOrgId:o,types:i,summary:a.summary,content:a.content,variables:{[lh]:String(d+c+u)}},`Compared ${Ot(i.length,"component type")} of ${f} with ${g}: ${c} only in ${f}, ${d} only in ${g}, ${u} modified, ${l} unchanged, ${p} not compared.`)}}function Hk(s){switch(s.status){case"critical":return`${s.message} (critical)`;case"unknown":return`${s.message} (could not be read)`;case"warning":return`${s.message} (warning)`;default:return s.message}}function mC(s){return async e=>{let t=new Date().toISOString(),{orgId:r,checks:n}=Jk.parse({orgId:e.config.orgId,checks:e.config.checks}),o=s.orgName(r)??r,i=await s.readOrgHealth(r,n.map(l=>zk[l])),a=n.map((l,p)=>({check:l,signal:i[p]})),d={};for(let{check:l,signal:p}of a){let f=p?Uk[l].read(p):void 0;f!==void 0&&p.status!=="unknown"&&(d[Uk[l].variable]=String(f))}let c={orgId:r,checks:a.map(({check:l,signal:p})=>({check:l,status:p?.status??"unknown",message:p?.message??"Not read"})),variables:d},u=a.filter(({signal:l})=>!l||l.status==="critical"||l.status==="unknown");return u.length>0?It(e,t,c,`Pre-check "${e.name}" failed on ${o}: ${u.map(({check:l,signal:p})=>p?Hk(p):`${l} was not read`).join("; ")}.`):xr(e,t,c,`${a.length===1?"The check":`${a.length} checks`} passed on ${o}: ${a.map(({signal:l})=>Hk(l)).join("; ")}.`)}}function yC(s){return async(e,t)=>{let r=new Date().toISOString(),{message:n}=Vk.parse({message:e.config.message});return s.notify?(s.notify(t.pipelineName?`${t.pipelineName}: ${n}`:n),xr(e,r,{message:n},s.ranFrom==="commandLine"?"Printed the message: a run from the command line has no VS Code window to show it in.":"Showed a notification in VS Code.")):It(e,r,{},`Notification step "${e.name}" cannot show a notification: there is no VS Code window to show it in.`)}}function Xk(s,e,t){let r=`Approval step "${e.name}"`;if(s.ranFrom!=="commandLine")return`${r} cannot ask anyone: there is no VS Code window to ask in.`;let n=`${r} cannot ask anyone: this run has no terminal to ask in.`;if(t===void 0)return`${n} Run it in a terminal.`;let o=wC(s,t);return o!==void 0?`${n} Run it in a terminal: it stands before a write to ${o}, a sandbox marked Staging, which only a person at a terminal approves, never --approve.`:`${n} Run it in a terminal, or answer it ahead with --approve "${e.name}".`}function wC(s,e){for(let t of e.steps.slice(e.index+1)){if(t.type==="approval")return;let r;if(t.type==="sync"){let n=li(s,t);r="problem"in n?void 0:n.config.targetOrgId}else(t.type==="seed"||t.type==="anonymize")&&(r=nn((t.config??{}).orgId));if(r!==void 0&&s.orgTier?.(r)==="staging")return s.orgName(r)??r}}function bC(s){return(e,t)=>{let r=`Approval step "${e.name}"`;if(!s.askApproval)return Xk(s,e,t);switch(mh(e.config)){case"timeout":return`${r} waits for a time it cannot keep: set a whole number of minutes from 1 to ${fh} (a day).`;case"message":return`${r} has a message that is not text, or is longer than ${gh} characters.`;default:return}}}function Bk(s){switch(s.via){case"page":return" on the Automation page";case"notification":return" in the VS Code notification";case"terminal":return" at the terminal";case"commandLine":return" ahead, on the command line (--approve)";default:return""}}function RC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Approval step "${e.name}"`;if(!s.askApproval)return It(e,r,{},Xk(s,e,void 0));let o=hh(e.config)??ph,i=e.config?.message,a=typeof i=="string"&&i.trim()!==""?i.trim():void 0,d=await s.askApproval({stepId:e.id,stepName:e.name,...t.pipelineName?{pipelineName:t.pipelineName}:{},...a?{message:a}:{},timeoutMs:o*6e4},t.signal),c={approval:d};switch(d.decision){case"approved":return{...xr(e,r,c,`Approved${Bk(d)} at ${d.at}.`),approval:d};case"rejected":return{...It(e,r,c,`${n} was rejected${Bk(d)} at ${d.at}.`),approval:d};case"timedOut":return{...It(e,r,c,`${n} was not approved in time: nobody answered within ${Ot(o,"minute")}.`),approval:d};case"cancelled":return{...It(e,r,c,`${n} was stopped before anyone answered.`),approval:d}}}}function li(s,e){let t=`Sync step "${e.name}"`,r=(e.config??{}).configId;if(typeof r!="string"||r.trim()==="")return{problem:`${t} names no saved Sync configuration: choose the one it runs.`};let n=s.savedSyncConfig?.(r);if(n==null)return{problem:`${t} names a Sync configuration that is no longer saved (${r}): choose another.`};let o=Sn.safeParse({config:n});if(!o.success){let d=o.error.issues[0];return{problem:`${t} names a Sync configuration that no longer validates (${d.path.slice(1).join(".")}: ${d.message}): open it on the Sync page and save it again.`}}let i=n,a=typeof i.name=="string"&&i.name!==""?i.name:r;return{config:i,name:a}}function Kk(s){return(s.listSyncConfigs?.()??[]).flatMap(t=>{if(typeof t!="object"||t===null)return[];let{id:r,name:n}=t;if(typeof r!="string"||r==="")return[];let o=typeof n=="string"&&n!==""?n:r;if(!Sn.safeParse({config:t}).success)return[{id:r,name:o,valid:!1}];let i=t;return[{id:r,name:o,valid:!0,sourceOrgId:i.sourceOrgId,targetOrgId:i.targetOrgId,...s.syncGuard?{guard:s.syncGuard(i).decision}:{}}]})}function Yk(s){return s===void 0||s.steps.slice(0,s.index).some(e=>e.type==="approval")}function vC(s){return(e,t)=>{let r=`Sync step "${e.name}"`;if(!s.runSync||!s.savedSyncConfig||!s.syncGuard)return`${r} cannot run here: Sync is not available in this window.`;let n=li(s,e);if("problem"in n)return n.problem;let{config:o}=n,i=$r(s,r,o.sourceOrgId,"the source org of its configuration")??$r(s,r,o.targetOrgId,"the target org of its configuration");if(i)return i;let a=s.syncGuard(o);if(a.decision==="refused")return`${r} writes where Production Guard refuses it, whatever anyone answers: ${a.reason}.`;if(a.decision==="asks"&&!Yk(t)){let d=s.orgName(o.targetOrgId)??o.targetOrgId;return`${r} writes to ${d}, which Production Guard asks about before a write, and nobody may be there to answer when the pipeline runs: put an Approval step before it.`}}}function Hp(s){let e=s.previousResults.filter(r=>r.stepType==="approval"),t=e[e.length-1];return{approved:t?.status==="completed"&&t.approval?.decision==="approved"}}function Bp(s,e){let t=[],r=s.filter(o=>o.delta?.read==="full"&&o.delta.reason==="first_run").map(o=>o.objectApiName);r.length>0&&t.push(`first run from this store for ${r.join(", ")}: no watermark yet, every record ${e?"was":"is"} read`);let n=s.filter(o=>o.delta?.read==="delta");return n.length>0&&t.push(`${n.map(o=>o.objectApiName).join(", ")} read from the last run's watermark`),t}var qk=3;function SC(s){let e=s.filter(r=>r.failed>0).flatMap(r=>ol(r.errors).map(n=>`${r.objectApiName}, ${n.count} \xD7 ${n.example}`));if(e.length===0)return"";let t=e.length-qk;return`; refused: ${e.slice(0,qk).join("; ")}`+(t>0?`; and ${Ot(t,"other reason")}`:"")}function kC(s){return async(e,t)=>{let r=new Date().toISOString(),n=li(s,e);if("problem"in n)throw new Error(n.problem);if(!s.runSync)throw new Error(`Sync step "${e.name}" cannot run here: Sync is not available in this window.`);let{config:o,name:i}=n,a=await s.runSync(o,Hp(t),t.signal);if(a.cancelled)throw new Rt(`Sync step "${e.name}" was cancelled: ${a.error??"the run stopped before it synced every object."}`);let d=s.orgName(o.targetOrgId)??o.targetOrgId,c=a.summary,u={configId:o.id,configName:i,operationId:a.operationId,status:a.status,totalProcessed:a.totalProcessed,totalSuccess:a.totalSuccess,totalFailed:a.totalFailed,totalSkipped:a.totalSkipped,objects:a.objectResults.map(f=>{let g=f.failed>0?ol(f.errors):[];return{objectApiName:f.objectApiName,operation:f.operation,processed:f.processed,success:f.success,failed:f.failed,skipped:f.skipped,...g.length>0?{refusals:g}:{},...f.delta?{delta:f.delta}:{}}}),...typeof c=="object"&&c!==null?{summary:c}:{}},l=Bp(a.objectResults,!0).map(f=>`; ${f}`).join(""),p=`${Ot(a.totalSuccess,"record")} written, ${a.totalFailed} failed and ${a.totalSkipped} skipped of ${a.totalProcessed} read${l}`;if(a.status!=="success"){let f=[a.error,gd(a)].filter(g=>g!==void 0&&g!=="");return It(e,r,u,`Sync step "${e.name}" ran "${i}" into ${d} and did not complete: ${p}`+SC(a.objectResults)+(f.length>0?`; ${f.join("; ")}`:"."))}return xr(e,r,u,`Synced "${i}" into ${d}: ${p}.`)}}function nn(s){return typeof s=="string"&&s.trim()!==""?s.trim():void 0}function qp(s){let e=s.issues[0];return e?e.path.length>0?`${e.path.join(".")}: ${e.message}`:e.message:"its configuration is not one"}function OC(s,e){return s!==void 0&&e!==void 0&&s.length>=15&&s.slice(0,15)===e.slice(0,15)}function Cd(s){return s.pipelineName??s.pipelineId}function Qk(s,e,t,r,n){let o=s.orgName(t)??t,i=ea(s.orgTier?.(t)??"production");if(i==="refused")return`${e} writes to ${o}, a production org or one SandForge cannot tell is not: a pipeline never ${r} one, whatever an Approval step answers. Choose a sandbox, a scratch org or a Developer Edition org.`;if(i==="needsApproval"&&!Yk(n))return`${e} writes to ${o}, a sandbox marked Staging, which a pipeline ${r} only once an Approval step before it has approved the run: put an Approval step before it.`}function Zk(s,e,t){return s.retries!==void 0&&s.retries>0?`${e} is given retries, and is never tried again: ${t}. Set its retries to 0.`:void 0}function Wp(s){if(s instanceof Rt)return;let e=s?.code;return typeof e=="string"?e:void 0}function IC(s){return(e,t)=>{let r=`Seed step "${e.name}"`;if(!s.seed||!s.savedSeedTemplate)return`${r} cannot run here: Seed is not available in this window.`;let n=e.config??{},o=$r(s,r,n.orgId,"the org it seeds");if(o)return o;let i=nn(n.templateId);if(i===void 0)return`${r} names no Seed template: choose the one it seeds with.`;let a=String(n.orgId),d=os(a,i,c=>s.savedSeedTemplate?.(c));return"refusal"in d?`${r}: ${d.refusal.message}`:Zk(e,r,"a second try would write a second set of records")??Qk(s,r,a,"seeds",t)}}function AC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Seed step "${e.name}"`;if(!s.seed)throw new Error(`${n} cannot run here: Seed is not available in this window.`);let{orgId:o,templateId:i}=Zi.parse({orgId:e.config.orgId,templateId:nn(e.config.templateId)}),a=s.orgName(o)??o,d;try{d=await s.seed({orgId:o,templateId:i,pipeline:{name:Cd(t)},answer:Hp(t)},t.signal)}catch(f){let g=Wp(f);if(g===void 0)throw f;return It(e,r,{orgId:o,templateId:i,code:g},`${n}: ${f.message}`)}let{result:c}=d,u={orgId:o,templateId:i,operationId:d.operationId,runId:d.runId,status:c.status,totalRecordsCreated:c.totalRecordsCreated,totalRecordsFailed:c.totalRecordsFailed,objects:c.objectResults.map(f=>({objectApiName:f.objectApiName,recordsCreated:f.recordsCreated,recordsFailed:f.recordsFailed})),...d.automation.length>0?{automation:d.automation}:{}},l=Ot(c.totalRecordsCreated,"record"),p="take them back from Seed's History";if(c.cancelled)throw new Rt(`${n} was cancelled: it had created ${l} in ${a}, which stay there; ${p}.`);return c.status!=="success"?It(e,r,u,`${n} seeded ${a} and did not complete: ${l} created, ${c.totalRecordsFailed} refused; ${p}.`):xr(e,r,u,`Seeded ${l} into ${a}: ${p}.`)}}function eO(s){let e=(s.listSeedTemplates?.()??[]).map(n=>({raw:n,builtIn:!1})),t=Ji.map(n=>({raw:n,builtIn:!0})),r=new Set;return[...e,...t].flatMap(({raw:n,builtIn:o})=>{if(typeof n!="object"||n===null)return[];let{id:i,name:a}=n;if(typeof i!="string"||i===""||r.has(i))return[];r.add(i);let d=typeof a=="string"&&a!==""?a:i,c=Do.safeParse(n);return[{id:i,name:d,builtIn:o,valid:c.success,usesAi:c.success&&jp(c.data).length>0}]})}function TC(s){let e=[];for(let t of s.rules){let r=t.fieldPattern.split(".")[0];r&&!e.includes(r)&&e.push(r)}return e}function tO(s){return(s.maskingTemplates?.()??[]).map(e=>({id:e.id,name:e.name,builtIn:e.builtIn,objects:TC(e)}))}function EC(s){return(e,t)=>{let r=`Anonymize step "${e.name}"`;if(!s.anonymize||!s.maskingTemplates)return`${r} cannot run here: DataOps is not available in this window.`;let n=e.config??{},o=$r(s,r,n.orgId,"the org it masks");if(o)return o;let i=nn(n.templateId);if(i===void 0)return`${r} names no masking template: choose the one it masks with.`;let a=String(n.orgId),d=s.maskingTemplates(),c=nn(n.object),u=nn(n.where),l=Yb({orgId:a,templateId:i,...c!==void 0?{object:c}:{},...u!==void 0?{where:u}:{},...e.retries!==void 0?{retries:e.retries}:{}},f=>d.some(g=>g.id===f));if("refusal"in l)return`${r}: ${l.refusal.message}`;let p=Cs.safeParse({orgId:a,templateId:i,...$d(n)});return p.success?p.data.verify&&!s.verifyMasking?`${r} cannot verify the masking here: DataOps's verification is not available in this window. Turn off its verification, or run the pipeline where it is.`:Qk(s,r,a,"masks",t):`${r} does not read (${qp(p.error)}).`}}function $d(s){return Object.fromEntries(["acceptAutomation","acceptEmails","muteAutomation","purgeHistory","verify"].flatMap(e=>s[e]===void 0?[]:[[e,s[e]]]))}var Wk=3;function PC(s){let e=[...new Set(s.errors.map(r=>`${r.objectApiName}: ${r.message}`))];if(e.length===0)return s.message?` (${s.message})`:"";let t=e.length-Wk;return`, refused by the org: ${e.slice(0,Wk).join("; ")}`+(t>0?`; and ${Ot(t,"other reason")}`:"")}function CC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Anonymize step "${e.name}"`;if(!s.anonymize)throw new Error(`${n} cannot run here: DataOps is not available in this window.`);let o=nn(e.config.object),i=nn(e.config.where),{orgId:a,templateId:d,acceptAutomation:c,acceptEmails:u,muteAutomation:l,purgeHistory:p,verify:f}=Cs.parse({orgId:e.config.orgId,templateId:nn(e.config.templateId),...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...$d(e.config)}),g=s.orgName(a)??a,h=H=>H?` ${Qt(H,g).map(J=>J.trim()).join("; ")}.`:"",m;try{m=await s.anonymize({orgId:a,templateId:d,...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...e.retries!==void 0?{retries:e.retries}:{},...p?{purgeHistory:!0}:{},accord:{acceptAutomation:c,acceptEmails:u,muteAutomation:l},pipeline:{name:Cd(t)},answer:Hp(t)},t.signal)}catch(H){let J=Wp(H);if(J===void 0)throw H;let W=H.snapshot,Z=Js(H);return It(e,r,{orgId:a,templateId:d,code:J,...W!==void 0?{snapshot:W}:{},...Z?{mutedAutomation:Z}:{}},`${n}: ${H.message}`+(typeof W?.operationId=="string"?` The snapshot ${W.operationId} it took keeps the values it wrote over, in clear, until it is deleted on the DataOps page.`:"")+h(Z))}let{result:y}=m,v=y.snapshot?`the snapshot ${y.snapshot.operationId} keeps the values it wrote over, in clear, until it is deleted on the DataOps page, where a restore writes them back`:"no snapshot was kept",b={orgId:a,templateId:d,...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},operationId:m.operationId,status:y.status,recordsProcessed:y.recordsProcessed,recordsFailed:y.recordsFailed,recordsNotMasked:y.recordsNotMasked,objects:y.objects,message:y.message,errors:y.errors,...y.snapshot?{snapshot:y.snapshot}:{},...y.mutedAutomation?{mutedAutomation:y.mutedAutomation}:{},...p?{purgeHistory:!0}:{},...f?{verify:!0}:{},...y.history?{history:y.history}:{}},k=h(y.mutedAutomation),S=y.history?nb(y.history.objects):"",C=S?` ${S}`:"";if(y.cancelled)throw new Rt(`${n} was cancelled: it masked ${Ot(y.recordsProcessed,"record")} in ${g} before the stop, and ${y.recordsNotMasked} still hold their values; ${v}.`+C+k);let R=f?await $C(s,a,y,t.signal):void 0;if(Object.assign(b,R?.output??{}),t.signal?.aborted)throw new Rt(`${n} was cancelled as it verified the masking: it masked ${Ot(y.recordsProcessed,"record")} in ${g}; ${v}.${C}`+k);let w=R?` ${R.words}`:"",P=y.objects.filter(H=>H.notMasked>0);if(y.recordsNotMasked>0){let H=`${P.map(J=>`${J.notMasked} of ${J.objectApiName}`).join(", ")} still hold their values${PC(y)}`;return It(e,r,b,`${n} masked ${g} and did not complete: ${H}; ${v}.${C}${w}${k}`)}let O=o!==void 0?i!==void 0?`the ${o} rows where ${i}`:`every ${o} row`:`every row of ${y.objects.map(H=>H.objectApiName).join(", ")}`,E=`Masked ${Ot(y.recordsProcessed,"record")} in ${g}, ${O}; ${v}.`,$=Zb(y.history);return $!==void 0||R?.fails===!0?It(e,r,b,`${n}: ${E}${C}`+($!==void 0?` Yet ${$}.`:"")+`${w}${k}`):xr(e,r,b,`${E}${C}${w}${k}`)}}async function $C(s,e,t,r){if(!t.snapshot)return t.recordsProcessed===0?{words:"Nothing to verify: the run masked no record.",fails:!1,output:{}}:{words:"Yet its verification has nothing to read the records against: the run kept no snapshot.",fails:!0,output:{}};if(!s.verifyMasking)return{words:"Yet its masking was not verified: DataOps's verification is not available here.",fails:!0,output:{}};try{let n=await s.verifyMasking({orgId:e,backupId:t.snapshot.operationId},r);return{words:eR(n),fails:n.verdict!=="clean",output:{verification:qS(n)}}}catch(n){let o=Wp(n),i=I(n);return{words:`Yet its verification was refused${o!==void 0?` (${o})`:""}: ${i}`,fails:!0,output:{verifyRefused:{...o!==void 0?{code:o}:{},message:i}}}}}function xC(s){return e=>{let t=`Checkpoint step "${e.name}"`;if(!s.takeCheckpoint)return`${t} cannot run here: Checkpoints are not available in this window.`;let r=e.config??{},n=$r(s,t,r.orgId,"the org it takes");if(n)return n;let o=String(r.orgId);if((s.orgTier?.(o)??"production")==="production")return`${t} names ${s.orgName(o)??o}, a production org or one SandForge cannot tell is not: SandForge takes no checkpoint of one.`;let i=wn.safeParse(r);if(!i.success)return`${t} does not read (${qp(i.error)}).`}}function DC(s){return s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:s<1024*1024*1024?`${(s/1024/1024).toFixed(1)} MB`:`${(s/1024/1024/1024).toFixed(2)} GB`}function NC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Checkpoint step "${e.name}"`;if(!s.takeCheckpoint)throw new Error(`${n} cannot run here: Checkpoints are not available in this window.`);let o=wn.parse(e.config),i=s.orgName(o.orgId)??o.orgId,a;try{a=await s.takeCheckpoint({config:o,origin:{pipeline:Cd(t),step:e.name,trigger:s.trigger??"manual"}},t.signal)}catch(u){if(!(u instanceof Cr))throw u;return It(e,r,{orgId:o.orgId,code:u.code},u.message)}let d=a.movedWhileTaken,c=d.changed+d.deleted+d.created;return xr(e,r,{orgId:o.orgId,operationId:a.operationId,checkpointId:a.checkpointId,name:a.name,records:a.records,objects:a.objects,bytes:a.bytes,movedWhileTaken:d},`Took the checkpoint '${a.name}' of ${i}: ${Ot(a.records,"record")} of ${Ot(a.objects,"object")}, ${DC(a.bytes)} on this machine, `+(o.keepDays===0?"kept until it is deleted":`kept ${Ot(o.keepDays,"day")}`)+(c>0?`; ${Ot(c,"record")} changed while it was taken.`:"."))}}var jC={damaged:"whose file cannot be read: it can only be deleted",taking:"whose take is under way or never ended",failed:"whose take failed: it can only be deleted",refreshed:"of the org a sandbox was before its refresh: the sandbox is another org now, which the checkpoint no longer rewinds; exported, it is still replayed in another org. Take a checkpoint of the sandbox again, and choose it",scratchExpired:"of a scratch org that has expired, which it no longer rewinds; exported, it is still replayed in another org"};function rO(s,e,t,r){let n=s.checkpointKept?.(r);if(n===void 0)return;if(!n.kept)return{why:"missing",problem:`${e} rewinds to the checkpoint ${r}, which is not kept on this machine: it was deleted or expired, or the pipeline came from another machine. Take a checkpoint here, choose it, and confirm the step again.`};let o=n.name!==void 0?`'${n.name}'`:r;if(!n.valid){let a=n.why??"damaged";return{why:a,problem:`${e} rewinds to the checkpoint ${o}, ${jC[a]}.`}}let i=s.organizationIdsOf?.(t)??[];if(n.organizationId!==void 0&&!i.some(a=>OC(a,n.organizationId)))return{why:"otherOrg",problem:`${e} rewinds ${s.orgName(t)??t} to the checkpoint ${o}, which was taken of another org.`}}function MC(s){return e=>{let t=`Rewind step "${e.name}"`;if(!s.rewind||!s.rewindGrant)return`${t} cannot run here: Checkpoints are not available in this window.`;let r=e.config??{},n=$r(s,t,r.orgId,"the org it rewinds");if(n)return n;let o=String(r.orgId);if((s.orgTier?.(o)??"production")==="production")return`${t} writes to ${s.orgName(o)??o}, a production org or one SandForge cannot tell is not: SandForge rewinds none.`;let i=xt.safeParse(r);if(!i.success)return`${t} does not read (${qp(i.error)}).`;let a=Zk(e,t,"a second try would read the org after the first one wrote, with nobody to read its preview");if(a)return a;let d=s.rewindGrant(s.pipelineId??"",e);return"refusal"in d?Mn(e.name,d.refusal):rO(s,t,o,i.data.checkpointId)?.problem}}function _p(s){return{deleted:s.deleted.reduce((e,t)=>e+t.deleted,0),gaveBack:s.restored.reduce((e,t)=>e+t.restored+(t.restoredWithout??0),0),broughtBack:s.undeleted.reduce((e,t)=>e+t.undeleted,0),madeAgain:(s.recreated??[]).reduce((e,t)=>e+t.created,0)}}function Lp(s){let e=_p(s);return`${e.deleted} deleted, ${e.gaveBack} given their values back, ${e.broughtBack} brought back from the recycle bin`+(e.madeAgain>0?`, ${e.madeAgain} made again with new Ids`:"")}function Fp(s){return s.undo?`Undo on the Checkpoints page takes it back until ${s.undo.until}`:"it wrote nothing Undo would take back"}function LC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Rewind step "${e.name}"`;if(!s.rewind||!s.rewindGrant)throw new Error(`${n} cannot run here: Checkpoints are not available in this window.`);let o=xt.parse(e.config),i=s.rewindGrant(t.pipelineId,e);if("refusal"in i)return It(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:"NOT_CONFIRMED"},Mn(e.name,i.refusal));let a=s.orgName(o.orgId)??o.orgId,d=g=>g?` ${Qt(g,a).map(h=>h.trim()).join("; ")}.`:"",c;try{c=await s.rewind({config:o,grant:i.grant,origin:{pipeline:Cd(t),step:e.name,trigger:s.trigger??"manual"}},t.signal)}catch(g){let h=(g instanceof Cr?g.result?.mutedAutomation:void 0)??Js(g);if(!(g instanceof Cr)){if(!h||g instanceof Rt)throw g;return It(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,mutedAutomation:h},`${I(g)}${d(h)}`)}return It(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:g.code,...g.alsoRefused.length>0?{alsoRefused:[...g.alsoRefused]}:{},...g.result?{status:g.result.status,..._p(g.result)}:{},...h?{mutedAutomation:h}:{}},`${g.message}${d(h)}`)}let{result:u}=c,l=u.residual.reduce((g,h)=>g+h.count,0),p={orgId:o.orgId,checkpointId:c.checkpointId,operationId:c.operationId,rewindId:u.rewindId,status:u.status,..._p(u),residual:l,...u.undo?{undoUntil:u.undo.until}:{},apiRequests:u.apiRequests.used,...u.mutedAutomation?{mutedAutomation:u.mutedAutomation}:{}},f=d(u.mutedAutomation);if(u.status==="cancelled")throw new Rt(`${n} was stopped part way in ${a}: ${Lp(u)}; ${Fp(u)}.${f}`);return u.status!=="success"?It(e,r,p,`${n} rewound ${a} and did not complete (${u.status}): ${Lp(u)}; ${Ot(l,"record")} still ${l===1?"differs":"differ"} from the checkpoint`+(u.unread&&u.unread.length>0?`, and ${u.unread.map(g=>g.objectApiName).join(", ")} could not be read`:"")+`; ${Fp(u)}.${f}`):xr(e,r,p,`Rewound ${a} to the checkpoint ${c.checkpointId}: ${Lp(u)}, with ${Ot(u.apiRequests.used,"API request")}; ${Fp(u)}.${f}`)}}function nO(s,e,t,r){let n=r?{granted:{at:r.grantedAt,digestMatches:r.matches}}:{},o=xt.safeParse(e.config??{});if(!o.success)return{stepId:e.id,valid:!1,why:"config",...n};let{orgId:i,checkpointId:a}=o.data,d=rO({...s,checkpointKept:()=>t},"The step",i,a);return{stepId:e.id,checkpointId:a,valid:d===void 0,...d?{why:d.why}:{},...n}}function oO(s,e){s.registerHandler("backup",gC(e),uC(e)),s.registerHandler("compare",hC(e),lC(e)),s.registerHandler("precheck",mC(e),pC(e)),s.registerHandler("notification",yC(e),fC(e)),s.registerHandler("approval",RC(e),bC(e)),s.registerHandler("sync",kC(e),vC(e)),s.registerHandler("seed",AC(e),IC(e)),s.registerHandler("anonymize",CC(e),EC(e)),s.registerHandler("checkpoint",NC(e),xC(e)),s.registerHandler("rewind",LC(e),MC(e))}function an(s,e,t,r){let n=new Date().toISOString();return{stepId:s.id,stepName:s.name,stepType:s.type,status:"completed",output:{...t,dryRun:!0},summary:r,startTime:e,endTime:n,duration:new Date(n).getTime()-new Date(e).getTime()}}function on(s,e,t,r){let n=new Date().toISOString();return{stepId:s.id,stepName:s.name,stepType:s.type,status:"failed",output:{...t,dryRun:!0},error:r,startTime:e,endTime:n,duration:new Date(n).getTime()-new Date(e).getTime()}}function sn(s,e){return`${s} ${e}${s===1?"":"s"}`}function pi(s){return typeof s=="string"&&s.trim()!==""?s.trim():void 0}function xd(s){return s.pipelineName??s.pipelineId}function zp(s){if(s instanceof Rt)return;let e=s?.code;return typeof e=="string"?e:void 0}function ss(s){return new Error(`${s} cannot be simulated here: nothing can read what it would do. Nothing was written.`)}function FC(s){return s<6e4?`${s/1e3} s`:s<36e5?`${Math.round(s/6e4)} min`:`${(s/36e5).toFixed(1)} h`}function aO(s){return`about ${sn(s.apiRequests,"API request")} of the ${s.apiRequestsLeft} the org has left today, about ${s.seconds} s`}function _C(s){let e=t=>s.reduce((r,n)=>r+t(n),0);return`${e(t=>t.insert)} to create, ${e(t=>t.update)} to update, ${e(t=>t.delete)} to delete, ${e(t=>t.skipped)} skipped and ${e(t=>t.refused)} refused of ${e(t=>t.read)} read`}function sO(s){let e=Bp(s.objects,!1);return s.cutAtReadCap&&s.cutAtReadCap.length>0&&e.push(`${s.cutAtReadCap.join(", ")} read only up to ${s.readCap??"the bound of"} records (sync.maxRecordsPerObject): the run copies part of each`),e.length>0?`; ${e.join("; ")}`:""}var iO=3;function UC(s){let e=s.flatMap(r=>(r.refusedFor??[]).map(({note:n})=>`${r.objectApiName}, ${n.replace(/\.$/,"")}`));if(e.length===0)return"";let t=e.length-iO;return`; refused: ${e.slice(0,iO).join("; ")}`+(t>0?`; and ${sn(t,"other reason")}`:"")}function HC(s){let e=new Date().toISOString(),t=Pb(s.config)??0;return Promise.resolve(an(s,e,{wouldWait:t},`Would wait ${FC(t)}: a simulation does not wait.`))}function BC(s){let e=new Date().toISOString();return Promise.resolve(an(s,e,{asked:!1},"Not asked in a simulation: the route goes on as if it were approved."))}function qC(s){return e=>{let t=new Date().toISOString(),r=pi(e.config.message)??"",n=s.ranFrom==="commandLine"?"Not printed in a simulation; the run would print":"Not shown in a simulation; the run would show in VS Code";return Promise.resolve(an(e,t,{message:r},`${n}: "${r}"`))}}function WC(s){return e=>{let t=new Date().toISOString(),{orgId:r,objects:n}=Hs.parse({orgId:e.config.orgId,objects:e.config.objects}),o=s.orgName(r)??r;return Promise.resolve(an(e,t,{orgId:r,objects:n},`Would take a snapshot of ${sn(n.length,"object")} of ${o} (${n.join(", ")}): a simulation takes none.`))}}function zC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Sync step "${e.name}"`,o=li(s,e);if("problem"in o)throw new Error(o.problem);if(!s.simulateSync)throw ss(n);let{config:i,name:a}=o,d=s.orgName(i.targetOrgId)??i.targetOrgId,c;try{c=await s.simulateSync(i,t.signal)}catch(f){let g=zp(f);if(g===void 0)throw f;return on(e,r,{configId:i.id,code:g},`${n} would be refused: ${f.message}`)}if(c.cancelled)throw new Rt(`${n} was stopped before its simulation read every object. Nothing was written.`);let u={configId:i.id,configName:a,operationId:c.operationId,objects:c.objects.map(f=>({objectApiName:f.objectApiName,operation:f.operation,read:f.read,insert:f.insert,update:f.update,delete:f.delete,skipped:f.skipped,refused:f.refused,...f.refusedFor?{refusedFor:f.refusedFor}:{},...f.delta?{delta:f.delta}:{}})),...c.readCap!==void 0?{readCap:c.readCap}:{},...c.cutAtReadCap?{cutAtReadCap:c.cutAtReadCap}:{}},l=_C(c.objects);return c.error?on(e,r,u,`${n} would stop on ${c.failedObject??"an object"}: ${c.error}`):c.objects.reduce((f,g)=>f+g.refused,0)>0?on(e,r,u,`${n} would run "${a}" into ${d} and not complete: ${l}${sO(c)}${UC(c.objects)}. Nothing was written.`):an(e,r,u,`Would sync "${a}" into ${d}: ${l}${sO(c)}. Nothing was written.`)}}function GC(s){let e=s.previousResults.filter(t=>t.stepType==="approval");return{approved:e[e.length-1]?.status==="completed"}}function JC(s,e){return OS(s,e)}function VC(s,e){let t=`about ${sn(s.estimate,"API request")}`;return s.verdict==="unread"?`${t}; what ${e} has left today could not be read (${s.unread})`:`${t} of the ${s.remaining} ${e} has left today`}function XC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Seed step "${e.name}"`,{orgId:o,templateId:i}=Zi.parse({orgId:e.config.orgId,templateId:pi(e.config.templateId)}),a=s.orgName(o)??o,d=os(o,i,l=>s.savedSeedTemplate?.(l));if("refusal"in d)return on(e,r,{orgId:o,templateId:i,code:d.refusal.code},`${n} would be refused: ${d.refusal.message}`);if(!s.previewSeed)throw ss(n);let{template:c}=d.asked,u;try{u=await s.previewSeed({orgId:o,templateId:i,pipeline:{name:xd(t)},answer:GC(t)},t.signal)}catch(l){let p=zp(l);if(p===void 0)throw l;return on(e,r,{orgId:o,templateId:i,code:p},`${n} would be refused: ${l.message}`)}return an(e,r,{orgId:o,templateId:i,records:u.records,objects:u.objects,storage:u.storage,apiRequests:u.apiRequests,...u.automation.length>0?{automation:u.automation}:{}},`Would seed "${c.name}" into ${a}: ${sn(u.records,"record")} of ${sn(u.objects,"object")}, as its template asks; ${JC(u.storage,a)}; ${VC(u.apiRequests,a)}. Nothing was written.`)}}function KC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Anonymize step "${e.name}"`;if(!s.previewMasking)throw ss(n);let o=pi(e.config.object),i=pi(e.config.where),{orgId:a,templateId:d,acceptAutomation:c,acceptEmails:u,muteAutomation:l,purgeHistory:p,verify:f}=Cs.parse({orgId:e.config.orgId,templateId:pi(e.config.templateId),...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...$d(e.config)}),g=s.orgName(a)??a;try{let h=await s.previewMasking({orgId:a,templateId:d,...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...e.retries!==void 0?{retries:e.retries}:{},...p?{purgeHistory:!0}:{},accord:{acceptAutomation:c,acceptEmails:u,muteAutomation:l},pipeline:{name:xd(t)},answer:{approved:!0}},t.signal),m=h.objects.filter(b=>b.records>0).map(b=>`${b.records} of ${b.objectApiName} (${b.fields.join(", ")})`),y=Qb(h.history,p,Qw),v=(y?` ${y}`:"")+(f?" Once it ended, the step would verify the masking against that snapshot: a value left fails it.":"");return an(e,r,{orgId:a,templateId:d,records:h.records,objects:h.objects,...h.history?{history:h.history}:{},...p?{purgeHistory:!0}:{},...f?{verify:!0}:{}},h.records===0?`Would mask nothing in ${g}: no row of ${h.objects.map(b=>b.objectApiName).join(", ")} holds anything to mask. Nothing was written.`:`Would mask ${sn(h.records,"record")} in ${g}: ${m.join("; ")}, after a snapshot of them.${v} Nothing was written.`)}catch(h){let m=zp(h);if(m===void 0)throw h;return on(e,r,{orgId:a,templateId:d,code:m},`${n} would be refused: ${h.message}`)}}}function YC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Checkpoint step "${e.name}"`;if(!s.estimateTake)throw ss(n);let o=wn.parse(e.config),i=s.orgName(o.orgId)??o.orgId;try{let a=await s.estimateTake({config:o,origin:{pipeline:xd(t),step:e.name,trigger:s.trigger??"manual"}},t.signal);return an(e,r,{orgId:o.orgId,objects:a.objects,records:a.records,leftOut:a.leftOut,estimate:a.estimate},`Would take a checkpoint of ${i}: ${sn(a.records,"record")} of ${sn(a.objects,"object")} now, ${aO(a.estimate)}. Nothing was taken.`)}catch(a){if(!(a instanceof Cr))throw a;return on(e,r,{orgId:o.orgId,code:a.code},`${n} would be refused: ${a.message}`)}}}function QC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Rewind step "${e.name}"`;if(!s.rewindGrant||!s.previewRewind)throw ss(n);let o=xt.parse(e.config),i=s.rewindGrant(t.pipelineId,e);if("refusal"in i)return on(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:"NOT_CONFIRMED"},Mn(e.name,i.refusal));let a=s.orgName(o.orgId)??o.orgId;try{let d=await s.previewRewind({config:o,grant:i.grant,origin:{pipeline:xd(t),step:e.name,trigger:s.trigger??"manual"}},t.signal);return an(e,r,{orgId:o.orgId,checkpointId:d.checkpointId,toDelete:d.toDelete,toGiveBack:d.toGiveBack,toBringBack:d.toBringBack,toRecreate:d.toRecreate,estimate:d.estimate},`Would rewind ${a} to the checkpoint ${d.checkpointId}: ${d.toDelete} to delete, ${d.toGiveBack} to give their values back, ${d.toBringBack} to bring back from the recycle bin`+(d.toRecreate>0?`, ${d.toRecreate} to make again with new Ids`:"")+`, ${aO(d.estimate)}. Nothing was written.`)}catch(d){if(!(d instanceof Cr))throw d;return on(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:d.code,...d.alsoRefused.length>0?{alsoRefused:[...d.alsoRefused]}:{}},`${n} would be refused: ${d.message}`)}}}function dO(s,e){s.wrapHandler("delay",()=>HC),s.wrapHandler("approval",()=>BC),s.wrapHandler("notification",()=>qC(e)),s.wrapHandler("backup",()=>WC(e)),s.wrapHandler("sync",()=>zC(e)),s.wrapHandler("seed",()=>XC(e)),s.wrapHandler("anonymize",()=>KC(e)),s.wrapHandler("checkpoint",()=>YC(e)),s.wrapHandler("rewind",()=>QC(e))}var is=new Map,cO=(s,e)=>`${s}::${e}`;async function er(s,e,t,r=Date.now){let n=cO(s,e),o=is.get(n);if(o&&r()-o.at<3e5)return o.value;let i=t();is.set(n,{at:r(),value:i});try{return await i}catch(a){throw is.get(n)?.value===i&&is.delete(n),a}}function uO(s){let e=cO(s,"");for(let t of is.keys())t.startsWith(e)&&is.delete(t)}var ZC=K({orgId:L(),detectedAt:L(),evidence:Be(["connection","monitor","production"]),previousOrganizationId:L().optional(),organizationId:L().optional(),previousInstanceName:L().optional(),instanceName:L().optional(),sandboxName:L().optional(),reportedBy:L().optional()}),e$=K({organizationId:L(),instanceName:L().optional(),formerOrganizationIds:Re(L()),refreshes:Re(ZC)}),lO="sandbox-refresh:",t$="sandbox-refresh",pO=10,r$=20,n$=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function Gp(s){return s!==void 0&&n$.test(s)?s.slice(0,15):void 0}function fO(s){try{return new URL(s).hostname.toLowerCase()}catch{return}}function o$(s){let e=fO(s.instanceUrl),t=".my.salesforce.com";return e?.endsWith(t)?e.slice(0,-t.length):void 0}function s$(s,e,t){let r=t.toLowerCase(),n=o$(s);return n&&fO(e.instanceUrl)?.startsWith(`${n}--${r}.`)?!0:e.username.toLowerCase()===`${s.username.toLowerCase()}.${r}`}var Dd=class{constructor(e){this.deps=e;this.now=e.now??(()=>new Date)}deps;listeners=new Set;now;onRefreshDetected(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}observe(e,t,r){let n=this.deps.orgManager.getOrg(e);if(n?.orgType!=="Sandbox")return;let o=Gp(t.organizationId);if(!o)return;let i=this.read(e),a=i??this.baselineOf(n);if(!a){this.write(e,{organizationId:o,instanceName:t.instanceName,formerOrganizationIds:[],refreshes:[]});return}if(o===a.organizationId){let p=t.instanceName!==void 0&&t.instanceName!==a.instanceName;(!i||p)&&this.write(e,{...a,instanceName:t.instanceName??a.instanceName});return}if(a.formerOrganizationIds.includes(o))return;let[d,...c]=a.refreshes,u=d?.evidence==="production"&&d.organizationId===void 0?d:void 0,l={...u??{orgId:e,detectedAt:this.now().toISOString(),evidence:r},previousOrganizationId:a.organizationId,organizationId:o,previousInstanceName:a.instanceName,instanceName:t.instanceName};return this.write(e,{organizationId:o,instanceName:t.instanceName,formerOrganizationIds:[a.organizationId,...a.formerOrganizationIds].slice(0,r$),refreshes:(u?[l,...c]:[l,...a.refreshes]).slice(0,pO)}),this.deps.log?.(`[sandbox-refresh] ${n.alias}: org ${a.organizationId} is now ${o} (${r})`),u||this.emit(l),l}noteCompletedRefresh(e){let t=this.deps.orgManager.getOrg(e.orgId);if(!t)return[];let r=[];for(let n of this.deps.orgManager.getAllOrgs()){if(n.orgType!=="Sandbox"||n.id===t.id||!s$(t,n,e.sandboxName))continue;let o=this.read(n.id)??this.baselineOf(n);if(!o)continue;let i=Date.parse(e.refreshDate);if(o.refreshes.some(c=>c.evidence!=="production"&&Date.parse(c.detectedAt)>=i))continue;let d={orgId:n.id,detectedAt:this.now().toISOString(),evidence:"production",sandboxName:e.sandboxName,reportedBy:t.id};this.write(n.id,{...o,refreshes:[d,...o.refreshes].slice(0,pO)}),this.deps.log?.(`[sandbox-refresh] ${n.alias}: ${t.alias} reports the refresh of "${e.sandboxName}"`),r.push(d),this.emit(d)}return r}refreshesOf(e){return this.read(e)?.refreshes??[]}organizationIdOf(e){return this.read(e)?.organizationId}wasRefreshedTo(e,t){let r=Gp(t);return r!==void 0&&this.refreshesOf(e).some(n=>n.organizationId===r)}baselineOf(e){let t=Gp(e.orgId);return t===void 0?void 0:{organizationId:t,formerOrganizationIds:[],refreshes:[]}}read(e){let t=this.deps.configStore.get(`${lO}${e}`);if(t===void 0)return;let r=e$.safeParse(t);if(!r.success){this.deps.log?.(`[sandbox-refresh] ignoring an unreadable record for ${e}`);return}return r.data}write(e,t){this.deps.configStore.set(`${lO}${e}`,t,t$)}emit(e){for(let t of this.listeners)try{t(e)}catch(r){this.deps.log?.(`[sandbox-refresh] a listener failed: ${String(r)}`)}}};import{readFile as i$,writeFile as a$}from"node:fs/promises";import{homedir as d$}from"node:os";import{basename as Jp}from"node:path";async function c$(){let[s,e,t,r,n,o,i,a,d,c,u]=await Promise.all([import("./chunk-GFGMGFSH.mjs"),import("./chunk-FRSIEASH.mjs"),import("./chunk-BNPQEQXC.mjs"),import("./chunk-ZEGSMW5A.mjs"),import("./chunk-TFDF3DBN.mjs"),import("./chunk-WJHMB3SL.mjs"),import("./chunk-VNNDYPBL.mjs"),import("./chunk-3EHPAFKV.mjs"),import("./chunk-K4TQ7YHX.mjs"),import("./chunk-YGTOX7IL.mjs"),import("./chunk-GYFIXUJG.mjs")]);return{recoveryFactsOf:s.recoveryFactsOf,recoveryAckKeyOf:s.recoveryAckKeyOf,readAcks:s.readAcks,frozenDatasetDirOf:s.frozenDatasetDirOf,recoveryStatusOf:e.recoveryStatusOf,awaitingAddressesOf:t.awaitingAddressesOf,recoveryUsersOf:t.recoveryUsersOf,recoveryTestersKey:t.recoveryTestersKey,readSavedTesters:t.readSavedTesters,saveTesters:t.saveTesters,replacedRunOf:t.replacedRunOf,choicesKeyOf:t.choicesKeyOf,planSignatureOf:t.planSignatureOf,changingUsersOf:t.changingUsersOf,usersDoneOf:t.usersDoneOf,usersAuditObjectsOf:t.usersAuditObjectsOf,ObservedUsersRunStore:t.ObservedUsersRunStore,journalDirOf:r.journalDirOf,newestHandoffOf:r.newestHandoffOf,recoveryHandoffNoteOf:r.recoveryHandoffNoteOf,recoveryHandoffPathOf:r.recoveryHandoffPathOf,writeRecoveryHandoff:r.writeRecoveryHandoff,guardUsersOrg:n.guardUsersOrg,usersToRestoreOf:n.usersToRestoreOf,planUsersGated:n.planUsersGated,gatedPlanAnswerOf:n.gatedPlanAnswerOf,applyUsers:o.applyUsers,UsersRunStore:i.UsersRunStore,defaultUsersStoreRoot:i.defaultUsersStoreRoot,readAudits:a.readAudits,myDomainHostOf:d.myDomainHostOf,openCheckpointStore:c.openCheckpointStore,defaultCheckpointStoreRoot:c.defaultCheckpointStoreRoot,ReplayStore:u.ReplayStore,defaultReplayStoreRoot:u.defaultReplayStoreRoot}}var u$=new Set(["recovery:status","recovery:users:list","recovery:users:plan","recovery:users:apply","recovery:users:cancel","recovery:users:config:save","recovery:users:config:export","recovery:users:config:import","recovery:audit","recovery:handoff","recovery:handoff:open","recovery:ack"]),tt=class extends Error{constructor(t,r,n=!1,o){super(r);this.code=t;this.retryable=n;this.step=o;this.name="Refused"}code;retryable;step},gO="SandForge writes and reads a users.json on the disk of the machine it runs on: pick a folder there.",l$={async pickUsersExport(s){let e=await import("vscode"),t=await e.window.showSaveDialog({title:e.l10n.t("Export the testers list as users.json"),saveLabel:e.l10n.t("Export"),defaultUri:e.Uri.joinPath(e.Uri.file(d$()),s),filters:{JSON:["json"]}});if(t!==void 0){if(t.scheme!=="file")throw new tt("INVALID_PAYLOAD",gO);return t.fsPath}},async pickUsersImport(){let s=await import("vscode"),t=(await s.window.showOpenDialog({title:s.l10n.t("Import the testers list from a users.json"),openLabel:s.l10n.t("Import"),canSelectFiles:!0,canSelectFolders:!1,canSelectMany:!1,filters:{JSON:["json"]}}))?.[0];if(t!==void 0){if(t.scheme!=="file")throw new tt("INVALID_PAYLOAD",gO);return t.fsPath}}},p$=async s=>{let e=await import("vscode");await e.window.showTextDocument(e.Uri.file(s),{preview:!1})};function f$(s,e,t){return{org:s,users:[],emailsToPeople:0,apiRequests:t,refusals:[e]}}function g$(s){let e=0,t=0,r=0;for(let n of s.users){n.changes.some(o=>!("name"in o))&&(e+=1);for(let o of n.changes)"name"in o&&(o.to==="added"?t+=1:r+=1)}return{updated:e,added:t,removed:r}}function Vp(s,e){return s.length>=15&&s.slice(0,15)===e.slice(0,15)}var h$=4e3,Nd=class{constructor(e,t={}){this.deps=e;this.options=t;this.dialogs=t.dialogs??l$,this.openInEditor=t.openInEditor??p$,this.now=t.now??(()=>new Date),t.checkpointStore&&(this.checkpoints=Promise.resolve(t.checkpointStore)),t.usersStore&&(this.usersStore=t.usersStore),t.replayStore&&(this.replayStore=t.replayStore)}deps;options;loaded;checkpoints;usersStore;replayStore;dialogs;openInEditor;now;running=new Map;simulated=new Map;listed=new Map;audited=new Map;statusListeners=new Set;setCheckpointStore(e){this.checkpoints=Promise.resolve(e)}onStatusChanged(e){return this.statusListeners.add(e),()=>this.statusListeners.delete(e)}async progressCountOf(e){let t=await this.modules(),r=await t.recoveryFactsOf(this.factsDeps(t),e);if(!("facts"in r))return;let n=t.recoveryStatusOf(r.facts);return{done:n.done,total:n.total}}async handle(e){if(!u$.has(e.type))return!1;switch(e.type){case"recovery:status":return await this.handleStatus(e),!0;case"recovery:users:list":return await this.handleUsersList(e),!0;case"recovery:users:plan":return await this.handleUsersPlan(e),!0;case"recovery:users:apply":return await this.handleUsersApply(e),!0;case"recovery:users:cancel":return this.handleUsersCancel(e),!0;case"recovery:users:config:save":return await this.handleConfigSave(e),!0;case"recovery:users:config:export":return await this.handleConfigExport(e),!0;case"recovery:users:config:import":return await this.handleConfigImport(e),!0;case"recovery:audit":return await this.handleAudit(e),!0;case"recovery:handoff":return await this.handleHandoff(e),!0;case"recovery:handoff:open":return await this.handleHandoffOpen(e),!0;case"recovery:ack":return await this.handleAck(e),!0;default:return!1}}async handleStatus(e){let t=x(Zn,e,"recovery:error",this.deps);if(t)try{let r=await this.statusOf(t.orgId);this.respond(e,"recovery:status:response",{status:r})}catch(r){this.fail(e,r)}}async handleAck(e){let t=x(Bg,e,"recovery:error",this.deps);if(t)try{let r=this.registered(t.orgId),n=await this.modules(),o=this.deps.sandboxRefreshes,i=r.orgType==="Sandbox"?o?.refreshesOf(t.orgId)[0]:void 0,a=n.recoveryAckKeyOf(t.orgId,i,u=>o?.organizationIdOf(u)),d=n.readAcks(this.deps.configStore,a);t.what==="finish"?d.finishedAt=this.now().toISOString():t.what==="resume"?delete d.finishedAt:t.mark==="cleared"?delete d.steps[t.step]:d.steps[t.step]=t.mark,this.deps.configStore.set(a,Ug.parse(d),"recovery");let c=await this.statusOf(t.orgId);this.respond(e,"recovery:ack:response",{status:c}),this.changed(t.orgId)}catch(r){this.fail(e,r)}}async handleUsersList(e){let t=x(Zn,e,"recovery:error",this.deps);if(t)try{let r=await this.modules(),n=await this.reach(r,t.orgId,"users"),o=await r.usersToRestoreOf(n.org),i=await this.users(r).list(n.organization.organizationId),a=r.recoveryUsersOf(o.users,r.awaitingAddressesOf(i));this.listed.set(t.orgId,{organizationId:n.organization.organizationId,total:o.total});let d=r.readSavedTesters(this.deps.configStore,r.recoveryTestersKey(r.myDomainHostOf(n.registered.instanceUrl),t.orgId));this.respond(e,"recovery:users:list:response",{orgId:t.orgId,users:a,total:o.total,...d!==void 0?{saved:d}:{}}),this.changed(t.orgId)}catch(r){this.fail(e,r,"users")}}async handleUsersPlan(e){let t=x(Zu,e,"recovery:error",this.deps);if(t)try{let r=await this.modules(),n=await this.reach(r,t.orgId,"users"),{answer:o}=await this.planOf(r,n,t);this.simulated.set(t.orgId,{choices:r.choicesKeyOf(t),signature:r.planSignatureOf(o)}),this.respond(e,"recovery:users:plan:response",{orgId:t.orgId,plan:o})}catch(r){this.fail(e,r,"users")}}async handleUsersApply(e){let t=x(Zu,e,"recovery:error",this.deps);if(!t)return;let{orgId:r}=t;if(this.running.has(r)){this.fail(e,new tt("FAILED","A run of the users of this org is under way from this window: wait for it to end. Nothing was read or written.",!0,"users"));return}let n=new AbortController;this.running.set(r,n);try{let o=await this.modules(),i=this.simulated.get(r);if(i===void 0||i.choices!==o.choicesKeyOf(t))throw new tt("ORG_CHANGED","No simulation of these choices was answered on this page: simulate them, then apply. Nothing was read or written.",!1,"users");let a=await this.reach(o,r,"users"),{answer:d,gated:c}=await this.planOf(o,a,t);if(o.planSignatureOf(d)!==i.signature)throw new tt("ORG_CHANGED",`${a.orgName} changed since the simulation: a run now would not do what it showed. Simulate again. Nothing was written.`,!1,"users");let u=d.refusals??[];if(c===void 0||u.length>0)throw new tt("FAILED",`${u.map(y=>y.message).join(" ")} Nothing was written.`.trim(),!1,"users");let l=await this.consultGuard(e,a,d);if(n.signal.aborted)throw this.recordUsersRun(e,r,"stopped",l),new tt("CANCELLED","Stopped before the first write: nothing was written.");let p=o.changingUsersOf(d),f=y=>{this.deps.broker.postToWebview(A(this.deps,e,"recovery:users:progress",{orgId:r,done:y,total:p}))};f(0);let g=new o.ObservedUsersRunStore({root:this.users(o).root},y=>f(o.usersDoneOf(y,d))),h;try{h=await o.applyUsers({org:a.org,organization:a.organization,users:Qu(t.config),store:g,signal:n.signal,...c.options})}catch(y){throw this.recordUsersRun(e,r,"failure",l),y}if(h.kind==="refused")throw this.recordUsersRun(e,r,"stopped",l),new tt("ORG_CHANGED",`${a.orgName} changed since the plan read it: ${(h.plan.refusals??[]).map(y=>y.message).join(" ")} Nothing was written.`,!1,"users");let m={...h.answer,apiRequests:a.typingRequests+a.org.requests()+c.outsideRequests};this.recordUsersRun(e,r,m.status,l,m,o),this.respond(e,"recovery:users:apply:response",{orgId:r,applied:m})}catch(o){this.fail(e,o,"users")}finally{this.running.delete(r),this.simulated.delete(r),this.changed(r)}}handleUsersCancel(e){let t=x(Zn,e,"recovery:error",this.deps);t&&this.running.get(t.orgId)?.abort()}async planOf(e,t,r){let{org:n,organization:o}=t,i=u=>t.typingRequests+n.requests()+u,a;if(r.replaces!==void 0){let u=await e.replacedRunOf(this.users(e),o.organizationId,r.replaces);if("refusal"in u)return{answer:f$(o,u.refusal,i(0))};a=u.record}let d=await e.planUsersGated({conn:t.conn,org:n,orgName:t.orgName,users:Qu(r.config),...a!==void 0?{previous:a}:{},acceptUserEmails:r.acceptUserEmails,acceptEmails:r.acceptEmails,acceptAutomation:r.acceptAutomation,voice:"page",now:this.now()});return{answer:e.gatedPlanAnswerOf(d,o,i(d.outsideRequests)),gated:d}}async consultGuard(e,t,r){let n=this.deps.infraServices?.productionGuard;if(!n)throw new tt("FAILED",ve.message,!1,"users");let o=Pe(t.registered),{updated:i,added:a,removed:d}=g$(r),c=[{operation:"delete",objectName:"PermissionSetAssignment, GroupMember",recordCount:d},{operation:"update",objectName:"User, UserLogin",recordCount:i},{operation:"insert",objectName:"PermissionSetAssignment, GroupMember",recordCount:a}].filter(l=>l.recordCount>0),u="allowed";for(let l of c){let p=await et(n,{orgId:t.registered.id,orgTier:o,module:"recovery",...l});if(u=oo(u,p.decision),p.decision==="refused")throw this.recordUsersRun(e,t.registered.id,"stopped",u),new tt("FAILED",`Operation blocked by Production Guard: ${p.check.blockedReason??p.check.impactSummary} Nothing was written.`,!1,"users");if(p.decision==="declined")throw this.recordUsersRun(e,t.registered.id,"stopped",u),new tt("CANCELLED",`Production Guard asked before this run (${p.check.impactSummary}), and the answer was no. Nothing was written.`,!1,"users")}return u}recordUsersRun(e,t,r,n,o,i){Y(this.deps,{action:"users_apply",module:"recovery",operationId:e.id,orgId:t,outcome:r,guard:n,...o!==void 0&&i!==void 0?{objects:i.usersAuditObjectsOf(o)}:{},details:o!==void 0?{run:o.run,emailsToPeople:o.emailsToPeople}:{}})}async handleConfigSave(e){let t=x(el,e,"recovery:error",this.deps);if(t)try{let r=this.registered(t.orgId),n=await this.modules(),o=n.saveTesters(this.deps.configStore,n.recoveryTestersKey(n.myDomainHostOf(r.instanceUrl),t.orgId),t.config,this.now());this.respond(e,"recovery:users:config:save:response",{orgId:t.orgId,savedAt:o.savedAt}),this.changed(t.orgId)}catch(r){this.fail(e,r,"users")}}async handleConfigExport(e){let t=x(el,e,"recovery:error",this.deps);if(!t)return;let r;try{if(this.registered(t.orgId),r=await this.dialogs.pickUsersExport("users.json"),r===void 0){this.respond(e,"recovery:users:config:export:response",{status:"cancelled",orgId:t.orgId});return}await a$(r,`${JSON.stringify(t.config,null,2)}
15
+ `,{encoding:"utf8",mode:384}),this.respond(e,"recovery:users:config:export:response",{status:"saved",orgId:t.orgId,fileName:Jp(r)})}catch(n){this.fail(e,this.pathless(n,r),"users")}}async handleConfigImport(e){let t=x(Zn,e,"recovery:error",this.deps);if(!t)return;let r;try{let n=this.registered(t.orgId);if(r=await this.dialogs.pickUsersImport(),r===void 0){this.respond(e,"recovery:users:config:import:response",{status:"cancelled",orgId:t.orgId});return}let o=Jp(r),i;try{i=JSON.parse(await i$(r,"utf8"))}catch(c){throw new tt("INVALID_PAYLOAD",`${o} does not read as JSON (${I(c)}). Nothing was kept.`,!1,"users")}let a=_g.safeParse(i);if(!a.success){let c=a.error.issues.map(u=>{let l=u.path.map(String).join(".");return l===""?u.message:`${l}: ${u.message}`});throw new tt("INVALID_PAYLOAD",`${o} is not a users.json of sandforge users --config: ${c.join("; ")}. Nothing was kept.`,!1,"users")}let d=await this.modules();d.saveTesters(this.deps.configStore,d.recoveryTestersKey(d.myDomainHostOf(n.instanceUrl),t.orgId),a.data,this.now()),this.respond(e,"recovery:users:config:import:response",{status:"read",orgId:t.orgId,fileName:o,config:a.data}),this.changed(t.orgId)}catch(n){this.fail(e,this.pathless(n,r),"users")}}async handleAudit(e){let t=x(Hg,e,"recovery:error",this.deps);if(t)try{let r=await this.modules(),n=await this.reach(r,t.orgId),{conn:o,organization:i}=n,a=r.myDomainHostOf(o.instanceUrl)??r.myDomainHostOf(n.registered.instanceUrl),d=await r.readAudits({transport:{request:l=>o.request(l)},journalDir:this.journalDir(r),now:this.now},{org:{organizationId:i.organizationId,kind:i.kind,alias:n.orgName,...a!==void 0?{host:a}:{}},asked:t.asked,save:t.save});for(let l of d.notes)this.deps.log(`[INFO] recovery:audit: ${l}`);let c=this.audited.get(t.orgId),u=c!==void 0&&Vp(c.organizationId,i.organizationId)?c.audit:{};this.audited.set(t.orgId,{organizationId:i.organizationId,audit:{...u,...d.result.deliverability!==void 0?{deliverability:d.result.deliverability}:{},...d.result.schedules!==void 0?{schedules:d.result.schedules}:{},...d.result.endpoints!==void 0?{endpoints:d.result.endpoints}:{}}}),this.respond(e,"recovery:audit:response",{orgId:t.orgId,audit:d.result}),this.changed(t.orgId)}catch(r){this.fail(e,r)}}async handleHandoff(e){let t=x(Zn,e,"recovery:error",this.deps);if(t)try{let r=this.registered(t.orgId),n=await this.modules(),o=await this.statusOf(t.orgId),i=o.organizationId;if(i===void 0)throw new tt("NOT_CONNECTED",`The org ${o.alias} is now is not known yet: only its production's history reported its refresh. Connect to it once, then write the note. Nothing was written.`,!0,"handoff");let a=this.now().toISOString(),d=this.audited.get(t.orgId),c=n.recoveryHandoffNoteOf({status:o,org:{organizationId:i,kind:r.orgType==="Sandbox"?"sandbox":r.orgType==="Scratch"?"scratch":"developer",alias:o.alias,...o.myDomainHost!==void 0?{host:o.myDomainHost}:{}},...d!==void 0&&Vp(d.organizationId,i)?{audits:d.audit}:{},at:a,...this.options.sandforgeVersion!==void 0?{sandforgeVersion:this.options.sandforgeVersion}:{}}),u=n.recoveryHandoffPathOf(this.journalDir(n),{organizationId:i,at:a});await n.writeRecoveryHandoff(u,c);try{await this.openInEditor(u)}catch(l){this.deps.log(`[WARN] recovery:handoff: the note was not opened: ${I(l)}`)}this.respond(e,"recovery:handoff:response",{orgId:t.orgId,path:u}),this.changed(t.orgId)}catch(r){this.fail(e,r,"handoff")}}async handleHandoffOpen(e){let t=x(Zn,e,"recovery:error",this.deps);if(t)try{let r=await this.modules(),n=await this.statusOf(t.orgId),o=n.organizationId!==void 0?await r.newestHandoffOf(this.journalDir(r),n.organizationId):void 0;if(o===void 0)throw new tt("NOTE_NOT_FOUND",`No handoff note of ${n.alias} as it is now is kept on this machine: write one. Nothing was written.`,!1,"handoff");try{await this.openInEditor(o.path)}catch(i){throw new tt("FAILED",`The handoff note could not be opened in the editor: ${I(i)}`,!0,"handoff")}this.respond(e,"recovery:handoff:open:response",{orgId:t.orgId,path:o.path})}catch(r){this.fail(e,r,"handoff")}}modules(){return this.loaded??=c$(),this.loaded}async openedCheckpoints(e){this.checkpoints??=Promise.resolve().then(()=>{let t=e.openCheckpointStore({root:e.defaultCheckpointStoreRoot()});if("store"in t)return t.store;throw new tt("FAILED",`The checkpoints cannot be read in ${t.refusal.path}: ${t.refusal.reason}.`)});try{return await this.checkpoints}catch(t){throw this.checkpoints=void 0,t}}users(e){return this.usersStore??=new e.UsersRunStore({root:e.defaultUsersStoreRoot()}),this.usersStore}replays(e){return this.replayStore??=new e.ReplayStore({root:e.defaultReplayStoreRoot()}),this.replayStore}journalDir(e){return this.options.journalDir??e.journalDirOf()}factsDeps(e){let t=this.deps.sandboxRefreshes;return{configStore:this.deps.configStore,orgOf:r=>this.deps.orgManager.getOrg(r),refreshesOf:r=>t?.refreshesOf(r)??[],organizationIdOf:r=>t?.organizationIdOf(r),checkpoints:()=>this.openedCheckpoints(e),replays:()=>this.replays(e),users:()=>this.users(e),journalDir:this.journalDir(e),frozenDatasetDir:()=>e.frozenDatasetDirOf(this.deps.configStore),usersListed:(r,n)=>{let o=this.listed.get(r);return o!==void 0&&Vp(o.organizationId,n)?o.total:void 0}}}async statusOf(e){let t=await this.modules(),r=await t.recoveryFactsOf(this.factsDeps(t),e);if("refused"in r)throw this.registered(e),new tt(r.refused,`${e} is not an org SandForge brings back into service.`);return t.recoveryStatusOf(r.facts)}registered(e,t){let r=this.deps.orgManager.getOrg(e);if(r===void 0)throw new tt("ORG_NOT_FOUND",`No org is registered in SandForge as ${e}: connect it on the Organizations page.`,!1,t);if(!Io(r))throw new tt("NOT_A_DEVELOPMENT_ORG",`${we(r,r.username)} is registered as a production org: SandForge brings back into service a sandbox, a scratch org or a Developer Edition org, and reads nothing of a production org's. Nothing was read or written.`,!1,t);return r}async reach(e,t,r){let n=this.registered(t,r),o=we(n,n.username),i;try{i=await B(t,this.deps.orgRegistry,this.deps.orgManager)}catch(d){throw new tt("NOT_CONNECTED",`${o} could not be reached (${I(d)}): reconnect it on the Organizations page. Nothing was read or written.`,!0,r)}let a=await e.guardUsersOrg(i,{orgName:o,registered:n});if(!a.allowed){let{refusal:d}=a;throw new tt(d.code==="PRODUCTION"?"NOT_A_DEVELOPMENT_ORG":"NOT_CONNECTED",d.message,d.code==="ORG_UNTYPED",r)}return{registered:n,orgName:o,conn:i,org:a.org,organization:a.organization,typingRequests:a.typingRequests}}changed(e){for(let t of[...this.statusListeners])try{t(e)}catch(r){this.deps.log(`[WARN] recovery: a listener of the steps failed: ${I(r)}`)}}respond(e,t,r){let n=A(this.deps,e,t,r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}pathless(e,t){return e instanceof tt||t===void 0?e:new Error(I(e).replaceAll(t,Jp(t)))}fail(e,t,r){let n=t instanceof tt?t:new tt("FAILED",I(t),!0,r),o=n.message.trim()===""?n.code:n.message,i=n.step??r;T(this.deps,e.type,"recovery:error",e,new Error(o.slice(0,h$)),{code:n.code,retryable:n.retryable,...i!==void 0?{extraPayload:{step:i}}:{}})}};var m$=5,y$=5e3,w$=3e4,b$=K({device_code:L().min(1).max(4096),user_code:L().regex(/^[A-Za-z0-9-]{4,32}$/),verification_uri:L().min(1).max(2048),interval:Te().int().positive().max(300).optional(),expires_in:Te().int().positive().optional()}),R$=K({access_token:L().min(1),refresh_token:L().min(1).optional(),instance_url:L().min(1).max(2048)}),hO=K({error:L().min(1),error_description:L().optional()}),uo=class extends Error{constructor(){super("Sign-in cancelled."),this.name="DeviceLoginCancelledError"}},jd=class extends Error{constructor(e){super(e),this.name="RefusedByHostError"}};function v$(s,e){return new Promise((t,r)=>{if(e?.aborted){r(new uo);return}let n=()=>{clearTimeout(o),r(new uo)},o=setTimeout(()=>{e?.removeEventListener("abort",n),t()},s);e?.addEventListener("abort",n,{once:!0})})}function yO(s){let e=es(s);if(!(!e.ok||e.url.username!==""||e.url.password!=="")&&!(e.url.port!==""||!Sh(e.url.hostname)))return e.url}function mO(s){return`Salesforce refused the device sign-in: ${s.error_description?`${s.error_description} (${s.error})`:s.error}`}var Md=class{fetchFn;now;sleep;constructor(e={}){this.fetchFn=e.fetch??((t,r)=>fetch(t,r)),this.now=e.now??Date.now,this.sleep=e.sleep??v$}async authorize(e,t,r){let n=await this.post(e,{response_type:"device_code",client_id:t},r),o=hO.safeParse(n);if(o.success)throw new Error(mO(o.data));let i=b$.safeParse(n);if(!i.success)throw new Error("Salesforce answered the device sign-in without a usable code.");let a=yO(i.data.verification_uri);if(!a)throw new Error("Salesforce sent a verification page that is not on a Salesforce host.");let d=Math.min((i.data.expires_in??Number.POSITIVE_INFINITY)*1e3,Ig);return{deviceCode:i.data.device_code,userCode:i.data.user_code,verificationUri:a.href,intervalMs:(i.data.interval??m$)*1e3,expiresAt:this.now()+d}}async awaitApproval(e,t,r,n){let o=r.intervalMs;for(;;){let i=r.expiresAt-this.now();if(i<=0||(await this.sleep(Math.min(o,i),n),this.now()>=r.expiresAt))break;let a;try{a=await this.post(e,{grant_type:"device",client_id:t,code:r.deviceCode},n)}catch(c){if(n?.aborted)throw new uo;if(c instanceof jd)throw c;continue}let d=hO.safeParse(a);if(d.success){if(d.data.error==="authorization_pending")continue;if(d.data.error==="slow_down"){o+=y$;continue}throw new Error(mO(d.data))}return S$(a)}throw new Error("The code expired before it was approved. Start the sign-in again for a new one.")}async post(e,t,r){if(r?.aborted)throw new uo;let n=AbortSignal.timeout(w$),o;try{o=await this.fetchFn(`${e}/services/oauth2/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams(t).toString(),signal:r?AbortSignal.any([r,n]):n})}catch(a){throw r?.aborted?new uo:a}let i=await o.text();try{return JSON.parse(i)}catch{throw new jd(`Salesforce answered HTTP ${o.status} with a page instead of JSON. Check the login URL.`)}}};function S$(s){let e=R$.safeParse(s);if(!e.success)throw new Error("Salesforce approved the sign-in without an access token and an instance URL.");if(!e.data.refresh_token)throw new Error('Salesforce signed you in without a refresh token, so the Salesforce CLI could not keep the session. Give the external client app the "Perform requests at any time (refresh_token, offline_access)" scope, then sign in again.');let t=yO(e.data.instance_url);if(!t||t.pathname!=="/"||t.search!==""||t.hash!=="")throw new Error("Salesforce approved the sign-in for an instance that is not a Salesforce host.");return{refreshToken:e.data.refresh_token,instanceUrl:t.origin}}import{readFile as k$,readdir as O$}from"node:fs/promises";import{join as wO}from"node:path";var I$=/^[^.][^@/\\]*@[^/\\]+\.json$/;async function bO(s,e=Date.now()){let t=wO(s,".sfdx"),r;try{r=await O$(t)}catch{return 0}let n=new Set;return await Promise.all(r.filter(o=>I$.test(o)&&!o.endsWith(".partial.json")).map(async o=>{let i=await A$(wO(t,o),e);i&&n.add(i)})),n.size}async function A$(s,e){try{let t=JSON.parse(await k$(s,"utf8"));if(typeof t!="object"||t===null)return;let{orgId:r,username:n,expirationDate:o}=t;if(typeof r!="string"||r===""||typeof n!="string")return;if(typeof o=="string"){let i=Date.parse(o);if(Number.isFinite(i)&&i+1440*60*1e3<=e)return}return r}catch{return}}import{homedir as T$}from"node:os";var E$=new Set(["org:list","org:connect","org:connect:cancel","org:disconnect","org:select","org:update","org:open-in-browser","org:cli-status","org:assign-right"]),RO=15e3,vO="The Salesforce CLI holds no connected org yet. Use Log in with your browser on the Organizations page: it opens the Salesforce login page.",Ld=class{constructor(e,t={}){this.deps=e;this.browser=t.browser??new jn,this.deviceLogin=t.deviceLogin??new Md,this.countCliOrgs=t.countCliOrgs??(()=>bO(T$())),this.connectTo=t.connectTo??(r=>xh(r))}deps;browser;deviceLogin;countCliOrgs;connectTo;pendingSignIns=new Map;async handle(e){if(!E$.has(e.type))return!1;switch(e.type){case"org:list":return this.handleOrgList(e),!0;case"org:connect":return await this.handleOrgConnect(e),!0;case"org:connect:cancel":return this.handleConnectCancel(e),!0;case"org:disconnect":return await this.handleOrgDisconnect(e),!0;case"org:select":return this.handleOrgSelect(e),!0;case"org:update":return this.handleOrgUpdate(e),!0;case"org:open-in-browser":return await this.handleOpenInBrowser(e),!0;case"org:cli-status":return await this.handleCliStatus(e),!0;case"org:assign-right":return await this.handleAssignRight(e),!0;default:return!1}}async handleCliStatus(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let[t,r]=await Promise.all([this.deps.sfdxBridge.isCliAvailable().catch(()=>!1),this.countCliOrgs().catch(()=>0)]),n=A(this.deps,e,"org:cli-status:response",{available:t,orgCount:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}async handleAssignRight(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Nw,e,"org:error",this.deps);if(!t)return;let r=!1;try{let o=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager);r=await Jb({query:async i=>o.query(i)})}catch(o){this.deps.log(`[WARN] org:assign-right: not read: ${I(o)}`)}let n=A(this.deps,e,"org:assign-right:response",{orgId:t.orgId,...r?{cannotAssign:!0}:{}});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleOrgList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.deps.orgManager.getAllOrgs(),r=A(this.deps,e,"org:list:response",{orgs:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id}`)}async handleOrgConnect(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Tw,e,"org:error",this.deps);if(!t)return;let r=t;switch(r.authMethod){case"sfdx_import":await this.handleSfdxImport(e);break;case"usernamePassword":await this.handleUsernamePassword(e,r);break;case"oauth_web":await this.handleOAuthWeb(e,r);break;case"jwt":await this.handleJwt(e);break;case"oauth_device":await this.handleOAuthDevice(e);break;default:Ae(this.deps,"warning","Auth Method",`${r.authMethod} is not yet supported.`),this.failConnect(e,`${r.authMethod} is not yet supported.`,"UNSUPPORTED_AUTH");break}this.syncOrgState()}failConnect(e,t,r){T(this.deps,"org:connect","org:error",e,new Error(t),{code:r,retryable:!1})}notifyCliMissing(e){Ae(this.deps,"error","Salesforce CLI",`${Os} ${e}`,{actions:[{label:"Install the CLI",command:"sf-cli-install",url:Og}]})}ackConnect(e,t){let r=A(this.deps,e,"org:statusChanged",{orgId:t,status:"connected"});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id}`)}async handleSfdxImport(e){try{if(!await this.deps.sfdxBridge.isCliAvailable()){this.notifyCliMissing("Importing orgs from the CLI needs it."),this.failConnect(e,Os,"SF_CLI_NOT_FOUND");return}let r=[],n=await this.deps.sfdxBridge.listOrgs(d=>{r.push(d)});if(n.length===0&&r.length>0){let d=this.reportUnreadable(r);Ae(this.deps,"error","Import Failed",d),this.failConnect(e,d,"SFDX_IMPORT_FAILED");return}if(n.length===0){Ae(this.deps,"info","Import",vO,{autoDismissMs:null,code:"NO_CLI_ORGS"}),this.failConnect(e,vO,"NO_CLI_ORGS");return}let o=await this.saveImported(n),i=this.deps.orgManager.getAllOrgs(),a=A(this.deps,e,"org:list:response",{orgs:i});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id}`),Ae(this.deps,"success","Import",`Imported ${n.length} org(s) from SF CLI.`),r.length>0&&Ae(this.deps,"warning","Import",this.reportUnreadable(r),{autoDismissMs:null}),this.ackConnect(e,o[0])}catch(t){let r=I(t);this.deps.log(`[ERR] org:sfdx-import: ${r}`),Ae(this.deps,"error","Import Failed",r),this.failConnect(e,r,"SFDX_IMPORT_FAILED")}}reportUnreadable(e){for(let o of e)this.deps.log(`[WARN] org:import: ${o.why==="notConnected"?"not connected":"no access token for"} ${o.alias??o.username}: ${o.reason}`);let t=o=>o.map(i=>`${we(i)} (${i.reason})`).join("; "),r=e.filter(o=>o.why!=="notConnected"),n=e.filter(o=>o.why==="notConnected");return[...n.length>0?[`The Salesforce CLI cannot reach these orgs, so they were not imported: ${t(n)}. Log in to each again with the CLI, or use Log in with your browser; a scratch org past its date is gone, create a new one.`]:[],...r.length>0?[`No access token from the Salesforce CLI, so not imported: ${t(r)}`]:[]].join(" ")}async saveImported(e){let t=await Promise.all(e.map(n=>this.typedImport(n))),r=[];for(let{org:n,credentials:o}of t){let i=this.refreshedEntryFor(n);i&&this.deps.log(`[INFO] org:import: ${i.alias} was refreshed into org ${n.orgId}; its entry is updated`);let a=i?{...n,id:i.id}:n;await this.deps.orgRegistry.saveOrg(a,o),r.push(a.id)}return r}async typedImport(e){let{org:t,credentials:r}=e;if(t.orgType!=="Production"||(t.metadata.edition??"")!=="")return e;let{accessToken:n,instanceUrl:o}=r;if(!n||!o)return e;try{let i=await Eh(this.connectTo({instanceUrl:o,accessToken:n,version:t.metadata.apiVersion}).then(u=>na(u)),RO,`the org did not answer within ${RO/1e3} s`),a=eo({isSandbox:i.sandbox,edition:i.edition}),{safetyTier:d,color:c}=Br(a);return a!==t.orgType&&this.deps.log(`[INFO] org:import: ${t.alias} says it is ${i.edition??(i.sandbox?"a sandbox":"no edition")}; typed ${a}`),{credentials:r,org:{...t,orgType:a,safetyTier:d,appearance:{...t.appearance,color:c},metadata:{...t.metadata,edition:i.edition??""}}}}catch(i){return this.deps.log(`[WARN] org:import: ${t.alias} gave no edition and could not be asked what it is (${I(i)}): typed Production until it is reconnected`),e}}refreshedEntryFor(e){let t=this.deps.sandboxRefreshes;if(!t||this.deps.orgManager.getOrg(e.id))return;let r=e.username.toLowerCase();return this.deps.orgManager.getAllOrgs().find(n=>n.username.toLowerCase()===r&&t.wasRefreshedTo(n.id,e.orgId))}async handleUsernamePassword(e,t){if(!t.username||!t.password){Ae(this.deps,"error","Auth","Username and password are required."),this.failConnect(e,"Username and password are required.","MISSING_CREDENTIALS");return}let r=this.resolveLoginUrl(e,t);if(!r)return;let n=await this.deps.authProvider.authenticate({method:"usernamePassword",loginUrl:r,username:t.username,password:t.password,securityToken:t.securityToken});if(!n.success||!n.accessToken||!n.instanceUrl){Ae(this.deps,"error","Auth Failed",n.error??"Authentication failed"),this.failConnect(e,n.error??"Authentication failed","AUTH_FAILED");return}try{let o=await this.deps.authProvider.validateConnection(n.accessToken,n.instanceUrl),i=eo({isSandbox:o.isSandbox,edition:o.orgType}),{safetyTier:a,color:d}=Br(i),c={id:o.orgId,alias:t.alias??t.username??o.username,username:o.username,...o.orgName?{organizationName:o.orgName}:{},instanceUrl:n.instanceUrl,orgId:o.orgId,orgType:i,authMethod:"usernamePassword",safetyTier:a,appearance:{color:d,icon:"cloud",position:0},metadata:{apiVersion:ko.DEFAULT_API_VERSION,edition:o.orgType,features:[]},status:"connected",lastConnected:new Date().toISOString(),tags:[]},u=this.deps.authProvider.buildConnectionConfig({method:"usernamePassword",loginUrl:r,username:t.username,password:t.password,securityToken:t.securityToken},n);await this.deps.orgRegistry.saveOrg(c,u);let l=A(this.deps,e,"org:statusChanged",{orgId:c.id,status:"connected"});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`),Ae(this.deps,"success","Connected",`${we(c)} connected.`)}catch(o){let i=I(o);this.deps.log(`[ERR] org:username-password: ${i}`),Ae(this.deps,"error","Validation Failed",`Auth succeeded but org validation failed: ${i}`),this.failConnect(e,`Auth succeeded but org validation failed: ${i}`,"ORG_VALIDATION_FAILED")}}resolveLoginUrl(e,t){let r=t.loginUrl??"https://login.salesforce.com",n=ra(r);if(n.ok)return n.origin;let o=n.reason==="not-https"?"Login URL must use HTTPS.":n.reason==="not-salesforce"?`Login URL must be a Salesforce login host (login.salesforce.com, test.salesforce.com or a My Domain): "${r}". For an org on another Salesforce cloud, log in with "sf org login web --instance-url <url>", then add it with Import from Salesforce CLI.`:n.reason==="not-origin"?`Login URL must name a host only, with no path, query or credentials: "${r}".`:`Invalid login URL: "${r}".`;Ae(this.deps,"error","Auth",o),this.failConnect(e,o,"INVALID_LOGIN_URL")}async handleOAuthWeb(e,t){let r=this.resolveLoginUrl(e,t);if(r)try{if(!await this.deps.sfdxBridge.isCliAvailable()){this.notifyCliMissing("OAuth web login runs through it."),this.failConnect(e,Os,"SF_CLI_NOT_FOUND");return}let o=t.alias??"",i=await this.deps.sfdxBridge.loginWeb(o,r);await this.importSignedInOrg(e,i,"OAuth")}catch(n){let o=I(n);this.deps.log(`[ERR] org:oauth-web: ${o}`),Ae(this.deps,"error","OAuth Failed",o),this.failConnect(e,o,"OAUTH_WEB_FAILED")}}async handleJwt(e){let t=x(Ew,e,"org:error",this.deps);if(!t)return;let r=this.resolveLoginUrl(e,t);if(r)try{if(!await this.requireCli(e,"JWT sign-in runs through it."))return;let n=await this.deps.sfdxBridge.loginJwt({username:t.username,clientId:t.clientId,keyFile:t.jwtKeyFile,loginUrl:r,alias:t.alias||void 0});await this.importSignedInOrg(e,n,"JWT")}catch(n){let o=I(n);this.deps.log(`[ERR] org:jwt: ${o}`),Ae(this.deps,"error","JWT Sign-in Failed",o),this.failConnect(e,o,"JWT_LOGIN_FAILED")}}async handleOAuthDevice(e){let t=x(Pw,e,"org:error",this.deps);if(!t)return;let r=this.resolveLoginUrl(e,t);if(!r)return;let n=new AbortController;this.pendingSignIns.set(e.id,n);try{if(!await this.requireCli(e,"The device sign-in hands its session to it."))return;let o=await this.deviceLogin.authorize(r,t.clientId,n.signal),i=A(this.deps,e,"org:device-code",{userCode:o.userCode,verificationUri:o.verificationUri,expiresAt:o.expiresAt});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`);let a=await this.browser.open(o.verificationUri);a.status==="error"&&this.deps.log(`[WARN] org:oauth-device: verification page not opened: ${a.message}`);let d=await this.deviceLogin.awaitApproval(r,t.clientId,o,n.signal);if(n.signal.aborted)throw new Error("Sign-in cancelled.");let c=await this.deps.sfdxBridge.loginWithRefreshToken({clientId:t.clientId,refreshToken:d.refreshToken,instanceUrl:d.instanceUrl,alias:t.alias||void 0});await this.importSignedInOrg(e,c,"Device Sign-in")}catch(o){if(n.signal.aborted){this.deps.log(`[INFO] org:oauth-device cancelled id=${e.id}`),this.failConnect(e,"Sign-in cancelled.","CANCELLED");return}let i=I(o);this.deps.log(`[ERR] org:oauth-device: ${i}`),Ae(this.deps,"error","Device Sign-in Failed",i),this.failConnect(e,i,"OAUTH_DEVICE_FAILED")}finally{this.pendingSignIns.delete(e.id)}}handleConnectCancel(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Cw,e,"org:error",this.deps);t&&this.pendingSignIns.get(t.requestId)?.abort()}async requireCli(e,t){return await this.deps.sfdxBridge.isCliAvailable()?!0:(this.notifyCliMissing(t),this.failConnect(e,Os,"SF_CLI_NOT_FOUND"),!1)}async importSignedInOrg(e,t,r){let n=await this.deps.sfdxBridge.findOrg(t.username);if(!n)throw new Error(`Signed in as ${t.username}, but "sf org display" does not show that org as connected.`);let[o]=await this.saveImported([n]);Ae(this.deps,"success",r,`${we(n.org)} connected.`),this.ackConnect(e,o??n.org.id)}async handleOrgDisconnect(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x($w,e,"org:error",this.deps);if(!t)return;let r=t;Po().remove(r.orgId),await this.deps.orgRegistry.removeOrg(r.orgId);let n=A(this.deps,e,"org:statusChanged",{orgId:r.orgId,status:"disconnected"});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`),this.syncOrgState()}handleOrgSelect(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(xw,e,"org:error",this.deps);if(!t)return;let{orgId:r}=t;if(!this.deps.orgManager.getOrg(r)){Ae(this.deps,"warning","Orgs",`Unknown org: ${r}`);return}this.deps.onOrgSelected?.(r);let n=A(this.deps,e,"org:selected",{orgId:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleOrgUpdate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(jw,e,"org:error",this.deps);if(!t)return;let r=this.deps.orgManager.getOrg(t.orgId);if(!r){T(this.deps,"org:update","org:error",e,new Error(`Unknown org: ${t.orgId}`),{code:"ORG_NOT_FOUND",retryable:!1});return}try{this.deps.orgRegistry.updateOrgMetadata({...r,alias:t.alias,appearance:{...r.appearance,color:t.color},tags:t.tags,...t.staging!==void 0?{staging:t.staging}:{}})}catch(o){T(this.deps,"org:update","org:error",e,o,{code:"ORG_UPDATE_FAILED",retryable:!0});return}let n=A(this.deps,e,"org:list:response",{orgs:this.deps.orgManager.getAllOrgs()});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`),this.syncOrgState()}async handleOpenInBrowser(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Dw,e,"org:error",this.deps);if(!t)return;let r=this.deps.orgManager.getOrg(t.orgId);if(!r){T(this.deps,"org:open-in-browser","org:error",e,new Error(`No registered org has the id "${t.orgId}".`),{code:"ORG_NOT_FOUND",retryable:!1});return}let n=es(r.instanceUrl);if(!n.ok){let a=n.reason==="not-https"?`its instance URL must use HTTPS, got "${n.protocol}"`:"its instance URL is not a valid URL";T(this.deps,"org:open-in-browser","org:error",e,new Error(`Cannot open "${we(r)}": ${a}.`),{code:"INVALID_INSTANCE_URL",retryable:!1});return}let o=await this.browser.open(n.url.toString());o.status==="error"&&this.deps.log(`[WARN] org:open-in-browser: not opened: ${o.message}`);let i=A(this.deps,e,"org:open-in-browser:response",o);this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} status=${o.status}`)}syncOrgState(){let e=this.deps.orgManager.getAllOrgs();this.deps.stateSync.updateState({orgs:e})}};function P$(s){let e=xg.safeParse(s.services?.getSandforgeSetting?.("forge.graphView","auto"));return e.success?e.data:"auto"}function Xp(s){return ih(s.services?.getSandforgeSetting?.("anonymization.mode","ask"))}var C$=new Set(["settings:get","settings:update","telemetry:status","telemetry:toggle","anonymization:mode:ask"]),Fd=class{constructor(e){this.deps=e}deps;async handle(e){if(!C$.has(e.type))return!1;switch(e.type){case"settings:get":return this.handleSettingsGet(e),!0;case"settings:update":return this.handleSettingsUpdate(e),!0;case"telemetry:status":return this.handleTelemetryStatus(e),!0;case"telemetry:toggle":return await this.handleTelemetryToggle(e),!0;case"anonymization:mode:ask":return await this.handleAnonymizationModeAsk(e),!0;default:return!1}}postSettings(){this.deps.broker.postToWebview({id:this.deps.nextId(),type:"settings:response",timestamp:Date.now(),payload:this.settingsPayload()})}settingsPayload(){return{settings:this.deps.configStore.getByCategory("settings"),forgeGraphView:P$(this.deps),anonymizationMode:Xp(this.deps)}}async handleAnonymizationModeAsk(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=(a,d)=>{let c=A(this.deps,e,"anonymization:mode:ask:response",{mode:a,setting:Xp(this.deps),kept:d});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id} mode=${a} kept=${String(d)}`)},r=Xp(this.deps),n=this.deps.services?.askAnonymizationMode;if(r!=="ask"||!n){t(ah(r),!1);return}let o;try{o=await n()}catch(a){this.deps.log(`[WARN] anonymization:mode:ask: ${I(a)}`)}if(o===void 0){t("standard",!1);return}let i=!1;if(this.deps.services?.setSandforgeSetting)try{await this.deps.services.setSandforgeSetting("anonymization.mode",o),i=!0}catch(a){this.deps.log(`[WARN] anonymization:mode:ask: the answer was not kept: ${I(a)}`)}t(o,i),i&&this.postSettings()}handleSettingsGet(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=A(this.deps,e,"settings:response",this.settingsPayload());this.deps.broker.postToWebview(t),this.deps.log(`[TX] ${t.type} id=${t.id}`)}handleSettingsUpdate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Mw,e,"settings:error",this.deps);if(!t)return;let r=t;this.deps.configStore.set(r.key,r.value,"settings");let n=A(this.deps,e,"settings:response",this.settingsPayload());this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleTelemetryStatus(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.deps.services?.getSandforgeSetting?.("telemetry",!1)??!1,r=this.deps.services?.telemetry.getTelemetryEventCount()??0,n=A(this.deps,e,"telemetry:status:response",{enabled:t,eventCount:r});this.deps.broker.postToWebview(n)}async handleTelemetryToggle(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Lw,e,"settings:error",this.deps);if(!t)return;let{enabled:r}=t;if(!this.deps.services?.setSandforgeSetting){let n=A(this.deps,e,"telemetry:toggle:response",{success:!1,enabled:this.deps.services?.getSandforgeSetting?.("telemetry",!1)??!1,error:"Settings backend not available \u2014 telemetry preference was not persisted."});this.deps.broker.postToWebview(n);return}try{await this.deps.services.setSandforgeSetting("telemetry",r);let n=this.deps.services.getSandforgeSetting?.("telemetry",r)??r,o=A(this.deps,e,"telemetry:toggle:response",{success:!0,enabled:n});this.deps.broker.postToWebview(o)}catch(n){this.deps.log(`[ERR] telemetry:toggle: ${I(n)}`);let o=A(this.deps,e,"telemetry:toggle:response",{success:!1,enabled:this.deps.services.getSandforgeSetting?.("telemetry",!1)??!1,error:I(n)});this.deps.broker.postToWebview(o)}}};var Kp={DailyApiRequests:{weight:.2,category:"limits"},DataStorageMB:{weight:.2,category:"storage"},DailyBulkApiBatches:{weight:.15,category:"limits"},DailyBulkV2QueryJobs:{weight:.15,category:"limits"},DailyAsyncApexExecutions:{weight:.15,category:"jobs"}},Yp=1,SO=.15,$$=.55;function kO(s){let e=Math.max(0,Math.min(100,s)),t;return e<=50?t=100-e*.6:t=70-(e-50)*1.4,Math.max(0,Math.min(100,Math.round(t)))}function x$(s){let e=Math.max(0,Math.min(100,s)),t;return e<=75?t=e/75*70:t=70+(e-75)/25*30,Math.max(0,Math.min(100,Math.round(t)))}function Qp(s,e,t){if(s<=e)return 100;if(s>=t)return 20;let r=(s-e)/(t-e);return Math.round(100-r*80)}function OO(s){switch(s){case"up":return"degrading";case"down":return"improving";case"stable":return"stable"}}function IO(s){return s.direction!=="up"?0:Math.min(15,Math.max(0,Math.abs(s.changePercent)*.5))}function fi(s){return s>=70?"healthy":s>=40?"warning":"critical"}function AO(s,e){if(e<75)return"No action needed.";let t=e>=90?"Urgent: ":"";switch(s){case"DailyApiRequests":return`${t}Review scheduled batch jobs and integrations consuming API calls.`;case"DataStorageMB":return`${t}Consider archiving old records or cleaning up attachments.`;case"DailyBulkApiBatches":return`${t}Group small Bulk API loads into fewer, larger jobs, or spread them over several days.`;case"DailyBulkV2QueryJobs":return`${t}Review the integrations that run Bulk API 2.0 queries, and how often they run.`;case"DailyAsyncApexExecutions":return`${t}Review queued and scheduled Apex jobs for efficiency.`;default:return`${t}Monitor this limit and optimize usage if it continues to grow.`}}function TO(s){let e=s.max-s.remaining;return`${s.usedPercent}% used (${e.toLocaleString()} / ${s.max.toLocaleString()})`}var _d=class{calculate(e){let t=[],r=this.countOptionalDimensions(e),n=this.computeLimitsWeightMultiplier(r);this.addCoreLimitFactors(e,t,n),this.addRemainingLimitFactors(e,t,n);let o=this.computeOptionalDimensionWeight(r);this.addMetadataDimension(e,t,o),this.addCoverageDimension(e,t,o),this.addSecurityDimension(e,t,o);let{weightedSum:i,totalWeight:a}=t.reduce((f,g)=>({weightedSum:f.weightedSum+g.score*g.weight,totalWeight:f.totalWeight+g.weight}),{weightedSum:0,totalWeight:0}),d=a>0?Math.round(i/a):100,c=this.scoreToOverallStatus(d),l=[...t].sort((f,g)=>f.score-g.score).filter(f=>f.status!=="healthy").slice(0,3),p=this.buildSummary(c,l);return{overallScore:d,overallStatus:c,factors:t,summary:p,topRisks:l}}countOptionalDimensions(e){let t=0;return(e.metadataCounts!==void 0||e.orgInfo!==void 0)&&t++,e.codeCoverage!==void 0&&t++,e.securitySettings!==void 0&&t++,t}computeLimitsWeightMultiplier(e){if(e===0)return Yp;let t=e*SO;return Math.max($$,Yp-t)}computeOptionalDimensionWeight(e){return e===0?0:SO}addCoreLimitFactors(e,t,r){for(let[n,o]of Object.entries(Kp)){let i=e.limits.find(p=>p.name===n);if(!i)continue;let a=kO(i.usedPercent),d=this.fetchTrendData(e,n),c=d?OO(d.direction):"stable",u=d?IO(d):0,l=Math.max(0,Math.round(a-u));t.push({name:i.name,category:o.category,score:l,weight:o.weight*r,status:fi(l),detail:TO(i),recommendation:AO(i.name,i.usedPercent),trend:c})}}addRemainingLimitFactors(e,t,r){let n=new Set(Object.keys(Kp)),o=e.limits.filter(c=>!n.has(c.name)&&c.usedPercent>0);if(o.length===0)return;let i=Object.values(Kp).reduce((c,u)=>c+u.weight,0),d=Math.max(0,(Yp-i)*r)/o.length;for(let c of o){let u=kO(c.usedPercent),l=this.fetchTrendData(e,c.name),p=l?OO(l.direction):"stable",f=l?IO(l):0,g=Math.max(0,Math.round(u-f));t.push({name:c.name,category:"limits",score:g,weight:d,status:fi(g),detail:TO(c),recommendation:AO(c.name,c.usedPercent),trend:p})}}addMetadataDimension(e,t,r){if(e.metadataCounts===void 0&&e.orgInfo===void 0)return;let n=e.metadataCounts?.customObjectCount??e.orgInfo?.customObjectCount??0,o=e.metadataCounts?.customFieldCount??0,i=e.metadataCounts?.apexClassCount??e.orgInfo?.apexClassCount??0,a=Math.round(Qp(n,50,500)*.4+Qp(o,200,2e3)*.3+Qp(i,100,1e3)*.3),d=`${n} custom objects, ${o} custom fields, ${i} Apex classes`,c=a<60?"High metadata complexity detected - consider consolidating custom objects and reviewing unused Apex classes":"Metadata complexity is manageable";t.push({name:"Metadata Complexity",category:"metadata",score:a,weight:r,status:fi(a),detail:d,recommendation:c,trend:"stable"})}addCoverageDimension(e,t,r){if(e.codeCoverage===void 0)return;let n=x$(e.codeCoverage),o=`${Math.round(e.codeCoverage)}% org-wide Apex code coverage`,i=e.codeCoverage<75?`Code coverage is at ${Math.round(e.codeCoverage)}% - Salesforce requires minimum 75% for deployment`:"Code coverage meets Salesforce requirements";t.push({name:"Code Coverage",category:"coverage",score:n,weight:r,status:fi(n),detail:o,recommendation:i,trend:"stable"})}addSecurityDimension(e,t,r){if(e.securitySettings===void 0)return;let{score:n,detail:o,recommendation:i}=this.scoreSecuritySettings(e.securitySettings);t.push({name:"Security Settings",category:"security",score:n,weight:r,status:fi(n),detail:o,recommendation:i,trend:"stable"})}scoreSecuritySettings(e){let t=0,r=[];e.passwordMinLength>=12?t+=25:e.passwordMinLength>=8?t+=15:(t+=5,r.push("password minimum length is below 8 characters")),e.passwordComplexity?t+=20:r.push("password complexity requirements are disabled"),e.sessionTimeout<=120?t+=20:e.sessionTimeout<=480?t+=10:r.push("session timeout exceeds 8 hours"),e.mfaEnabled?t+=20:r.push("MFA is not enabled"),e.ipRestrictions?t+=15:r.push("login IP restrictions are not configured");let n=r.length===0?"All security settings are properly configured":`${r.length} security issue(s) found`,o=r.length===0?"Security configuration is strong":`Improve security: ${r.join(", ")}`;return{score:t,detail:n,recommendation:o}}fetchTrendData(e,t){if(e.trends)return e.trends[t];if(e.trendStorage)return e.trendStorage.getTrendData(e.orgId,t)}scoreToOverallStatus(e){return e>=70?"healthy":e>=40?"warning":"critical"}buildSummary(e,t){return e==="healthy"&&t.length===0?"Your org is healthy. All limits are within safe thresholds.":e==="healthy"?`Your org is healthy but ${t[0].name} is trending up.`:e==="warning"?`Warning: ${t.map(o=>o.name).join(", ")} approaching limits. Review recommendations.`:`Critical: ${t.map(n=>n.name).join(", ")} at dangerous levels. Immediate action required.`}};var D$=Re(K({version:L()}));function EO(s){let e=D$.parse(s).map(({version:t})=>t).filter(t=>Number.isFinite(Number(t)));if(e.length===0)throw new Error("The org listed no API version under /services/data.");return e.reduce((t,r)=>Number(r)>Number(t)?r:t)}function N$(s){if(!s)return;let e=new Date(s);return Number.isNaN(e.getTime())?void 0:e.toISOString()}var Ud=class{cache=new Map;cacheTtlMs;constructor(e=300*1e3){this.cacheTtlMs=e}async fetch(e,t){let r=this.cache.get(e);if(r&&Date.now()-r.fetchedAt<this.cacheTtlMs)return r.data;let[n,o,i,a,d,c]=await Promise.all([t.latestApiVersion(),t.queryOrg(),t.queryCount("SELECT COUNT() FROM User WHERE IsActive = true"),t.queryCount("SELECT COUNT() FROM EntityDefinition WHERE DeploymentStatus != null AND QualifiedApiName LIKE '%__c'"),t.queryCount("SELECT COUNT() FROM ApexClass"),t.queryCount("SELECT COUNT() FROM FlowDefinitionView WHERE IsActive = true")]),u=o.namespacePrefix||void 0,l=N$(o.createdDate),p={name:o.name,orgId:o.orgId,type:o.type,edition:o.edition,instanceName:o.instanceName,apiVersion:n,userCount:i,customObjectCount:a,apexClassCount:d,flowCount:c,...u!==void 0?{namespacePrefix:u}:{},...l!==void 0?{createdDate:l}:{}};return this.cache.set(e,{data:p,fetchedAt:Date.now()}),p}clearCache(e){e?this.cache.delete(e):this.cache.clear()}};function PO(s){return Object.entries(s).map(([e,{Max:t,Remaining:r}])=>({name:e,max:t,remaining:r,usedPercent:t>0?Math.round((t-r)/t*100):0}))}var Zp=1440*60*1e3,CO=7*Zp,j$=500*1024,M$=900*1e3,L$=2,F$="trends",_$=new Set(Gi),U$=Zp,Bd=class{configStore;lastSaveTimestamps=new Map;constructor(e){this.configStore=e}trendKey(e){return`trend:${e}`}record(e,t){let r=Date.now();this.isRateLimited(e,r)||this.append(e,this.read(e),t,r)}recordAndGetTrends(e,t,r){let n=Date.now(),o=this.read(e),a=(this.isRateLimited(e,n)?o:this.append(e,o,t,n)).filter(u=>u.timestamp>=Hd(n-CO)),d=a.filter(u=>u.timestamp>=Hd(n-U$)),c={};for(let u of r)c[u]=this.computeTrend(u,a,d);return c}getHistory(e,t=Zp){let r=Hd(Date.now()-t);return this.read(e).filter(n=>n.timestamp>=r)}getTrendData(e,t){let r=this.getHistory(e);return this.computeTrend(t,r,r)}purge(e){let t=this.trendKey(e);this.configStore.delete(t),this.lastSaveTimestamps.delete(e)}read(e){return this.configStore.get(this.trendKey(e))??[]}isRateLimited(e,t){return t-(this.lastSaveTimestamps.get(e)??0)<M$}append(e,t,r,n){let o=Hd(n-CO),i=[...t,r].filter(d=>d.timestamp>=o).map(d=>({...d,limits:d.limits.filter(c=>_$.has(c.name))})),a=this.trimToSizeLimit(i);return this.configStore.set(this.trendKey(e),a,F$),this.lastSaveTimestamps.set(e,n),a}computeTrend(e,t,r){let{values:n,timestamps:o}=$O(e,t),{values:i}=$O(e,r);if(i.length<2)return{limitName:e,direction:"stable",changePercent:0,sparklineData:n,timestamps:o};let a=i[0],d=i[i.length-1],c=d-a,u;Math.abs(c)<=L$?u="stable":c>0?u="up":u="down";let l;if(u==="up"&&d<100){let p=this.getTimeSpanMs(r);if(p>0){let f=c/p;if(f>0){let h=(100-d)/f;l=Math.round(h/(3600*1e3)*10)/10}}}return{limitName:e,direction:u,changePercent:Math.round(c*10)/10,predictedTimeToLimit:l,sparklineData:n,timestamps:o}}getTimeSpanMs(e){if(e.length<2)return 0;let t=new Date(e[0].timestamp).getTime();return new Date(e[e.length-1].timestamp).getTime()-t}trimToSizeLimit(e){let t=[...e];for(;t.length>0&&!(new TextEncoder().encode(JSON.stringify(t)).length<=j$);)t.shift();return t}};function Hd(s){return new Date(s).toISOString()}function $O(s,e){let t=[],r=[];for(let n of e){let o=n.limits.find(i=>i.name===s);o&&(t.push(o.usedPercent),r.push(n.timestamp))}return{values:t,timestamps:r}}var qd=class{onNotify;definitions=new Map;activeAlerts=new Map;lastTriggered=new Map;constructor(e){this.onNotify=e}addDefinition(e){this.definitions.set(e.id,e)}removeDefinition(e){this.definitions.delete(e)}getDefinitions(){return[...this.definitions.values()]}evaluate(e,t,r){for(let n of this.definitions.values()){if(!n.enabled||n.metric!==e||!H$(n.condition,t))continue;let o=`${n.id}:${r}`;if(this.isInCooldown(n,o))continue;let i=this.createAlert(n,t,r);return this.activeAlerts.set(i.id,i),this.lastTriggered.set(o,Date.now()),this.onNotify(i),i}return null}getActiveAlerts(){return[...this.activeAlerts.values()].filter(e=>e.status==="active"||e.status==="acknowledged")}acknowledgeAlert(e){let t=this.activeAlerts.get(e);t&&(t.status="acknowledged",t.acknowledgedAt=new Date().toISOString())}resolveAlert(e){let t=this.activeAlerts.get(e);t&&(t.status="resolved",t.resolvedAt=new Date().toISOString())}restoreAlerts(e){for(let t of e)if(t.status==="active"||t.status==="acknowledged"){this.activeAlerts.set(t.id,t);let r=`${t.definitionId}:${t.orgId}`,n=Date.parse(t.triggeredAt);!Number.isNaN(n)&&n>(this.lastTriggered.get(r)??0)&&this.lastTriggered.set(r,n)}}dismissAlert(e){let t=this.activeAlerts.get(e);t&&(t.status="dismissed")}isInCooldown(e,t){let r=this.lastTriggered.get(t);if(r===void 0)return!1;let n=e.cooldownMinutes*60*1e3;return Date.now()-r<n}createAlert(e,t,r){return{id:`alert-${globalThis.crypto.randomUUID()}`,definitionId:e.id,severity:e.severity,status:"active",message:`${e.name}: ${e.metric} is ${t} (threshold: ${e.condition.threshold})`,currentValue:t,threshold:e.condition.threshold,orgId:r,triggeredAt:new Date().toISOString()}}};function H$(s,e){switch(s.operator){case"gt":return e>s.threshold;case"gte":return e>=s.threshold;case"lt":return e<s.threshold;case"lte":return e<=s.threshold;case"eq":return e===s.threshold;case"neq":return e!==s.threshold}}var as="alert:state:",ef="alerts";var Wd=class{constructor(e){this.configStore=e}configStore;saveAlerts(e){this.configStore.set(`${as}active`,e,ef)}loadAlerts(){let e=this.configStore.get(`${as}active`);return Array.isArray(e)?e:[]}saveDefinitions(e){this.configStore.set(`${as}definitions`,e,ef)}loadDefinitions(){let e=this.configStore.get(`${as}definitions`);return Array.isArray(e)?e:[]}saveHistory(e){let t=this.loadHistory(),r=new Set(t.map(a=>a.id)),n=e.filter(a=>!r.has(a.id));if(n.length===0)return;let o=[...t,...n],i=o.length>500?o.slice(o.length-500):o;this.configStore.set(`${as}history`,i,ef)}loadHistory(){let e=this.configStore.get(`${as}history`);return Array.isArray(e)?e:[]}};var tf=[{id:"alert-api-critical",name:"API Requests Critical",description:"Fires when daily API request usage reaches 90% of the org limit",enabled:!0,metric:"DailyApiRequests",condition:{operator:"gte",threshold:90},severity:"critical",cooldownMinutes:15,notificationChannels:["vscode_notification"]},{id:"alert-storage-critical",name:"Data Storage Critical",description:"Fires when data storage usage reaches 85% of the org limit",enabled:!0,metric:"DataStorageMB",condition:{operator:"gte",threshold:85},severity:"critical",cooldownMinutes:30,notificationChannels:["vscode_notification"]},{id:"alert-async-critical",name:"Async Apex Critical",description:"Fires when daily async Apex execution usage reaches 90% of the org limit",enabled:!0,metric:"DailyAsyncApexExecutions",condition:{operator:"gte",threshold:90},severity:"critical",cooldownMinutes:15,notificationChannels:["vscode_notification"]},{id:"alert-email-warning",name:"Workflow Emails Warning",description:"Fires when daily workflow email usage reaches 80% of the org limit",enabled:!0,metric:"DailyWorkflowEmails",condition:{operator:"gte",threshold:80},severity:"warning",cooldownMinutes:30,notificationChannels:["vscode_notification"]},{id:"alert-filestorage-critical",name:"File Storage Critical",description:"Fires when file storage usage reaches 85% of the org limit",enabled:!0,metric:"FileStorageMB",condition:{operator:"gte",threshold:85},severity:"critical",cooldownMinutes:30,notificationChannels:["vscode_notification"]}];var zd=class{queryErrors;errorCache=new Map;truncatedCache=new Map;constructor(e){this.queryErrors=e}async fetch(e){let t=new Date(Date.now()-864e5).toISOString(),{records:r,truncated:n}=await this.queryErrors(e,t);return this.errorCache.set(e,r),this.truncatedCache.set(e,n),r}getRecentErrors(e){return this.errorCache.get(e)??[]}isTruncated(e){return this.truncatedCache.get(e)??!1}getErrorsByType(e){let t=this.getRecentErrors(e),r=new Map;for(let n of t){let o=r.get(n.errorType)??0;r.set(n.errorType,o+1)}return r}};var Gd=class{querySessions;sessionCache=new Map;truncatedCache=new Map;constructor(e){this.querySessions=e}async fetch(e){let{records:t,truncated:r}=await this.querySessions(e);return this.sessionCache.set(e,t),this.truncatedCache.set(e,r),t}getActiveSessions(e){return this.sessionCache.get(e)??[]}isTruncated(e){return this.truncatedCache.get(e)??!1}getActiveUserCount(e){let t=this.getActiveSessions(e);return new Set(t.map(n=>n.userId)).size}};var Jd=class{fetchLogs;analyses=new Map;truncatedCache=new Map;constructor(e){this.fetchLogs=e}analyze(e){let t=B$(e),r=q$(e),n=W$(e),o=e.durationMs,i=z$(t,r,n,o);return{logId:e.id,totalDuration:e.durationMs,soqlQueries:t,dmlStatements:r,heapUsed:n,cpuTime:o,issues:i}}async fetchAndAnalyze(e,t=10){let{records:r,truncated:n}=await this.fetchLogs(e,t),o=r.map(i=>this.analyze(i));return this.analyses.set(e,o),this.truncatedCache.set(e,n),o}isTruncated(e){return this.truncatedCache.get(e)??!1}getRecentAnalyses(e){return this.analyses.get(e)??[]}getTopIssues(e){let t=this.analyses.get(e)??[],r=new Map;for(let n of t)for(let o of n.issues){let i=`${o.type}:${o.message}`,a=r.get(i);a?a.count++:r.set(i,{issue:o,count:1})}return[...r.values()].sort((n,o)=>o.count-n.count).map(n=>n.issue)}};function B$(s){return Math.min(Math.floor(s.logSize/500),100)}function q$(s){return Math.min(Math.floor(s.logSize/1e3),150)}function W$(s){return Math.min(s.logSize*10,6e6)}function z$(s,e,t,r){let n=[];return s>=100?n.push({type:"soql_in_loop",severity:"critical",message:`SOQL query limit reached: ${s}/100`}):s>=100*.8&&n.push({type:"governor_warning",severity:"warning",message:`Approaching SOQL query limit: ${s}/100`}),e>=150?n.push({type:"excessive_dml",severity:"critical",message:`DML statement limit reached: ${e}/150`}):e>=150*.6&&n.push({type:"governor_warning",severity:"warning",message:`Approaching DML statement limit: ${e}/150`}),t>=6e6?n.push({type:"large_heap",severity:"critical",message:`Heap size limit reached: ${t}/6000000`}):t>=6e6*.7&&n.push({type:"large_heap",severity:"warning",message:`Approaching heap size limit: ${t}/6000000`}),r>5e3&&n.push({type:"slow_query",severity:"warning",message:`Slow execution: ${r}ms exceeds 5000ms threshold`}),n}var G$=new Set(Jg);function DO(s){return typeof s=="string"&&G$.has(s)?s:"Unknown"}function J$(){let s=new Map;return{load:e=>s.get(e),save:(e,t)=>{s.set(e,t)}}}function xO(s){return`${s.sandboxName}:${s.refreshDate}`}var Vd=class{querySandboxes;onRefreshDetected;seen;refreshCache=new Map;supportedCache=new Map;truncatedCache=new Map;constructor(e,t,r=J$()){this.querySandboxes=e,this.onRefreshDetected=t,this.seen=r}async fetch(e){let{supported:t,events:r,truncated:n}=await this.querySandboxes(e);if(this.refreshCache.set(e,r),this.supportedCache.set(e,t),this.truncatedCache.set(e,n),!t)return r;let o=r.filter(d=>d.status==="Completed"),i=this.seen.load(e);if(i!==void 0){let d=new Set(i);for(let c of o)d.has(xO(c))||this.onRefreshDetected?.(c)}let a=o.map(xO);return(i===void 0||a.some(d=>!i.includes(d)))&&this.seen.save(e,a),r}isSupported(e){return this.supportedCache.get(e)??!0}isTruncated(e){return this.truncatedCache.get(e)??!1}getRecentRefreshes(e){return this.refreshCache.get(e)??[]}isRefreshInProgress(e){return(this.refreshCache.get(e)??[]).some(r=>Vg(r.status))}};var Xd=class s{providers;constructor(e){this.providers=e}async computeHealth(e){let t=await Promise.all(this.providers.map(c=>c(e))),r=s.computeScore(t),n=r===null?"unknown":s.statusFromScore(r),o=t.find(c=>c.name==="apiLimits"),i=t.find(c=>c.name==="storage"),a=t.find(c=>c.name==="activeJobs"),d=t.find(c=>c.name==="recentErrors");return{orgId:e,overall:n,apiLimitsStatus:o?.status??"unknown",storageStatus:i?.status??"unknown",failedJobs:a?.status==="unknown"?null:a?.count??null,failedJobsOutOf:a?.status==="unknown"?null:a?.outOf??null,recentErrorLogs:d?.status==="unknown"?null:d?.count??null,lastChecked:new Date().toISOString()}}static computeScore(e){let t=e.filter(n=>n.status!=="unknown");if(t.length===0)return null;let r=t.reduce((n,o)=>n+o.score,0);return Math.round(r/t.length)}static statusFromScore(e){return e>=80?"healthy":e>=50?"degraded":"critical"}};var NO=new Set(["Queued","Processing"]),Kd=class{queryJobs;jobCache=new Map;constructor(e){this.queryJobs=e}async fetch(e){let t=await this.queryJobs(e);return this.jobCache.set(e,t),t}getActiveJobs(e){return(this.jobCache.get(e)??[]).filter(r=>NO.has(r.status))}getFailedJobs(e){return(this.jobCache.get(e)??[]).filter(r=>r.status==="Failed")}getJobStats(e){let t=this.jobCache.get(e)??[];return{total:t.length,active:t.filter(r=>NO.has(r.status)).length,completed:t.filter(r=>r.status==="Completed").length,failed:t.filter(r=>r.status==="Failed").length}}};var V$=3e4,X$=1440*60*1e3,jO=100,MO=50,LO=20,FO="sandbox-process-seen:";function K$(s){return{load:e=>{let t=s.get(`${FO}${e}`);return Array.isArray(t)?t.filter(r=>typeof r=="string"):void 0},save:(e,t)=>{s.set(`${FO}${e}`,t,"sandbox-refresh")}}}function Y$(s){return s instanceof Eo?s.code==="ORG_AUTH_EXPIRED":Oh(s)||ul(s)!==void 0}function gi(s){let e=ul(s);return e!==void 0&&!(s instanceof Eo)?`the org could not be reached (${e})`:I(s)}function _O(s){let e=new Bd(s.configStore),t=async(R,w,P)=>{try{return await P(await s.getConnection(R))}catch(O){if(!Y$(O))throw O;s.log(`[WARN] monitor:${w} ${R}: ${gi(O)}; read again on a new connection`);try{return await P(await s.getConnection(R,{again:!0}))}catch(E){throw E instanceof Eo&&E.code==="ORG_TEMPORARILY_UNREACHABLE"?O:E}}},r=new Wd(s.configStore),n=new qd(R=>{s.log(`[ALERT] ${R.severity}: ${R.message}`);let w=R.severity==="critical"?"error":"warning";s.notify(w,R.message),r.saveAlerts(n.getActiveAlerts())}),o=r.loadDefinitions(),i=o.length>0?o:tf;for(let R of i)n.addDefinition(R);o.length===0&&r.saveDefinitions(tf);let a=r.loadAlerts();n.restoreAlerts(a);let d=new zd(async(R,w)=>{let P=await s.getConnection(R),{records:O,truncated:E}=await _s(P,`SELECT Id, Operation, Status, DurationMilliseconds, LogLength, StartTime, LogUser.Username FROM ApexLog WHERE Status != 'Success' AND StartTime > ${w} ORDER BY StartTime DESC LIMIT ${MO}`,MO);return $e(P.limitInfo,"monitor:error-logs apexLog"),{records:O.map($=>({id:$.Id,errorType:$.Status,message:`${$.Operation} - ${$.Status}`,timestamp:$.StartTime,user:$.LogUser?.Username??void 0,context:$.Operation})),truncated:E}}),c=async(R,w)=>{let P=await R.query(`SELECT COUNT() FROM ApexLog WHERE Status != 'Success' AND StartTime > ${w}`);return $e(R.limitInfo,"monitor:refresh apexLogCount"),P.totalSize},u=new Gd(async R=>{let w=await s.getConnection(R),{records:P,truncated:O}=await _s(w,`SELECT Id, UsersId, Users.Username, LoginType, SessionType, CreatedDate, SourceIp FROM AuthSession ORDER BY CreatedDate DESC LIMIT ${jO}`,jO);return $e(w.limitInfo,"monitor:sessions authSession"),{records:P.map(E=>({sessionId:E.Id,userId:E.UsersId,username:E.Users?.Username??E.UsersId,sessionType:E.SessionType??E.LoginType??"Unknown",loginTime:E.CreatedDate,sourceIp:E.SourceIp??""})),truncated:O}}),l=new Jd(async(R,w)=>{let P=await s.getConnection(R),{records:O,truncated:E}=await _s(P,`SELECT Id, Operation, Status, DurationMilliseconds, LogLength, StartTime, LogUser.Username FROM ApexLog ORDER BY StartTime DESC LIMIT ${w}`,w);return $e(P.limitInfo,"monitor:apex-insights apexLog"),{records:O.map($=>({id:$.Id,operation:$.Operation??"Unknown",status:$.Status,durationMs:$.DurationMilliseconds??0,logSize:$.LogLength??0,startTime:$.StartTime,user:$.LogUser?.Username??"Unknown"})),truncated:E}}),p=new Set,f=new Vd(async R=>{if(p.has(R))return{supported:!1,events:[],truncated:!1};let w=await s.getConnection(R),P;try{P=await _s(w,`SELECT Id, SandboxName, Status, CreatedDate, Description FROM SandboxProcess ORDER BY CreatedDate DESC LIMIT ${LO}`,LO)}catch(O){let E=O instanceof Error?O.message:String(O);if(E.includes("SandboxProcess")&&E.includes("not supported"))return p.add(R),{supported:!1,events:[],truncated:!1};throw O}return $e(w.limitInfo,"monitor:sandbox-refresh sandboxProcess"),{supported:!0,events:P.records.map(O=>({orgId:R,sandboxName:O.SandboxName??"Unknown",refreshDate:O.CreatedDate,status:DO(O.Status),sourceOrg:O.Description??void 0})),truncated:P.truncated}},R=>s.onSandboxRefreshCompleted?.(R),K$(s.configStore)),g=new Map,h=async(R,w)=>{let P=g.get(R);if(P&&Date.now()-P.fetchedAt<V$)return P.data;let O=await w.request(`/services/data/${Oo}/limits`);return g.set(R,{data:O,fetchedAt:Date.now()}),O},m=async R=>{try{let P=(await t(R,"apiLimits",$=>h(R,$))).DailyApiRequests;if(!P||!P.Max)return{name:"apiLimits",status:"unknown",score:0,message:"No API limit reported"};let O=Math.round((P.Max-P.Remaining)/P.Max*100);return{name:"apiLimits",status:O>80?"critical":O>60?"warning":"ok",score:100-O,message:`API usage at ${O}%`,percent:O}}catch(w){return{name:"apiLimits",status:"unknown",score:0,message:`Unable to fetch limits: ${gi(w)}`}}},y=async R=>{try{let P=(await t(R,"storage",$=>h(R,$))).DataStorageMB;if(!P||!P.Max)return{name:"storage",status:"unknown",score:0,message:"No storage limit reported"};let O=Math.round((P.Max-P.Remaining)/P.Max*100);return{name:"storage",status:O>85?"critical":O>70?"warning":"ok",score:100-O,message:`Storage usage at ${O}%`,percent:O}}catch(w){return{name:"storage",status:"unknown",score:0,message:`Unable to fetch storage: ${gi(w)}`}}},v=async R=>{let w;try{let E=new Date(Date.now()-X$).toISOString();w=await t(R,"recentErrors",$=>c($,E))}catch(E){return{name:"recentErrors",status:"unknown",score:0,message:`Unable to fetch error logs: ${gi(E)}`}}let P=Math.max(0,100-w*5);return{name:"recentErrors",status:w>10?"critical":w>3?"warning":"ok",score:P,count:w,message:`${w} recent errors`}},b=async R=>{let w=await Ft(R,`SELECT Id, JobType, Status, NumberOfErrors, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${mn.monitorJobs}`);return $e(R.limitInfo,"monitor:refresh asyncJobs"),w.map(P=>({id:P.Id,jobType:P.JobType??"Batch",status:P.Status,createdBy:P.CreatedById,createdDate:P.CreatedDate,failedRecords:P.NumberOfErrors}))},k=new Kd(R=>t(R,"activeJobs",b)),S=async R=>{try{await k.fetch(R);let w=k.getJobStats(R),P=Math.max(0,100-w.failed*10);return{name:"activeJobs",status:w.failed>5?"critical":w.failed>0?"warning":"ok",score:P,count:w.failed,outOf:w.total,message:`${w.active} active, ${w.failed} failed of ${w.total} recent jobs`}}catch(w){return{name:"activeJobs",status:"unknown",score:0,message:`Unable to fetch jobs: ${gi(w)}`}}},C=new Xd([m,y,v,S]);return{trendStorage:e,alertStateStore:r,alertEngine:n,errorLogMonitor:d,userSessionMonitor:u,apexLogAnalyzer:l,sandboxRefreshTracker:f,healthCheck:C,healthSignals:{apiLimits:m,storage:y,recentErrors:v,activeJobs:S},getOrFetchLimits:h,forgetOrg:R=>{g.delete(R)}}}var UO=25e3,HO=20,Q$=20,Z$=20,ex=500,WO=`SELECT Id, JobType, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${mn.monitorJobs}`,tx=`SELECT Id, JobType, Status, NumberOfErrors, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${mn.monitorJobs}`,rx=new Set([WO,tx]),nx=new Set(["Queued","Preparing","Processing"]),ox=new Set(["BatchApex","Queueable","Future"]),hi=3600*1e3,BO=hi,qO=3;function rf(s){let e=Math.floor(s/60),t=s%60;return e>0?`${e}h${String(t).padStart(2,"0")}m`:`${t}m`}function sx(s,e){return s.status===e.status&&s.batchesProcessed===e.batchesProcessed&&s.totalBatches===e.totalBatches}function ix(s,e,t){let r=new Map;for(let n of e){let o=s?.get(n.id);if(o!==void 0&&sx(o,n)){r.set(n.id,o);continue}r.set(n.id,{status:n.status,batchesProcessed:n.batchesProcessed,totalBatches:n.totalBatches,unchangedSinceMs:t,movedWhileWatched:o!==void 0})}return r}function ax(s,e,t){let r=[],n=[],o=[];for(let a of s){if(!nx.has(a.status)||!ox.has(a.jobType))continue;let d=e.get(a.id),c=d===void 0?null:t-d.unchangedSinceMs,u=a.batchesProcessed,l=a.totalBatches;if(a.status==="Processing"&&u!==null&&l!==null&&u<l&&c!==null&&c>=hi){n.push({job:a,stillMs:c,done:u,total:l});continue}if(d?.movedWhileWatched===!0&&c!==null&&c<hi)continue;let p=t-Date.parse(a.createdDate);p>=BO&&o.push({job:a,ageMs:p,stillMs:c})}n.sort((a,d)=>d.stillMs-a.stillMs);for(let{job:a,stillMs:d,done:c,total:u}of n){let l=rf(Math.floor(d/6e4));r.push({type:"stuck",severity:"critical",title:`${a.jobType} ${a.id}: no batch completed in ${l}`,detail:`${c} of ${u} batches processed, unchanged across ${l} of observation by this dashboard while ${a.status} (stall bound ${hi/6e4}m).`,affectedJobs:[a.id],recommendation:"Check the job in Setup > Apex Jobs first. If it is still at the same batch, abort it and re-run it once the cause is known."})}let i=new Map;for(let a of s){if(a.status==="Aborted"||a.status!=="Failed"&&a.failedRecords<=0)continue;let d=i.get(a.jobType)??[];d.push(a),i.set(a.jobType,d)}for(let[a,d]of i){if(d.length<qO)continue;let c=d.reduce((u,l)=>u+(l.failedRecords||0),0);r.push({type:"frequent_failures",severity:"critical",title:`${d.length} ${a} jobs failed`,detail:`${d.length} of the last ${s.length} jobs are ${a} failures (${c} failed batch execution(s) reported) \u2014 at or above the ${qO}-failure pattern threshold.`,affectedJobs:d.map(u=>u.id),recommendation:`Open the most recent ${a} failure and read its extended status: a repeat at this rate is a defect or a data problem, not contention.`})}if(o.length>0){o.sort((p,f)=>f.ageMs-p.ageMs);let a=o[0],d=rf(Math.floor(a.ageMs/6e4)),{batchesProcessed:c,totalBatches:u}=a.job,l=c===null||u===null||u<=0?"it reports no batch counter, so its progress cannot be observed":a.stillMs===null||a.stillMs<6e4?`${c} of ${u} batches processed, first seen at these values on this refresh`:`${c} of ${u} batches processed, unchanged over the ${rf(Math.floor(a.stillMs/6e4))} watched so far`;r.push({type:"long_running",severity:"warning",title:o.length===1?`1 job unfinished ${d} after submission`:`${o.length} jobs unfinished ${BO/6e4}m or more after submission`,detail:`${a.job.jobType} ${a.job.id} is ${a.job.status}, submitted ${d} ago; ${l}. Time since submission includes time spent queued: it is not evidence of a stall.`,affectedJobs:o.map(({job:p})=>p.id),recommendation:`Keep this dashboard refreshing to measure progress, or check the job in Setup > Apex Jobs. A batch is called stuck only once its batch counter stays unchanged for ${hi/6e4}m of watching; a job without batch counters never is.`})}return r}var dx=new Set(["monitor:refresh","monitor:open-apex-jobs","monitor:live-operations","monitor:storage","monitor:deployments","monitor:api-usage","monitor:error-logs","monitor:sessions","monitor:apex-insights","monitor:sandbox-refresh","monitor:alerts","monitor:alert:acknowledge","monitor:alert:dismiss"]),Yd=class{constructor(e,t){this.deps=e;this.externalBrowser=t??new jn;let r=_O({configStore:e.configStore,log:n=>e.log(n),notify:(n,o)=>Ae(e,n,"Alert",o),getConnection:async(n,o)=>(o?.again===!0&&Po().remove(n),this.withSharedJobQuery(n,await B(n,e.orgRegistry,e.orgManager))),onSandboxRefreshCompleted:n=>{e.sandboxRefreshes?.noteCompletedRefresh(n)}});this.trendStorage=r.trendStorage,this.forgetServicesOrg=r.forgetOrg,this.alertStateStore=r.alertStateStore,this.alertEngine=r.alertEngine,this.errorLogMonitor=r.errorLogMonitor,this.userSessionMonitor=r.userSessionMonitor,this.apexLogAnalyzer=r.apexLogAnalyzer,this.sandboxRefreshTracker=r.sandboxRefreshTracker,this.healthCheck=r.healthCheck,this.healthSignals=r.healthSignals,this.getOrFetchLimits=r.getOrFetchLimits}deps;trendStorage;orgInfoFetcher=new Ud;healthCalculator=new _d;liveOperationTracker;getOrFetchLimits;forgetServicesOrg;errorLogMonitor;userSessionMonitor;apexLogAnalyzer;sandboxRefreshTracker;healthCheck;healthSignals;alertEngine;alertStateStore;inFlightJobRecords=new Map;jobProgress=new Map;externalBrowser;setLiveOperationTracker(e){this.liveOperationTracker=e,e.onChange(this.onLiveOperationsChange)}onLiveOperationsChange=()=>this.pushLiveOperationsSoon();livePush;dispose(){this.livePush!==void 0&&(clearTimeout(this.livePush),this.livePush=void 0),this.liveOperationTracker?.offChange(this.onLiveOperationsChange)}pushLiveOperationsSoon(){this.livePush===void 0&&(this.livePush=setTimeout(()=>{this.livePush=void 0;let e={id:this.deps.nextId(),type:"monitor:live-operations:changed",timestamp:Date.now(),payload:{operations:(this.liveOperationTracker?.getAll()??[]).map(t=>({...t}))}};this.deps.broker.postToWebview(e)},ex),this.livePush.unref?.())}async readOrgHealth(e,t){let r=[];for(let n of t)r.push(await this.healthSignals[n](e));return r}getAlertEngine(){return this.alertEngine}forgetOrg(e){this.forgetServicesOrg(e),this.orgInfoFetcher.clearCache(e),this.jobProgress.delete(e),this.trendStorage.purge(e)}async handle(e){if(!dx.has(e.type))return!1;switch(e.type){case"monitor:refresh":return await this.handleRefresh(e),!0;case"monitor:open-apex-jobs":return await this.handleOpenApexJobs(e),!0;case"monitor:live-operations":return this.handleLiveOperations(e),!0;case"monitor:storage":return await this.handleStorage(e),!0;case"monitor:deployments":return await this.handleDeployments(e),!0;case"monitor:api-usage":return await this.handleApiUsage(e),!0;case"monitor:error-logs":return await this.handleErrorLogs(e),!0;case"monitor:sessions":return await this.handleSessions(e),!0;case"monitor:apex-insights":return await this.handleApexInsights(e),!0;case"monitor:sandbox-refresh":return await this.handleSandboxRefresh(e),!0;case"monitor:alerts":return this.handleAlerts(e),!0;case"monitor:alert:acknowledge":return this.handleAlertAcknowledge(e),!0;case"monitor:alert:dismiss":return this.handleAlertDismiss(e),!0;default:return!1}}withSharedJobQuery(e,t){return new Proxy(t,{get:(r,n)=>{if(n==="query")return i=>{let a=this.inFlightJobRecords.get(e);return a!==void 0&&rx.has(i)?Promise.resolve({done:!0,totalSize:a.length,records:a}):r.query(i)};let o=Reflect.get(r,n,r);return typeof o=="function"?o.bind(r):o}})}pastDeadline(e,t){return e.aborted?(this.deps.log(`[WARN] monitor:refresh outlived its ${UO}ms bound; skipping ${t}`),!0):!1}async handleRefresh(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Yr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{await new pe(UO).withTimeout("monitor:refresh",n=>this.executeRefresh(e,r,n))}catch(n){T(this.deps,"monitor:refresh","monitor:error",e,n)}}async executeRefresh(e,t,r){try{let n=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager),[o,i]=await Promise.allSettled([this.getOrFetchLimits(t.orgId,n),Ft(n,WO)]);if(o.status==="rejected")throw o.reason;let a=PO(o.value);$e(n.limitInfo,"monitor:refresh limits");let d=[];for(let R of a){let w=this.alertEngine.evaluate(R.name,R.usedPercent,t.orgId);w&&d.push(w)}if(this.alertStateStore.saveAlerts(this.alertEngine.getActiveAlerts()),d.length>0&&this.alertStateStore.saveHistory(d),i.status==="rejected")throw i.reason;let c=i.value;if($e(n.limitInfo,"monitor:refresh asyncJobs"),this.inFlightJobRecords.set(t.orgId,c),this.pastDeadline(r,"org info and health check"))return;let u=Date.now(),l=c.map(R=>({id:R.Id,jobType:R.JobType??"Unknown",status:R.Status,createdBy:R.CreatedById,createdDate:R.CreatedDate,failedRecords:R.NumberOfErrors,batchesProcessed:R.JobItemsProcessed??null,totalBatches:R.TotalJobItems??null})),p=c.length>=mn.monitorJobs,f=l.map(({id:R,jobType:w,status:P,createdBy:O,createdDate:E,failedRecords:$})=>({id:R,jobType:w,status:P,createdBy:O,createdDate:E,failedRecords:$})),g=ix(this.jobProgress.get(t.orgId),l,u);this.jobProgress.set(t.orgId,g);let h=ax(l,g,u),m={orgId:t.orgId,limits:a,timestamp:new Date().toISOString()},y=this.trendStorage.recordAndGetTrends(t.orgId,m,Gi),[v,b]=await Promise.all([this.fetchOrgInfo(t.orgId,n),this.computeOrgHealth(t.orgId)]);v&&this.deps.sandboxRefreshes?.observe(t.orgId,{organizationId:v.orgId,instanceName:v.instanceName||void 0},"monitor");let k=this.healthCalculator.calculate({limits:a,orgId:t.orgId,trends:y,orgInfo:v}),S=k.overallScore;if(this.pastDeadline(r,"the monitor:data reply"))return;let C=A(this.deps,e,"monitor:data",{limits:a,jobs:f,jobsTruncated:p,healthScore:S,healthReport:k,trends:y,jobInsights:h,orgInfo:v,orgHealthStatus:b,lastUpdated:new Date().toISOString()});this.deps.broker.postToWebview(C),this.deps.log(`[TX] ${C.type} id=${C.id}`)}catch(n){if(this.pastDeadline(r,`the failure "${I(n)}"`))return;T(this.deps,"monitor:refresh","monitor:error",e,n)}finally{this.inFlightJobRecords.delete(t.orgId)}}async computeOrgHealth(e){try{return await this.healthCheck.computeHealth(e)}catch(t){this.deps.log(`[WARN] HealthCheck failed: ${String(t)}`);return}}async fetchOrgInfo(e,t){try{let r={latestApiVersion:async()=>EO(await t.request("/services/data")),queryOrg:async()=>{let n=this.deps.orgManager.getOrg(e),o=await Ft(t,"SELECT Name, Id, OrganizationType, InstanceName, NamespacePrefix, CreatedDate FROM Organization LIMIT 1");$e(t.limitInfo,"monitor:refresh orgInfo");let i=o[0];return{name:i?.Name??n?.alias??"",orgId:i?.Id??e,type:n?.orgType??"Production",edition:i?.OrganizationType??n?.metadata.edition??"",instanceName:i?.InstanceName??"",namespacePrefix:i?.NamespacePrefix,createdDate:i?.CreatedDate}},queryCount:async n=>(await t.query(n)).totalSize};return await this.orgInfoFetcher.fetch(e,r)}catch(r){this.deps.log(`[WARN] OrgInfo fetch failed: ${String(r)}`);return}}handleLiveOperations(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.liveOperationTracker?.getAll()??[],r=A(this.deps,e,"monitor:live-operations:response",{operations:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id}`)}async handleStorage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Yr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await B(r.orgId,this.deps.orgRegistry,this.deps.orgManager),o=await n.request(`/services/data/${Oo}/limits/recordCount`);$e(n.limitInfo,"monitor:storage recordCount");let i=(o.sObjects??[]).filter(f=>f.count>0).sort((f,g)=>g.count-f.count),a=i.slice(0,Z$),d=a.map(f=>f.name).filter(f=>/^[A-Za-z][A-Za-z0-9_]*$/.test(f)),c=new Map;if(d.length>0){let f=await Ft(n,`SELECT QualifiedApiName, Label FROM EntityDefinition WHERE QualifiedApiName IN (${d.map(g=>`'${g}'`).join(", ")})`);$e(n.limitInfo,"monitor:storage entityDefinition");for(let g of f)g.Label&&c.set(g.QualifiedApiName,g.Label)}let u=a.map(f=>({objectName:f.name,label:c.get(f.name)??f.name,recordCount:f.count})),l=i.reduce((f,g)=>f+g.count,0),p=A(this.deps,e,"monitor:storage:response",{success:!0,objects:u,totalRecords:l,objectCount:i.length});this.deps.broker.postToWebview(p),this.deps.log(`[TX] ${p.type} id=${p.id}`)}catch(n){T(this.deps,"monitor:storage","monitor:error",e,n)}}async handleDeployments(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Yr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await B(r.orgId,this.deps.orgRegistry,this.deps.orgManager),i=(await n.tooling.query(`SELECT Id, Status, StartDate, CompletedDate, CreatedBy.Name, NumberComponentsTotal, NumberComponentErrors FROM DeployRequest ORDER BY StartDate DESC LIMIT ${HO}`)).records;$e(n.limitInfo,"monitor:deployments deployRequest");let a=i.map(c=>({id:c.Id,status:c.Status,startDate:c.StartDate,completedDate:c.CompletedDate??void 0,createdBy:c.CreatedBy?.Name??"Unknown",componentCount:c.NumberComponentsTotal??0,errorCount:c.NumberComponentErrors??0})),d=A(this.deps,e,"monitor:deployments:response",{success:!0,deployments:a,truncated:i.length>=HO});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(n){T(this.deps,"monitor:deployments","monitor:error",e,n)}}async handleApiUsage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Yr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await B(r.orgId,this.deps.orgRegistry,this.deps.orgManager),o=await this.getOrFetchLimits(r.orgId,n);$e(n.limitInfo,"monitor:api-usage limits");let i=["DailyApiRequests","DailyBulkApiBatches","DailyBulkV2QueryJobs","DailyBulkV2QueryFileStorageMB","DailyStreamingApiEvents","DailyGenericStreamingApiEvents","DailyDurableStreamingApiEvents","DailyAsyncApexExecutions","HourlyAsyncReportRuns","HourlyTimeBasedWorkflow","DailyWorkflowEmails","MassEmail","SingleEmail","HourlyPublishedPlatformEvents","DailyStandardVolumePlatformEvents"],a=[];for(let c of i){let u=o[c];if(u&&typeof u.Max=="number"){let l=u.Max-u.Remaining,p=u.Max>0?Math.round(l/u.Max*100):0;a.push({category:c,used:l,max:u.Max,usedPercent:p})}}a.sort((c,u)=>u.usedPercent-c.usedPercent);let d=A(this.deps,e,"monitor:api-usage:response",{success:!0,categories:a});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(n){T(this.deps,"monitor:api-usage","monitor:error",e,n)}}async handleOpenApexJobs(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Dy,e,"monitor:error",this.deps);if(!t)return;let r=this.deps.orgManager.getOrg(t.orgId);if(!r){T(this.deps,"monitor:open-apex-jobs","monitor:error",e,new Error(`No registered org has the id "${t.orgId}".`),{code:"ORG_NOT_FOUND"});return}let n=ok(r.instanceUrl);if(!n.ok){let o=n.reason==="not-https"?`its instance URL must use HTTPS, got "${n.protocol}"`:"its instance URL is not a valid URL";T(this.deps,"monitor:open-apex-jobs","monitor:error",e,new Error(`Cannot open Apex Jobs for "${we(r)}": ${o}.`),{code:"INVALID_INSTANCE_URL"});return}try{let o=await this.externalBrowser.open(n.url),i=A(this.deps,e,"monitor:open-apex-jobs:response",o);this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} status=${o.status}`)}catch(o){T(this.deps,"monitor:open-apex-jobs","monitor:error",e,o)}}async handleErrorLogs(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Yr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await this.errorLogMonitor.fetch(r.orgId),i=[...this.errorLogMonitor.getErrorsByType(r.orgId).entries()].map(([d,c])=>({type:d,count:c})),a=A(this.deps,e,"monitor:error-logs:response",{success:!0,errors:n,errorsByType:i,totalCount:n.length,truncated:this.errorLogMonitor.isTruncated(r.orgId)});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id}`)}catch(n){T(this.deps,"monitor:error-logs","monitor:error",e,n)}}async handleSessions(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Yr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await this.userSessionMonitor.fetch(r.orgId),o=this.userSessionMonitor.getActiveUserCount(r.orgId),i=A(this.deps,e,"monitor:sessions:response",{success:!0,sessions:n,activeUserCount:o,truncated:this.userSessionMonitor.isTruncated(r.orgId)});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(n){T(this.deps,"monitor:sessions","monitor:error",e,n)}}async handleApexInsights(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Yr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await this.apexLogAnalyzer.fetchAndAnalyze(r.orgId,Q$),o=this.apexLogAnalyzer.getTopIssues(r.orgId),i=A(this.deps,e,"monitor:apex-insights:response",{success:!0,analyses:n,topIssues:o,truncated:this.apexLogAnalyzer.isTruncated(r.orgId)});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(n){T(this.deps,"monitor:apex-insights","monitor:error",e,n)}}async checkSandboxIdentity(e){let t=this.deps.sandboxRefreshes;if(!(!t||this.deps.orgManager.getOrg(e)?.orgType!=="Sandbox"))try{let r=await B(e,this.deps.orgRegistry,this.deps.orgManager),[n]=await Ft(r,"SELECT Id, InstanceName FROM Organization");$e(r.limitInfo,"monitor:sandbox-refresh organization"),n&&t.observe(e,{organizationId:n.Id,instanceName:n.InstanceName??void 0},"monitor")}catch(r){this.deps.log(`[WARN] monitor:sandbox-refresh identity check: ${I(r)}`)}}async handleSandboxRefresh(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Yr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{await this.checkSandboxIdentity(r.orgId);let n=await this.sandboxRefreshTracker.fetch(r.orgId),o=this.sandboxRefreshTracker.isRefreshInProgress(r.orgId),i=A(this.deps,e,"monitor:sandbox-refresh:response",{success:!0,supported:this.sandboxRefreshTracker.isSupported(r.orgId),refreshes:n,inProgress:o,truncated:this.sandboxRefreshTracker.isTruncated(r.orgId),detected:this.deps.sandboxRefreshes?.refreshesOf(r.orgId)??[]});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(n){T(this.deps,"monitor:sandbox-refresh","monitor:error",e,n)}}handleAlerts(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.alertEngine.getActiveAlerts(),r=this.alertStateStore.loadHistory(),n=A(this.deps,e,"monitor:alerts:result",{alerts:t,history:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleAlertAcknowledge(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Tl,e,"monitor:error",this.deps);if(!t)return;let r=t;this.alertEngine.acknowledgeAlert(r.alertId),this.alertStateStore.saveAlerts(this.alertEngine.getActiveAlerts());let n=A(this.deps,e,"monitor:alert:acknowledge:response",{success:!0});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleAlertDismiss(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Tl,e,"monitor:error",this.deps);if(!t)return;let r=t;this.alertEngine.dismissAlert(r.alertId),this.alertStateStore.saveAlerts(this.alertEngine.getActiveAlerts());let n=A(this.deps,e,"monitor:alert:dismiss:response",{success:!0});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}};var nf="seed:template:",zO="seedTemplates",dn=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${nf}${e.id}`,e,zO)}load(e){return this.configStore.get(`${nf}${e}`)}list(){let e=this.configStore.getByCategory(zO);return Object.values(e).sort((r,n)=>n.updatedAt.localeCompare(r.updatedAt))}delete(e){return this.configStore.delete(`${nf}${e}`)}};var Qd=class{templates=new Map;generateId;now;store;constructor(e,t,r){this.generateId=e,this.now=t,this.store=r}create(e){let t=this.now(),r={...e,id:this.generateId(),createdAt:t,updatedAt:t};return this.templates.set(r.id,r),this.store?.save(r),r}get(e){let t=this.templates.get(e);if(t)return t;if(this.store){let r=this.store.load(e);return r&&this.templates.set(e,r),r}}list(){return Array.from(this.templates.values()).sort((e,t)=>t.updatedAt.localeCompare(e.updatedAt))}update(e,t){let r=this.templates.get(e);if(!r)throw new Error(`Template not found: ${e}`);let n={...r,...t,id:r.id,createdAt:r.createdAt,updatedAt:this.now()};return this.templates.set(e,n),this.store?.save(n),n}delete(e){let t=this.templates.delete(e);return this.store&&this.store.delete(e)||t}duplicate(e,t){let r=this.templates.get(e);if(!r)throw new Error(`Template not found: ${e}`);let n=this.now(),o={...r,id:this.generateId(),name:t,version:1,createdAt:n,updatedAt:n};return this.templates.set(o.id,o),this.store?.save(o),o}};var GO=[{id:"assureur-fr",name:"Assureur fran\xE7ais",description:"Compagnie d'assurance fran\xE7aise avec contrats, sinistres et assur\xE9s.",industry:"Insurance",locale:"fr-FR",dataPatterns:{Name:{fieldType:"string",generator:"faker",params:{method:"company.name",locale:"fr"},examples:["AXA Pr\xE9voyance","Mutuelle du Soleil","Groupe Assurancia"]},FirstName:{fieldType:"string",generator:"faker",params:{method:"person.firstName",locale:"fr"},examples:["Jean","Marie","Philippe"]},LastName:{fieldType:"string",generator:"faker",params:{method:"person.lastName",locale:"fr"},examples:["Dupont","Martin","Lefebvre"]},SIRET__c:{fieldType:"string",generator:"pattern",params:{pattern:"###########00##"},examples:["12345678900012","98765432100034","55566677800015"]},Contract_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Auto","Habitation","Sant\xE9","Vie","Responsabilit\xE9 Civile"]},examples:["Auto","Habitation","Sant\xE9"]},Premium__c:{fieldType:"currency",generator:"range",params:{min:200,max:5e3,currency:"EUR"},examples:["450.00","1200.50","3200.00"]}}},{id:"hospital-us",name:"H\xF4pital am\xE9ricain",description:"Hospital system with patients, procedures, and medical codes.",industry:"Healthcare",locale:"en-US",dataPatterns:{FirstName:{fieldType:"string",generator:"faker",params:{method:"person.firstName",locale:"en_US"},examples:["James","Sarah","Michael"]},LastName:{fieldType:"string",generator:"faker",params:{method:"person.lastName",locale:"en_US"},examples:["Johnson","Williams","Smith"]},MRN__c:{fieldType:"string",generator:"sequence",params:{prefix:"MRN-",padLength:8},examples:["MRN-00000001","MRN-00000002","MRN-00000003"]},ICD10_Code__c:{fieldType:"string",generator:"random_pick",params:{values:["J06.9","I10","E11.9","M54.5","J18.9","K21.0","N39.0"]},examples:["J06.9","I10","E11.9"]},CPT_Code__c:{fieldType:"string",generator:"random_pick",params:{values:["99213","99214","99215","99203","99204","36415","71046"]},examples:["99213","99214","36415"]},Insurance_Provider__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Blue Cross","Aetna","UnitedHealth","Cigna","Medicare","Medicaid"]},examples:["Blue Cross","Aetna","Medicare"]}}},{id:"ecommerce-b2c",name:"E-commerce B2C",description:"Online retail with products, orders, customers, and reviews.",industry:"Retail",locale:"en-US",dataPatterns:{Product_Name__c:{fieldType:"string",generator:"faker",params:{method:"commerce.productName"},examples:["Ergonomic Steel Chair","Wireless Bluetooth Headphones","Organic Cotton T-Shirt"]},SKU__c:{fieldType:"string",generator:"sequence",params:{prefix:"SKU-",padLength:6},examples:["SKU-000001","SKU-000002","SKU-000003"]},Price__c:{fieldType:"currency",generator:"range",params:{min:9.99,max:999.99,currency:"USD"},examples:["29.99","149.50","499.00"]},Order_Status__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Pending","Processing","Shipped","Delivered","Returned","Cancelled"]},examples:["Pending","Shipped","Delivered"]},Rating__c:{fieldType:"number",generator:"range",params:{min:1,max:5},examples:["4","5","3"]},Review_Text__c:{fieldType:"textarea",generator:"ai_generate",params:{prompt:"Product review, 1-3 sentences, realistic tone"},examples:["Great product, fast shipping!","Good quality but runs small.","Exactly as described."]}}},{id:"banque-eu",name:"Banque europ\xE9enne",description:"European bank with accounts, transactions, IBAN/BIC codes.",industry:"Banking",locale:"fr-FR",dataPatterns:{IBAN__c:{fieldType:"string",generator:"faker",params:{method:"finance.iban",locale:"fr"},examples:["FR7630006000011234567890189","DE89370400440532013000","ES9121000418450200051332"]},BIC__c:{fieldType:"string",generator:"faker",params:{method:"finance.bic"},examples:["BNPAFRPPXXX","DEUTDEFFXXX","BBVAESMMXXX"]},Transaction_Amount__c:{fieldType:"currency",generator:"range",params:{min:-1e4,max:5e4,currency:"EUR"},examples:["1250.00","-450.75","15000.00"]},Transaction_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Virement","Pr\xE9l\xE8vement","Carte","Ch\xE8que","Esp\xE8ces"]},examples:["Virement","Carte","Pr\xE9l\xE8vement"]},Account_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Courant","\xC9pargne","PEL","Titre","Professionnel"]},examples:["Courant","\xC9pargne","PEL"]},Risk_Score__c:{fieldType:"number",generator:"range",params:{min:0,max:100},examples:["15","42","78"]}}},{id:"startup-saas",name:"Startup SaaS",description:"SaaS company with subscriptions, MRR metrics, churn tracking.",industry:"Technology",locale:"en-US",dataPatterns:{Company_Name__c:{fieldType:"string",generator:"faker",params:{method:"company.name"},examples:["Acme Cloud","DataSync Pro","NeuralFlow AI"]},Plan__c:{fieldType:"picklist",generator:"weighted_pick",params:{values:{Free:.4,Starter:.25,Pro:.2,Enterprise:.15}},examples:["Free","Pro","Enterprise"]},MRR__c:{fieldType:"currency",generator:"range",params:{min:0,max:25e3,currency:"USD"},examples:["0.00","499.00","12500.00"]},Churn_Risk__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Low","Medium","High","Critical"]},examples:["Low","Medium","High"]},Active_Users__c:{fieldType:"number",generator:"range",params:{min:1,max:500},examples:["12","85","250"]},NPS_Score__c:{fieldType:"number",generator:"range",params:{min:-100,max:100},examples:["72","-15","45"]}}},{id:"immobilier",name:"Immobilier",description:"Agence immobili\xE8re avec biens, mandats et visites.",industry:"Real Estate",locale:"fr-FR",dataPatterns:{Property_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Appartement","Maison","Studio","Loft","Terrain","Local commercial"]},examples:["Appartement","Maison","Studio"]},Surface__c:{fieldType:"number",generator:"range",params:{min:15,max:300,unit:"m\xB2"},examples:["45","120","85"]},Price__c:{fieldType:"currency",generator:"range",params:{min:5e4,max:2e6,currency:"EUR"},examples:["185000","450000","1200000"]},City__c:{fieldType:"string",generator:"random_pick",params:{values:["Paris","Lyon","Marseille","Bordeaux","Toulouse","Nantes","Lille"]},examples:["Paris","Lyon","Bordeaux"]},Mandate_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Exclusif","Simple","Semi-exclusif"]},examples:["Exclusif","Simple","Semi-exclusif"]},DPE__c:{fieldType:"picklist",generator:"weighted_pick",params:{values:{A:.05,B:.1,C:.2,D:.3,E:.2,F:.1,G:.05}},examples:["C","D","B"]}}},{id:"education",name:"\xC9ducation",description:"Educational institution with students, courses, and grades.",industry:"Education",locale:"fr-FR",dataPatterns:{Student_ID__c:{fieldType:"string",generator:"sequence",params:{prefix:"STU-",padLength:6},examples:["STU-000001","STU-000002","STU-000003"]},FirstName:{fieldType:"string",generator:"faker",params:{method:"person.firstName",locale:"fr"},examples:["L\xE9a","Hugo","Emma"]},LastName:{fieldType:"string",generator:"faker",params:{method:"person.lastName",locale:"fr"},examples:["Bernard","Petit","Robert"]},Course_Name__c:{fieldType:"string",generator:"random_pick",params:{values:["Math\xE9matiques","Physique","Histoire","Anglais","Informatique","Philosophie"]},examples:["Math\xE9matiques","Physique","Informatique"]},Grade__c:{fieldType:"number",generator:"range",params:{min:0,max:20,precision:1},examples:["14.5","8.0","17.5"]},Semester__c:{fieldType:"picklist",generator:"random_pick",params:{values:["S1","S2","S3","S4","S5","S6"]},examples:["S1","S2","S3"]}}},{id:"logistique",name:"Logistique",description:"Logistics company with parcels, warehouses, and shipment tracking.",industry:"Logistics",locale:"fr-FR",dataPatterns:{Tracking_Number__c:{fieldType:"string",generator:"sequence",params:{prefix:"TRK-",padLength:10},examples:["TRK-0000000001","TRK-0000000002","TRK-0000000003"]},Status__c:{fieldType:"picklist",generator:"random_pick",params:{values:["En pr\xE9paration","Exp\xE9di\xE9","En transit","En livraison","Livr\xE9","Retourn\xE9"]},examples:["Exp\xE9di\xE9","En transit","Livr\xE9"]},Weight__c:{fieldType:"number",generator:"range",params:{min:.1,max:500,unit:"kg"},examples:["2.5","15.0","125.0"]},Warehouse__c:{fieldType:"string",generator:"random_pick",params:{values:["Paris-Nord","Lyon-Est","Marseille-Port","Bordeaux-Sud","Lille-Centre"]},examples:["Paris-Nord","Lyon-Est","Marseille-Port"]},Carrier__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Colissimo","Chronopost","DHL","FedEx","UPS","GLS"]},examples:["Colissimo","Chronopost","DHL"]},Delivery_Date__c:{fieldType:"date",generator:"relative_date",params:{minDaysFromNow:1,maxDaysFromNow:14},examples:["2026-03-01","2026-03-05","2026-03-12"]}}},{id:"rh",name:"Ressources humaines",description:"HR department with employees, leaves, payroll, and performance.",industry:"Human Resources",locale:"fr-FR",dataPatterns:{Employee_ID__c:{fieldType:"string",generator:"sequence",params:{prefix:"EMP-",padLength:5},examples:["EMP-00001","EMP-00002","EMP-00003"]},Department__c:{fieldType:"picklist",generator:"random_pick",params:{values:["R&D","Marketing","Ventes","RH","Finance","Support","Direction"]},examples:["R&D","Marketing","Finance"]},Contract_Type__c:{fieldType:"picklist",generator:"weighted_pick",params:{values:{CDI:.6,CDD:.2,Stage:.1,Alternance:.1}},examples:["CDI","CDD","Stage"]},Salary__c:{fieldType:"currency",generator:"range",params:{min:25e3,max:12e4,currency:"EUR"},examples:["35000","55000","85000"]},Leave_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Cong\xE9s pay\xE9s","RTT","Maladie","Sans solde","Maternit\xE9","Formation"]},examples:["Cong\xE9s pay\xE9s","RTT","Maladie"]},Leave_Days__c:{fieldType:"number",generator:"range",params:{min:.5,max:25},examples:["1","5","12"]}}},{id:"ong",name:"ONG/Association",description:"Non-profit organization with donors, campaigns, and volunteers.",industry:"Non-Profit",locale:"fr-FR",dataPatterns:{Donor_Type__c:{fieldType:"picklist",generator:"weighted_pick",params:{values:{Particulier:.7,Entreprise:.2,Fondation:.1}},examples:["Particulier","Entreprise","Fondation"]},Donation_Amount__c:{fieldType:"currency",generator:"range",params:{min:5,max:5e4,currency:"EUR"},examples:["25.00","150.00","5000.00"]},Campaign_Name__c:{fieldType:"string",generator:"ai_generate",params:{prompt:"Charity campaign name, inspiring and concise"},examples:["Solidarit\xE9 Hiver 2026","Course pour la Vie","Un Toit Pour Tous"]},Volunteer_Status__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Actif","Inactif","En formation","Suspendu"]},examples:["Actif","En formation","Inactif"]},Hours_Volunteered__c:{fieldType:"number",generator:"range",params:{min:1,max:200},examples:["8","40","120"]},Tax_Receipt__c:{fieldType:"boolean",generator:"weighted_pick",params:{values:{true:.8,false:.2}},examples:["true","false","true"]}}}],Zd=class{customPersonas=new Map;customCounter=0;getBuiltInPersonas(){return[...GO]}getPersona(e){let t=GO.find(r=>r.id===e);return t||this.customPersonas.get(e)}async createCustomPersona(e,t){let r=ux(e),n=await t(r),o=px(n);this.customCounter+=1;let i=`custom-${Date.now()}-${this.customCounter}`,a={id:i,name:o.name,description:o.description,industry:o.industry,locale:o.locale,dataPatterns:o.dataPatterns};return this.customPersonas.set(i,a),a}getCustomPersonas(){return Array.from(this.customPersonas.values())}},JO=vg(s=>typeof s=="string"&&s.trim().length>0?Number(s):s,Te().finite()),lo=JO.optional().catch(void 0),of=L().min(1).optional().catch(void 0),sf={faker:K({method:L().transform((s,e)=>{let t=Kg(s);return t||(e.addIssue({code:Sg.custom,message:`unknown faker method ${s}`}),bg)}),locale:of}),random_pick:K({values:Re(Rg([L(),Te(),Ve()]).transform(String)).min(1)}),weighted_pick:K({values:Bi(L(),JO).refine(s=>Object.keys(s).length>0)}),range:K({min:lo,max:lo,currency:of}),sequence:K({prefix:of,start:lo,step:lo,padLength:lo}),pattern:K({pattern:L().min(1)}),ai_generate:K({prompt:L().min(1)}),relative_date:K({minDaysFromNow:lo,maxDaysFromNow:lo})},cx={faker:'{ "method": one of the faker methods below, "locale" (optional): e.g. "fr_FR" }',random_pick:'{ "values": ["value1", "value2"] }',weighted_pick:'{ "values": { "value1": 0.7, "value2": 0.3 } }',range:'{ "min": number, "max": number, "currency" (optional): e.g. "EUR" }',sequence:'{ "prefix": "INV-", "start" (optional): integer, "step" (optional): integer }',pattern:'{ "pattern": a mask where # stands for a digit, e.g. "FR-#####" }',ai_generate:'{ "prompt": what to write in the field }, only on string and textarea fields',relative_date:'{ "minDaysFromNow": integer, "maxDaysFromNow": integer, negative for the past }'};function ux(s){let e=Object.keys(sf);return["You are a data generation expert. Based on the following description, create a data generation persona for Salesforce.","",`Description: ${s}`,"","Respond with ONLY a JSON object in this exact format (no markdown, no extra text):","{",' "name": "Persona name",',' "description": "Brief description",',' "industry": "Industry name",',' "locale": "locale code (e.g. en-US, fr-FR)",',' "dataPatterns": {',' "FieldApiName": {',' "fieldType": "string|number|picklist|currency|date|boolean|textarea",',` "generator": "${e.join("|")}",`,' "params": the params of that generator, listed below,',' "examples": ["example1", "example2", "example3"]'," }"," }","}","","Params of each generator:",...e.map(r=>`- ${r}: ${cx[r]}`),"",`Faker methods: ${Xg.join(", ")}.`,"A pattern that uses another generator, another faker method or other params is discarded.","","Include at least 5 relevant field patterns for the described industry."].join(`
16
+ `)}function lx(s){let e=s.generator;if(typeof e!="string"||!Object.hasOwn(sf,e))return null;let r=sf[e].safeParse(s.params??{});if(!r.success)return null;let n=typeof s.fieldType=="string"?s.fieldType:"string";return e==="ai_generate"&&!qg(n)?null:{fieldType:n,generator:e,params:r.data,examples:Array.isArray(s.examples)?s.examples.filter(o=>typeof o=="string"):[]}}function px(s){let e;try{e=Lg(Fg,s)}catch{throw new Error("AI response is not a valid JSON object. The AI model returned an unexpected format \u2014 try again or check the AI provider configuration.")}let t={};for(let[a,d]of Object.entries(e.dataPatterns))if(typeof d=="object"&&d!==null){let c=lx(d);c&&(t[a]=c)}let{name:r,description:n,industry:o,locale:i}=e;return{name:r,description:n,industry:o,locale:i,dataPatterns:t}}var ds="SEED_WRITE_DECLINED",VO=6e4;function cn(s){let e=s?.read.gate.audit;return e===void 0?{}:{details:{deliverability:e,...s?.accepted===!0?{confirmed:"emails"}:{}}}}var ZO="the checkpoints of this window are not open to the Seed page",Xt=class extends Error{constructor(t,r,n){super(r);this.code=t;this.refusal=n;this.name="SeedCheckpointStopped"}code;refusal};async function mi(s,e){try{if(!s)throw new Error(ZO);return{ask:e,planned:await s.scope(e,{})}}catch(t){throw new Xt(Cn,Rr(t))}}async function yi(s,e,t,r,n){let o=await Xa(async()=>{if(!s)throw new Error(ZO);return s.take(e.ask,{runId:t},{planned:e.planned,signal:r,onProgress:({percentage:i,processedObjects:a,totalObjects:d})=>n(Math.round(i),a,d,_o(i))})});if("stop"in o)throw new Xt(o.stop.code,o.stop.message,o.stop.refusal);return o.checkpoint}async function Ln(s,e,t,r,n){if(!(!e||!s))try{return await s.settle(e,t)}catch(o){return r(`[WARN] ${n}: the checkpoint '${e.name}' taken before the run is kept: `+I(o)),e}}function wi(s,e){let t=new Set(s);return(r,n)=>t.has(r)&&(n==="insert"||e&&n==="update")}function rc(s,e){return typeof s.unread=="string"?{firing:[]}:gr(s,void 0,e)}function XO(s,e,t){return t==="refuse"?{code:kt.unanswered,message:`The seed needed an answer before it wrote \u2014 ${e} delivers the emails what still runs sends, or would not say whether it does \u2014 and no Approval step before it approved the run: put one before it. Nothing was written.`}:{code:BR,message:s.gate.stop?.message??"The seed was refused for its emails. Nothing was written."}}var fx={ask:(s,e)=>s.confirmRun(e),unanswered:"goOn"};function gx(s,e){let t=[];return s.check.verdict==="unread"&&t.push(`the data storage ${e} has left could not be read (${s.check.unread})`),s.api.verdict==="near"&&t.push(`it would leave ${e} ${s.api.remaining-s.api.estimate} of its ${s.api.max} daily API requests`),t.join(", and ")}function KO(s,e){return`The seed needed an answer before it wrote \u2014 ${gx(s,e)} \u2014 and no Approval step before it approved the run: put one before it. Nothing was written.`}function YO(s,e,t){if(xs(s))return t(`[OFFLINE] seed NOT queued for replay (inserts are not idempotent): ${e}`),{offlineReplayAvailable:!1,retryHint:"Seed operations are not queued for offline replay (inserts are not idempotent \u2014 replaying could duplicate records). Re-run the template manually once the org is reachable again."}}var ec=1e3;function hx(s){return Array.isArray(s.objectResults)?{...s,objectResults:s.objectResults.map(e=>{let t=e.createdIds.length>ec||e.errors.length>ec;return t?{...e,createdIds:e.createdIds.slice(0,ec),errors:e.errors.slice(0,ec),truncated:t}:e})}:s}function QO(s){return{query:async e=>s.tooling.query(e),queryMore:async e=>s.tooling.queryMore(e)}}function mx(s){return s.objectResults.flatMap(t=>t.errors)[0]??"The seed wrote no records."}var yx=new Set(["seed:execute","seed:automation","seed:describe-global","seed:describe-object","seed:template:save","seed:template:load","seed:template:list","seed:template:delete","seed:list-personas","seed:create-persona","seed:scenario:packs","seed:scenario:prepare","seed:scenario:execute","seed:scenario:agents","seed:scenario:save","seed:scenario:test-file"]),tc=class{constructor(e){this.deps=e;this.seedTemplateStore=new dn(e.configStore),this.templateManager=new Qd(()=>crypto.randomUUID(),()=>new Date().toISOString(),this.seedTemplateStore),this.personaManager=new Zd}deps;seedTemplateStore;templateManager;personaManager;registry;liveTracker;runCreations;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}setRunCreations(e){this.runCreations=e}runningRuns=new Set;isRunning(e){return this.runningRuns.has(e)}setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-UK3QLBHW.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}readAutomation(e,t,r,n,o,i,a){let d=this.targetAutomation;return yd({org:n,objects:r,writes:o,readAutomation:c=>i===void 0?new pe(VO).withTimeout("seed automation",()=>d.read(e,c)):typeof i.unread=="string"?Promise.reject(new Error(i.unread)):Promise.resolve(i),readLimits:()=>Or(t),...a?{deliverability:a}:{},...i===void 0?{readDeliverability:()=>Pe(this.deps.orgManager.getOrg(e))==="production"?Promise.resolve(Gt):Jt(t)}:{}})}setMuteLeases(e){this.muteLeases=e}muteLeases={};setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}beforeRunCheckpoints;checkpointProgress(e){return(t,r,n,o)=>{_e(this.deps,e,t,r,n,o),this.liveTracker?.updateProgress(e,t,r,n,o)}}async handleAutomation(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(cy,e,"seed:automation:error",this.deps);if(t)try{let r=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager),n=this.deps.orgManager.getOrg(t.orgId),o=await this.readAutomation(t.orgId,r,t.objects,we(n,t.orgId),LS(t.objects,t.publishes===!0));if("error"in o)throw new Error(o.error);let i=A(this.deps,e,"seed:automation:response",{orgId:t.orgId,objects:t.objects,preview:o.preview});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(r){T(this.deps,"seed:automation","seed:automation:error",e,r,{retryable:!0})}}async handle(e){if(!yx.has(e.type))return!1;switch(e.type){case"seed:describe-global":return await this.handleDescribeGlobal(e),!0;case"seed:describe-object":return await this.handleDescribeObject(e),!0;case"seed:execute":return await this.handleExecute(e),!0;case"seed:automation":return await this.handleAutomation(e),!0;case"seed:template:save":return await this.handleTemplateSave(e),!0;case"seed:template:load":return await this.handleTemplateLoad(e),!0;case"seed:template:list":return await this.handleTemplateList(e),!0;case"seed:template:delete":return await this.handleTemplateDelete(e),!0;case"seed:list-personas":return await this.handleListPersonas(e),!0;case"seed:create-persona":return await this.handleCreatePersona(e),!0;case"seed:scenario:packs":return await this.handleScenarioPacks(e),!0;case"seed:scenario:prepare":return await this.handleScenarioPrepare(e),!0;case"seed:scenario:execute":return await this.handleScenarioExecute(e),!0;case"seed:scenario:agents":return await this.handleScenarioAgents(e),!0;case"seed:scenario:save":return await this.handleScenarioSave(e),!0;case"seed:scenario:test-file":return await this.handleScenarioTestFile(e),!0;default:return!1}}workspaceFolders(){return this.deps.services?.getWorkspaceFolders?.()??[]}answerScenario(e,t,r){let n=A(this.deps,e,t,r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}async handleScenarioPacks(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!!x(fy,e,"seed:error",this.deps))try{let{listScenarioPacks:t,nodeScenarioPackFiles:r}=await import("./chunk-LT4GHEI2.mjs"),n=this.workspaceFolders(),o=await t(r(),n);this.answerScenario(e,"seed:scenario:packs:response",{packs:o,workspace:n.length>0})}catch(t){T(this.deps,"seed:scenario:packs","seed:error",e,t)}}async handleScenarioPrepare(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(gy,e,"seed:error",this.deps);if(t)try{let r=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager),{prepareScenario:n,readScenarioCaseStatus:o,scenarioKnowledge:i}=await import("./chunk-3MVWGL5A.mjs"),{seedObjectAccess:a}=await import("./chunk-FI3R5ZOQ.mjs"),d=await o(async l=>(await r.query(l)).records),c=await i(a(r),l=>r.describe(l)),u=n(t.pack,{caseStatus:d,knowledge:c,...t.seed!==void 0?{seed:t.seed}:{},...t.articleBodyField!==void 0?{articleBodyField:t.articleBodyField}:{}});this.answerScenario(e,"seed:scenario:prepare:response",{...u})}catch(r){T(this.deps,"seed:scenario:prepare","seed:error",e,r,{retryable:!0})}}async handleScenarioExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(hy,e,"seed:error",this.deps);if(!t)return;let{compileScenario:r,ScenarioCompileError:n}=await import("./chunk-JV2LAKWQ.mjs"),o;try{o=r(t.pack,t.options)}catch(a){if(!(a instanceof n))throw a;T(this.deps,"seed:scenario:execute","seed:error",e,a,{code:"SCENARIO_INVALID",retryable:!1});return}let i=Do.safeParse(o.template);if(!i.success){T(this.deps,"seed:scenario:execute","seed:error",e,new Error(`The scenario compiled to a template the seed refuses: ${i.error.issues[0]?.message??"invalid"}`),{code:"SCENARIO_INVALID",retryable:!1});return}await this.runAsked(e,{orgId:t.orgId,template:i.data,...t.locale!==void 0?{locale:t.locale}:{},...t.muteAutomation!==void 0?{muteAutomation:t.muteAutomation}:{},...t.checkpointFirst?{checkpointFirst:t.checkpointFirst}:{}},{pack:t.pack,options:t.options,compiled:o})}async keepScenario(e,t,r){let{compiled:n,pack:o}=t,i=n.tests.filter(l=>l.openCase!==void 0),a=new Set(i.map(l=>l.openCase?.caseKey)),d=Object.keys(r).filter(l=>a.has(l)).length,c={packId:o.id,packName:o.name,tests:n.tests.length,openCasesWritten:d,openCases:a.size};if(d===0)return{...c,companion:{kind:"none"}};let u=this.runCreations;if(!u)return{...c,companion:{kind:"failed",message:"The runs are not kept in this window."}};try{let{nodeScenarioSidecarFiles:l,scenarioRunSidecar:p,writeScenarioRunSidecar:f}=await import("./chunk-6KVBCFVS.mjs");return await f(l(),u.storagePath,p({runId:e.operationId,pack:o,compiled:n,options:t.options,caseIds:r})),{...c,companion:{kind:"kept"}}}catch(l){let p=I(l);return this.deps.log(`[WARN] seed:scenario:execute ${e.operationId}: the companion file could not be written, so its test file cannot be: ${p}`),{...c,companion:{kind:"failed",message:p}}}}async handleScenarioAgents(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(my,e,"seed:error",this.deps);if(t)try{let r=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager),{readAgentCatalog:n}=await import("./chunk-JPEVIXNH.mjs"),{scenarioCasePicklists:o,toolingQueryAll:i}=await import("./chunk-3MVWGL5A.mjs"),{scenarioProjectOf:a}=await import("./chunk-RTCMYMED.mjs"),d=await n(i(QO(r))),c=await o(u=>r.describe(u));this.answerScenario(e,"seed:scenario:agents:response",{orgId:t.orgId,agents:d.kind==="agents"?{kind:"agents",agents:d.catalog.agents}:d,project:await a(this.workspaceFolders()),...c?{casePicklists:c}:{}})}catch(r){T(this.deps,"seed:scenario:agents","seed:error",e,r,{retryable:!0})}}async handleScenarioSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(yy,e,"seed:error",this.deps);if(t)try{let{nodeScenarioPackFiles:r,saveScenarioPack:n}=await import("./chunk-LT4GHEI2.mjs"),o=await n(r(),this.workspaceFolders(),t.pack,t.overwrite===!0);this.answerScenario(e,"seed:scenario:save:response",{outcome:o})}catch(r){T(this.deps,"seed:scenario:save","seed:error",e,r)}}async handleScenarioTestFile(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(wy,e,"seed:error",this.deps);if(!t)return;let r=n=>this.answerScenario(e,"seed:scenario:test-file:response",{runId:t.runId,outcome:n});try{let n=this.runCreations,o=n?await n.get(t.runId):void 0,i=o?this.deps.orgManager.getOrg(o.targetOrgId):void 0;if(!n||!o||!i){r({kind:"unavailable",reason:"run-unknown",message:o?"The org this run wrote to is no longer connected to SandForge: reconnect it on the Organizations page, then write the test file again.":"Nothing of this run is kept any more."});return}let a=await B(o.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),{readAgentCatalog:d}=await import("./chunk-JPEVIXNH.mjs"),{nodeAgentTestSpecFiles:c}=await import("./chunk-VJNEW5MQ.mjs"),{toolingQueryAll:u}=await import("./chunk-3MVWGL5A.mjs"),{findScenarioPack:l,nodeScenarioPackFiles:p}=await import("./chunk-LT4GHEI2.mjs"),{nodeScenarioSidecarFiles:f}=await import("./chunk-6KVBCFVS.mjs"),{scenarioProjectOf:g,writeRunTestFile:h}=await import("./chunk-RTCMYMED.mjs"),m=this.workspaceFolders(),y=await h({sidecar:f(),spec:c()},{runId:t.runId,storagePath:n.storagePath,project:await g(m),alias:we(i,o.targetOrgId),choice:t.choice,...t.overwrite!==void 0?{overwrite:t.overwrite}:{},readCatalog:()=>d(u(QO(a))),findPack:(v,b)=>l(p(),m,v,b)});r(y)}catch(n){T(this.deps,"seed:scenario:test-file","seed:error",e,n,{retryable:!0})}}async handleTemplateSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ly,e,"seed:error",this.deps);if(t)try{let r=t.template;if(r.id&&this.templateManager.get(r.id)){let n=this.templateManager.update(r.id,r),o=A(this.deps,e,"seed:template:save:response",{success:!0,id:n.id});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}else{let n=this.templateManager.create(r),o=A(this.deps,e,"seed:template:save:response",{success:!0,id:n.id});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}}catch(r){T(this.deps,"seed:template:save","seed:error",e,r)}}async handleTemplateLoad(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Ol,e,"seed:error",this.deps);if(t)try{let r=this.seedTemplateStore.load(t.id),n=A(this.deps,e,"seed:template:load:response",{template:r??null});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){T(this.deps,"seed:template:load","seed:error",e,r)}}async handleTemplateList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let r=this.seedTemplateStore.list().map(o=>({id:o.id,name:o.name,description:o.description,tags:o.tags,updatedAt:o.updatedAt,objectCount:o.objects.length,totalRecords:o.objects.reduce((i,a)=>i+a.recordCount,0)})),n=A(this.deps,e,"seed:template:list:response",{templates:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(t){T(this.deps,"seed:template:list","seed:error",e,t)}}async handleTemplateDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Ol,e,"seed:error",this.deps);if(t)try{let r=this.seedTemplateStore.delete(t.id),n=A(this.deps,e,"seed:template:delete:response",{success:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){T(this.deps,"seed:template:delete","seed:error",e,r)}}async handleListPersonas(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.personaManager.getBuiltInPersonas(),r=this.personaManager.getCustomPersonas(),n=[...t,...r].map(i=>({id:i.id,name:i.name,description:i.description,industry:i.industry,locale:i.locale,dataPatterns:i.dataPatterns})),o=A(this.deps,e,"seed:list-personas:response",{personas:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(t){T(this.deps,"seed:list-personas","seed:error",e,t)}}async handleCreatePersona(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(py,e,"seed:error",this.deps);if(t)try{let r=t;if(!r.description||r.description.trim().length===0){let c=A(this.deps,e,"seed:create-persona:response",{persona:{id:"",name:"",description:"",industry:"",locale:"",dataPatterns:{}},success:!1,error:"Description is required to create a custom persona"});this.deps.broker.postToWebview(c);return}let n=this.deps.services;if(!n?.isAIEnabled())throw new Error("AI is disabled. Enable sandforge.ai.enabled and add your Anthropic API key in SandForge Settings > AI > API key to create custom personas.");let o=async c=>(await n.aiClient().chat({messages:[{role:"user",content:c}]})).text,i=await this.personaManager.createCustomPersona(r.description,o),a={id:i.id,name:i.name,description:i.description,industry:i.industry,locale:i.locale,dataPatterns:i.dataPatterns},d=A(this.deps,e,"seed:create-persona:response",{persona:a,success:!0});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(r){T(this.deps,"seed:create-persona","seed:error",e,r)}}buildSeedCallAI(){let e=this.deps.services;return e?.isAIEnabled()?async t=>{try{return(await e.aiClient().chat({messages:[{role:"user",content:t}]})).text}catch(r){return this.deps.log(`[AI] seed data generation failed, falling back to faker: ${I(r)}`),"[]"}}:async()=>"[]"}async handleDescribeGlobal(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(dy,e,"seed:error",this.deps);if(!t)return;let r=t,n=ut(this.deps);try{let o=await B(r.orgId,this.deps.orgRegistry,this.deps.orgManager),d=(await new pe(n.timeouts.describeGlobal).withTimeout("describe-global",()=>o.describeGlobal())).sobjects.filter(u=>u.createable).filter(u=>!Xi(u.name)).map(u=>({apiName:u.name,label:u.label,recordCount:0,dependencies:[]})),c=A(this.deps,e,"seed:describe-global:response",{objects:d});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(o){T(this.deps,"seed:describe-global","seed:error",e,o)}}async handleDescribeObject(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(uy,e,"seed:error",this.deps);if(!t)return;let r=t,n=ut(this.deps);try{let o=await B(r.orgId,this.deps.orgRegistry,this.deps.orgManager),i=St(r.objectApiName),d=await new pe(n.timeouts.describe).withTimeout("describe-object",()=>o.describe(i)),c=d.fields.filter(p=>p.createable).map(p=>({fieldApiName:p.name,label:p.label,type:p.type,required:!p.nillable&&!p.defaultedOnCreate,picklistValues:p.picklistValues?.map(f=>f.value)??[],referenceTo:p.referenceTo??[],length:p.length,integerDigits:Yg(p),objectApiName:r.objectApiName})),u=DS(i,d.recordTypeInfos,i===Co?await sp(o):[]),l=A(this.deps,e,"seed:describe-object:response",{objectApiName:r.objectApiName,objectLabel:d.label,fields:c,recordTypes:u});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`)}catch(o){T(this.deps,"seed:describe-object","seed:error",e,o)}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ay,e,"seed:error",this.deps);if(!t)return;let r=t;if(r.dryRun===!0){T(this.deps,"seed:execute","seed:error",e,new Error('Seed has no dry run: remove "dryRun" from this request to run the seed.'),{code:"DRY_RUN_UNSUPPORTED",retryable:!1});return}await this.runAsked(e,r)}async runAsked(e,t,r){let n=e.id,o={module:"seed",operation:e.type};try{let i=await this.clearSeed(t,n,o,fx,r!==void 0);if("refusal"in i){let{refusal:u}=i;T(this.deps,"seed:execute","seed:error",e,new Error(u.message),{code:u.code,retryable:!1,...u.extraPayload?{extraPayload:u.extraPayload}:{}}),u.failed&&Le(this.deps,n,u.message,!1,{context:o,...u.failed.authored?{authored:!0}:{}});return}let a=r?`Seed of the scenario ${r.pack.name}`:"Seed data generation",{abortController:d,execution:c}=this.beginSeed(e,i,n,o,a,void 0,r);this.registry?this.registry.register(n,"seed",a,c,d):await c}catch(i){this.deps.infraServices?.performanceTracker?.complete(n),this.liveTracker?.fail(n,I(i));let a=YO(i,n,this.deps.log);T(this.deps,"seed:execute","seed:error",e,i,{code:xo(i),retryable:!0,extraPayload:a}),Le(this.deps,n,I(i),!0,{extraPayload:a,context:o})}}async clearSeed(e,t,r,n,o=!1,i=!1){let a=V=>{i||Y(this.deps,V)},d=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200,c=e.template.objects.map(V=>({...V,batchSize:V.batchSize??d}));Object.assign(r,Jr(c));let u=await B(e.orgId,this.deps.orgRegistry,this.deps.orgManager),l={...e.template,objects:c},p=l.objects.some(V=>V.objectApiName===Co)?NS(l,await sp(u)):{template:l,personObjects:[]};if("refusal"in p)return{refusal:{code:"RECORD_TYPES_MIXED",message:p.refusal}};let f={orgId:e.orgId,template:p.template,personObjects:p.personObjects,locale:await jS(e.locale,u)},g=e.template.objects.reduce((V,ae)=>V+ae.recordCount,0),h=[],m=V=>{h.push(V),this.deps.log(`[WARN] seed:execute ${t}: ${V}`)},y=this.deps.orgManager.getOrg(f.orgId),v=we(y,f.orgId),b=p.template.objects.map(V=>({objectApiName:V.objectApiName,recordCount:V.recordCount})),k=this.targetAutomation,S=await new pe(VO).withTimeout("seed automation",()=>k.read(f.orgId,b.map(V=>V.objectApiName))).catch(V=>({unread:I(V)})),C=MS(p.template,o),R;if("muteAutomation"in e&&e.muteAutomation===!0)try{R=await Et(async()=>_t(u),S,{...this.muteLeases,writes:C})}catch(V){if(!jt(V))throw V;return a({action:"seed_execute",module:"seed",operationId:t,orgId:f.orgId,outcome:"stopped",code:V.code}),{refusal:{code:V.code,message:V.message,extraPayload:{},failed:{authored:!0}}}}R&&(f.mute=R);let w=HS(e.fit,g);w&&(f.fit=w);let{describedFieldsOf:P,requiredForAccountKinds:O}=await import("./chunk-YZKZC62O.mjs"),E=0,$=P(async V=>(E++,u.describe(V))),H=FS(S,R?.plan,C,await _S(p.template,S,$.unset)),J=await ir({read:S,...R?.plan?{plan:R.plan}:{},writes:C,readDeliverability:()=>Pe(y)==="production"?Promise.resolve(Gt):Jt(u),accepted:!1,target:v,run:"seed",keepsAddresses:!0}),W={read:J,accepted:!1};f.emails=W;let Z=J.gate.verdict==="asks",_;if(e.checkpointFirst!==void 0){let V={module:"seed",orgId:f.orgId,operationId:t,written:b.filter(ae=>ae.recordCount>0).map(ae=>ae.objectApiName),running:H.running??{firing:[]},request:e.checkpointFirst};try{_=await mi(this.beforeRunCheckpoints,V)}catch(ae){if(!(ae instanceof Xt))throw ae;return a({action:"seed_execute",module:"seed",operationId:t,orgId:f.orgId,outcome:"stopped",code:ae.code}),{refusal:{code:ae.code,message:ae.message,extraPayload:{},failed:{authored:!0}}}}}let{seedObjectAccess:Q,templateTheOrgTakes:N}=await import("./chunk-FI3R5ZOQ.mjs"),z=await N(p.template,Q(u)),oe=RS(js(this.deps.services),p.template),re=await bS(z,{describeCreateableFields:$.createable,describeRequiredFields:O($,p.personObjects)},oe),q={duplicateRules:Wo(S),partition:oe,slices:re,slicesRead:E,bulkThreshold:ut(this.deps).bulk.threshold,automationRead:$n(S)},F=await IS(Vt(u,f.orgId),z,p.personObjects,we(y,f.orgId),_?.planned,{...xn(J.ofRun),...Vb(R?.plan)},q,H.room);if(F.check.verdict==="unread"&&m(`the data storage the org has left could not be read (${F.check.unread}): whether the records fit is not known`),F.refusal){let V=F.refusedFor==="checkpoint",ae=V?Cn:F.refusedFor==="apiRequests"?Uo:op,ee=V?F.checkpointRefusal?.code:void 0;a({action:"seed_execute",module:"seed",operationId:t,orgId:f.orgId,outcome:"stopped",code:ae,...ee!==void 0?{details:{checkpointRefusal:ee}}:{}});let fe=F.check,D=V?void 0:US(AS(F),z,p.personObjects,H.room,q);return{refusal:{code:ae,message:F.refusal,extraPayload:{...fe.verdict==="unread"||ae!==op?{}:{estimateMB:Number(Ks(fe.estimateMB)),remainingMB:fe.remainingMB,...kr(fe),maxMB:fe.maxMB,org:we(y,f.orgId)},...ee!==void 0?{checkpointRefusal:ee}:{},...D?{fit:D}:{}},failed:{authored:!0}}}}let ne=await this.readAutomation(f.orgId,u,b.map(V=>V.objectApiName),v,C,R?.automation??S,J.gate.deliverability),ke=wd(ne,b,v);for(let V of ke.unknown??[])m(V);if(ke.refusal)return a({action:"seed_execute",module:"seed",operationId:t,orgId:f.orgId,outcome:"stopped",code:ip}),{refusal:{code:ip,message:ke.refusal,extraPayload:{...ke.figures?{...ke.figures}:{},...o?{scenario:!0}:{}},failed:{authored:!0}}};if(i)return{preview:{records:z.objects.reduce((V,ae)=>V+ae.recordCount,0),objects:z.objects.length,storage:F.check,apiRequests:F.api,automation:ap(ne,v),warnings:h},storage:F,asks:F.check.verdict==="unread"||F.api.verdict==="near"||_!==void 0||Z,emailsAsked:Z,emails:J};let de=this.deps.infraServices?.productionGuard;if(!de)return Y(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:f.orgId,outcome:"stopped",code:ve.code}),{refusal:{code:ve.code,message:ve.message,failed:{authored:!1}}};let Ze={orgId:f.orgId,orgTier:Pe(y),operation:"insert",objectName:"SeedData",recordCount:g,module:"seed"},{check:xe,decision:Ue}=await et(de,Ze);if((Ue==="refused"||Ue==="declined")&&Y(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:f.orgId,outcome:"stopped",guard:Ue}),Ue==="refused")throw bn(xe.blockedReason??xe.impactSummary);if(Ue==="declined")return{refusal:{code:Dt.declined,message:"Operation cancelled by user (confirmation declined).",failed:{authored:!1}}};if(F.check.verdict==="unread"||F.api.verdict==="near"||_!==void 0||Z){let V=await n.ask(de,{stage:"write",module:"seed",org:v,orgTier:Pe(y),objects:p.template.objects.map(ae=>({objectApiName:ae.objectApiName,rows:ae.recordCount})).sort((ae,ee)=>ee.rows-ae.rows),total:g,storage:Dn(F.check),counted:!0,...Ho(F.api),..._?{checkpoint:_.planned}:{},...J.gate.confirmation});if(V==="confirmed"&&Z&&(W.accepted=!0),V==="declined")return Y(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:f.orgId,outcome:"stopped",guard:Ue,code:ds,...cn(W)}),{refusal:{code:ds,message:"The seed was cancelled before it wrote anything. Nothing was written.",failed:{authored:!0}}};if(V==="unavailable"&&Z){let ae=XO(J,v,n.unanswered);return Y(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:f.orgId,outcome:"stopped",guard:Ue,code:ae.code,...cn(W)}),{refusal:{...ae,failed:{authored:!0}}}}if(V==="unavailable"&&_!==void 0)return Y(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:f.orgId,outcome:"stopped",guard:Ue,code:kt.unanswered}),{refusal:{code:kt.unanswered,message:`The seed needed an answer before it wrote \u2014 the checkpoint it takes first reads whole tables of ${v} \u2014 and there was no one to ask. Nothing was written.`,failed:{authored:!0}}};if(V==="unavailable"&&n.unanswered==="refuse")return Y(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:f.orgId,outcome:"stopped",guard:Ue,code:kt.unanswered}),{refusal:{code:kt.unanswered,message:KO(F,v),failed:{authored:!0}}};V==="unavailable"&&this.deps.log(`[WARN] seed:execute ${t}: nobody could be asked about the storage or the API requests the org has left; the seed goes on`)}return{conn:u,run:f,plannedRecords:g,storageMB:F.check.estimateMB,...F.rowBytes?{rowBytes:F.rowBytes}:{},guardDecision:Ue,automation:ne,orgName:v,warnings:h,..._?{checkpoint:_}:{}}}beginSeed(e,t,r,n,o,i,a){this.deps.infraServices?.performanceTracker?.start(r,"seed"),Ge(this.deps,r,"seed",o),this.liveTracker?.register(r,"seed",o,t.plannedRecords),Tt({action:"seed_execute",orgId:t.run.orgId,operationId:r},{mb:t.storageMB,...t.rowBytes?{rowBytes:t.rowBytes}:{}});let d=new AbortController,c=this.executeSeed(e,t.conn,t.run,r,d,n,t.guardDecision,i,a,t.checkpoint);return{abortController:d,execution:c}}pipelineSeedOf(e){let t=this.deps.orgManager.getOrg(e.orgId);if(!t)throw ur(kt.orgUnknown,`The org the seed writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was written.`);let r=_k(Pe(t),e.answer,we(t,e.orgId));if(r)throw r;let n=os(e.orgId,e.templateId,o=>this.seedTemplateStore.load(o));if("refusal"in n)throw n.refusal;return n.asked}async previewForPipeline(e,t){let r=this.pipelineSeedOf(e),n={module:"seed",operation:"seed:pipeline"},o={ask:()=>Promise.resolve(e.answer.approved?"confirmed":"unavailable"),unanswered:"refuse"},i=await this.clearSeed(r,crypto.randomUUID(),n,o,!1,!0);if("refusal"in i)throw ur(i.refusal.code,i.refusal.message);if(t?.aborted)throw new Rt("The simulation of the seed was stopped before it said what the seed would meet. Nothing was written.");if(i.asks&&!e.answer.approved){let a=we(this.deps.orgManager.getOrg(e.orgId),e.orgId);if(i.emailsAsked){let d=XO(i.emails,a,o.unanswered);throw ur(d.code,d.message)}throw ur(kt.unanswered,KO(i.storage,a))}return i.preview}async seedForPipeline(e,t){let r=this.pipelineSeedOf(e),n=Rn("seed:pipeline",crypto.randomUUID(),"seed:execute"),o=n.id,i={module:"seed",operation:n.type},a={ask:()=>Promise.resolve(e.answer.approved?"confirmed":"unavailable"),unanswered:"refuse"};return ja(e.answer,async()=>{let d=await this.clearSeed(r,o,i,a);if("refusal"in d)throw ur(d.refusal.code,d.refusal.message);if(t?.aborted)throw Y(this.deps,{action:"seed_execute",module:"seed",operationId:o,orgId:e.orgId,outcome:"stopped",guard:d.guardDecision,code:ht}),new Rt("The seed was cancelled before it wrote anything. Nothing was written.");let c=ap(d.automation,d.orgName);for(let m of c)this.deps.log(`[INFO] seed:execute ${o}: ${m}`);let u,l=`Pipeline seed of ${r.template.name}`,{abortController:p,execution:f}=this.beginSeed(n,d,o,i,l,{pipeline:e.pipeline,ended:m=>{u=m}});this.registry?.register(o,"seed",l,f,p);let g=()=>{this.registry?this.registry.abort(o):p.abort()};t?.addEventListener("abort",g,{once:!0});try{await f}finally{t?.removeEventListener("abort",g)}let h=u;if(h===void 0)throw new Error("The seed ended without a result.");if("error"in h)throw h.error instanceof Error?h.error:new Error(I(h.error));return{operationId:o,runId:h.result.operationId,result:h.result,automation:c,warnings:d.warnings}})}async executeSeed(e,t,r,n,o,i,a,d,c,u){let l=ut(this.deps),p=new Date().toISOString(),f,g=!1,h={},m=r.template.name,y={origin:"generator",...typeof m=="string"?{label:m}:{}};try{let v=yr(this.deps),b=new nd({retryConfig:l.retry,signal:o.signal,onRetry:(ce,Ee,Ne)=>{this.deps.log(`[RETRY] seed insert attempt=${ce} code=${Ee.originalError.statusCode} delay=${Ne}ms`)}}),k=this.deps,S=crypto.randomUUID(),C=d?this.deps.orgManager.getOrg(r.orgId)?.orgId:void 0,R=this.runCreations?.recorder({runId:S,targetOrgId:r.orgId,startedAt:p,...d?{pipeline:d.pipeline}:{},...C?{targetOrganizationId:C}:{}});Ir(R,()=>t.identity(),`seed:execute ${n}`);let w={base:0,total:0},P=(ce,Ee,Ne)=>{let it=w.base+ce,nt=Math.max(w.total,it,Ee,1),Ce=Math.round(it/nt*100);_e(k,n,Ce,it,nt,Ne),this.liveTracker?.updateProgress(n,Ce,it,nt,Ne)},O=Zv({conn:t,bulkThreshold:l.bulk.threshold,bulkManager:v,retry:b,signal:o.signal,label:`seed:execute ${n}`,log:ce=>this.deps.log(ce),onProgress:P,...R?{calls:{sending:(ce,Ee,Ne)=>R.sending(ce,Ee,Ne),answered:(ce,Ee)=>R.answered(ce,Ee)}}:{}}),E=async(ce,Ee,Ne,it)=>{Ne.length>0&&(g=!0);let nt=await O(ce,Ee,Ne,it);return R?.note(Ee,nt.successIds),nt},$=ce=>this.deps.log(`[WARN] seed:execute ${n}: what the run created could not all be kept, so removing it may leave some of it in the org: ${I(ce)}`),{SeedValidator:H}=await import("./chunk-5EHHQ5UX.mjs"),{DataPlanBuilder:J}=await import("./chunk-IT3DGX37.mjs"),{FieldMapper:W}=await import("./chunk-QGVL5EW3.mjs"),{ReferenceLinker:Z}=await import("./chunk-D2X6U3MS.mjs"),{AIDataGenerator:_}=await import("./chunk-YGBNZYT4.mjs"),{FakerFallback:Q}=await import("./chunk-CB4U22NR.mjs"),{readExistingParentIds:N,readPresentParentIds:z}=await import("./chunk-JSNMUTY6.mjs"),{seedObjectAccess:oe}=await import("./chunk-FI3R5ZOQ.mjs"),{describedFieldsOf:re,requiredForAccountKinds:q}=await import("./chunk-YZKZC62O.mjs"),{seedTargetOf:F}=await import("./chunk-72AWCN7U.mjs"),ne=c?(await import("./chunk-C5EQ7GFC.mjs")).seedKnowledge:void 0,ke=new _(this.buildSeedCallAI()),de=new Q(r.locale),Ze=new W({aiGenerator:ke,fakerFallback:de}),xe=new Z,Ue=new H,V=new J,{SeedGrappeAdapter:ae}=await import("./chunk-PTTHSSQO.mjs"),ee=js(this.deps.services),fe=re(ce=>t.describe(ce)),D={validator:Ue,describeCreateableFields:fe.createable,describeVisibleFields:fe.visible,describeComputedFields:fe.computed,describePicklistValues:fe.picklistValues,describeFieldLengths:fe.lengths,describeRequiredFields:q(fe,r.personObjects),objectAccess:oe(t),readExistingParentIds:(ce,Ee,Ne)=>N(t,ce,Ee,Ne),readPresentParentIds:(ce,Ee)=>z(t,ce,Ee),describeKeyPrefix:fe.keyPrefix,...F(t),planBuilder:V,fieldMapper:Ze,referenceLinker:xe,insert:E,generateId:()=>crypto.randomUUID(),now:()=>new Date().toISOString(),services:this.deps.services,grappeAdapter:new ae(()=>crypto.randomUUID(),ee?.grappeSize),grappeConfig:ee,onGrappeEvent:ce=>la(this.deps,ce),onProgress:ce=>{w.base=ce.processedRecords,w.total=ce.totalRecords,P(0,ce.totalRecords,`Insert ${ce.objectApiName}`)},signal:o.signal,...c&&ne?{onRowIds:(ce,Ee)=>{ce==="Case"&&Object.assign(h,Ee)},knowledge:ne({org:t,plan:{publish:!0,links:c.compiled.closedCaseArticles},...R?{journal:R}:{},signal:o.signal})}:{}};if(!this.deps.services)throw new Error("SeedOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let G=this.deps.services.seedOrchestrator(D),ue=r.template;_e(this.deps,n,0,0,1,"Validating template and building plan");let j;this.runningRuns.add(S);let se=r.mute,U=se?.muted;try{u&&(f=await yi(this.beforeRunCheckpoints,u,S,o.signal,this.checkpointProgress(n)),R?.checkpoint?.(f));let ce=se?.prepared?await se.prepared.acquire(S):void 0;ce&&(U=ce.outcome);let Ee=ce&&r.emails?r.emails.read.afterLease(ce.outcome,r.emails.accepted):void 0;if(ce&&Ee)throw U=await ce.release(),new Xt(Ee.code,Ee.message);j=await G.execute(ue,r.orgId,S).finally(async()=>{ce&&(U=await ce.release())}),U&&(j={...j,mutedAutomation:U});let Ne=await Ln(this.beforeRunCheckpoints,f,g,this.deps.log,`seed:execute ${n}`);f=void 0,Ne&&(j={...j,checkpoint:Ne})}catch(ce){throw await R?.end({status:"failure",finishedAt:new Date().toISOString(),objectResults:[]}).catch($),this.runningRuns.delete(S),ce}await R?.end({finishedAt:new Date().toISOString(),status:j.status,...j.cancelled?{cancelled:!0}:{},objectResults:j.objectResults}).catch($),c&&(j={...j,scenario:await this.keepScenario(j,c,h)}),this.runningRuns.delete(S),j.cancelled||_e(this.deps,n,100,1,1,"Seed complete");let te=j.totalRecordsCreated;this.deps.infraServices?.performanceTracker?.update(n,te,1),this.deps.infraServices?.performanceTracker?.complete(n),j.cancelled?(this.registry?.abort(n),me(this.deps,n,{aborted:!0,totalRecords:te}),this.liveTracker?.cancel(n)):(me(this.deps,n,{status:j.status,totalRecords:te}),j.status==="failure"?this.liveTracker?.fail(n,mx(j)):j.status==="partial"?this.liveTracker?.partial(n):this.liveTracker?.complete(n));let Se=j.objectResults.some(ce=>ce.recordsCreated+ce.recordsFailed>0),De=j.cancelled===!0?Se?"cancelled":"stopped":j.status;Y(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:De,...De==="stopped"?{code:ot}:{},guard:a,objects:j.objectResults.map(ce=>({...bt(ce.objectApiName),created:ce.recordsCreated,failed:ce.recordsFailed})),source:y,...j.mutedAutomation?{muted:ft(j.mutedAutomation)}:{},...j.checkpoint?.state==="taken"?{checkpointId:j.checkpoint.checkpointId}:{},...r.fit?{fit:r.fit}:{},...cn(r.emails)});let qe=A(this.deps,e,"seed:execute:response",hx(j));if(this.deps.broker.postToWebview(qe),this.deps.log(`[TX] ${qe.type} id=${qe.id}`),d?.ended({result:j}),j.status==="failure"&&!j.cancelled)return{status:"failure"}}catch(v){this.deps.infraServices?.performanceTracker?.complete(n);let b=await Ln(this.beforeRunCheckpoints,f,g,this.deps.log,`seed:execute ${n}`),k=b?.state==="deleted"?`${I(v)} ${Zr}`:void 0,S=k!==void 0?new Error(k):v;if(v instanceof Xt){if(v.code===ot)this.registry?.abort(n),me(this.deps,n,{aborted:!0,totalRecords:0}),this.liveTracker?.cancel(n);else{let P=I(S);this.liveTracker?.fail(n,P),Le(this.deps,n,P,!1,{context:i,authored:!0})}let w=v.refusal?.code;return Y(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:"stopped",guard:a,code:v.code,...w!==void 0||r.emails?.read.gate.audit!==void 0?{details:{...cn(r.emails).details,...w!==void 0?{checkpointRefusal:w}:{}}}:{}}),T(this.deps,"seed:execute","seed:error",e,S,{code:v.code,retryable:!1,...w!==void 0?{extraPayload:{checkpointRefusal:w}}:{}}),d?.ended({error:v}),v.code===ot?void 0:{status:"failure"}}this.liveTracker?.fail(n,I(S));let C=jt(v)?v:void 0;Y(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:C?"stopped":"failure",guard:a,source:y,...C?{code:C.code}:{},...b?.state==="taken"?{checkpointId:b.checkpointId}:{},...r.fit?{fit:r.fit}:{},...cn(r.emails)});let R=YO(v,n,this.deps.log);return T(this.deps,"seed:execute","seed:error",e,v,{...C?{code:C.code}:{},retryable:!0,extraPayload:{...R,...b?{checkpoint:b}:{}}}),Le(this.deps,n,I(S),!0,{extraPayload:R,context:i}),d?.ended({error:S}),{status:"failure"}}}};function wx(s){if(s.length>512)throw new Error(`SOQL WHERE clause too long (${s.length} > 512 chars)`);return jh(s)}var bi=class{log;described=new WeakMap;constructor(e){this.log=e.log}describe(e,t){let r=this.described.get(e);r||(r=new Map,this.described.set(e,r));let n=r.get(t);return n||(n=e.describe(t),r.set(t,n)),n}async fetchRecords(e,t,r){let n=await this.getQueryFields(e,t),o=this.buildSoql(n,t,r),i=this.cleanRecords(await Ms(o,async a=>{let d=[],c=await e.query(a);for(d.push(...c.records);!c.done&&c.nextRecordsUrl;)c=await e.queryMore(c.nextRecordsUrl),d.push(...c.records);return d}));return this.log(`[CloneRecordFetcher] Fetched ${i.length} records from ${t}`),i}async countRecords(e,t,r,n=[]){let o=`SELECT COUNT() FROM ${Xe(t)}${this.whereOf(r,n)}`;return(await e.query(o)).totalSize}async fetchSample(e,t,r,n,o=[]){let i=await this.getQueryFields(e,t),a=this.buildSoql(i,t,n,o);return a+=` LIMIT ${r}`,this.cleanRecords(await Ms(a,async d=>(await e.query(d)).records))}async getQueryFields(e,t){let r=await this.describe(e,t),n=new Set;n.add("Id");for(let o of r.fields)(o.createable||o.type==="reference")&&n.add(o.name);return Array.from(n)}buildSoql(e,t,r,n=[]){return`SELECT ${e.join(", ")} FROM ${Xe(t)}${this.whereOf(r,n)}`}whereOf(e,t){let r=e?wx(e):void 0;return t.length===0?r?` WHERE ${r}`:"":` WHERE ${[...r?[`(${r})`]:[],...t].join(" AND ")}`}cleanRecords(e){return e.map(t=>{let r={...t};return delete r.attributes,r})}};var Ri=class{resolveInsertOrder(e,t){if(e.length===0)return[];let r=new Set(e),n=t.filter(l=>l.from!==l.to&&r.has(l.from)&&r.has(l.to)),o=new Map(e.map(l=>[l,new Set])),i=new Map(e.map(l=>[l,new Set])),a=new Map(e.map(l=>[l,new Set]));for(let l of n)o.get(l.to)?.add(l.from),l.required&&(af(l)?a:i).get(l.to)?.add(l.from);let d=sa(i).filter(l=>l.length>1);if(d.length>0)throw new Error(Rx(d,n.filter(l=>!af(l))));let c=new Map(e.map(l=>[l,new Set([...i.get(l)??[],...a.get(l)??[]])])),u=sa(c).some(l=>l.length>1)?i:c;return bx(sa(o),o,e).flatMap(l=>l.length>1?Nh(l,u):l)}lookupsOf(e,t){return t.filter(r=>r.to===e&&!af(r)).map(r=>({field:r.fieldApiName,referenceTo:r.from}))}lookupsFilledAfter(e,t){let r=new Map(e.map((n,o)=>[n,o]));return t.filter(n=>{let o=r.get(n.to),i=r.get(n.from);return!n.required&&o!==void 0&&i!==void 0&&i>=o})}detectSelfReferentialEdges(e){return e.filter(t=>t.from===t.to)}buildEdgesFromDescribe(e,t){let r=new Set(e),n=[];for(let o of e){let i=t.get(o);if(i){for(let a of i.fields)if(a.createable!==!1&&!(o===rr&&a.name==="ActivityId")&&a.type==="reference"&&a.referenceTo){let d=As(o,a.name,a.nillable)||a.updateable===!1;for(let c of a.referenceTo)r.has(c)&&n.push({from:c,to:o,fieldApiName:a.name,relationshipType:"lookup",required:d})}}}for(let o of ml(r))n.push({from:o.sourceObject,to:o.targetObject,fieldApiName:o.relationshipName,relationshipType:"lookup",required:!0});return n}};function bx(s,e,t){let r=new Map;t.forEach((c,u)=>{r.has(c)||r.set(c,u)});let n=new Map;s.forEach((c,u)=>c.forEach(l=>n.set(l,u)));let o=s.map(c=>Math.min(...c.map(u=>r.get(u)??1/0))),i=s.map((c,u)=>{let l=new Set;for(let p of c)for(let f of e.get(p)??[]){let g=n.get(f);g!==void 0&&g!==u&&l.add(g)}return l}),a=new Set,d=[];for(;d.length<s.length;){let c=-1;for(let u=0;u<s.length;u++)a.has(u)||[...i[u]].some(l=>!a.has(l))||(c===-1||o[u]<o[c])&&(c=u);if(c===-1)break;a.add(c),d.push(s[c])}return d}function af(s){return ml(new Set([s.from,s.to])).some(e=>e.sourceObject===s.from&&e.targetObject===s.to&&e.relationshipName===s.fieldApiName)}function Rx(s,e){let t=s.flatMap(r=>{let n=new Set(r);return e.filter(o=>o.required&&n.has(o.from)&&n.has(o.to)).map(o=>`${o.to}.${o.fieldApiName}`)});return`Cycle detected among objects: ${s.flat().join(", ")}. ${vx(t)} must be set when the record is created, so no object of the cycle can be written first.`}function vx(s){return s.length<=1?s.join(""):`${s.slice(0,-1).join(", ")} and ${s[s.length-1]}`}function df(s){return s==="insert"||s==="upsert"}function nc(s,e){return{sending:(t,r,n)=>{df(r)&&s.sending(t,n,r==="upsert"?{upsert:!0}:void 0)},opened:(t,r,n,o)=>{df(r)&&s.sending(t,n,{job:o,...r==="upsert"?{upsert:!0}:{}})},answered:(t,r,n)=>{if(!df(r))return;let o=hd(r,n);s.answered(t,o),e?.(o.length)}}}var kx=new Set(["seed:clone:describe-source","seed:clone:preview","seed:clone:execute"]),Ox=5,Ix=10,Ax=-1,eI="Operation blocked by Production Guard: ",Dr={confirmationDeclined:"PRODUCTION_CONFIRMATION_DECLINED",guardBlocked:"PRODUCTION_GUARD_BLOCKED",failed:"CLONE_FAILED",emailsExceeded:"CLONE_EMAILS_EXCEEDED",apiBudgetExceeded:"API_BUDGET_EXCEEDED",storageExceeded:"CLONE_STORAGE_EXCEEDED"},Tx=3;function Ex(s,e){let t=s.filter(n=>n.recordCount>0).map(n=>({objectApiName:n.objectApiName,rows:n.recordCount,bytes:En(n.objectApiName,{rows:n.recordCount})})).sort((n,o)=>o.bytes-n.bytes),r=Sr({storageBytes:t.reduce((n,o)=>n+o.bytes,0)},e);if(r.verdict==="exceeds")return{estimateMB:r.estimateMB,remainingMB:r.remainingMB,maxMB:r.maxMB,...kr(r),heaviest:t.slice(0,Tx).map(({objectApiName:n,rows:o,bytes:i})=>({objectApiName:n,rows:o,mb:i/(1024*1024)}))}}function tI(s){let e=s<10?100:10;return String(s<=0?0:Math.ceil(s*e-1e-9)/e)}function dI(s,e){let t=s.heaviest.map(r=>`${r.objectApiName} (${r.rows} records, ${tI(r.mb)} MB)`).join(", ");return`its records take about ${tI(s.estimateMB)} MB of data storage, and ${e} has ${s.remainingMB} MB left of ${s.maxMB} MB${Ka(s,e)}. The heaviest: ${t}. Narrow their filter or leave them out, then preview again; or copy a sample of the source that fits with Forge (Depth ALL, Records per object: A sample that fits the target).`}function Px(s,e){return`The clone was refused before it wrote anything: ${dI(s,e)} Nothing was written.`}var Cx=6e4,$x={neutralized:!1,fields:[],values:0},xx="PREVIEWED_FOR_OTHER_ORGS",Dx="NOT_PREVIEWED",Nx="PREVIEW_NOT_HELD",jx=50,sc=class{constructor(e){this.deps=e}deps;registry;liveTracker;previewedOrgs=new Map;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-UK3QLBHW.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async emailGate(e,t,r,n,o,i){let a=r.filter(c=>c.recordCount>0);if(a.length===0)return;let d=await yd({org:n,objects:a.map(c=>c.objectApiName),readAutomation:c=>o===void 0?this.readTargetAutomation(e,c):typeof o.unread=="string"?Promise.reject(new Error(o.unread)):Promise.resolve(o),readLimits:()=>Or(t),...i?{deliverability:i}:{}});return wd(d,a,n)}readTargetAutomation(e,t){let r=this.targetAutomation;return new pe(Cx).withTimeout("clone automation",()=>r.read(e,t))}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}beforeRunCheckpoints;setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}runCreations;runningRuns=new Set;setRunCreations(e){this.runCreations=e}isRunning(e){return this.runningRuns.has(e)}async endKept(e,t,r){if(!e)return!1;try{return await e.end({finishedAt:new Date().toISOString(),status:r.status,...r.cancelled?{cancelled:!0}:{},objectResults:[]}),!0}catch(n){return this.deps.log(`[WARN] seed:clone:execute ${t}: what the clone created could not all be kept, so removing it may leave some of it in the org: ${I(n)}`),!1}finally{this.runningRuns.delete(t)}}stoppedForCheckpoint(e,t,r,n,o){let{operationId:i}=t;if(r.code===ot){Y(this.deps,{...t,outcome:"stopped",source:void 0,code:ot}),this.registry?.abort(i),me(this.deps,i,{aborted:!0,totalInserted:0,totalFailed:0}),this.liveTracker?.cancel(i);let c={status:"partial",objectResults:[],totalSourceRecords:0,totalInserted:0,totalFailed:0,durationMs:o,cancelled:!0};this.deps.broker.postToWebview(A(this.deps,e,"seed:clone:execute:response",c));return}let a=r.refusal?.code,d=a!==void 0?{checkpointRefusal:a}:{};Y(this.deps,{...t,outcome:"stopped",source:void 0,code:r.code,...a!==void 0?{details:d}:{}}),Le(this.deps,i,r.message,!1,{context:n,authored:!0,extraPayload:{code:r.code,...d}}),this.liveTracker?.fail(i,r.message)}async handle(e){if(!kx.has(e.type))return!1;switch(e.type){case"seed:clone:describe-source":return await this.handleDescribeSource(e),!0;case"seed:clone:preview":return await this.handlePreview(e),!0;case"seed:clone:execute":return await this.handleExecute(e),!0;default:return!1}}async handleDescribeSource(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(by,e,"seed:clone:error",this.deps);if(t)try{let r=await B(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await r.describeGlobal();$e(r.limitInfo,"seed:clone:describe-source");let o=n.sobjects.filter(a=>a.createable&&a.queryable).filter(a=>!Xi(a.name)).map(a=>({apiName:a.name,label:a.label,recordCount:Ax})),i=A(this.deps,e,"seed:clone:describe-source:response",{objects:o});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} count=${o.length}`)}catch(r){T(this.deps,"seed:clone:describe-source","seed:clone:error",e,r)}}async handlePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Il,e,"seed:clone:error",this.deps);if(t)try{let r=await B(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),o=new bi({log:this.deps.log}),i=new Ri,a=t.objects.map(S=>S.objectApiName),d=new Map(t.objects.map(S=>[S.objectApiName,S.whereClause])),c=new Map,u=new Map,l=[],p=[];for(let S of t.objects){let C;try{C=await Promise.all([oc("target",S.objectApiName,()=>n.describe(S.objectApiName)),oc("source",S.objectApiName,()=>o.describe(r,S.objectApiName))])}catch(P){if(!(P instanceof cs))throw P;p.push(P);continue}let[R,w]=C;$e(n.limitInfo,`seed:clone:preview describe ${S.objectApiName} in the target`),$e(r.limitInfo,`seed:clone:preview describe ${S.objectApiName}`),c.set(S.objectApiName,R),u.set(S.objectApiName,w)}if(p.length>0)throw new cs(p.flatMap(S=>S.objectApiNames),p[0].why);for(let S of t.objects){let C=Lh(S.objectApiName,nI(S.objectApiName,c.get(S.objectApiName),u.get(S.objectApiName)),d),[R,w,P]=await Promise.all([o.countRecords(r,S.objectApiName,S.whereClause,C),o.fetchSample(r,S.objectApiName,Ox,S.whereClause,C),C.length>0?o.countRecords(r,S.objectApiName,S.whereClause):void 0]),O=P===void 0?0:P-R;l.push({objectApiName:S.objectApiName,recordCount:R,...O>0?{leftToThePlatform:O}:{},sampleRecords:w.map(E=>zx(E,Ix))})}let f=i.buildEdgesFromDescribe(a,oI(c,u)),g=i.resolveInsertOrder(a,f),h=l.map(S=>({...S,relationships:i.lookupsOf(S.objectApiName,f)})),m=_x(i.lookupsFilledAfter(g,f),g),y=Ux(g,u,c),v=Hx(g,c,u),b={objects:h,insertOrder:g,...m.length>0?{filledAfterInsert:m}:{},...y.length>0?{sourceOnlyLookups:y}:{},...v.length>0?{targetOnlyRequiredLookups:v}:{}},k=A(this.deps,e,"seed:clone:preview:response",b);this.deps.broker.postToWebview(k),this.deps.log(`[TX] ${k.type} id=${k.id}`),this.rememberPreview(e.id,t,new Map(l.map(S=>[S.objectApiName,S.recordCount])),new Set(i.lookupsFilledAfter(g,f).map(S=>S.to)))}catch(r){let n=r instanceof cs?r:void 0;T(this.deps,"seed:clone:preview","seed:clone:error",e,r,{...n?{code:Lx,retryable:!1,extraPayload:{objectApiName:n.objectApiName,objectApiNames:n.objectApiNames,org:we(this.deps.orgManager.getOrg(t.targetOrgId),t.targetOrgId)}}:{}})}}rememberPreview(e,t,r,n){this.previewedOrgs.set(e,{sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,recordCounts:r,secondPass:n});for(let o of this.previewedOrgs.keys()){if(this.previewedOrgs.size<=jx)break;this.previewedOrgs.delete(o)}}refusedAgainstItsPreview(e){if(e.previewId===void 0)return{code:Dx,reason:"Clone refused: it names no preview. Preview it, then run the preview shown."};let t=this.previewedOrgs.get(e.previewId);if(!t)return{code:Nx,reason:"Clone refused: the preview it names is not one SandForge answered, or no longer holds. Preview it again."};if(t.sourceOrgId!==e.sourceOrgId||t.targetOrgId!==e.targetOrgId)return{code:xx,reason:"Clone refused: its preview was made for another source or target org. Preview it again."}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Il,e,"seed:clone:error",this.deps);if(!t)return;let r=this.refusedAgainstItsPreview(t);if(r!==void 0){T(this.deps,e.type,"seed:clone:error",e,new Error(r.reason),{code:r.code});return}let n=e.id,o=Date.now(),i={module:"seed",operation:e.type,...Jr(t.objects.map(k=>({objectApiName:k.objectApiName})))},a=new AbortController,d=()=>{},c=new Promise((k,S)=>{d=C=>C===void 0?k():S(C)});c.catch(()=>{}),this.registry?.register(n,"clone",`Clone ${t.objects.length} object(s)`,c,a);let u={action:"seed_clone",module:"seed",operationId:n,orgId:t.targetOrgId,outcome:"failure",source:{origin:"org",orgId:t.sourceOrgId}},l=!1,p,f=0,g,h=!1,m=[],y=!!(t.upsert&&t.externalIdField),v=dS(t.keepContactPoints===!0?{keepContactPoints:!0}:{}),b=()=>v?.report()??$x;try{let k=this.deps.infraServices?.productionGuard;if(!k){Y(this.deps,{...u,outcome:"stopped",source:void 0,code:ve.code}),Le(this.deps,n,ve.message,!1,{context:i,extraPayload:{code:ve.code}}),d(new Error(ve.message));return}let S=this.deps.orgManager.getOrg(t.targetOrgId),C={orgId:t.targetOrgId,orgTier:Pe(S),operation:t.upsert?"upsert":"insert",objectName:t.objects.map(M=>M.objectApiName).join(", ")||"CloneData",recordCount:"unknown",module:"clone"},{check:R,decision:w}=await et(k,C);if(u.guard=w,(w==="refused"||w==="declined")&&Y(this.deps,{...u,outcome:"stopped",source:void 0}),w==="refused")throw new Error(`${eI}${R.blockedReason??R.impactSummary}`);if(w==="declined"){let M="Operation cancelled by user (confirmation declined).";Le(this.deps,n,M,!1,{context:i,extraPayload:{code:Dr.confirmationDeclined}}),d(new Error(M));return}let P=await B(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),O=await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),E=we(S,t.targetOrgId),$=this.previewedOrgs.get(t.previewId??""),H=$?.recordCounts,J=t.objects.map(M=>({objectApiName:M.objectApiName,recordCount:H?.get(M.objectApiName)??0})),W=J.filter(M=>M.recordCount>0).map(M=>M.objectApiName),Z=(M,X,le)=>{let Oe=le!==void 0?{checkpointRefusal:le}:{};Y(this.deps,{...u,outcome:"stopped",source:void 0,code:M,...le!==void 0?{details:Oe}:{}}),Le(this.deps,n,X,!1,{context:i,authored:!0,extraPayload:{code:M,...Oe}}),d(new Error(X))},_,Q=W.length>0?await this.readTargetAutomation(t.targetOrgId,W).catch(M=>({unread:I(M)})):{unread:"the clone sends no record"},N=W.length>0?await ir({read:Q,writes:wi(W,!0),readDeliverability:()=>Pe(S)==="production"?Promise.resolve(Gt):Jt(O),accepted:!1,target:E,run:"clone",keepsAddresses:t.keepContactPoints===!0}):void 0,z=N?.gate.verdict==="asks";if(t.checkpointFirst!==void 0){try{_=await mi(this.beforeRunCheckpoints,{module:"seed",orgId:t.targetOrgId,operationId:n,written:W,running:rc(Q,wi(W,!0)),request:t.checkpointFirst})}catch(X){if(!(X instanceof Xt))throw X;Z(X.code,X.message);return}let M=Va(_.planned);if(M){Z(M.code,M.message,M.refusal.code);return}}let oe=await this.emailGate(t.targetOrgId,O,J,E,Q,N?.gate.deliverability);for(let M of oe?.unknown??[])this.deps.log(`[WARN] seed:clone:execute ${n}: ${M}`);let re=await vr(Vt(O,t.targetOrgId)).catch(M=>({unread:I(M)})),q=t.upsert?void 0:Ex(J,re);if(oe?.refusal&&oe.figures){let M=Mx(oe.figures,q?`It would be refused for its data storage too: ${dI(q,E)}`:void 0);Y(this.deps,{...u,outcome:"stopped",source:void 0,code:Dr.emailsExceeded}),Le(this.deps,n,M,!1,{context:i,authored:!0,extraPayload:{code:Dr.emailsExceeded,...oe.figures,...q?{alsoRefused:[{code:Dr.storageExceeded,org:E,...q}]}:{}}}),d(new Error(M));return}let F="unread"in re?await ar(O).catch(M=>({unread:I(M)})):re.dailyApiRequests;if(q){let M=Px(q,E);Y(this.deps,{...u,outcome:"stopped",source:void 0,code:Dr.storageExceeded}),Le(this.deps,n,M,!1,{context:i,authored:!0,extraPayload:{code:Dr.storageExceeded,org:E,...q}}),d(new Error(M));return}let ne=Pn({run:kS(J.map(M=>({objectApiName:M.objectApiName,rows:M.recordCount})),{threshold:ut(this.deps).bulk.threshold,perCall:this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200),duplicateRules:Wo(Q),...$?{secondPass:$.secondPass}:{},automationRead:W.length>0?$n(Q):0}),...Bo(_?.planned),...xn(N?.ofRun)},F);ne.verdict==="unread"&&this.deps.log(`[WARN] seed:clone:execute ${n}: the daily API requests the target has left could not be read (${ne.unread})`);let ke=Ja(ne,E,Ta);if(ke){Y(this.deps,{...u,outcome:"stopped",source:void 0,code:Dr.apiBudgetExceeded}),Le(this.deps,n,ke,!1,{context:i,authored:!0,extraPayload:{code:Dr.apiBudgetExceeded}}),d(new Error(ke));return}let de=!1;if(_||z){let M=J.filter(le=>le.recordCount>0).map(le=>({objectApiName:le.objectApiName,rows:le.recordCount})).sort((le,Oe)=>Oe.rows-le.rows),X=await k.confirmRun({stage:"write",module:"seed",org:E,orgTier:Pe(S),objects:M,total:M.reduce((le,Oe)=>le+Oe.rows,0),storage:Dn(Sr({storageBytes:M.reduce((le,Oe)=>le+En(Oe.objectApiName,{rows:Oe.rows}),0)},re)),counted:!0,...Ho(ne),..._?{checkpoint:_.planned}:{},...N?.gate.confirmation});if(X!=="confirmed"){let le=N?.gate.stop;X!=="declined"&&!_&&le?Z(le.code,le.message):Z(X==="declined"?ds:kt.unanswered,X==="declined"?"The clone was cancelled before it wrote anything. Nothing was written.":`The clone needed an answer before it wrote \u2014 the checkpoint it takes first reads whole tables of ${E} \u2014 and there was no one to ask. Nothing was written.`);return}de=z}if(u.details=cn(N?{read:N,accepted:de}:void 0).details,Ge(this.deps,n,"clone",`Clone ${t.objects.length} object(s)`),this.liveTracker?.register(n,"clone",`Clone ${t.objects.length} object(s)`),Tt(u,J.reduce((M,X)=>M+En(X.objectApiName,{rows:X.recordCount}),0)/1048576),_)try{g=await yi(this.beforeRunCheckpoints,_,n,a.signal,(M,X,le,Oe)=>{_e(this.deps,n,M,X,le,Oe),this.liveTracker?.updateProgress(n,M,X,le,Oe)})}catch(M){if(!(M instanceof Xt))throw M;this.stoppedForCheckpoint(e,u,M,i,Date.now()-o),d(M.code===ot?void 0:M);return}l=!0;let Ze=ut(this.deps),xe=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200;i.batchSize=xe;let Ue=new Map,V={objects:0,records:0,of:1};p=this.runCreations?.recorder({runId:n,targetOrgId:t.targetOrgId,sourceOrgId:t.sourceOrgId,startedAt:new Date(o).toISOString(),origin:"clone"}),g&&p?.checkpoint?.(g),Ir(p,()=>O.identity(),`seed:clone:execute ${n}`),p&&this.runningRuns.add(n);let ae=new Nn({...p?{calls:nc(p,M=>{f+=M})}:{},keyPrefixOf:M=>Ue.get(M)?.keyPrefix,connection:O,bulkExecutor:new kn(Ze.bulk.threshold),bulkManager:yr(this.deps),retryConfig:Ze.retry,signal:a.signal,onProgress:(M,X,le)=>{_e(this.deps,n,X>0?Math.round(M/X*100):0,M,X,le),this.liveTracker?.updateProgress(n,Math.round((V.objects+M/Math.max(X,1))/V.of*100),V.records+M,0,le)},log:M=>this.deps.log(M)}),ee=new bi({log:this.deps.log}),fe=new Ri,D=t.objects.map(M=>M.objectApiName),G=new Set(D),ue=new Map,j=new Map,se=new Map;for(let M of D){let[X,le]=await Promise.all([oc("target",M,()=>O.describe(M)),oc("source",M,()=>ee.describe(P,M))]);$e(O.limitInfo,`seed:clone:execute describe ${M}`),$e(P.limitInfo,`seed:clone:execute describe ${M} in the source`),ue.set(M,X),j.set(M,le),se.set(M,Ar(X).fields??[]),Ue.set(M,{keyPrefix:X.keyPrefix??null,recordTypes:Om(X.recordTypeInfos)})}let U=fe.buildEdgesFromDescribe(D,oI(ue,j)),te=fe.resolveInsertOrder(D,U),Se=fe.lookupsFilledAfter(te,U);V.of=Math.max(te.length,1);let De=new Map(t.objects.map(M=>[M.objectApiName,M])),qe=new Map,ce=new Map,Ee=new Map,Ne=[],it=new Mh,nt=0,Ce=!1,zn=new Map,Gn=[],fn=G.has(aa),Ct=M=>Ft(O,M),Mi=new Map,pr=new Map,Li=no(wr(M=>Ft(P,M)),async M=>j.get(M)??await ee.describe(P,M)),bo=new Map,Ro=async(M,X)=>{if(X.length===0)return;let le=await Li(M);for(let Oe of le){let ge=!1;for(let We of X)Oe in We&&(ge||=We[Oe]!==null&&We[Oe]!==void 0,delete We[Oe]);ge&&bo.set(M,(bo.get(M)??new Set).add(Oe))}},Mr=async(M,X)=>{let le=(ue.get(M)?.fields??[]).filter(We=>We.type==="reference"),Oe=await lv({lookups:le,rows:X,known:Mi,query:Ct});if(Oe.size===0)return;let ge=pr.get(M)??new Map;for(let We of X)for(let{name:he}of le){let Ke=We[he];typeof Ke!="string"||!Oe.has(Ke)||(delete We[he],ge.set(he,(ge.get(he)??0)+1))}ge.size!==0&&(pr.set(M,ge),this.deps.log(`[INFO] seed:clone ${M}: written without a user or a queue the target does not hold, which the platform fills (the owner with the user the clone writes as): `+[...ge].map(([We,he])=>`${We} on ${he}`).join(", ")))},vo=async(M,X)=>{await Ro(M,X),await Mr(M,X),v&&cS(v,M,se.get(M)??[],X,y?t.externalIdField:void 0),X.length>0&&(h=!0);try{return{outcomes:t.upsert&&t.externalIdField?await ae.upsert(M,t.externalIdField,X,xe):await ae.insert(M,X,xe),stopped:!1}}catch(le){if(!(le instanceof Zo))throw le;return{outcomes:le.written,stopped:!0}}},$t=(M,X,le,Oe)=>{M.forEach((ge,We)=>{let he=typeof X[We]?.Id=="string"?X[We].Id:"";if(ge.success){le.insertedCount++,he&&ge.id&&(qe.set(he,ge.id),le.idMappings.push({sourceId:he,targetId:ge.id}));let Ke=ge.id;if(Ke)for(let{fieldName:Je,sourceRefId:Lt}of Oe[We]??[])Ne.push({objectApiName:le.objectApiName,newId:Ke,sourceId:he||void 0,fieldName:Je,sourceRefId:Lt})}else ge.existingId?(le.linkedCount=(le.linkedCount??0)+1,he&&(qe.set(he,ge.existingId),le.idMappings.push({sourceId:he,targetId:ge.existingId}))):(le.failedCount++,le.errors.push({sourceId:he,message:ge.errors[0]??"Unknown insert error"}))})},So=async M=>{let X=new Map((m.find(he=>he.objectApiName===rr)?.idMappings??[]).map(he=>[he.sourceId,he.targetId])),le=new Map;for(let[he,Ke]of zn){let Je=X.get(he);Je&&le.set(Ke,Je)}let Oe=M.map(he=>String(he.Id)).filter(he=>le.has(he));if(Oe.length===0)return new Map;let ge;try{ge=await _h(Ct,[...new Set(Oe.map(he=>le.get(he)??""))])}catch(he){return this.deps.log(`[seed:clone] tasks written with the clone's emails not looked up, written as read: ${I(he)}`),new Map}let We=new Map;for(let he of Oe){let Ke=ge.get(le.get(he)??"");Ke&&We.set(he,Ke)}return We},Lr=async(M,X,le)=>{if(Bh[M]===void 0)return new Map;let Oe;try{Oe=await qh(Ct,M,le)}catch(We){return this.deps.log(`[seed:clone] ${M}: the relations the target holds not looked up, written as read: ${I(We)}`),new Map}let ge=new Map;for(let[We,he]of Oe){let Ke=X[We]?.Id;typeof Ke=="string"&&ge.set(Ke,he)}return ge},Fi=async(M,X)=>{if(ce.size===0)return new Map;let le=ue.get(mr),Oe=[...new Set(X.flatMap(Je=>Object.keys(Je)))].filter(Je=>iI(le,Je)),ge;try{ge=await Hh(Ct,X.map((Je,Lt)=>({OpportunityId:Je.OpportunityId,[Ns]:Je[Ns],IsPrimary:M[Lt]?.IsPrimary})),Je=>ce.get(Je),Oe)}catch(Je){return this.deps.log(`[seed:clone] ${mr}: the roles the platform wrote with the clone's opportunities not looked up, written as read \u2014 an opportunity may hold the role of its contact twice: ${I(Je)}`),new Map}let{found:We,alike:he}=ge;if(he.length>0){this.deps.log(`[seed:clone] ${mr}: ${Uh(he.length)}`);for(let Je of he)ce.delete(String(X[Je]?.OpportunityId))}let Ke=new Map;for(let[Je,Lt]of We){let At=M[Je]?.Id;typeof At=="string"&&(Ke.set(At,String(Lt.Id)),Ee.set(At,Lt),ce.delete(String(X[Je]?.OpportunityId)))}return Ke},Fr=async(M,X)=>{let le=ue.get(mr),Oe=[];if(M.forEach(([he,Ke],Je)=>{let Lt=Ee.get(String(he.Id))??{},At=Object.entries(X[Je]??{}).filter(([rt,gn])=>iI(le,rt)&&gn!==null&&gn!==void 0&&String(Lt[rt]??"")!==String(gn));At.length>0&&Oe.push({Id:Ke,...Object.fromEntries(At)})}),Oe.length===0||Ce||a.signal.aborted)return;let ge;try{ge=await ae.update(mr,Oe,xe)}catch(he){if(!(he instanceof Zo))throw he;Ce=!0,ge=he.written}let We=Oe.flatMap((he,Ke)=>ge[Ke]?.success?[]:[`${he.Id}: ${ge[Ke]?.errors[0]??"not updated"}`]);We.length>0&&this.deps.log(`[seed:clone] ${mr}: linked, and left as the platform wrote them, without the fields of the source's roles: ${We.slice(0,3).join(" | ")}`)},Ss=async()=>{fn=!1;let M=Gn.splice(0,Gn.length),X=m.find(he=>he.objectApiName===rr);if(M.length===0||!X||Ce)return;if(a.signal.aborted){Ce=!0;return}let le=M.map(he=>aI(rr,he,ue.get(rr),G,qe)),Oe=sI(rr,M,le,Se,qe),{outcomes:ge,stopped:We}=await vo(rr,le);$t(ge,M,X,Oe),V.records+=M.length,We&&(Ce=!0)};for(let M=0;M<te.length;M++){if(a.signal.aborted){Ce=!0;break}let X=te[M],le=De.get(X);_e(this.deps,n,Math.round(M/te.length*100),M,te.length,`Cloning ${X}`),V.objects=M,this.liveTracker?.updateProgress(n,Math.round(M/te.length*100),V.records,0,`Cloning ${X}`);let Oe;try{Oe=await ee.fetchRecords(P,X,le.whereClause)}catch(be){nt++,m.push({objectApiName:X,sourceCount:0,insertedCount:0,failedCount:0,idMappings:[],errors:[{sourceId:"",message:I(be)}]});continue}let ge=it.keep(X,Oe,nI(X,ue.get(X),j.get(X)).map(({name:be})=>be)),We=Oe.length-ge.length;if(X===rr)for(let be of ge){let He=be.ActivityId;typeof be.Id=="string"&&typeof He=="string"&&He!==""&&zn.set(be.Id,He)}let he=ge.map(be=>aI(X,be,ue.get(X),G,qe)),Ke=Wx(ge,ue.get(X));Ke.length>0&&this.deps.log(`[INFO] seed:clone ${X}: ${Ke.length} field(s) the target does not have left out \u2014 ${Ke.join(", ")}`);let Je=sI(X,ge,he,Se,qe),Lt=Im(X,he,Ue.get(X)?.recordTypes??[]);if(Lt.length>0){nt++,m.push({objectApiName:X,sourceCount:Oe.length,insertedCount:0,failedCount:ge.length,...We>0?{leftToThePlatform:We}:{},idMappings:[],errors:Lt.map(be=>{let He=ge.find((Me,at)=>Am(he[at],[be]));return{sourceId:typeof He?.Id=="string"?He.Id:be.recordTypeId,message:Tm(be)}})});continue}if(X===rr&&fn){let be=ge.map(He=>Fh(He));Gn.push(...ge.filter((He,Me)=>be[Me])),ge=ge.filter((He,Me)=>!be[Me]),he=he.filter((He,Me)=>!be[Me]),Je=Je.filter((He,Me)=>!be[Me])}let At=X===aa?await So(ge):X===mr?await Fi(ge,he):await Lr(X,ge,he),rt=[],gn=[];if(At.size>0){let be=ge.map(He=>!At.has(String(He.Id)));ge.forEach((He,Me)=>{be[Me]||(rt.push([He,At.get(String(He.Id))??""]),gn.push(he[Me]))}),ge=ge.filter((He,Me)=>be[Me]),he=he.filter((He,Me)=>be[Me]),Je=Je.filter((He,Me)=>be[Me])}if(a.signal.aborted){Ce=!0;break}let{outcomes:ks,stopped:ye}=await vo(X,he);if(ye&&(Ce=!0,ks.length===0))break;if(X===Gx&&ks.forEach((be,He)=>{let Me=he[He]?.[Ns];be.success&&be.id&&be.created!==!1&&typeof Me=="string"&&Me!==""&&ce.set(be.id,Me)}),X===mr&&rt.length>0&&await Fr(rt,gn),rt.length>0){let be=ue.get(X),He=await Wh(X,rt,Me=>be?.fields.find(at=>at.name===Me)?.updateable!==!1,async Me=>{try{return await ae.update(X,Me,xe)}catch(at){if(!(at instanceof Zo))throw at;return Ce=!0,at.written}},()=>Ce||a.signal.aborted);He&&this.deps.log(`[seed:clone] ${X}: ${He}`)}let Fe={objectApiName:X,sourceCount:Oe.length,insertedCount:0,failedCount:0,linkedCount:At.size,...X===mr&&At.size>0?{writtenByThePlatform:At.size}:{},...We>0?{leftToThePlatform:We}:{},...Ke.length>0?{fieldsNotInTarget:Ke}:{},idMappings:[],errors:[]};for(let[be,He]of At)qe.set(be,He),Fe.idMappings.push({sourceId:be,targetId:He});if($t(ks,ge,Fe,Je),m.push(Fe),V.records+=ge.length,Ce)break;X===aa&&await Ss()}await Ss();let pt;if(Ne.length>0&&(a.signal.aborted&&(Ce=!0),pt=Ce?qx(Ne):await Bx({owed:Ne,idMap:qe,targetConn:O,targetOrgId:t.targetOrgId,stopped:()=>a.signal.aborted,report:M=>{_e(this.deps,n,100,V.records,V.records,M),this.liveTracker?.updateProgress(n,100,V.records,0,M)}}),a.signal.aborted&&(Ce=!0),p&&pt.filled>0)){let M=new Map;for(let{objectApiName:X,newId:le}of Ne)M.set(X,[...M.get(X)??[],le]);for(let[X,le]of M)p.wroteAgain(X,le)}for(let M of m){let X=pr.get(M.objectApiName);X&&(M.lookupsNotCarried=[...X].map(([Oe,ge])=>({field:Oe,records:ge})));let le=bo.get(M.objectApiName);le&&(M.encryptedLeftOut=[...le].sort())}let Jn=m.reduce((M,X)=>M+X.sourceCount,0),_r=m.reduce((M,X)=>M+X.insertedCount,0),Vn=m.reduce((M,X)=>M+(X.linkedCount??0),0),_i=m.reduce((M,X)=>M+(X.leftToThePlatform??0),0),Xn=m.reduce((M,X)=>M+X.failedCount,0),Ui=Xn===0&&nt===0?"success":_r+Vn>0?"partial":"failure",je=pt!==void 0&&pt.filled<pt.owed,ze=b(),Ye=(Ce||je)&&Ui==="success"?"partial":Ui,dt=await this.endKept(p,n,{status:Ye,cancelled:Ce});p=void 0;let ct=await Ln(this.beforeRunCheckpoints,g,h,this.deps.log,`seed:clone:execute ${n}`);g=void 0;let Qe={status:Ye,objectResults:m,totalSourceRecords:Jn,totalInserted:_r,totalLinked:Vn,..._i>0?{totalLeftToThePlatform:_i}:{},totalFailed:Xn,...pt?{secondPass:pt}:{},durationMs:Date.now()-o,...Ce?{cancelled:!0}:{},contactPoints:ze,...dt&&f>0?{runId:n}:{}};l=!1;let Ur=Ce?_r+Xn>0?"cancelled":"stopped":Qe.status;Y(this.deps,{...rI(u,Ur,m,y,ze),...Ur==="stopped"?{code:ot}:{},...ct?.state==="taken"?{checkpointId:ct.checkpointId}:{}});let wt=!Ce&&Qe.status==="failure"?"No record could be cloned.":void 0;Ce?(this.registry?.abort(n),me(this.deps,n,{aborted:!0,totalInserted:_r,totalFailed:Xn}),this.liveTracker?.cancel(n)):(me(this.deps,n,{status:Qe.status,totalInserted:_r,totalFailed:Xn}),wt!==void 0?this.liveTracker?.fail(n,wt):Qe.status==="partial"?this.liveTracker?.partial(n):this.liveTracker?.complete(n));let fr={...Qe,...ct?{checkpoint:ct}:{}},Yt=A(this.deps,e,"seed:clone:execute:response",fr);this.deps.broker.postToWebview(Yt),this.deps.log(`[TX] ${Yt.type} id=${Yt.id} status=${Qe.status}`),d(wt===void 0?void 0:new Error(wt))}catch(k){let S=await Ln(this.beforeRunCheckpoints,g,h,this.deps.log,`seed:clone:execute ${n}`);l&&Y(this.deps,{...rI(u,"failure",m,y,b()),...S?.state==="taken"?{checkpointId:S.checkpointId}:{}}),await this.endKept(p,n,{status:"failure",cancelled:!1});let C=S?.state==="deleted"?`${I(k)} ${Zr}`:I(k);this.deps.log(`[ERR] seed:clone:execute: ${C}`),Le(this.deps,n,I(k),!0,{context:i,extraPayload:{code:C.startsWith(eI)?Dr.guardBlocked:Dr.failed,...S?{checkpoint:S}:{}}}),this.liveTracker?.fail(n,C),d(k)}}};function Mx(s,e){let t=[`narrow the filters of ${s.objects.join(", ")} or leave them out`,`turn off ${s.senders.map(r=>`"${r}"`).join(", ")}`,...s.bypasses.map(r=>"give the user the clone writes as "+(r.permissionSet?`the permission set ${r.permissionSet}, whose ${r.permission}`:`a permission set holding ${r.permission}, which`)+" keeps them quiet")];return`The clone was refused before it wrote anything: its records would make ${s.org} send about ${HR(s.emails,s.limit)}, ${s.remaining} of ${s.max} left today. Past what is left, a flow that sends in the save refuses its record (CANNOT_EXECUTE_FLOW_TRIGGER), and the org's own emails stop for the rest of the day. To clone them, ${t.join("; or ")}. ${e?`${e} `:""}Nothing was written.`}function rI(s,e,t,r,n){return{...s,details:{...s.details,...Kr(n).details},outcome:e,objects:t.map(o=>({...bt(o.objectApiName),...r?{upserted:o.insertedCount}:{created:o.insertedCount},failed:o.failedCount})),carried:Object.fromEntries(t.map(o=>[o.objectApiName,o.idMappings.length]))}}function nI(s,e,t){let r=new Set((t?.fields??[]).map(n=>n.name));return(e?.fields??[]).filter(n=>n.type==="reference"&&r.has(n.name)&&As(s,n.name,n.nillable)).map(n=>({name:n.name,referenceTo:n.referenceTo??[]}))}async function oc(s,e,t){try{return await t()}catch(r){let n=I(r);throw s==="target"&&Fx(r,n)?new cs(e,n):new Error(`${e} could not be described in the ${s} org: ${n}`)}}var Lx="OBJECT_NOT_IN_TARGET",cs=class extends Error{constructor(t,r){let n=typeof t=="string"?[t]:t,o=n.length===1,i=o?n[0]:`${n.slice(0,-1).join(", ")} and ${n[n.length-1]}`,a=o?"it":"them";super(`${i} ${o?"is":"are"} not in the target org, or the user SandForge connects as there may not see ${a} (${r}): untick ${a} to clone the others, or deploy ${a} to the target first (Compare, Deploy from Diff) and give that user access to ${a}.`);this.why=r;this.objectApiNames=n,this.name="ObjectNotInTargetError"}why;objectApiNames;get objectApiName(){return this.objectApiNames[0]??""}};function Fx(s,e){return s?.errorCode==="NOT_FOUND"||/\bNOT_FOUND\b|requested resource does not exist|INVALID_TYPE/.test(e)}function oI(s,e){return new Map([...s].map(([t,r])=>{let n=new Map((e.get(t)?.fields??[]).map(i=>[i.name,i.referenceTo??[]])),o=r.fields.flatMap(i=>{if(i.type!=="reference")return[i];let a=n.get(i.name)??[],d=(i.referenceTo??[]).filter(c=>a.includes(c));return d.length>0?[{...i,referenceTo:d}]:[]});return[t,{fields:o}]}))}function _x(s,e){let t=new Map(e.map((r,n)=>[r,n]));return s.map(r=>({objectApiName:r.to,field:r.fieldApiName,referenceTo:r.from})).sort((r,n)=>(t.get(r.objectApiName)??0)-(t.get(n.objectApiName)??0))}function Ux(s,e,t){let r=new Set(s);return s.flatMap(n=>{let o=ic(t.get(n));return o?(e.get(n)?.fields??[]).filter(i=>i.type==="reference"&&i.createable!==!1&&!o.has(i.name)).flatMap(i=>(i.referenceTo??[]).filter(a=>r.has(a)).map(a=>({objectApiName:n,field:i.name,referenceTo:a}))):[]})}function Hx(s,e,t){return s.flatMap(r=>{let n=ic(t.get(r));return n?(e.get(r)?.fields??[]).filter(o=>o.type==="reference"&&!n.has(o.name)&&o.createable!==!1&&o.defaultedOnCreate!==!0&&As(r,o.name,o.nillable)).flatMap(o=>(o.referenceTo??[]).map(i=>({objectApiName:r,field:o.name,referenceTo:i}))):[]})}function sI(s,e,t,r,n){let o=r.filter(c=>c.to===s),i=new Set(o.filter(c=>c.from!==s).map(c=>c.fieldApiName)),a=new Set(o.map(c=>c.fieldApiName)),d=new Set(e.map(c=>c.Id).filter(c=>typeof c=="string"));return t.map((c,u)=>{let l=[];for(let p of a){let f=e[u]?.[p];typeof f!="string"||f===""||n.has(f)||p in c&&(!i.has(p)&&!d.has(f)||(delete c[p],l.push({fieldName:p,sourceRefId:f})))}return l})}async function Bx(s){let{owed:e,targetConn:t}=s,{patchCycleFkUpdates:r}=await import("./chunk-PKYDNZJK.mjs"),n=await r({pendingFkUpdates:e,remapper:s.idMap,updateRecords:async(o,i,a)=>{let d=await t.sobject(i).update(a,{allowRecursive:!0,headers:Vi()});return(Array.isArray(d)?d:[d]).map((c,u)=>{let l=a[u]?.Id;return{id:c.id??(typeof l=="string"?l:""),success:c.success,errors:(c.success?[]:c.errors).map(ob)}})},targetOrgId:s.targetOrgId,enabled:!0,stopped:s.stopped,onProgress:o=>s.report(o.message)});return{owed:e.length,filled:e.length-(n?.failedCount??0),samples:(n?.samples??[]).map(({recordSummary:o,messages:i})=>({record:o,messages:i}))}}function qx(s){let e=[...new Set(s.map(t=>t.objectApiName))];return{owed:s.length,filled:0,samples:[{record:`${e.join(", ")}: ${s.length} lookup${s.length===1?"":"s"} not sent`,messages:["The run was cancelled before they were filled in: they stay empty."]}],cancelledBefore:!0}}function ic(s){let e=new Set((s?.fields??[]).map(t=>t.name));return e.size>0?e:null}function Wx(s,e){let t=ic(e);if(!t)return[];let r=new Set;for(let n of s)for(let o of Object.keys(n))o!=="Id"&&!t.has(o)&&r.add(o);return[...r].sort()}function zx(s,e){let t={};for(let[r,n]of Object.entries(s)){if(Object.keys(t).length>=e)break;n==null||n===""||(t[r]=n)}return t}var Gx="Opportunity";function iI(s,e){if(e==="OpportunityId"||e===Ns)return!1;let t=s?.fields.find(r=>r.name===e);return t!==void 0&&t.updateable!==!1}function aI(s,e,t,r,n){let o=new Set((t?.fields??[]).filter(d=>d.createable===!1).map(d=>d.name)),i=ic(t),a={};for(let[d,c]of Object.entries(e))d==="Id"||o.has(d)||i&&!i.has(d)||(a[d]=c);if(t)for(let d of t.fields){if(d.type!=="reference"||!(d.referenceTo??[]).some(u=>r.has(u)))continue;let c=a[d.name];typeof c=="string"&&n.has(c)&&(a[d.name]=n.get(c))}for(let d of da(s,a))delete a[d];return a}var Jx=new Set(["double","currency","percent","int","integer"]),ac=class{validate(e,t,r,n){let o=[],i=new Map(r.map(a=>[a.name,a]));for(let a=0;a<e.length&&o.length<100;a++){let d=e[a];for(let c of t){if(o.length>=100)break;if(!c.sfFieldApiName)continue;let u=i.get(c.sfFieldApiName);if(!u)continue;let l=d[c.csvHeader]??"";if(l===""&&!u.nillable&&u.defaultValue===null){o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"missing_required",message:`Required field "${c.sfFieldApiName}" is empty`,value:l});continue}if(l!==""){if(Jx.has(u.type.toLowerCase())){let p=parseFloat(l);isNaN(p)&&o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"type_mismatch",message:`Expected numeric value for field "${c.sfFieldApiName}", got "${l}"`,value:l})}u.length&&u.length>0&&l.length>u.length&&o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"length_exceeded",message:`Value exceeds max length ${u.length} for field "${c.sfFieldApiName}" (got ${l.length})`,value:l}),u.type.toLowerCase()==="picklist"&&u.picklistValues&&u.picklistValues.length>0&&(u.picklistValues.map(f=>f.value).includes(l)||o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"invalid_picklist",message:`Invalid picklist value "${l}" for field "${c.sfFieldApiName}"`,value:l}))}}}if(n&&o.length<100){let a=t.find(d=>d.sfFieldApiName===n);if(a){let d=new Map;for(let c=0;c<e.length&&o.length<100;c++){let u=e[c][a.csvHeader]??"";if(u==="")continue;let l=d.get(u);l!==void 0?o.push({row:c+1,column:a.csvHeader,field:n,errorType:"duplicate_external_id",message:`Duplicate external ID "${u}" (also in row ${l})`,value:u}):d.set(u,c+1)}}}return{valid:o.length===0,errors:o,warningCount:0}}};var Vx=new Set(["seed:csv:validate","seed:csv:execute"]),Xx=100,cI="IMPORT_CANCELLED",Kx=6e4,cf="CSV_STORAGE_EXCEEDED";function Yx(s){let e=s<10?100:10;return String(s<=0?0:Math.ceil(s*e-1e-9)/e)}function Qx(s,e,t){let r=e>0?En(s,{rows:e})/e:0,n=SR(t);return r>0?Math.max(0,Math.floor(n*1024*1024/r)):0}var dc=class{constructor(e){this.deps=e}deps;registry;liveTracker;setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}runCreations;runningRuns=new Set;setRunCreations(e){this.runCreations=e}isRunning(e){return this.runningRuns.has(e)}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}beforeRunCheckpoints;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-UK3QLBHW.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async handle(e){if(!Vx.has(e.type))return!1;switch(e.type){case"seed:csv:validate":return await this.handleValidate(e),!0;case"seed:csv:execute":return await this.handleExecute(e),!0;default:return!1}}async endKept(e,t,r){if(!e)return!1;try{return await e.end({finishedAt:new Date().toISOString(),status:r.status,...r.cancelled?{cancelled:!0}:{},objectResults:[]}),!0}catch(n){return this.deps.log(`[WARN] seed:csv:execute ${t}: what the import created could not all be kept, so removing it may leave some of it in the org: ${I(n)}`),!1}finally{this.runningRuns.delete(t)}}stoppedForCheckpoint(e,t,r,n){let{operationId:o}=t;if(r.code===ot){Y(this.deps,{...t,outcome:"stopped",source:void 0,code:cI}),this.registry?.abort(o),me(this.deps,o,{aborted:!0,insertedCount:0,failedCount:0}),this.liveTracker?.cancel(o);let d={insertedCount:0,failedCount:0,errors:[],cancelled:!0};this.deps.broker.postToWebview(A(this.deps,e,"seed:csv:execute:response",d));return}let i=r.refusal?.code,a=i!==void 0?{checkpointRefusal:i}:{};Y(this.deps,{...t,outcome:"stopped",source:void 0,code:r.code,...i!==void 0?{details:a}:{}}),T(this.deps,"seed:csv:execute","seed:csv:error",e,r,{code:r.code,retryable:!1,...i!==void 0?{extraPayload:a}:{}}),Le(this.deps,o,r.message,!1,{context:n,authored:!0,extraPayload:{code:r.code,...a}}),this.liveTracker?.fail(o,r.message)}async handleValidate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Al,e,"seed:csv:error",this.deps);if(t)try{let r=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager),n=await r.describe(t.objectApiName);$e(r.limitInfo,`seed:csv:validate describe ${t.objectApiName}`);let i=new ac().validate(t.records,t.columnMappings,n.fields,t.externalIdField),a=A(this.deps,e,"seed:csv:validate:response",i);this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id} valid=${i.valid}`)}catch(r){T(this.deps,"seed:csv:validate","seed:csv:error",e,r)}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Al,e,"seed:csv:error",this.deps);if(!t)return;let r=e.id,n={module:"seed",operation:e.type,objectName:t.objectApiName},o=new AbortController,i=()=>{},a=new Promise((g,h)=>{i=m=>m===void 0?g():h(m)});a.catch(()=>{}),this.registry?.register(r,"csv","CSV import",a,o);let d={action:"seed_csv_import",module:"seed",operationId:r,orgId:t.orgId,outcome:"failure",source:{origin:"csv"}},c=!1,u,l=0,p,f=!1;try{let g=this.deps.infraServices?.productionGuard;if(!g){Y(this.deps,{...d,outcome:"stopped",source:void 0,code:ve.code}),T(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(ve.message),{code:ve.code,retryable:!1}),Le(this.deps,r,ve.message,!1,{context:n,extraPayload:{code:ve.code}}),i(new Error(ve.message));return}let h=this.deps.orgManager.getOrg(t.orgId),m={orgId:t.orgId,orgTier:Pe(h),operation:t.externalIdField?"upsert":"insert",objectName:t.objectApiName,recordCount:t.records.length,module:"seed"},{check:y,decision:v}=await et(g,m);if(d.guard=v,(v==="refused"||v==="declined")&&Y(this.deps,{...d,outcome:"stopped",source:void 0}),v==="refused")throw bn(y.blockedReason??y.impactSummary);if(v==="declined"){let ee="Operation cancelled by user (confirmation declined).";T(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(ee),{code:Dt.declined}),Le(this.deps,r,ee,!1,{context:n}),i(new Error(ee));return}let b=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager),k=we(h,t.orgId),S=(ee,fe,D)=>{let G=D!==void 0?{checkpointRefusal:D}:{};Y(this.deps,{...d,outcome:"stopped",source:void 0,code:ee,...D!==void 0?{details:G}:{}}),T(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(fe),{code:ee,retryable:!1,...D!==void 0?{extraPayload:G}:{}}),Le(this.deps,r,fe,!1,{context:n,authored:!0,extraPayload:{code:ee,...G}}),i(new Error(fe))},C=this.targetAutomation,R=wi([t.objectApiName],!!t.externalIdField),w=await new pe(Kx).withTimeout("csv automation",()=>C.read(t.orgId,[t.objectApiName])).catch(ee=>({unread:I(ee)}));typeof w.unread=="string"&&this.deps.log(`[WARN] seed:csv:execute ${r}: what the org runs on ${t.objectApiName} could not be read (${w.unread}): it is asked about its emails, and a checkpoint holds the object alone`);let P=await ir({read:w,writes:R,readDeliverability:()=>Pe(h)==="production"?Promise.resolve(Gt):Jt(b),accepted:!1,target:k,run:"seed",keepsAddresses:!0}),O=P.gate.verdict==="asks",E;if(t.checkpointFirst!==void 0){try{E=await mi(this.beforeRunCheckpoints,{module:"seed",orgId:t.orgId,operationId:r,written:[t.objectApiName],running:rc(w,R),request:t.checkpointFirst})}catch(fe){if(!(fe instanceof Xt))throw fe;S(fe.code,fe.message);return}let ee=Va(E.planned);if(ee){S(ee.code,ee.message,ee.refusal.code);return}}let $=await vr(Vt(b,t.orgId)).catch(ee=>({unread:I(ee)})),H="unread"in $?await ar(b).catch(ee=>({unread:I(ee)})):$.dailyApiRequests,J=Sr({storageBytes:En(t.objectApiName,{rows:t.records.length})},$);if(!t.externalIdField&&J.verdict==="exceeds"){let ee=t.records.length,fe=Qx(t.objectApiName,ee,J),D=kr(J),G=fe>0?`room for about ${fe} of them: split the file and import one part at a time, freeing data storage in between as needed.`:`room for none of them: free data storage in ${k}, then import it again.`,ue=`The import was refused before it wrote anything: its ${ee} rows take about ${Yx(J.estimateMB)} MB of data storage, and ${k} has ${J.remainingMB} MB left of ${J.maxMB} MB${Ka(D,k)}, ${G} Nothing was written.`;Y(this.deps,{...d,outcome:"stopped",source:void 0,code:cf});let j={org:k,rows:ee,fitting:fe,estimateMB:J.estimateMB,remainingMB:J.remainingMB,maxMB:J.maxMB,...D};T(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(ue),{code:cf,retryable:!1,extraPayload:j}),Le(this.deps,r,ue,!1,{context:n,authored:!0,extraPayload:{code:cf,...j}}),i(new Error(ue));return}let W=Pn({run:vS([{objectApiName:t.objectApiName,rows:t.records.length}],{threshold:ut(this.deps).bulk.threshold,perCall:this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200),duplicateRules:Wo(w)})+SS(0,$n(w)),...Bo(E?.planned),...xn(P.ofRun)},H);W.verdict==="unread"&&this.deps.log(`[WARN] seed:csv:execute ${r}: the daily API requests the org has left could not be read (${W.unread})`);let Z=Ja(W,we(h,t.orgId),Ta);if(Z){Y(this.deps,{...d,outcome:"stopped",source:void 0,code:Uo}),T(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(Z),{code:Uo,retryable:!1}),Le(this.deps,r,Z,!1,{context:n,authored:!0,extraPayload:{code:Uo}}),i(new Error(Z));return}let _=!1;if(E||O){let ee=t.records.length,fe=await g.confirmRun({stage:"write",module:"seed",org:k,orgTier:Pe(h),objects:[{objectApiName:t.objectApiName,rows:ee}],total:ee,storage:Dn(Sr({storageBytes:En(t.objectApiName,{rows:ee})},$)),...Ho(W),...E?{checkpoint:E.planned}:{},...P.gate.confirmation});if(fe!=="confirmed"){let D=P.gate.stop;fe!=="declined"&&!E&&D?S(D.code,D.message):S(fe==="declined"?ds:kt.unanswered,fe==="declined"?"The import was cancelled before it wrote anything. Nothing was written.":`The import needed an answer before it wrote \u2014 the checkpoint it takes first reads whole tables of ${k} \u2014 and there was no one to ask. Nothing was written.`);return}_=O}if(d.details=cn({read:P,accepted:_}).details,Ge(this.deps,r,"seed",`CSV import ${t.records.length} record(s) into ${t.objectApiName}`),this.liveTracker?.register(r,"csv",`CSV import ${t.records.length} record(s) into ${t.objectApiName}`,t.records.length),Tt(d,J.estimateMB),E)try{p=await yi(this.beforeRunCheckpoints,E,r,o.signal,(ee,fe,D,G)=>{_e(this.deps,r,ee,fe,D,G),this.liveTracker?.updateProgress(r,ee,fe,D,G)})}catch(ee){if(!(ee instanceof Xt))throw ee;this.stoppedForCheckpoint(e,d,ee,n),i(ee.code===ot?void 0:ee);return}c=!0;let Q=ut(this.deps),N=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200;n.batchSize=N,u=this.runCreations?.recorder({runId:r,targetOrgId:t.orgId,startedAt:new Date().toISOString(),origin:"csv"}),p&&u?.checkpoint?.(p),Ir(u,()=>b.identity(),`seed:csv:execute ${r}`),u&&this.runningRuns.add(r);let z=new Nn({connection:b,bulkExecutor:new kn(Q.bulk.threshold),bulkManager:yr(this.deps),retryConfig:Q.retry,signal:o.signal,onProgress:(ee,fe,D)=>{let G=fe>0?Math.round(ee/fe*100):0;_e(this.deps,r,G,ee,fe,D),this.liveTracker?.updateProgress(r,G,ee,fe,D)},log:ee=>this.deps.log(ee),...u?{calls:nc(u,ee=>{l+=ee})}:{}}),oe=t.records.map(ee=>Zx(ee,t.columnMappings)),re=o.signal.aborted,q=[];if(!re){oe.length>0&&(f=!0);try{q=t.externalIdField?await z.upsert(t.objectApiName,t.externalIdField,oe,N):await z.insert(t.objectApiName,oe,N)}catch(ee){if(!(ee instanceof Zo))throw ee;re=!0,q=ee.written}}let F=[],ne=0;for(let ee of q)ee.success?ne++:F.length<Xx&&F.push(ee.errors[0]??"Unknown insert error");let ke=q.length-ne,de=ke===0?"success":ne>0?"partial":"failure",Ze=!re&&de==="failure"?F[0]??"No row could be imported.":void 0;c=!1;let xe=await Ln(this.beforeRunCheckpoints,p,f,this.deps.log,`seed:csv:execute ${r}`);p=void 0,re&&q.length===0?Y(this.deps,{...d,outcome:"stopped",source:void 0,code:cI}):Y(this.deps,{...d,outcome:re?"cancelled":de,objects:[{...bt(t.objectApiName),...t.externalIdField?{upserted:ne}:{created:ne},failed:ke}],...xe?.state==="taken"?{checkpointId:xe.checkpointId}:{}});let Ue=await this.endKept(u,r,{status:re&&de==="success"?"partial":de,cancelled:re});u=void 0;let V={insertedCount:ne,failedCount:ke,errors:F,...re?{cancelled:!0}:{},...Ue&&l>0?{runId:r}:{},...xe?{checkpoint:xe}:{}};re?(this.registry?.abort(r),me(this.deps,r,{aborted:!0,insertedCount:ne,failedCount:ke}),this.liveTracker?.cancel(r)):(me(this.deps,r,{status:de,insertedCount:ne,failedCount:ke}),Ze!==void 0?this.liveTracker?.fail(r,Ze):de==="partial"?this.liveTracker?.partial(r):this.liveTracker?.complete(r));let ae=A(this.deps,e,"seed:csv:execute:response",V);this.deps.broker.postToWebview(ae),this.deps.log(`[TX] ${ae.type} id=${ae.id} inserted=${ne} failed=${ke}`),i(Ze===void 0?void 0:new Error(Ze))}catch(g){let h=await Ln(this.beforeRunCheckpoints,p,f,this.deps.log,`seed:csv:execute ${r}`);c&&Y(this.deps,{...d,...h?.state==="taken"?{checkpointId:h.checkpointId}:{}}),await this.endKept(u,r,{status:"failure",cancelled:!1});let m=h?.state==="deleted"?`${I(g)} ${Zr}`:I(g);T(this.deps,"seed:csv:execute","seed:csv:error",e,g,{code:xo(g),retryable:!0,...h?{extraPayload:{checkpoint:h}}:{}}),Le(this.deps,r,m,!0,{context:n}),this.liveTracker?.fail(r,m),i(g)}}};function Zx(s,e){let t={};for(let r of e){if(!r.sfFieldApiName)continue;let n=s[r.csvHeader];n===void 0||n===""||(t[r.sfFieldApiName]=eD(n))}return t}function eD(s){if(s==="true")return!0;if(s==="false")return!1;if(s==="null")return null;let e=Number(s);return!Number.isNaN(e)&&s.trim()!==""?e:s}var tD={string:new Set(["string","textarea","richtext","phone","email","url","picklist","multipicklist","encryptedstring"]),int:new Set(["int","double","currency","percent","string"]),double:new Set(["double","currency","percent","string"]),currency:new Set(["currency","double","string"]),percent:new Set(["percent","double","string"]),boolean:new Set(["boolean","string"]),date:new Set(["date","datetime","string"]),datetime:new Set(["datetime","date","string"]),id:new Set(["id","reference","string"]),reference:new Set(["reference","id","string"]),picklist:new Set(["picklist","string","multipicklist"]),multipicklist:new Set(["multipicklist","string"]),phone:new Set(["phone","string"]),email:new Set(["email","string"]),url:new Set(["url","string"]),textarea:new Set(["textarea","richtext","string"]),richtext:new Set(["richtext","textarea","string"]),time:new Set(["time","string"]),base64:new Set(["base64","string"]),address:new Set(["address"]),location:new Set(["location"])},rD=[{source:"double",target:"int",reason:"Decimal portion will be truncated"},{source:"datetime",target:"date",reason:"Time portion will be lost"},{source:"richtext",target:"textarea",reason:"HTML formatting will be lost"},{source:"multipicklist",target:"picklist",reason:"Multiple selections may be lost"}];function uf(s,e){let t=s.toLowerCase(),r=e.toLowerCase();if(t===r)return!0;let n=tD[t];return n?n.has(r):r==="string"}var cc=class{validateMapping(e,t,r){let n=[],o=[],i=new Map(e.map(d=>[d.apiName,d])),a=new Map(t.map(d=>[d.apiName,d]));for(let[d,c]of Object.entries(r)){let u=i.get(d),l=a.get(c);if(!u||!l)continue;let p=this.checkTypeCompatibility(d,u.type,c,l.type);p.compatible?p.reason&&o.push(p):n.push(p)}return{valid:n.length===0,errors:n,warnings:o}}validateRecords(e,t){let r=[];for(let n=0;n<e.length;n++){let o=e[n];for(let i of t){let a=o[i.apiName];if(i.required&&uI(a)){r.push({recordIndex:n,field:i.apiName,message:`Required field '${i.apiName}' is missing or empty`});continue}if(uI(a))continue;let d=this.validateValueType(a,i);if(d){r.push({recordIndex:n,field:i.apiName,message:d});continue}if(i.maxLength!==void 0&&typeof a=="string"&&a.length>i.maxLength&&r.push({recordIndex:n,field:i.apiName,message:`Value exceeds max length of ${i.maxLength} (got ${a.length})`}),i.picklistValues&&i.picklistValues.length>0){let c=String(a);i.picklistValues.includes(c)||r.push({recordIndex:n,field:i.apiName,message:`Value '${c}' is not a valid picklist value. Allowed: ${i.picklistValues.join(", ")}`})}}}return{valid:r.length===0,errors:r}}checkTypeCompatibility(e,t,r,n){let o=t.toLowerCase(),i=n.toLowerCase();if(o===i)return{sourceField:e,sourceType:t,targetField:r,targetType:n,compatible:!0};let a=uf(o,i),d=rD.find(c=>c.source===o&&c.target===i);return{sourceField:e,sourceType:t,targetField:r,targetType:n,compatible:a,reason:a?d?.reason:`Type '${t}' is not compatible with '${n}'`}}validateValueType(e,t){let r=t.type.toLowerCase();switch(r){case"boolean":if(typeof e!="boolean")return`Expected boolean but got ${typeof e}`;break;case"int":if(typeof e!="number"||!Number.isInteger(e))return`Expected integer but got ${typeof e=="number"?"float":typeof e}`;break;case"double":case"currency":case"percent":if(typeof e!="number")return`Expected number but got ${typeof e}`;break;case"date":case"datetime":if(typeof e!="string"||!nD(e))return`Expected valid ${r} string`;break}}};function uI(s){return s==null||s===""}function nD(s){let e=Date.parse(s);return!isNaN(e)}var uc=class{paused=!1;waiting=new Set;get isPaused(){return this.paused}pause(){this.paused=!0}resume(){this.paused=!1;let e=[...this.waiting];this.waiting.clear();for(let t of e)t()}async whilePaused(e){!this.paused||e?.aborted||await new Promise(t=>{let r=()=>{this.waiting.delete(r),e?.removeEventListener("abort",r),t()};this.waiting.add(r),e?.addEventListener("abort",r,{once:!0})})}};var lf=3e4,lI=6e4,pf="Nothing was read or written.",pI="Nothing was read.",fI="the checkpoints of this window are not open to the Sync page",sD=new Set(["sync:execute","sync:simulate","sync:write-order","sync:pause","sync:resume","sync:describe-global","sync:describe-fields","sync:config:save","sync:config:load","sync:config:list","sync:config:delete","sync:config:reset-delta"]),gI={insert:0,update:1,upsert:2,delete:3};function gf(s,e){let t=s.objects??[],r="insert";for(let o of t)gI[o.operation]>gI[r]&&(r=o.operation);s.mode==="delta"&&s.propagateDeletes===!0&&(r="delete");let n=t.map(o=>o.objectApiName);return{orgId:s.targetOrgId,orgTier:Pe(e),operation:r,objectName:n.length>0?n.join(", "):"SyncData",recordCount:"unknown",module:"sync"}}function iD(s){return s.map(e=>{let t={...bt(e.objectApiName),failed:e.failed+(e.delta?.deleteFailed??0),deleted:e.delta?.deleted??0};switch(e.operation){case"insert":return{...t,created:e.success};case"update":return{...t,updated:e.success};case"delete":return{...t,deleted:e.success};case"upsert":{let r=e.upsertSplit??{created:0,updated:0},n=e.success-r.created-r.updated;return{...t,created:r.created,updated:r.updated,...n>0?{upserted:n}:{}}}}})}var aD=new Set(["direct","rename"]),ff=20,dD=K({fields:Re(K({name:L(),type:L(),createable:Ve(),updateable:Ve()}).loose())});function hI(s,e,t){let r=dD.safeParse(s);if(r.success)return r.data.fields;let n=r.error.issues[0];throw new Error(`The ${t} org described ${e} in a shape field types cannot be compared on (${n.path.join(".")}: ${n.message}), so the sync was not started and nothing was written.`)}function mI(s){if(s==="ask")return{emailsLiftedBy:"Untick Mute automation to be asked about them and sync all the same"};let e=$b();return e?{emailsAccepted:e.approved,emailsLiftedBy:"Approve an Approval step put before this Sync step to sync all the same"}:{emailsLiftedBy:"Run it from the Sync page, which asks before it writes, to sync all the same"}}var lc=class{constructor(e){this.deps=e;this.syncConfigStore=new Pt(e.configStore)}deps;activeOperationIds=new Set;dmlTracker=new ba;syncConfigStore;registry;historyLogger;liveTracker;pauseGates=new Map;runCreations;backupRecords;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-UK3QLBHW.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}confirmAboveRecords(){let e=this.deps.services?.getSandforgeSetting?.("safety.confirmAboveRecords",en);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):en}readCap(){return fd(this.deps.services?.getSandforgeSetting?.("sync.maxRecordsPerObject",void 0))}writeGateFor(e,t,r,n,o,i){let{targetConn:a}=t,d=this.deps.orgManager.getOrg(e.targetOrgId),c=this.targetAutomation,u=this.deps.infraServices?.productionGuard,l=mI(r),p=this.readCap(),f=TS(e,async g=>{let{totalSize:h}=await a.query(g);return Math.min(h,p)});return ES({readStorage:()=>new pe(lf).withTimeout("sync:limits",()=>vr(Vt(a,e.targetOrgId))),readApiBudget:()=>new pe(lf).withTimeout("sync:limits",()=>ar(a)),readAutomation:n??(g=>new pe(lI).withTimeout("sync:automation",()=>c.read(e.targetOrgId,g))),readLimits:()=>new pe(lf).withTimeout("sync:limits",()=>Or(a)),readDeliverability:()=>Pe(d)==="production"?Promise.resolve(Gt):Jt(a),emails:{target:we(d,e.targetOrgId),accepted:l.emailsAccepted===!0,keepsAddresses:e.keepContactPoints===!0},confirmAboveRecords:this.confirmAboveRecords(),bulkThreshold:ut(this.deps).bulk.threshold,...o?{checkpointFirst:o}:{},...i?{mutePlan:i}:{},...f?{countTarget:f,readRetries:ut(this.deps).retry.maxRetries}:{},targetFields:async g=>((await t.describeTargetFields(g)).fields??[]).map(h=>h.name)},{policy:r,org:we(d,e.targetOrgId),orgTier:Pe(d),...u?{confirm:g=>u.confirmRun(g)}:{},emailsLiftedBy:l.emailsLiftedBy})}setRegistry(e){this.registry=e}setMuteLeases(e){this.muteLeases=e}muteLeases={};setHistoryLogger(e){this.historyLogger=e}setLiveOperationTracker(e){this.liveTracker=e}setRunCreations(e){this.runCreations=e}setBackupRecordStore(e){this.backupRecords=e}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}beforeRunCheckpoints;runCheckpointOf(e,t,r,n){let o=this.beforeRunCheckpoints,i={runId:t},a,d,c,u;return{gate:{scope:async(l,p)=>{if(!o)throw new Error(fI);return a={module:"sync",orgId:e.targetOrgId,operationId:t,written:[...l],running:p,request:r},d=await o.scope(a,i),u=d.refusal,d},take:async l=>{if(!o||!a)throw new Error(fI);let p=await o.take(a,i,{planned:l,...n?{signal:n.signal,onProgress:f=>{let g=_o(f.percentage),h=Math.round(f.percentage),{processedObjects:m,totalObjects:y}=f;_e(this.deps,t,h,m,y,g),this.liveTracker?.updateProgress(t,h,m,y,g)}}:{}});return p.taken?(c=p.checkpoint,n?.recorder?.checkpoint?.(p.checkpoint)):"refusal"in p&&(u=p.refusal),p}},planned:()=>d,taken:()=>c,refusal:()=>u}}async settleRunCheckpoint(e,t,r){let n=e?.taken();if(!(!n||!this.beforeRunCheckpoints))try{return await this.beforeRunCheckpoints.settle(n,t)}catch(o){return this.deps.log(`[WARN] sync ${r}: the checkpoint '${n.name}' taken before the run is kept: ${I(o)}`),n}}isRunning(e){return this.activeOperationIds.has(e)}async handle(e){if(!sD.has(e.type))return!1;switch(e.type){case"sync:describe-global":return await this.handleDescribeGlobal(e),!0;case"sync:describe-fields":return await this.handleDescribeFields(e),!0;case"sync:execute":return await this.handleExecute(e),!0;case"sync:simulate":return await this.handleSimulate(e),!0;case"sync:write-order":return await this.handleWriteOrder(e),!0;case"sync:pause":return await this.handleRunControl(e,"pause"),!0;case"sync:resume":return await this.handleRunControl(e,"resume"),!0;case"sync:config:save":return await this.handleConfigSave(e),!0;case"sync:config:load":return await this.handleConfigLoad(e),!0;case"sync:config:list":return await this.handleConfigList(e),!0;case"sync:config:delete":return await this.handleConfigDelete(e),!0;case"sync:config:reset-delta":return await this.handleConfigResetDelta(e),!0;default:return!1}}refusedFieldless(e,t,r,n,o){let i=Ao(t.objects);return i.length===0?!1:(T(this.deps,r,n,e,new Error(`${To(i)} ${o}`),{code:Yi,extraPayload:{rules:i}}),!0)}async handleConfigSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Um,e,"sync:error",this.deps);if(t&&!this.refusedFieldless(e,t.config,"sync:config:save","sync:error","Nothing was saved."))try{let r=t.config;if(vh(this.syncConfigStore.list(),r.id,r.name)){let o=A(this.deps,e,"sync:config:save:response",{success:!1,id:r.id,code:"DUPLICATE_NAME"});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} DUPLICATE_NAME`);return}this.syncConfigStore.save(r);let n=A(this.deps,e,"sync:config:save:response",{success:!0,id:r.id});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){T(this.deps,"sync:config:save","sync:error",e,r)}}async handleConfigLoad(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(va,e,"sync:error",this.deps);if(t)try{let r=this.syncConfigStore.load(t.id),n=A(this.deps,e,"sync:config:load:response",{config:r??null});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){T(this.deps,"sync:config:load","sync:error",e,r)}}async handleConfigList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let r=this.syncConfigStore.list().map(o=>{let i=this.syncConfigStore.loadDelta(o.id);return{id:o.id,name:o.name,description:o.description,updatedAt:o.updatedAt,mode:o.mode,propagateDeletes:o.propagateDeletes===!0,watermarks:i.kind==="stored"?i.state.entries.length:0}}),n=A(this.deps,e,"sync:config:list:response",{configs:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(t){T(this.deps,"sync:config:list","sync:error",e,t)}}async handleConfigDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(va,e,"sync:error",this.deps);if(t)try{let r=this.syncConfigStore.delete(t.id);await this.runCreations?.idMap().delete(t.id).catch(o=>this.deps.log(`[WARN] sync:config:delete ${t.id}: ${I(o)}`));let n=A(this.deps,e,"sync:config:delete:response",{success:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){T(this.deps,"sync:config:delete","sync:error",e,r)}}async handleConfigResetDelta(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(va,e,"sync:error",this.deps);if(t)try{if(!this.syncConfigStore.load(t.id))throw new Error("This configuration is no longer saved: there is nothing to reset.");let r=this.syncConfigStore.clearDelta(t.id),n=A(this.deps,e,"sync:config:reset-delta:response",{success:!0,id:t.id,cleared:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} cleared=${r}`)}catch(r){T(this.deps,"sync:config:reset-delta","sync:error",e,r)}}deltaStoreFor(){return this.syncConfigStore.deltaStore()}fileStoreFor(){return this.syncConfigStore.fileStore()}idMapFor(){let e=this.runCreations;if(e)return Ib(e.idMap(),t=>this.syncConfigStore.isSaved(t))}recordRun(e,t,r,n,o,i){let a=iD(r.objectResults??[]),d=a.some(u=>u.created+u.updated+u.deleted+u.failed+(u.upserted??0)>0),c=r.cancelled===!0?d?"cancelled":"stopped":r.status;Y(this.deps,{action:"sync_execute",module:"sync",operationId:t,orgId:e.targetOrgId,outcome:c,...c==="stopped"?{code:ot}:{},guard:n,objects:a,source:{origin:"org",orgId:e.sourceOrgId},details:{triggeredBy:o,...so(i),...Kr(r.contactPoints).details},...r.mutedAutomation?{muted:ft(r.mutedAutomation)}:{},...r.checkpoint?.state==="taken"?{checkpointId:r.checkpoint.checkpointId}:{}})}recordRefused(e,t,r){Y(this.deps,{action:"sync_execute",module:"sync",operationId:e,orgId:t,outcome:"stopped",code:r})}recordStopped(e,t,r){Y(this.deps,{action:"sync_execute",module:"sync",operationId:e,orgId:t,outcome:"stopped",guard:r})}buildGuardRequest(e){return gf(e,this.deps.orgManager.getOrg(e.targetOrgId))}async assertFieldTypesMatch(e,t,r,n){let o=new cc,i=[],a=u=>({apiName:u.name,type:u.type});for(let u of e.objects){if(u.operation==="delete")continue;let l=u.objectApiName,p=new pe(n),[f,g]=await Promise.all([p.withTimeout(`describe-source-${l}`,()=>er(e.sourceOrgId,l,()=>t.describe(l))),p.withTimeout(`describe-target-${l}`,()=>er(e.targetOrgId,l,()=>r.describe(l)))]),h=hI(f,l,"source").map(a),m=hI(g,l,"target").filter(k=>k.createable||k.updateable).map(a),y=aS(u,{creatable:new Set(m.map(k=>k.apiName))}),v=$m(y.fieldMappings,y.excludedFields),b=[Object.fromEntries(h.filter(k=>!v.has(k.apiName.toLowerCase())).map(k=>[k.apiName,k.apiName])),...u.fieldMappings.filter(k=>aD.has(k.type)).map(k=>({[k.sourceField]:k.targetField}))];for(let k of b)for(let S of o.validateMapping(h,m,k).errors)i.push(`${l}.${S.sourceField} (${S.sourceType}) -> ${l}.${S.targetField} (${S.targetType})`)}if(i.length===0)return;let d=i.slice(0,ff).join("; "),c=i.length>ff?` and ${i.length-ff} more`:"";throw new Error(`Field types do not match between the orgs, so the sync was not started and nothing was written: ${d}${c}. Map each field onto a field of a compatible type, convert the value with a transform, or leave the field out: Exclude as its mapping on the Field Mapping step, or in the object's excludedFields in a saved configuration.`)}async handleDescribeGlobal(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Hm,e,"sync:error",this.deps);if(!t)return;let r=ut(this.deps);try{let n=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager),o=new pe(r.timeouts.describeGlobal),i=await o.withTimeout("describe-global",()=>n.describeGlobal());$e(n.limitInfo,"sync:describe-global");let a=i.sobjects.filter(l=>l.queryable&&!Ra(l.name)),d,c=[];if(t.targetOrgId===void 0)d=a.filter(l=>l.createable).map(l=>l.name);else{let l=await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),p=await o.withTimeout("describe-global",()=>l.describeGlobal());$e(l.limitInfo,"sync:describe-global target");let f=new Map(p.sobjects.map(g=>[g.name,{createable:g.createable,updateable:g.updateable}]));d=[];for(let g of a){let h=f.get(g.name);if(h&&(h.createable||h.updateable)){d.push(g.name);continue}g.createable&&c.push({objectApiName:g.name,why:h?"notCreateable":"notInTarget"})}}let u=A(this.deps,e,"sync:describe-global:response",{objects:d,...c.length>0?{unwritable:c}:{}});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`)}catch(n){T(this.deps,"sync:describe-global","sync:error",e,n)}}async handleDescribeFields(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Bm,e,"sync:error",this.deps);if(!t)return;let r=t,n=ut(this.deps);try{let o=await B(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),i=await B(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=new pe(n.timeouts.describe),[d,c]=await Promise.all([a.withTimeout("describe-source",()=>o.describe(r.objectApiName)),a.withTimeout("describe-target",()=>i.describe(r.objectApiName))]);$e(o.limitInfo,`sync:describe-fields source ${r.objectApiName}`),$e(i.limitInfo,`sync:describe-fields target ${r.objectApiName}`);let u=p=>p.filter(f=>f.createable).map(f=>({apiName:f.name,label:f.label,type:f.type})),l=A(this.deps,e,"sync:describe-fields:response",{objectApiName:r.objectApiName,sourceFields:u(d.fields),targetFields:u(c.fields)});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`)}catch(o){T(this.deps,"sync:describe-fields","sync:error",e,o)}}async handleWriteOrder(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Sl,e,"sync:error",this.deps);if(!t)return;let r=t.config;try{let n=await B(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),o=ut(this.deps).timeouts.describe,i=new Map;for(let u of r.objects){if(u.operation==="delete")continue;let l=u.objectApiName;try{let p=await new pe(o).withTimeout(`describe-target-${l}`,()=>er(r.targetOrgId,l,()=>n.describe(l)));i.set(l,fS(u,Ar(p)))}catch{}}let{order:a}=gS(r.objects,i),d=await this.encryptedMaskedOf(r,o).catch(()=>[]),c=A(this.deps,e,"sync:write-order:response",{order:a,...d.length>0?{encrypted:d}:{},readCap:this.readCap()});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(n){T(this.deps,"sync:write-order","sync:error",e,n)}}async encryptedMaskedOf(e,t){let r=e.objects.filter(a=>a.operation!=="delete");if(r.length===0)return[];let n=await B(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=no(wr(async a=>(await n.query(a)).records),a=>new pe(t).withTimeout(`describe-source-${a}`,()=>er(e.sourceOrgId,a,()=>n.describe(a)))),i=[];for(let a of r){let d=await o(a.objectApiName);d.length>0&&i.push({objectApiName:a.objectApiName,fields:d})}return i}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Sn,e,"sync:error",this.deps);t&&(this.refusedFieldless(e,t.config,"sync:execute","sync:error",pf)||await this.startExecution(e,t.config,"manual",t.muteAutomation===!0,t.checkpointFirst))}async handleSimulate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Sl,e,"sync:error",this.deps);if(!t||this.refusedFieldless(e,t.config,"sync:simulate","sync:error",pI))return;let r=e.id,n=t.config,o=`Simulation of a sync of ${n.objects.length} object(s), writing nothing`,i=new AbortController;Ge(this.deps,r,"sync",o),this.liveTracker?.register(r,"sync",o);let a=this.simulateSync(e,n,r,i,t.checkpointFirst);if(this.registry){let d=a.then(c=>({status:c===null||c.error?"failure":"success"}));this.registry.register(r,"sync",o,d,i)}else await a}async simulateSync(e,t,r,n,o,i){let a=ut(this.deps),d={module:"sync",operation:e.type,...Jr(t.objects)};try{let c=await this.readersFor(t,n.signal),{DataSync:u}=await import("./chunk-NICRSGLS.mjs"),{ConflictResolver:l}=await import("./chunk-CHCHAE4B.mjs"),{FieldMappingService:p}=await import("./chunk-O3GIN5TU.mjs"),{TransformPipeline:f}=await import("./chunk-HZUI56KZ.mjs"),{toolingQueriesOver:g,toolingValidationRules:h}=await import("./chunk-RQW5S67A.mjs"),{toolingRetrievesOver:m}=await import("./chunk-UK3QLBHW.mjs"),y=c.targetConn.tooling,v=async()=>{throw new Error("A simulation writes nothing: the write it reached was refused.")},b=new u({insert:v,update:v,upsert:v,delete:v,describeTargetFields:c.describeTargetFields});if(!this.deps.services)throw new Error("SyncOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let k=o?this.runCheckpointOf(t,r,o):void 0,S=this.deps.services.syncOrchestrator({dataSync:b,conflictResolver:new l,fieldMapping:new p,transformPipeline:new f,querySource:c.querySource,maskedSourceFields:c.maskedSourceFields,queryTarget:c.queryTarget,services:this.deps.services,signal:n.signal,findInTarget:c.findInTarget,bulkThreshold:a.bulk.threshold,describeTargetFields:c.describeTargetFields,readSourceIds:c.readSourceIds,countSource:c.countSource,countPersonAccounts:c.countPersonAccounts,writeGate:this.writeGateFor(t,c,"ask",void 0,k?.gate),queryTargetRows:c.queryTargetRows,recordTypes:c.recordTypes,currencies:c.currencies,standardPricebooks:c.standardPricebooks,deltaStore:this.deltaStoreFor(),deltaReads:c.deltaReads,idMap:this.idMapFor(),files:c.files,readValidationRules:h(async E=>(await nr({query:async $=>y.query($),queryMore:async $=>y.queryMore($)},E)).records,g(c.targetConn),m(c.targetConn),{reads:!0}),onSimulationProgress:(E,$,H)=>{let J=Math.round(E/$*100),W=`Simulating ${H}`;_e(this.deps,r,J,E,$,W),this.liveTracker?.updateProgress(r,J,E,$,W)}});await this.assertFieldTypesMatch(t,c.sourceConn,c.targetConn,a.timeouts.describe);let C=await S.simulate(t),R=k?.planned(),w=[...c.cutAtReadCap],P={...C,...R?{checkpoint:R}:{},readCap:c.readCap,...w.length>0?{cutAtReadCap:w}:{},operationId:r};P.cancelled?this.endCancelled(r):P.error?(this.liveTracker?.fail(r,P.error),Le(this.deps,r,P.error,!0,{context:d})):(_e(this.deps,r,100,1,1,"Simulation complete"),me(this.deps,r,{status:"success",simulated:!0}),this.liveTracker?.complete(r)),this.deps.log(`[sync] simulation ${r} ${P.cancelled?"stopped":"finished"}: `+P.objects.map(E=>`${E.objectApiName} insert=${E.insert} update=${E.update} delete=${E.delete} skipped=${E.skipped} refused=${E.refused} conflicts=${E.conflicts}`).join("; "));let O=A(this.deps,e,"sync:simulate:response",P);return this.deps.broker.postToWebview(O),this.deps.log(`[TX] ${O.type} id=${O.id}`),P}catch(c){return this.liveTracker?.fail(r,I(c)),T(this.deps,"sync:simulate","sync:error",e,c),Le(this.deps,r,I(c),!0,{context:d}),i?.(c),null}}async simulateForPipeline(e,t){let r=Sn.safeParse({config:e});if(!r.success)throw new Error(`Pipeline sync config failed validation: ${r.error.issues.map(f=>f.message).join("; ")}`);let n=Ao(r.data.config.objects);if(n.length>0)throw Object.assign(new Error(`${To(n)} ${pI}`),{code:Yi});let o=Rn("sync:pipeline",crypto.randomUUID(),"sync:simulate"),i=o.id,a=this.deps.services?.getSandforgeSetting?.("sync.defaultBatchSize",200)??200,d={...r.data.config,objects:r.data.config.objects.map(f=>({...f,batchSize:f.batchSize??a}))},c=`Pipeline simulation of a sync of ${d.objects.length} object(s), writing nothing`,u=new AbortController,l=()=>u.abort();t?.aborted&&u.abort(),t?.addEventListener("abort",l,{once:!0}),Ge(this.deps,i,"sync",c),this.liveTracker?.register(i,"sync",c);let p;try{let f=this.simulateSync(o,d,i,u,void 0,h=>{p=h});this.registry?.register(i,"sync",c,f.then(h=>({status:h===null||h.error?"failure":"success"})),u);let g=await f;if(g===null)throw p instanceof Error?p:new Error(I(p));return g}finally{t?.removeEventListener("abort",l)}}async handleRunControl(e,t){this.deps.log(`[RX] ${e.type} id=${e.id}`);let r=x(_m,e,"sync:error",this.deps);if(!r)return;let{operationId:n}=r,o=t==="pause"?"sync:pause:response":"sync:resume:response",i=this.pauseGates.get(n),a;i?(t==="pause"?(i.pause(),this.liveTracker?.pause(n)):(i.resume(),this.liveTracker?.resume(n)),a={success:!0,operationId:n,paused:i.isPaused}):a={success:!1,operationId:n,paused:!1,error:"No sync with this id is running: it has finished, or it was not started here."};let d=A(this.deps,e,o,a);this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id} paused=${a.paused}`)}async readersFor(e,t){let r=ut(this.deps),n=await B(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await B(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=this.readCap(),a=new Set,d=new nd({retryConfig:r.retry}),c=(O,E)=>async($,H,J)=>{let W=St(H.objectApiName),Z="",_=Us(H.where,J?.changedSince);_&&(Z+=` WHERE ${_}`),H.orderBy&&(Z+=` ORDER BY ${hl(H.orderBy)}`);let Q=!1,N=await d.execute(async()=>{Q=!1;let oe=(await O.describe(W)).fields.map(F=>F.name),re=oe.length>0?oe:["Id"],q={query:async F=>O.query(F),queryMore:async F=>O.queryMore(F)};return Ms(`SELECT ${re.join(", ")} FROM ${W}${Z}`,async F=>{let ne=await nr(q,F,i);return Q||=ne.truncated,ne.records})});if(!N.success)throw N.error??new Error("Query failed after retries");$e(O.limitInfo,`sync:execute query ${W}`);let z=N.result??[];if(Q){J?.onBoundReached?.();let oe=z.length>=i?`${i} records (sandforge.sync.maxRecordsPerObject)`:`${Math.max(500,Math.ceil(i/200))} pages`,re=E===e.sourceOrgId?"source":"target";re==="source"&&a.add(H.objectApiName);let q=re==="source"?"this sync copies a subset, not the whole object":"conflict detection ran against a subset of the destination";this.deps.log(`[WARN] sync:execute ${W} (${re}): read stopped at ${z.length} record(s) \u2014 bound: ${oe}. ${q}.`),Ae(this.deps,"warning","Sync",`${W}: only ${z.length} record(s) were read from the ${re} (bound: ${oe}) \u2014 ${q}. `+mS(re,i,hS))}return z},u=async(O,E,$)=>{let J=`SELECT COUNT() FROM ${St(E.objectApiName)}`,W=Us(E.where,$?.changedSince);W&&(J+=` WHERE ${W}`);let{totalSize:Z}=await n.query(J);return Math.min(Z,i)},l=async(O,E)=>{let $=St(O.objectApiName),H=Us(O.where,E?.changedSince),J=`SELECT COUNT() FROM ${$} WHERE IsPersonAccount = true`+(H?` AND (${H})`:"");try{return(await n.query(J)).totalSize}catch{return 0}},p=new Map,f=async O=>{let E=p.get(O);if(E)return E;let $=await o.describe(O),H=Ar($);return p.set(O,H),H},g=async O=>Ar(await o.describe(O)),h=async O=>(await nr({query:async E=>o.query(E),queryMore:async E=>o.queryMore(E)},O)).records,m=Em({query:async O=>o.query(O),queryMore:async O=>o.queryMore(O)},t),y=async(O,E,$,H)=>{let J=await m(O,E,$,H);return $e(o.limitInfo,`sync:simulate lookup ${E.objectApiName}`),J},v=xm({query:async(O,E)=>n.query(O,E),queryMore:async O=>n.queryMore(O)},{query:async O=>o.query(O),queryMore:async O=>o.queryMore(O)},t),b=O=>({pages:{query:async E=>O.query(E),queryMore:async E=>O.queryMore(E)},transport:O,create:async(E,$)=>O.sobject(E).create($,{headers:Vi()})}),k=async(O,E)=>{let H=`SELECT Id FROM ${St(O.objectApiName)}`,J=Us(O.where,E);J&&(H+=` WHERE ${J}`),O.orderBy&&(H+=` ORDER BY ${hl(O.orderBy)}`);let{records:W}=await nr(b(n).pages,H,i);return W.flatMap(Z=>typeof Z.Id=="string"?[Z.Id]:[])},S={copy:tS({[e.sourceOrgId]:b(n),[e.targetOrgId]:b(o)}),sourceIds:k,store:this.fileStoreFor(),...e.files!==void 0&&eS(this.deps.infraServices?.productionGuard,e.targetOrgId,this.deps.orgManager.getOrg(e.targetOrgId))?{deleteFromTarget:async(O,E)=>sb(await o.sobject(O).destroy(E),O).map($=>({id:$.id,success:$.success,errors:$.errors}))}:{}},C=async()=>{let{readSyncRecordTypes:O}=await import("./chunk-P2M5ZXWU.mjs");return O(b(n).pages,b(o).pages)},R=async()=>{let{readRunCurrencies:O}=await import("./chunk-OETEC3P7.mjs");return O(async E=>(await n.query(E)).records,async E=>(await o.query(E)).records,{source:async E=>(await n.tooling.query(E)).records,target:async E=>(await o.tooling.query(E)).records})},w=async()=>{let{readStandardPricebooks:O}=await import("./chunk-RJ6HHG7J.mjs");return O(async E=>(await n.query(E)).records,async E=>(await o.query(E)).records)},P=no(wr(async O=>(await n.query(O)).records),O=>er(e.sourceOrgId,O,()=>n.describe(O)));return{sourceConn:n,targetConn:o,querySource:c(n,e.sourceOrgId),queryTarget:c(o,e.targetOrgId),maskedSourceFields:P,countSource:u,describeTargetFields:f,describeTargetFieldsAgain:g,queryTargetRows:h,recordTypes:C,currencies:R,standardPricebooks:w,findInTarget:y,readSourceIds:O=>k(O),countPersonAccounts:l,deltaReads:v,files:S,readCap:i,cutAtReadCap:a}}async rerunFromSnapshot(e,t){this.deps.log(`[RX] sync:history:rerun id=${e.id}`);let r=x(Sn,{...e,payload:{config:t}},"sync:history:error",this.deps);r&&(this.refusedFieldless(e,r.config,"sync:history:rerun","sync:history:error",pf)||await this.startExecution(e,r.config,"rerun"))}async executeScheduled(e,t="schedule"){let r=Sn.safeParse({config:e});if(!r.success)throw new Error(`Scheduled sync config failed validation: ${r.error.issues.map(m=>m.message).join("; ")}`);let n=Ao(r.data.config.objects);if(n.length>0)throw Object.assign(new Error(`${To(n)} ${pf}`),{code:Yi});let o=t==="pipeline"?Rn("sync:pipeline",crypto.randomUUID(),"sync:execute"):Rn("sync:schedule",crypto.randomUUID(),"sync:execute"),i=o.id,a=this.deps.services?.getSandforgeSetting?.("sync.defaultBatchSize",200)??200,d={...r.data.config,objects:r.data.config.objects.map(m=>({...m,batchSize:m.batchSize??a}))},c=this.deps.infraServices?.productionGuard;if(!c)throw this.recordRefused(i,d.targetOrgId,ve.code),ua();let{check:u,decision:l}=await et(c,this.buildGuardRequest(d)),p=l;if((l==="refused"||l==="declined")&&this.recordStopped(i,d.targetOrgId,l),l==="refused")throw new Error(`Operation blocked by Production Guard: ${u.blockedReason??u.impactSummary}`);if(l==="declined")throw new Error(`${t==="pipeline"?"Pipeline":"Scheduled"} sync cancelled (confirmation declined).`);this.dmlTracker.register(i,"sync","upsert",d.objects?.length??0),this.activeOperationIds.add(i),this.deps.infraServices?.performanceTracker?.start(i,"sync");let f=`${t==="pipeline"?"Pipeline":"Scheduled"} sync of ${d.objects?.length??0} object(s)`;Ge(this.deps,i,"sync",f),this.liveTracker?.register(i,"sync",f,0,{pausable:!0});let g=new AbortController,h=this.executeSync(o,d,i,g,t,p);return this.registry?.register(i,"sync",f,h,g),h}async startExecution(e,t,r,n=!1,o){let i=e.id,a={module:"sync",operation:e.type},d=this.registry?.holdUntilStart(i);try{let c=this.deps.services?.getSandforgeSetting?.("sync.defaultBatchSize",200)??200,u=t,l={...u,objects:u.objects.map(b=>({...b,batchSize:b.batchSize??c}))};Object.assign(a,Jr(l.objects));let p=this.deps.infraServices?.productionGuard;if(!p){this.recordRefused(i,l.targetOrgId,ve.code),T(this.deps,"sync:execute","sync:error",e,new Error(ve.message),{code:ve.code}),Le(this.deps,i,ve.message,!1,{context:a});return}let{check:f,decision:g}=await et(p,this.buildGuardRequest(l)),h=g;if((g==="refused"||g==="declined")&&this.recordStopped(i,l.targetOrgId,g),g==="refused")throw bn(f.blockedReason??f.impactSummary);if(g==="declined"){let b="Operation cancelled by user (confirmation declined).";T(this.deps,"sync:execute","sync:error",e,new Error(b),{code:Dt.declined}),Le(this.deps,i,b,!1,{context:a});return}if(d?.signal.aborted){this.answerCancelledBeforeStart(e,l,g);return}if(this.dmlTracker.isDuplicate(i)){this.deps.log(`[WARN] Duplicate sync operation detected: ${i}`),T(this.deps,"sync:execute","sync:error",e,new Error(`Duplicate operation: ${i}`)),Le(this.deps,i,`Duplicate operation: ${i}`,!1,{context:a});return}this.dmlTracker.register(i,"sync","upsert",l.objects?.length??0),this.activeOperationIds.add(i),this.deps.infraServices?.performanceTracker?.start(i,"sync");let m=`Sync ${l.objects?.length??0} object(s)`;Ge(this.deps,i,"sync",m),this.liveTracker?.register(i,"sync",m,0,{pausable:!0});let y=new AbortController,v=this.executeSync(e,l,i,y,r,h,n,o);this.registry?this.registry.register(i,"sync",m,v,y):await v}catch(c){this.dmlTracker.markFailed(i),T(this.deps,"sync:execute","sync:error",e,c,{code:xo(c)}),Le(this.deps,i,I(c),!0,{context:a})}finally{d?.release()}}answerCancelledBeforeStart(e,t,r){Y(this.deps,{action:"sync_execute",module:"sync",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:r,code:ht});let n={configId:t.id,operationId:e.id,status:"partial",objectResults:[],totalProcessed:0,totalSuccess:0,totalFailed:0,totalSkipped:0,duration:0,timestamp:new Date().toISOString(),cancelled:!0,error:"Cancelled before it started: nothing was written."},o=A(this.deps,e,"sync:execute:response",n);this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} (cancelled before it started)`)}endCancelled(e){this.registry?.abort(e),me(this.deps,e,{aborted:!0}),this.liveTracker?.cancel(e)}async executeSync(e,t,r,n,o,i,a=!1,d){let c=t.id?t:{...t,id:r},u=ut(this.deps),l,p,f=!1,g,h=R=>({measure:w=>R.measure(w),hold:async w=>{let P=await R.hold(w);return g=P.answer.emails,P.answer.go&&Tt({action:"sync_execute",orgId:c.targetOrgId,operationId:r},{mb:P.check.storage.estimateMB,...P.rowBytes?{rowBytes:P.rowBytes}:{}}),P}}),m=new uc;this.pauseGates.set(r,m);let y=o==="pipeline"?this.deps.orgManager.getOrg(c.targetOrgId)?.orgId:void 0,v=this.runCreations?.recorder({runId:r,configId:c.id,configName:c.name??"",sourceOrgId:c.sourceOrgId,targetOrgId:c.targetOrgId,...y?{targetOrganizationId:y}:{}}),b=this.backupRecords,k=v&&b?ld({runId:r,orgId:c.targetOrgId,files:b,meta:this.deps.configStore}):void 0,S=d?this.runCheckpointOf(c,r,d,{signal:n.signal,...v?{recorder:v}:{}}):void 0,C=()=>{try{k?.close()}catch(R){this.deps.log(`[WARN] sync ${r}: the backup of what it wrote over could not be listed whole: `+I(R))}};try{let R=await this.readersFor(c,n.signal),{sourceConn:w,targetConn:P}=R;Ir(v,()=>P.identity(),`sync ${r}`);let O=R.queryTargetRows,E=v&&k?pd({query:O,backup:k,recorder:v,describe:R.describeTargetFields,viewsEncrypted:wr(O)}):void 0,$=new kn(u.bulk.threshold),H=yr(this.deps),J=new Nn({connection:P,bulkExecutor:$,bulkManager:H,retryConfig:u.retry,signal:n.signal,pauseGate:m,onProgress:(V,ae,ee)=>{let fe=Math.round(V/ae*100);_e(this.deps,r,fe,V,ae,ee),this.liveTracker?.updateProgress(r,fe,V,ae,ee)},log:V=>this.deps.log(V),...v?{calls:md(v,E)}:{}}),{DataSync:W}=await import("./chunk-NICRSGLS.mjs"),{ConflictResolver:Z}=await import("./chunk-CHCHAE4B.mjs"),{FieldMappingService:_}=await import("./chunk-O3GIN5TU.mjs"),{TransformPipeline:Q}=await import("./chunk-HZUI56KZ.mjs"),N=V=>{V.length>0&&(f=!0)},z=new W({upsert:(V,ae,ee,fe)=>(N(ee),J.upsert(V,ae,ee,fe)),insert:(V,ae,ee)=>(N(ae),J.insert(V,ae,ee)),update:(V,ae,ee)=>(N(ae),J.update(V,ae,ee)),delete:(V,ae,ee)=>(N(ae),J.delete(V,ae,ee)),describeTargetFields:R.describeTargetFields}),oe=new Z,re=new _,q=new Q,F={dataSync:z,conflictResolver:oe,fieldMapping:re,transformPipeline:q,querySource:R.querySource,maskedSourceFields:R.maskedSourceFields,queryTarget:R.queryTarget,services:this.deps.services,grappeConfig:js(this.deps.services),onGrappeEvent:V=>la(this.deps,V),countSource:R.countSource,countPersonAccounts:R.countPersonAccounts,describeTargetFields:R.describeTargetFields,describeTargetFieldsAgain:R.describeTargetFieldsAgain,leaseOfTheGate:()=>p?.lease(),queryTargetRows:O,readSourceIds:R.readSourceIds,findInTarget:R.findInTarget,writeGate:(()=>{let V=o==="schedule"||o==="pipeline"?"unattended":"ask";if(!a)return h(this.writeGateFor(c,R,V,void 0,S?.gate));let ae=this.targetAutomation;return p=CS((fe,D)=>this.writeGateFor(c,R,V,fe,S?.gate,D),fe=>new pe(lI).withTimeout("sync:automation",()=>ae.read(c.targetOrgId,fe)),fe=>Et(async()=>_t(P),fe,{...this.muteLeases,writes:PS}),r,{target:we(this.deps.orgManager.getOrg(c.targetOrgId),c.targetOrgId),liftedBy:mI(V).emailsLiftedBy}),h(p.gate)})(),recordTypes:R.recordTypes,currencies:R.currencies,standardPricebooks:R.standardPricebooks,signal:n.signal,pauseGate:m,deltaStore:this.deltaStoreFor(),deltaReads:R.deltaReads,files:{...R.files,onProgress:(V,ae)=>{_e(this.deps,r,V,0,0,ae),this.liveTracker?.updateProgress(r,V,0,0,ae)}},...v?{creations:v}:{},idMap:this.idMapFor()};if(!this.deps.services)throw new Error("SyncOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let ne=this.deps.services.syncOrchestrator(F);await this.assertFieldTypesMatch(c,w,P,u.timeouts.describe),_e(this.deps,r,10,0,1,"Initializing sync");let ke=await ne.execute(c).finally(async()=>{l=await p?.release()}),de=await this.settleRunCheckpoint(S,f,r),Ze=[...R.cutAtReadCap],xe={...ke,...Ze.length>0?{status:ke.status==="success"?"partial":ke.status,readCap:R.readCap,cutAtReadCap:Ze}:{},...l?{mutedAutomation:l}:{},...de?{checkpoint:de}:{}};if(await v?.end({status:xe.status,cancelled:xe.cancelled===!0}),C(),xe.cancelled?this.endCancelled(r):(_e(this.deps,r,100,1,1,"Sync complete"),me(this.deps,r,{status:xe.status??"completed"}),xe.status==="failure"?this.liveTracker?.fail(r,xe.error??"No record could be synced."):xe.status==="partial"?this.liveTracker?.partial(r):this.liveTracker?.complete(r)),this.dmlTracker.markCompleted(r),c.files){let V=xe.objectResults.flatMap(ae=>ae.files?[ae.files]:[]);this.deps.log(`[sync] ${r} files: ${rS(V)}`)}$e(w.limitInfo,"sync:execute completion (source)"),$e(P.limitInfo,"sync:execute completion (target)");try{this.historyLogger?.logExecution(c,xe,o)}catch(V){this.deps.log(`[WARN] sync history logging failed: ${I(V)}`)}this.recordRun(c,r,xe,i,o,g);let Ue=A(this.deps,e,"sync:execute:response",xe);return this.deps.broker.postToWebview(Ue),this.deps.log(`[TX] ${Ue.type} id=${Ue.id}`),xe}catch(R){await v?.end({status:"failure"}),C(),this.dmlTracker.markFailed(r);let w=await this.settleRunCheckpoint(S,f,r),P=w?.state==="deleted";if(this.liveTracker?.fail(r,I(R)),R instanceof pS){let H=S?.refusal(),J=P?`${R.message} ${Zr}`:R.message,W={...H?{checkpointRefusal:H.code}:{},...w?{checkpoint:w}:{}};return Y(this.deps,{action:"sync_execute",module:"sync",operationId:r,orgId:c.targetOrgId,outcome:"stopped",guard:i,code:R.code,details:{triggeredBy:o,...H?{checkpointRefusal:H.code}:{},...so(g)}}),T(this.deps,"sync:execute","sync:error",e,R,{code:R.code,extraPayload:W}),Le(this.deps,r,J,!1,{context:{module:"sync",operation:e.type,...Jr(c.objects)}}),{...R.result,configId:c.id,operationId:r,status:"failure",timestamp:new Date().toISOString(),error:J,...w?{checkpoint:w}:{}}}xs(R)&&o!=="rerun"&&d===void 0&&this.deps.infraServices?.offlineManager?this.deps.infraServices.offlineManager.enqueue({id:r,type:"sync",orgId:c.targetOrgId,payload:{config:c}})&&this.deps.log(`[OFFLINE] sync queued for replay on reconnect: ${r}`):xs(R)&&o==="rerun"&&this.deps.log(`[OFFLINE] sync replay failed again \u2014 not re-queued (replay outcomes surface via operation:failed): ${r}`);let O=P?new Error(`${I(R)} ${Zr}`):R;T(this.deps,"sync:execute","sync:error",e,R,{...w?{extraPayload:{checkpoint:w}}:{}}),Le(this.deps,r,I(O),!0,{context:{module:"sync",operation:e.type,...Jr(c.objects)}});let $={...(R instanceof lS?R.result:void 0)??{objectResults:[],totalProcessed:0,totalSuccess:0,totalFailed:0,totalSkipped:0,duration:0},configId:c.id,operationId:r,status:"failure",timestamp:new Date().toISOString(),error:I(O),...w?{checkpoint:w}:{}};try{this.historyLogger?.logExecution(c,$,o)}catch(H){this.deps.log(`[WARN] sync history logging failed: ${I(H)}`)}return this.recordRun(c,r,$,i,o,g),$}finally{this.pauseGates.delete(r),this.activeOperationIds.has(r)&&(this.deps.infraServices?.performanceTracker?.complete(r),this.activeOperationIds.delete(r))}}};var cD=new Set(["sync:history:list","sync:history:detail","sync:history:rerun","sync:history:export"]),pc=class{constructor(e,t,r){this.deps=e;this.historyStore=t;this.syncOps=r}deps;historyStore;syncOps;async handle(e){if(!cD.has(e.type))return!1;switch(e.type){case"sync:history:list":return this.handleList(e),!0;case"sync:history:detail":return this.handleDetail(e),!0;case"sync:history:export":return this.handleExport(e),!0;case"sync:history:rerun":return await this.handleRerun(e),!0;default:return!1}}handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.historyStore.list(),r=A(this.deps,e,"sync:history:list:response",{entries:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} count=${t.length}`)}catch(t){T(this.deps,"sync:history:list","sync:history:error",e,t)}}handleDetail(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(kl,e,"sync:history:error",this.deps);if(t)try{let r=this.historyStore.load(t.entryId)??null,n=A(this.deps,e,"sync:history:detail:response",{entry:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){T(this.deps,"sync:history:detail","sync:history:error",e,r)}}handleExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ny,e,"sync:history:error",this.deps);if(t)try{let r=t.format==="csv"?this.historyStore.exportAsCsv(t.entryIds):this.historyStore.exportAsJson(t.entryIds),n=A(this.deps,e,"sync:history:export:response",{data:r,format:t.format});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} format=${t.format}`)}catch(r){T(this.deps,"sync:history:export","sync:history:error",e,r)}}async handleRerun(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(kl,e,"sync:history:error",this.deps);if(!t)return;let r=this.historyStore.load(t.entryId);if(!r){T(this.deps,"sync:history:rerun","sync:history:error",e,new Error(`History entry not found: ${t.entryId}`),{code:"NOT_FOUND"});return}await this.syncOps.rerunFromSnapshot(e,r.configSnapshot)}};var uD=1e4;async function yI(s,e){if(s.configId!==void 0&&e.isSaved(s.configId))return{leftAsIs:!0,objects:[]};let t=new Set(s.objects);if(t.size===0)return{leftAsIs:!1,objects:[]};let r=c=>Nt(c).filter(u=>t.has(u.objectApiName)),n=(await e.runs()).find(c=>c.sourceOrgId===s.sourceOrgId&&c.targetOrgId===s.targetOrgId&&r(c).length>0);if(!n)return{leftAsIs:!1,objects:[]};let o=n.created.map(c=>c.objectApiName),i=r(n).sort((c,u)=>o.indexOf(c.objectApiName)-o.indexOf(u.objectApiName)),a,d=[];for(let{objectApiName:c,ids:u}of i){let l=u.slice(0,uD),p;try{p=await e.countInTarget(c,l)+(u.length-l.length)}catch(f){a??=f instanceof Error?f.message:String(f),p=u.length}p>0&&d.push({objectApiName:c,count:p})}return{leftAsIs:!1,run:{runId:n.runId,configName:n.configName,startedAt:n.startedAt,...n.realtime?{realtime:!0}:{}},objects:d,...a!==void 0?{unread:a}:{}}}var lD=new Set(["sync:removal:info","sync:removal:list","sync:remove","sync:remove:sweep","sync:remove:automation","sync:earlier-copies"]),pD=6e4,fD=12e4,wI=6e4,gD=6e4,bI="The run is still writing in another window: remove it once it has ended there.",fc=class{constructor(e,t,r,n=Mo){this.deps=e;this.history=t;this.isRunning=r;this.self=n;this.configs=new Pt(e.configStore)}deps;history;isRunning;self;creations;otherModuleRuns=()=>Promise.resolve([]);backups;registry;liveTracker;removing=new Set;configs;targetAutomation={read:async(e,t,r)=>(await this.ownReader()).read(e,t,r)};reader;elsewhere(e){return!this.isRunning(e.runId)&&ro(e,this.self)}stillWriting(e){return this.isRunning(e.runId)||ro(e,this.self)}setRunCreations(e){this.creations=e}setBackupRecordStore(e){this.backups=e}setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-UK3QLBHW.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async handle(e){if(!lD.has(e.type))return!1;switch(e.type){case"sync:removal:info":return await this.handleInfo(e),!0;case"sync:removal:list":return await this.handleList(e),!0;case"sync:remove":return await this.handleRemove(e),!0;case"sync:remove:sweep":return await this.handleSweepList(e),!0;case"sync:remove:automation":return await this.handleRemovalAutomation(e),!0;case"sync:earlier-copies":return await this.handleEarlierCopies(e),!0;default:return!1}}tierOf(e){let t=this.deps.orgManager.getOrg(e);return Pe(t)}infoOf(e,t=[]){let r=Nt(e),n=Eb(e,t),o=r.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length})),i=Lo(e),a=this.keptBack(i),d=Nl(e),c=jl(e),u=Gs(e),l={runId:e.runId,configId:e.configId,configName:e.configName,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,startedAt:e.startedAt,...e.end?{endedAt:e.end.at}:{},...!e.end&&e.inFlight?{inFlight:{objectApiName:e.inFlight.objectApiName,rows:e.inFlight.rows}}:{},...this.elsewhere(e)?{runningElsewhere:!0}:{},...e.realtime?{realtime:!0}:{},created:zs(e),left:o,...d>0?{overwritten:d}:{},...a.kept.length>0?{putBack:a.kept.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length})),...a.keptUntil!==void 0?{putBackKeptUntil:a.keptUntil}:{}}:{},...a.notKept>0?{putBackNotKept:a.notKept}:{},...c>0?{deleted:c}:{},...e.unkept?{notKeptEncrypted:e.unkept.flatMap(({objectApiName:m,fields:y})=>y.map(v=>`${m}.${v}`))}:{},...u.length>0?{bringBack:u.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length}))}:{},...e.removal?.undo?{removed:e.removal.undo}:{},...n.length>0?{writtenAgain:n}:{}},p=e.removal?.undo?Nt(e,!0):[],f=p.length>0?{...l,createdByObject:p.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length}))}:l,g=r.length>0||i.length>0||u.length>0?r:p;if(g.length===0&&i.length===0&&u.length===0)return f;let h=this.refusalOf(e,g,[...i,...u]);return h?{...f,refusal:h}:f}keptBack(e){return Fb(e,t=>this.deps.configStore.get(`backup:${t}`),Lb(this.deps.services))}removalStepsOf(e,t,r){let n=i=>[...new Set(i.map(({objectApiName:a})=>a))],o=n(Nt(e,t));return{bringBack:n(Gs(e)),giveBack:n(this.keptBack(Lo(e)).kept),setToDraft:or(o),delete:id(o,r,{userKept:e.runUserId!==void 0})}}async setsOfConfirmation(e){if(e.runUserId!==void 0||e.created.every(({ids:r})=>r.length===0))return{objects:[]};let t={objects:[On]};try{let r=await B(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await Vo(Wt(r,"sync:remove:automation"),e.created);return n.unread!==void 0?t:n}catch{return t}}guardRequestOf(e,t,r){let n=o=>o.reduce((i,a)=>i+a.ids.length,0);return{orgId:e.targetOrgId,orgTier:this.tierOf(e.targetOrgId),operation:t.length>0?"delete":"update",objectName:[...new Set([...t,...r].map(o=>o.objectApiName))].join(", "),recordCount:n(t)+n(r),module:"sync"}}refusalOf(e,t,r){if(this.isRunning(e.runId))return{code:"RUNNING",message:"The run is still writing: remove it once it has ended."};if(this.elsewhere(e))return{code:"RUNNING",message:bI};if(!this.deps.orgManager.getOrg(e.targetOrgId))return{code:"ORG_GONE",message:"The org the run wrote to is no longer connected: connect it again to remove the run."};let n=this.deps.infraServices?.productionGuard;if(!n)return{code:"NO_GUARD",message:ve.message};let o=n.check(this.guardRequestOf(e,t,r));return o.allowed?void 0:{code:"GUARD_BLOCKED",message:o.blockedReason??o.impactSummary}}async withJobAnswered(e){let t=this.creations;if(!t||(e.jobs??[]).length===0||this.stillWriting(e)||!this.deps.orgManager.getOrg(e.targetOrgId))return e;let r=`sync:removal of ${e.runId}`;try{let n=await new pe(gD).withTimeout(r,async()=>{let o=await B(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=Wt(o,r);return od(t,e,to(o),()=>i.serverTime())});for(let o of sd(r,n))this.deps.log(o);return n.some(o=>o.answered)?await t.get(e.runId)??e:e}catch(n){return this.deps.log(`[WARN] ${r}: the job could not be read back: ${I(n)}`),e}}async runOf(e){let t=await this.creations?.get(e);return t?this.withJobAnswered(t):void 0}async handleInfo(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Jm,e,"sync:remove:error",this.deps);if(t)try{let r=await this.runOf(t.runId),o=r!==void 0&&(Nt(r).length>0||Lo(r).length>0)?await this.creations?.list()??[]:[],i=A(this.deps,e,"sync:removal:info:response",{info:r?this.infoOf(r,o):null});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(r){T(this.deps,"sync:removal:info","sync:remove:error",e,r)}}async handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Vm,e,"sync:remove:error",this.deps);if(t===null)return;let r=t?.realtime===!0;try{let n=new Set(this.history.list().flatMap(d=>d.result.created?.runId?[d.result.created.runId]:[])),o=[];for(let d of await this.creations?.list()??[]){let c=n.has(d.runId)||d.realtime===!0!==r;o.push(c?d:await this.withJobAnswered(d))}let i=o.filter(d=>d.realtime===!0===r&&!n.has(d.runId)&&!this.isRunning(d.runId)&&(zs(d)>0||Nl(d)>0||jl(d)>0||!d.end&&d.inFlight!==void 0)),a=A(this.deps,e,"sync:removal:list:response",{runs:i.map(d=>this.infoOf(d,o))});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id} count=${i.length}`)}catch(n){T(this.deps,"sync:removal:list","sync:remove:error",e,n)}}async handleEarlierCopies(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Xm,e,"sync:remove:error",this.deps);if(t)try{let r=this.creations,n=await yI(t,{runs:async()=>await r?.list()??[],isSaved:i=>this.configs.isSaved(i),countInTarget:async(i,a)=>{let d=await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),c=St(i),u=0;for(let l of Ls(a.filter(Xr)))u+=(await d.query(`SELECT COUNT() FROM ${c} WHERE Id IN (${l})`)).totalSize;return u}}),o=A(this.deps,e,"sync:earlier-copies:response",{copies:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(r){T(this.deps,"sync:earlier-copies","sync:remove:error",e,r)}}async sweepInputOf(e,t,r,n){let o=this.targetAutomation,i=[...new Set([...t.created,...t.overwritten??[]].map(u=>u.objectApiName).filter(u=>!Ab.includes(u)))],a;try{a=await new pe(pD).withTimeout(`${r} automation`,()=>o.read(t.targetOrgId,i))}catch(u){a={error:I(u)}}let d=Wt(e,r),c=await ad(d,t.created,a,n,t.firstWrittenAt!==void 0?{at:t.firstWrittenAt,...t.lastWriteAt!==void 0?{lastAt:t.lastWriteAt}:{},serverTime:()=>d.serverTime()}:void 0,t.overwritten??[],{...t.runUserId?{runUserId:t.runUserId}:{},ties:{}});return Ko({...c,ties:{...c.ties,...await cd(t,c.writtenBetween,await this.creations?.list().catch(()=>[])??[],this.otherModuleRuns)}},d)}async localRunsOn(e){return dd(await this.creations?.list().catch(()=>[])??[],e)}setOtherModuleRuns(e){this.otherModuleRuns=e}async handleSweepList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Ym,e,"sync:remove:sweep:error",this.deps);if(!t)return;let r=(n,o)=>T(this.deps,"sync:remove:sweep","sync:remove:sweep:error",e,new Error(n),{code:o});try{let n=await this.runOf(t.runId);if(!n){r("Nothing this run created is kept: there is nothing to sweep after.","NOT_KEPT");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){r("The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}let o=await new pe(fD).withTimeout("sync:remove:sweep",async()=>{let i=await B(n.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=await this.sweepInputOf(i,n,"sync:remove:sweep");return zo(tn(i,"sync:remove:sweep"),a,n.removal?.removalSpans??[])});this.deps.broker.postToWebview(A(this.deps,e,"sync:remove:sweep:response",{runId:n.runId,listing:o}))}catch(n){T(this.deps,"sync:remove:sweep","sync:remove:sweep:error",e,n,{code:"SWEEP_ERROR",retryable:!0})}}async handleRemovalAutomation(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Qm,e,"sync:remove:automation:error",this.deps);if(!t)return;let r=(n,o)=>T(this.deps,"sync:remove:automation","sync:remove:automation:error",e,new Error(n),{code:o});try{let n=await this.runOf(t.runId);if(!n){r("Nothing this run created is kept: there is nothing to remove.","NOT_KEPT");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){r("The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}let o=Es(this.removalStepsOf(n,t.again===!0,await this.setsOfConfirmation(n)),t.sweptObjects??[]),i=[...new Set(Object.values(o).flat())],a=this.targetAutomation,d=await new pe(wI).withTimeout("sync:remove:automation",()=>a.read(n.targetOrgId,i,{undeletes:!0})),c=A(this.deps,e,"sync:remove:automation:response",{runId:n.runId,automation:d,steps:o});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(n){let o=n instanceof zt;T(this.deps,"sync:remove:automation","sync:remove:automation:error",e,n,{code:o?"TIMEOUT":"AUTOMATION_ERROR",retryable:!0})}}sweepOfRemoval(e){let{conn:t,run:r,input:n}=e;return Yo({input:async()=>{if(n instanceof Error)throw n;return n},org:tn(t,"sync:remove sweep",e.signal),options:{includeChanged:e.includeChanged,removalSpans:r.removal?.removalSpans??[],sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},guard:e.guard,guardOf:{orgId:r.targetOrgId,orgTier:this.tierOf(r.targetOrgId),operation:"delete",module:"sync"},onGuardDecision:(o,i)=>{let a=Jo(o,"");delete a.forgeId,Y(this.deps,{action:"cleanup_delete",module:"sync",operationId:`${e.operationId}-sweep`,orgId:r.targetOrgId,outcome:o.status==="refused"?"stopped":o.status,...i?{guard:i}:{},...o.status==="refused"?{code:Qo(i)}:{},objects:Go(o),details:{...a,runId:r.runId}})},keepMade:async(o,i,a)=>{await this.creations?.updateRemoval(r.runId,d=>ud(d,o,i,a)).catch(d=>{this.deps.log(`[WARN] sync:remove ${e.operationId}: what the sweep found made for the run could not be kept: ${I(d)}`)})}})}refuse(e,t,r,n=!1){T(this.deps,"sync:remove","sync:remove:error",e,new Error(t),{code:r,...n?{retryable:n}:{}})}recordNotRemoved(e,t,r,n={}){Y(this.deps,{action:"cleanup_delete",module:"sync",operationId:e.id,orgId:t.targetOrgId,outcome:r,...n,details:{runId:t.runId}})}setMuteLeases(e){this.muteLeases=e}muteLeases={};async handleRemove(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Km,e,"sync:remove:error",this.deps);if(!t)return;let r=this.creations;if(!r){this.refuse(e,"What Sync runs created is not kept in this window yet.","NOT_INITIALIZED",!0);return}let n;try{n=await this.runOf(t.runId)}catch(a){T(this.deps,"sync:remove","sync:remove:error",e,a,{code:"REMOVE_ERROR",retryable:!0});return}if(!n){this.refuse(e,"Nothing this run created is kept: it created nothing, or ran before runs kept what they created, or the record of it was dropped to make room.","NOT_KEPT");return}if(this.isRunning(n.runId)){this.refuse(e,"The run is still writing: remove it once it has ended.","RUNNING");return}if(this.elsewhere(n)){this.refuse(e,bI,"RUNNING");return}let o=t.again===!0;if(Nt(n,o).length===0&&Lo(n).length===0&&Gs(n).length===0){let a=n.removal?.undo?.removedAt??n.removal?.restoredAt??n.removal?.undeletedAt;a!==void 0?this.refuse(e,`What this run created was removed already, on ${a}.`,"ALREADY_REMOVED"):this.refuse(e,"This run created nothing to remove.","NOTHING_TO_REMOVE");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){this.refuse(e,"The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}if(this.removing.has(n.runId)){this.refuse(e,"What this run created is being removed already.","DUPLICATE");return}this.removing.add(n.runId);let i=this.registry?.holdUntilStart(e.id);try{await this.removeRun(e,r,n,{includeChanged:t.includeChanged===!0,sweep:t.sweep===!0,sweepLate:t.sweep===!0&&t.sweepLate===!0,sweepUntied:t.sweep===!0&&t.sweepUntied===!0,again:o,muteAutomation:t.muteAutomation===!0},i)}finally{this.removing.delete(n.runId),i?.release()}}async removeRun(e,t,r,n,o){let{includeChanged:i,again:a}=n,d=Nt(r,a),c=[...Lo(r),...Gs(r)],u=d.reduce((R,w)=>R+w.ids.length,0),l=c.reduce((R,w)=>R+w.ids.length,0),p=r.targetOrgId,f=this.deps.infraServices?.productionGuard;if(!f){this.recordNotRemoved(e,r,"stopped",{code:ve.code}),this.refuse(e,ve.message,ve.code);return}let{check:g,decision:h}=await et(f,this.guardRequestOf(r,d,c));if(h==="refused"||h==="declined"){this.recordNotRemoved(e,r,"stopped",{guard:h}),h==="refused"?this.refuse(e,`Operation blocked by Production Guard: ${g.blockedReason??g.impactSummary}`,Dt.blocked):this.refuse(e,"Operation cancelled by user (confirmation declined).",Dt.declined,!0);return}if(o?.signal.aborted){this.recordNotRemoved(e,r,"stopped",{guard:h,code:ht});let R={runId:r.runId,status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(A(this.deps,e,"sync:remove:response",{result:R,operationId:e.id}));return}let m=e.id,y=l>0?`Removing ${u} record(s) and file(s) a Sync run created, and giving ${l} record(s) it wrote over or deleted their values back`:`Removing ${u} record(s) and file(s) a Sync run created`,v=new AbortController,b=()=>{},k=new Promise((R,w)=>{b=P=>P===void 0?R():w(P)});k.catch(()=>{}),Ge(this.deps,m,"sync",y),this.registry?.register(m,"sync",y,k,v),this.liveTracker?.register(m,"sync",y,u+l);let S,C;try{let R=await B(p,this.deps.orgRegistry,this.deps.orgManager),w=n.sweep?await this.sweepInputOf(R,r,"sync:remove sweep",v.signal).catch(q=>new Error(I(q))):void 0;C=w?await this.sweepOfRemoval({conn:R,run:r,input:w,includeChanged:i,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,signal:v.signal,guard:f,operationId:m}):void 0;let P=C;await P?.ask();let O=Wt(R,"sync:remove"),E=await Vo(O,r.created),$;if(n.muteAutomation===!0){let q=Es(this.removalStepsOf(r,a,E),P?.takes??[]),F=[...new Set(Object.values(q).flat())],ne=this.targetAutomation,ke=await new pe(wI).withTimeout("sync:remove:automation",()=>ne.read(r.targetOrgId,F,{undeletes:!0})).catch(de=>({unread:I(de)}));$=await Et(async()=>_t(R),ke,{...this.muteLeases,writes:zr(q)})}let H,J=$?.muted,W=async()=>{let q=$?.prepared;!q||v.signal.aborted||(H=await q.acquire(m),J=H.outcome)},{result:Z,notes:_,earlierStamped:Q,emptied:N}=await Da({run:r,org:O,includeChanged:i,...a?{again:a}:{},store:t,configs:this.configs,links:t.idMap(),...this.backups?{backups:this.backups}:{},earlierRuns:Tb(r,await t.list().catch(()=>[])),undelete:q=>R.soap.undelete(q),...P?{sweep:q=>P.first(q),afterRemoval:q=>P.afterRemoval(q),automationMade:P.automationMade}:{},...r.runUserId?{runUserId:r.runUserId}:{},onUndeletable:Gr(this.deps,p,"sync:remove"),beforeFirstWrite:W,signal:v.signal,onProgress:(q,F,ne)=>{let ke=Math.min(100,Math.round(q/Math.max(F,1)*100));_e(this.deps,m,ke,q,F,ne),v.signal.aborted||this.registry?.updateProgress(m,ke),this.liveTracker?.updateProgress(m,ke,q,F,ne)}}).then(async q=>({...q,emptied:q.result.status==="cancelled"?{}:await E.take(q.duplicateSets)})).finally(async()=>{H&&(J=await H.release())}),z=await C?.settle();for(let q of[..._,...N.note?[N.note]:[]])this.deps.log(`[WARN] sync:remove ${m}: ${q}`);for(let{runId:q,records:F}of Q??[])this.deps.log(`[INFO] sync:remove ${m}: ${F} record(s) given back hold the values of the earlier run ${q} again, stamped on it`);let oe={...Z,objects:N.object?[...Z.objects,N.object]:Z.objects,status:No(Xo(Z.status,N),z),...z?{sweep:z}:{},...J?{mutedAutomation:J}:{}};Y(this.deps,{action:"cleanup_delete",module:"sync",operationId:m,orgId:p,outcome:jo({status:Xo(Z.status,N)}),guard:h,objects:xa(In(oe.objects),oe.restored??[],oe.undeleted??[]),...oe.leftBy?{leftBy:oe.leftBy}:{},...J?{muted:ft(J)}:{},details:{runId:r.runId}});let re=A(this.deps,e,"sync:remove:response",{result:oe,operationId:m});this.deps.broker.postToWebview(re),this.deps.log(`[TX] ${re.type} id=${re.id} status=${oe.status}`),oe.status==="cancelled"||oe.sweep?.status==="cancelled"?(me(this.deps,m,{aborted:!0}),this.liveTracker?.cancel(m)):(me(this.deps,m,{status:oe.status}),oe.status==="failure"?(S=new Error("Nothing this run created could be removed."),this.liveTracker?.fail(m,"Nothing this run created could be removed.")):oe.status==="partial"?this.liveTracker?.partial(m):this.liveTracker?.complete(m))}catch(R){S=R,await C?.settle().catch(()=>{});let w=jt(R)?R:void 0;this.recordNotRemoved(e,r,w?"stopped":"failure",{guard:h,...w?{code:w.code}:{}}),T(this.deps,"sync:remove","sync:remove:error",e,R,{code:w?.code??"REMOVE_ERROR",retryable:!0}),me(this.deps,m,{status:"failure"}),this.liveTracker?.fail(m,I(R))}finally{b(S)}}};var hD=new Set(["seed:removal:info","seed:removal:list","seed:remove","seed:remove:sweep","seed:remove:automation","seed:open-record"]),hf=6e4,mD=12e4,yD=6e4,RI="The seed is still writing: remove it once it has ended.",vI="The seed is still writing in another window: remove it once it has ended there.",gc=class{constructor(e,t,r=()=>!1,n=Mo){this.deps=e;this.isRunning=r;this.self=n;this.externalBrowser=t??new jn}deps;isRunning;self;creations;otherModuleRuns=()=>Promise.resolve([]);registry;liveTracker;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;removing=new Set;externalBrowser;elsewhere(e){return!this.isRunning(e.runId)&&ro(e,this.self)}setRunCreations(e){this.creations=e}setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-UK3QLBHW.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}async handle(e){return hD.has(e.type)?(e.type==="seed:removal:info"?await this.handleInfo(e):e.type==="seed:removal:list"?await this.handleList(e):e.type==="seed:remove:sweep"?await this.handleSweepList(e):e.type==="seed:remove:automation"?await this.handleRemovalAutomation(e):e.type==="seed:open-record"?await this.handleOpenRecord(e):await this.handleRemove(e),!0):!1}tierOf(e){let t=this.deps.orgManager.getOrg(e);return Pe(t)}infoOf(e){let t=Nt(e),r={runId:e.runId,targetOrgId:e.targetOrgId,startedAt:e.startedAt,endedAt:e.end?.at??e.lastWrittenAt??e.startedAt,...e.origin?{origin:e.origin}:{},...e.origin==="clone"?{sourceOrgId:e.sourceOrgId}:{},...e.pipeline?{pipeline:e.pipeline}:{},...e.end?{}:this.isRunning(e.runId)?{running:!0}:this.elsewhere(e)?{runningElsewhere:!0}:{unfinished:!0,...e.inFlight?{inFlight:{objectApiName:e.inFlight.objectApiName,rows:e.inFlight.rows}}:{}},created:zs(e),objects:[...new Set([...e.created.map(({objectApiName:d})=>d),...(e.overwritten??[]).map(({objectApiName:d})=>d)])],left:t.map(({objectApiName:d,ids:c})=>({objectApiName:d,count:c.length})),...e.removal?.undo?{removed:e.removal.undo}:{},...e.checkpoint?{checkpoint:e.checkpoint}:{}},n=e.removal?.undo?Nt(e,!0):[],o=n.length>0?{...r,createdByObject:n.map(({objectApiName:d,ids:c})=>({objectApiName:d,count:c.length}))}:r,i=t.length>0?t:n;if(i.length===0)return o;let a=this.refusalOf(e,i);return a?{...o,refusal:a}:o}async withScenario(e){let t=this.creations;if(!t||e.origin)return e;try{let{nodeScenarioSidecarFiles:r,readScenarioRunSidecar:n}=await import("./chunk-6KVBCFVS.mjs"),o=await n(r(),t.storagePath,e.runId);if(o.kind!=="read")return e;let{packId:i,agent:a}=o.sidecar;return{...e,scenario:{packId:i,...a?{agent:a.agent}:{}}}}catch{return e}}refusalOf(e,t){if(this.isRunning(e.runId))return{code:"RUNNING",message:RI};if(this.elsewhere(e))return{code:"RUNNING",message:vI};if(!this.deps.orgManager.getOrg(e.targetOrgId))return{code:"ORG_GONE",message:"The org the run wrote to is no longer connected: connect it again to remove the run."};let r=this.deps.infraServices?.productionGuard;if(!r)return{code:"NO_GUARD",message:ve.message};let n=r.check({orgId:e.targetOrgId,orgTier:this.tierOf(e.targetOrgId),operation:"delete",objectName:t.map(o=>o.objectApiName).join(", "),recordCount:t.reduce((o,i)=>o+i.ids.length,0),module:"seed"});return n.allowed?void 0:{code:"GUARD_BLOCKED",message:n.blockedReason??n.impactSummary}}async withJobAnswered(e){let t=this.creations;if(!t||(e.jobs??[]).length===0||this.isRunning(e.runId)||this.elsewhere(e)||!this.deps.orgManager.getOrg(e.targetOrgId))return e;let r=`seed:removal of ${e.runId}`;try{let n=await new pe(yD).withTimeout(r,async()=>{let o=await B(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=Wt(o,r);return od(t,e,to(o),()=>i.serverTime())});for(let o of sd(r,n))this.deps.log(o);return n.some(o=>o.answered)?await t.get(e.runId)??e:e}catch(n){return this.deps.log(`[WARN] ${r}: the job could not be read back: ${I(n)}`),e}}async runOf(e){let t=await this.creations?.get(e);return t?this.withJobAnswered(t):void 0}cleanupLineOf(e){let t=this.deps.orgManager.getOrg(e.targetOrgId);return Hv(e,"npx sandforge cleanup",t?.alias??"<alias>")}notKeptWords(e){let t="rewind the org to a checkpoint taken before it, or empty its objects (DataOps, Cleanup, Empty objects), which deletes all their records.";return e?`${Uv(e,this.cleanupLineOf(e))} Or ${t}`:`Nothing this run created is kept: it created nothing, or was dropped to make room for newer seeds. To take its records back, ${t}`}async handleInfo(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Zm,e,"seed:remove:error",this.deps);if(t)try{let r=await this.runOf(t.runId),n=r?void 0:await this.creations?.dropped(t.runId),o=A(this.deps,e,"seed:removal:info:response",{info:r?await this.withScenario(this.infoOf(r)):null,...n?{dropped:n,cleanupLine:this.cleanupLineOf(n)}:{}});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(r){T(this.deps,"seed:removal:info","seed:remove:error",e,r)}}async handleOpenRecord(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Oy,e,"seed:open-record:error",this.deps);if(!t)return;let r=(n,o)=>{T(this.deps,"seed:open-record","seed:open-record:error",e,new Error(n),{code:o})};try{let n=await this.creations?.get(t.runId);if(!n){r("Nothing of this run is kept any more.","NOT_KEPT");return}let o=t.recordId.slice(0,15),i;for(let{objectApiName:l,ids:p}of n.created){let f=p.find(g=>g.slice(0,15)===o);if(f){i={objectApiName:l,id:f};break}}if(!i){r("This record is not one this run created.","NOT_CREATED");return}let a=this.deps.orgManager.getOrg(n.targetOrgId);if(!a){r("The org this run wrote to is no longer connected.","ORG_NOT_FOUND");return}let d=bd(a.instanceUrl,i.objectApiName,i.id);if(!d.ok){let l=d.reason==="not-https"?`its instance URL must use HTTPS, got "${d.protocol}"`:d.reason==="invalid"?"its instance URL is not a valid URL":"the record is not one an address can be built for";r(`Cannot open the record in "${we(a)}": ${l}.`,d.reason==="not-a-record"?"NOT_CREATED":"INVALID_INSTANCE_URL");return}let c=await this.externalBrowser.open(d.url),u=A(this.deps,e,"seed:open-record:response",c);this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id} status=${c.status}`)}catch(n){T(this.deps,"seed:open-record","seed:open-record:error",e,n)}}async handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=[];for(let o of await this.creations?.list()??[])t.push(await this.withJobAnswered(o));let r=[];for(let o of t)r.push(await this.withScenario(this.infoOf(o)));let n=A(this.deps,e,"seed:removal:list:response",{runs:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} runs=${t.length}`)}catch(t){T(this.deps,"seed:removal:list","seed:remove:error",e,t)}}async sweepInputOf(e,t,r,n){let o=this.targetAutomation,i;try{i=await new pe(hf).withTimeout(`${r} automation`,()=>o.read(t.targetOrgId,t.created.map(c=>c.objectApiName)))}catch(c){i={error:I(c)}}let a=Wt(e,r),d=await ad(a,t.created,i,n,void 0,[],{...t.runUserId?{runUserId:t.runUserId}:{},ties:{}});return Ko({...d,ties:{...d.ties,...await cd(t,d.writtenBetween,await this.creations?.list().catch(()=>[])??[],this.otherModuleRuns)}},a)}async localRunsOn(e){return dd(await this.creations?.list().catch(()=>[])??[],e)}setOtherModuleRuns(e){this.otherModuleRuns=e}async handleSweepList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ty,e,"seed:remove:sweep:error",this.deps);if(!t)return;let r=(n,o)=>T(this.deps,"seed:remove:sweep","seed:remove:sweep:error",e,new Error(n),{code:o});try{let n=await this.runOf(t.runId);if(!n){r("Nothing this run created is kept: there is nothing to sweep after.","NOT_KEPT");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){r("The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}let o=await new pe(mD).withTimeout("seed:remove:sweep",async()=>{let i=await B(n.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=await this.sweepInputOf(i,n,"seed:remove:sweep");return zo(tn(i,"seed:remove:sweep"),a,n.removal?.removalSpans??[])});this.deps.broker.postToWebview(A(this.deps,e,"seed:remove:sweep:response",{runId:n.runId,listing:o}))}catch(n){T(this.deps,"seed:remove:sweep","seed:remove:sweep:error",e,n,{code:"SWEEP_ERROR",retryable:!0})}}removalStepsOf(e,t,r,n){let o=[...new Set(Nt(e,t).map(({objectApiName:i})=>i))];return Es({setToDraft:or(o),delete:id(o,r,{userKept:e.runUserId!==void 0})},n)}async setsOfConfirmation(e){if(e.runUserId!==void 0||e.created.every(({ids:r})=>r.length===0))return{objects:[]};let t={objects:[On]};try{let r=await B(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await Vo(Wt(r,"seed:remove:automation"),e.created);return n.unread!==void 0?t:n}catch{return t}}async handleRemovalAutomation(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ry,e,"seed:remove:automation:error",this.deps);if(!t)return;let r=(n,o)=>T(this.deps,"seed:remove:automation","seed:remove:automation:error",e,new Error(n),{code:o});try{let n=await this.runOf(t.runId);if(!n){r("Nothing this run created is kept: there is nothing to remove.","NOT_KEPT");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){r("The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}let o=this.removalStepsOf(n,t.again===!0,await this.setsOfConfirmation(n),t.sweptObjects??[]),i=[...new Set(Object.values(o).flat())],a=this.targetAutomation,d=await new pe(hf).withTimeout("seed:remove:automation",()=>a.read(n.targetOrgId,i)),c=A(this.deps,e,"seed:remove:automation:response",{runId:n.runId,automation:d,steps:o});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(n){T(this.deps,"seed:remove:automation","seed:remove:automation:error",e,n,{code:n instanceof zt?"TIMEOUT":"AUTOMATION_ERROR",retryable:!0})}}sweepOfRemoval(e){let{conn:t,run:r}=e;return Yo({input:()=>this.sweepInputOf(t,r,"seed:remove sweep",e.signal),org:tn(t,"seed:remove sweep",e.signal),options:{includeChanged:e.includeChanged,removalSpans:r.removal?.removalSpans??[],sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},guard:e.guard,guardOf:{orgId:r.targetOrgId,orgTier:this.tierOf(r.targetOrgId),operation:"delete",module:"seed"},onGuardDecision:(n,o)=>{let i=Jo(n,"");delete i.forgeId,Y(this.deps,{action:"cleanup_delete",module:"seed",operationId:`${e.operationId}-sweep`,orgId:r.targetOrgId,outcome:n.status==="refused"?"stopped":n.status,...o?{guard:o}:{},...n.status==="refused"?{code:Qo(o)}:{},objects:Go(n),details:{...i,runId:r.runId}})},keepMade:async(n,o,i)=>{await this.creations?.updateRemoval(r.runId,a=>ud(a,n,o,i)).catch(a=>{this.deps.log(`[WARN] seed:remove ${e.operationId}: what the sweep found made for the run could not be kept: ${I(a)}`)})}})}refuse(e,t,r,n=!1){T(this.deps,"seed:remove","seed:remove:error",e,new Error(t),{code:r,...n?{retryable:n}:{}})}recordNotRemoved(e,t,r,n={}){Y(this.deps,{action:"cleanup_delete",module:"seed",operationId:e.id,orgId:t.targetOrgId,outcome:r,...n,details:{runId:t.runId}})}setMuteLeases(e){this.muteLeases=e}muteLeases={};async handleRemove(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ey,e,"seed:remove:error",this.deps);if(!t)return;let r=this.creations,n=await this.runOf(t.runId);if(!r||!n){this.refuse(e,this.notKeptWords(await r?.dropped(t.runId)),"NOT_KEPT");return}let o=t.again===!0;if(Nt(n,o).length===0){n.removal?.undo?this.refuse(e,`What this run created was removed already, on ${n.removal.undo.removedAt}.`,"ALREADY_REMOVED"):this.refuse(e,"This run created nothing to remove.","NOTHING_TO_REMOVE");return}if(this.isRunning(n.runId)){this.refuse(e,RI,"RUNNING");return}if(this.elsewhere(n)){this.refuse(e,vI,"RUNNING");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){this.refuse(e,"The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}if(this.removing.has(n.runId)){this.refuse(e,"What this run created is being removed already.","DUPLICATE");return}this.removing.add(n.runId);let i=this.registry?.holdUntilStart(e.id);try{await this.removeRun(e,r,n,{includeChanged:t.includeChanged===!0,sweep:t.sweep===!0,sweepLate:t.sweep===!0&&t.sweepLate===!0,sweepUntied:t.sweep===!0&&t.sweepUntied===!0,again:o,muteAutomation:t.muteAutomation===!0},i)}finally{this.removing.delete(n.runId),i?.release()}}async removeRun(e,t,r,n,o){let{includeChanged:i,again:a}=n,d=Nt(r,a),c=d.reduce((S,C)=>S+C.ids.length,0),u=r.targetOrgId,l=this.deps.infraServices?.productionGuard;if(!l){this.recordNotRemoved(e,r,"stopped",{code:ve.code}),this.refuse(e,ve.message,ve.code);return}let{check:p,decision:f}=await et(l,{orgId:u,orgTier:this.tierOf(u),operation:"delete",objectName:d.map(S=>S.objectApiName).join(", "),recordCount:c,module:"seed"});if(f==="refused"||f==="declined"){this.recordNotRemoved(e,r,"stopped",{guard:f}),f==="refused"?this.refuse(e,`Operation blocked by Production Guard: ${p.blockedReason??p.impactSummary}`,Dt.blocked):this.refuse(e,"Operation cancelled by user (confirmation declined).",Dt.declined,!0);return}if(o?.signal.aborted){this.recordNotRemoved(e,r,"stopped",{guard:f,code:ht});let S={runId:r.runId,status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(A(this.deps,e,"seed:remove:response",{result:S,operationId:e.id}));return}let g=e.id,h=`Removing ${c} record(s) a Seed run created`,m=new AbortController,y=()=>{},v=new Promise((S,C)=>{y=R=>R===void 0?S():C(R)});v.catch(()=>{}),Ge(this.deps,g,"seed",h),this.registry?.register(g,"seed",h,v,m),this.liveTracker?.register(g,"seed",h,c);let b,k;try{let S=await B(u,this.deps.orgRegistry,this.deps.orgManager);k=n.sweep?await this.sweepOfRemoval({conn:S,run:r,includeChanged:i,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,signal:m.signal,guard:l,operationId:g}):void 0;let C=k;await C?.ask();let R=Wt(S,"seed:remove"),w=await Vo(R,r.created),P;if(n.muteAutomation===!0){let N=this.removalStepsOf(r,a,w,C?.takes??[]),z=N.delete??[],oe=this.targetAutomation,re=await new pe(hf).withTimeout("seed:remove automation",()=>oe.read(r.targetOrgId,z)).catch(q=>({unread:I(q)}));P=await Et(async()=>_t(S),re,{...this.muteLeases,writes:zr(N)})}let O,E=P?.muted,$=async()=>{let N=P?.prepared;!N||m.signal.aborted||(O=await N.acquire(g),E=O.outcome)},{result:H,notes:J,emptied:W}=await Da({run:r,org:R,includeChanged:i,...a?{again:a}:{},store:t,...C?{sweep:N=>C.first(N),afterRemoval:N=>C.afterRemoval(N),automationMade:C.automationMade}:{},...r.runUserId?{runUserId:r.runUserId}:{},onUndeletable:Gr(this.deps,u,"seed:remove"),beforeFirstWrite:$,signal:m.signal,onProgress:(N,z,oe)=>{let re=Math.min(100,Math.round(N/Math.max(z,1)*100));_e(this.deps,g,re,N,z,oe),m.signal.aborted||this.registry?.updateProgress(g,re),this.liveTracker?.updateProgress(g,re,N,z,oe)}}).then(async N=>({...N,emptied:N.result.status==="cancelled"?{}:await w.take(N.duplicateSets)})).finally(async()=>{O&&(E=await O.release())}),Z=await k?.settle();for(let N of[...J,...W.note?[W.note]:[]])this.deps.log(`[WARN] seed:remove ${g}: ${N}`);let _={runId:H.runId,status:No(Xo(H.status,W),Z),includeChanged:H.includeChanged,objects:W.object?[...H.objects,W.object]:H.objects,finishedAt:H.finishedAt,...H.leftBy?{leftBy:H.leftBy}:{},...Z?{sweep:Z}:{},...E?{mutedAutomation:E}:{}};Y(this.deps,{action:"cleanup_delete",module:"seed",operationId:g,orgId:u,outcome:jo({status:Xo(H.status,W)}),guard:f,objects:In(_.objects),..._.leftBy?{leftBy:_.leftBy}:{},...E?{muted:ft(E)}:{},details:{runId:r.runId}});let Q=A(this.deps,e,"seed:remove:response",{result:_,operationId:g});this.deps.broker.postToWebview(Q),this.deps.log(`[TX] ${Q.type} id=${Q.id} status=${_.status}`),_.status==="cancelled"||_.sweep?.status==="cancelled"?(me(this.deps,g,{aborted:!0}),this.liveTracker?.cancel(g)):(me(this.deps,g,{status:_.status}),_.status==="failure"?(b=new Error("Nothing this run created could be removed."),this.liveTracker?.fail(g,"Nothing this run created could be removed.")):_.status==="partial"?this.liveTracker?.partial(g):this.liveTracker?.complete(g))}catch(S){b=S,await k?.settle().catch(()=>{});let C=jt(S)?S:void 0;this.recordNotRemoved(e,r,C?"stopped":"failure",{guard:f,...C?{code:C.code}:{}}),T(this.deps,"seed:remove","seed:remove:error",e,S,{code:C?.code??"REMOVE_ERROR",retryable:!0}),me(this.deps,g,{status:"failure"}),this.liveTracker?.fail(g,I(S))}finally{y(b)}}};var hc="sync:history:all",SI="syncHistory";var mc=class{constructor(e){this.configStore=e}configStore;save(e){let t=this.loadAll(),r=t.findIndex(o=>o.id===e.id);r>=0?t[r]=e:t.push(e);let n=t.length>500?t.sort((o,i)=>o.startTime.localeCompare(i.startTime)).slice(t.length-500):t;this.configStore.set(hc,n,SI)}load(e){return this.loadAll().find(t=>t.id===e)}list(){return this.loadAll().sort((e,t)=>t.startTime.localeCompare(e.startTime))}delete(e){let t=this.loadAll(),r=t.filter(n=>n.id!==e);return r.length===t.length?!1:(this.configStore.set(hc,r,SI),!0)}exportAsJson(e){let t=this.getFilteredEntries(e);return JSON.stringify(t,null,2)}exportAsCsv(e){let t=this.getFilteredEntries(e),r="id,configName,status,totalProcessed,totalSuccess,totalFailed,totalSkipped,startTime,endTime,duration,triggeredBy",n=t.map(o=>{let i=this.csvEscape(o.configSnapshot.name);return[o.id,i,o.result.status,o.result.totalProcessed,o.result.totalSuccess,o.result.totalFailed,o.result.totalSkipped,o.startTime,o.endTime,o.result.duration,o.triggeredBy].join(",")});return[r,...n].join(`
17
+ `)}clear(){this.configStore.delete(hc)}loadAll(){let e=this.configStore.get(hc);return Array.isArray(e)?e:[]}getFilteredEntries(e){let t=this.list();if(!e||e.length===0)return t;let r=new Set(e);return t.filter(n=>r.has(n.id))}csvEscape(e){return e.includes(",")?`"${e}"`:e}};var wD=/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+:/;function bD(s){if(s.errors.length<=50)return s;let e=s.errors.slice(0,50),t=0;for(let r of s.errors.slice(50))wD.test(r)||e.includes(r)?t++:e.push(r);return t===0?{...s,errors:e}:{...s,errors:e,refusalsDropped:(s.refusalsDropped??0)+t}}var yc=class{constructor(e,t=()=>crypto.randomUUID()){this.historyStore=e;this.generateId=t}historyStore;generateId;logExecution(e,t,r,n){let i=new Date(t.timestamp).getTime()-t.duration,a={id:this.generateId(),configSnapshot:structuredClone(e),result:{...t,objectResults:t.objectResults.map(bD)},startTime:new Date(i).toISOString(),endTime:t.timestamp,triggeredBy:r,...n?{scheduleId:n}:{}};return this.historyStore.save(a),a}getHistory(){return this.historyStore.list()}getEntry(e){return this.historyStore.load(e)}exportHistory(e,t){return e==="csv"?this.historyStore.exportAsCsv(t):this.historyStore.exportAsJson(t)}};var RD={Report:"ReportFolder",Dashboard:"DashboardFolder",EmailTemplate:"EmailTemplateFolder"},vD=new Set(["compare:execute","compare:permissions","compare:snapshots","compare:drift","compare:validate-deployment","compare:deploy"]),SD=5;function kD(s){let e=new Map;for(let t of s.components){let r=e.get(t.componentType)??{objectApiName:t.componentType,created:0,updated:0,deleted:0,failed:0};if(t.outcome==="created")r.created+=1;else if(t.outcome==="changed")r.updated+=1;else if(t.outcome==="failed")r.failed+=1;else continue;e.set(t.componentType,r)}return[...e.values()]}var wc=class{constructor(e,t={}){this.deps=e;this.options=t}deps;options;validations=new Map;async handle(e){if(!vD.has(e.type))return!1;switch(e.type){case"compare:execute":return await this.handleCompareStart(e),!0;case"compare:permissions":return await this.handlePermissions(e),!0;case"compare:snapshots":return await this.handleSnapshots(e),!0;case"compare:drift":return await this.handleDrift(e),!0;case"compare:validate-deployment":return await this.handleValidateDeployment(e),!0;case"compare:deploy":return await this.handleDeploy(e),!0;default:return!1}}async handleValidateDeployment(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Ny,e,"compare:error",this.deps);if(!t)return;let r=t.testLevel==="RunSpecifiedTests"?t.runTests??[]:[];try{if(!await this.passGuard(e,t.targetOrgId,t.components,!0))return;let n=await B(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=await import("./chunk-XJE3LJHP.mjs"),a=this.options.waiting??i.DEFAULT_WAITING,d=this.progressTo(e),c=await i.retrieveComponents(i.metadataApiOf(n),n.version,t.components,{waiting:a,onProgress:d});if(c.managed.length>0){T(this.deps,"compare:validate-deployment","compare:error",e,new Error("A managed package installed "+c.managed.map(p=>`${p.componentType} ${p.fullName}`).join(", ")+" in the source, and it owns them: untick them and validate again. Nothing was sent to the target."),{code:"MANAGED",extraPayload:{managed:c.managed.map(p=>({componentType:p.componentType,fullName:p.fullName}))}});return}let u=c.retrieved.length>0?await i.deployPackage(i.metadataApiOf(o),c.zipFile,i.deployOptions(!0,t.testLevel,r),{waiting:a,onProgress:d}):void 0,l=i.deploymentReport(u,c,{sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,checkOnly:!0,testLevel:t.testLevel,runTests:r});l.success&&l.deployId&&this.keepValidation(l.deployId,{sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,zipFile:c.zipFile,components:c.retrieved,testLevel:t.testLevel,runTests:r}),this.post(A(this.deps,e,"compare:validate-deployment:response",{report:l}),l)}catch(n){T(this.deps,"compare:validate-deployment","compare:error",e,n,{code:await this.deployErrorCode(n)})}}async handleDeploy(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(jy,e,"compare:error",this.deps);if(!t)return;let r=this.validations.get(t.validationId);if(!r){T(this.deps,"compare:deploy","compare:error",e,new Error(`No successful validation ${t.validationId} is waiting in this window: validate the deployment, then deploy it. Nothing was deployed.`),{code:"NOT_VALIDATED"});return}if(r.targetOrgId!==t.targetOrgId){T(this.deps,"compare:deploy","compare:error",e,new Error(`Validation ${t.validationId} was run in another org than the one named. Nothing was deployed.`),{code:"TARGET_MISMATCH"});return}let n;try{if(n=await this.passGuard(e,r.targetOrgId,r.components,!1),!n)return;this.validations.delete(t.validationId);let o=await B(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=await import("./chunk-XJE3LJHP.mjs"),a=await i.deployPackage(i.metadataApiOf(o),r.zipFile,i.deployOptions(!1,r.testLevel,r.runTests),{waiting:this.options.waiting??i.DEFAULT_WAITING,onProgress:this.progressTo(e),...this.deps.infraServices?.deploymentsLetGo?{letGo:this.deps.infraServices.deploymentsLetGo}:{}}),d=i.deploymentReport(a,{missing:[],problems:[]},{sourceOrgId:r.sourceOrgId,targetOrgId:r.targetOrgId,checkOnly:!1,testLevel:r.testLevel,runTests:r.runTests});Y(this.deps,{action:"metadata_deploy",module:"compare",operationId:e.id,orgId:r.targetOrgId,outcome:d.success?"success":"failure",guard:n,objects:kD(d),source:{origin:"org",orgId:r.sourceOrgId}}),this.post(A(this.deps,e,"compare:deploy:response",{report:d}),d)}catch(o){let i=await this.endOfFollowing(o);if(n&&Y(this.deps,{action:"metadata_deploy",module:"compare",operationId:e.id,orgId:r.targetOrgId,guard:n,...i,source:{origin:"org",orgId:r.sourceOrgId}}),i.outcome==="unsettled"){this.answerLeftRunning(e,o,i.details?.deployId);return}T(this.deps,"compare:deploy","compare:error",e,o,{code:await this.deployErrorCode(o)})}}answerLeftRunning(e,t,r){let n=t instanceof Error?t.message:String(t);this.deps.log(`[INFO] compare:deploy: left running \u2014 ${n}`),this.deps.broker.postToWebview(A(this.deps,e,"compare:error",{message:n,code:"STILL_RUNNING",retryable:!1,leftRunning:!0,...typeof r=="string"?{deployId:r}:{}})),this.deps.log(`[TX] compare:error id=${e.id} left running`)}async endOfFollowing(e){let{DeploymentLetGo:t,DeploymentStillRunning:r}=await import("./chunk-XJE3LJHP.mjs");return e instanceof t?e.sent?{outcome:"unsettled",details:e.deployId!==void 0?{deployId:e.deployId}:{}}:{outcome:"stopped",code:ht}:e instanceof r&&e.kind==="deployment"?{outcome:"unsettled",details:{deployId:e.asyncId}}:{outcome:"failure"}}async passGuard(e,t,r,n){let o=this.deps.infraServices?.productionGuard??new xb,i=this.deps.orgManager.getOrg(t),a={orgId:t,orgTier:Pe(i),operation:"deploy",objectName:[...new Set(r.map(u=>u.componentType))].join(", "),recordCount:r.length,module:"compare"};if(n){let u=o.check(a);if(u.allowed)return"allowed";this.refuse(e,u.blockedReason??u.impactSummary);return}let{check:d,decision:c}=await et(o,a);if((c==="refused"||c==="declined")&&Y(this.deps,{action:"metadata_deploy",module:"compare",operationId:e.id,orgId:t,outcome:"stopped",guard:c}),c==="refused"){this.refuse(e,d.blockedReason??d.impactSummary);return}if(c==="declined"){T(this.deps,e.type,"compare:error",e,new Error("Operation cancelled by user (deployment confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}return c}refuse(e,t){T(this.deps,e.type,"compare:error",e,new Error(`Operation blocked by Production Guard: ${t}`),{code:"GUARD_BLOCKED"})}keepValidation(e,t){for(this.validations.set(e,t);this.validations.size>SD;){let r=this.validations.keys().next().value;if(r===void 0)break;this.validations.delete(r)}}progressTo(e){return t=>_e(this.deps,e.id,t.total>0?Math.round(t.done/t.total*100):0,t.done,t.total,t.step,t.deployId!==void 0?{deployId:t.deployId}:void 0)}post(e,t){this.deps.broker.postToWebview(e),this.deps.log(`[TX] ${e.type} id=${e.id} deploy=${t.deployId??"-"} status=${t.status}`)}async deployErrorCode(e){let{DeploymentLetGo:t,DeploymentStillRunning:r}=await import("./chunk-XJE3LJHP.mjs");return e instanceof t?e.sent?"STILL_RUNNING":ht:e instanceof r?"STILL_RUNNING":"DEPLOY_ERROR"}async handleCompareStart(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Bs,e,"compare:error",this.deps);if(!t)return;let r=t;try{let n=await this.compareOrgs(r),o=A(this.deps,e,"compare:execute:response",n);this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(n){T(this.deps,"compare:execute","compare:error",e,n)}}async compareOrgs(e,t){t?.throwIfAborted();let r=await B(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager);t?.throwIfAborted();let n=await B(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),{DiffEngine:o}=await import("./chunk-7F54PZUS.mjs"),{MetadataCompare:i}=await import("./chunk-6ROL3KBM.mjs"),{createContentReader:a}=await import("./chunk-HXS7ORUF.mjs"),d=new o,c=async(g,h)=>{let m=g===e.sourceOrgId?r:n,y=new Map,v=async S=>{t?.throwIfAborted();let C=await m.metadata.list(S);return $e(m.limitInfo,`compare:metadata list ${String(h)}`),Array.isArray(C)?C:[]},b=RD[h],k=b?(await v([{type:b}])).map(S=>({type:h,folder:S.fullName})):[{type:h}];for(let S=0;S<k.length;S+=3)for(let C of await v(k.slice(S,S+3)))y.set(C.fullName,JSON.stringify(C));return y},u=a(g=>g===e.sourceOrgId?r:n,t),l=new i(c,d,u,{budget:km(e.readBudget)});if(!this.deps.services)throw new Error("CompareHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let p=this.deps.services.compareOrchestrator({metadataCompare:l,diffEngine:d,services:this.deps.services}),f={id:crypto.randomUUID(),name:"compare-from-ui",sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,mode:"metadata",componentTypes:e.types,includeManaged:e.includeManaged??!0,createdAt:new Date().toISOString()};return p.execute(f,t)}async handlePermissions(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Sa,e,"compare:error",this.deps);if(!t)return;let r=t;try{let n=await B(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await B(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=async(h,m)=>{let y=await Ft(h,"SELECT Id, Name, Label, IsOwnedByProfile FROM PermissionSet WHERE IsOwnedByProfile = false");$e(h.limitInfo,`compare:permissions ${m}`);let v=await Ft(h,"SELECT Id, Name FROM Profile");return $e(h.limitInfo,`compare:permissions profiles ${m}`),{permSets:y,profiles:v}},[a,d]=await Promise.all([i(n,"source"),i(o,"target")]),c=new Set(a.permSets.map(h=>h.Name)),u=new Set(d.permSets.map(h=>h.Name)),l=new Set(a.profiles.map(h=>h.Name)),p=new Set(d.profiles.map(h=>h.Name)),f={permissionSets:{sourceOnly:a.permSets.filter(h=>!u.has(h.Name)).map(h=>({name:h.Name,label:h.Label})),targetOnly:d.permSets.filter(h=>!c.has(h.Name)).map(h=>({name:h.Name,label:h.Label})),shared:a.permSets.filter(h=>u.has(h.Name)).map(h=>({name:h.Name,label:h.Label}))},profiles:{sourceOnly:a.profiles.filter(h=>!p.has(h.Name)).map(h=>({name:h.Name})),targetOnly:d.profiles.filter(h=>!l.has(h.Name)).map(h=>({name:h.Name})),shared:a.profiles.filter(h=>p.has(h.Name)).map(h=>({name:h.Name}))}},g=A(this.deps,e,"compare:permissions:response",{permissions:f});this.deps.broker.postToWebview(g),this.deps.log(`[TX] ${g.type} id=${g.id}`)}catch(n){T(this.deps,"compare:permissions","compare:error",e,n)}}async handleSnapshots(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Sa,e,"compare:error",this.deps);if(!t)return;let r=t;try{let n=await B(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await B(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=async(f,g)=>{let h=await f.describeGlobal();$e(f.limitInfo,`compare:snapshots describeGlobal ${g}`);let m=h.sobjects.map(y=>({name:y.name,custom:y.custom,label:y.label,queryable:y.queryable}));return{totalObjects:m.length,customObjects:m.filter(y=>y.custom).length,standardObjects:m.filter(y=>!y.custom).length,queryableObjects:m.filter(y=>y.queryable).length,objects:m}},[a,d]=await Promise.all([i(n,"source"),i(o,"target")]),c=new Set(a.objects.map(f=>f.name)),u=new Set(d.objects.map(f=>f.name)),l={source:{orgId:r.sourceOrgId,totalObjects:a.totalObjects,customObjects:a.customObjects,standardObjects:a.standardObjects,queryableObjects:a.queryableObjects},target:{orgId:r.targetOrgId,totalObjects:d.totalObjects,customObjects:d.customObjects,standardObjects:d.standardObjects,queryableObjects:d.queryableObjects},diff:{sourceOnly:a.objects.filter(f=>!u.has(f.name)).map(f=>f.name),targetOnly:d.objects.filter(f=>!c.has(f.name)).map(f=>f.name),sharedCount:a.objects.filter(f=>u.has(f.name)).length},capturedAt:new Date().toISOString()},p=A(this.deps,e,"compare:snapshots:response",{snapshot:l});this.deps.broker.postToWebview(p),this.deps.log(`[TX] ${p.type} id=${p.id}`)}catch(n){T(this.deps,"compare:snapshots","compare:error",e,n)}}async handleDrift(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Sa,e,"compare:error",this.deps);if(!t)return;let r=t;try{let n=await B(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await B(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=async(f,g)=>{let h={},m=await Ft(f,"SELECT Name, LanguageLocaleKey, DefaultLocaleSidKey, TimeZoneSidKey, FiscalYearStartMonth FROM Organization LIMIT 1");if($e(f.limitInfo,`compare:drift companyInfo ${g}`),m[0])for(let[y,v]of Object.entries(m[0]))y!=="attributes"&&y!=="Id"&&(h[`Organization.${y}`]=String(v));return h},[a,d]=await Promise.all([i(n,"source"),i(o,"target")]),c=new Set([...Object.keys(a),...Object.keys(d)]),u=[];for(let f of c){let g=a[f],h=d[f];g===void 0?u.push({setting:f,sourceValue:"",targetValue:h??"",status:"missing_source"}):h===void 0?u.push({setting:f,sourceValue:g,targetValue:"",status:"missing_target"}):g!==h?u.push({setting:f,sourceValue:g,targetValue:h,status:"drift"}):u.push({setting:f,sourceValue:g,targetValue:h,status:"match"})}let l={items:u,totalChecked:u.length,driftCount:u.filter(f=>f.status==="drift").length,matchCount:u.filter(f=>f.status==="match").length,missingCount:u.filter(f=>f.status==="missing_source"||f.status==="missing_target").length,detectedAt:new Date().toISOString()},p=A(this.deps,e,"compare:drift:response",{drift:l});this.deps.broker.postToWebview(p),this.deps.log(`[TX] ${p.type} id=${p.id}`)}catch(n){T(this.deps,"compare:drift","compare:error",e,n)}}};import{randomBytes as LD}from"node:crypto";function kI(s,e,t){return s==="delete"?{...bt(e),deleted:t.done,failed:t.failed}:{...bt(e),updated:t.done,failed:t.failed}}async function bc(s,e,t){let r=crypto.randomUUID(),n=s.infraServices?.productionGuard;if(!n)return Y(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,outcome:"stopped",code:ve.code}),{ran:!1,operationId:r,code:ve.code,message:ve.message};let o=s.orgManager.getOrg(e.orgId),{check:i,decision:a}=await et(n,{orgId:e.orgId,orgTier:Pe(o),operation:e.operation,objectName:e.objectNames.join(", "),recordCount:e.recordCount,module:"dataops"}),d=a;if(a==="refused"||a==="declined")return Y(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,outcome:"stopped",guard:a}),{ran:!1,operationId:r,guard:a,message:a==="refused"?`Operation blocked by Production Guard: ${i.blockedReason??i.impactSummary}`:"Operation cancelled by user (confirmation declined)."};Ge(s,r,"dataops",e.description);let c=new AbortController,u=()=>{},l=new Promise((h,m)=>{u=y=>y===void 0?h():m(y)});l.catch(()=>{}),s.infraServices?.backgroundRegistry?.register(r,"dataops",e.description,l,c);let p=sr(t,r,"dataops",e.description,e.recordCount),f=[],g=0;try{let h=await e.run((v,b)=>{f.push({objectApiName:v,counts:b}),g+=b.done+b.failed;let k=Math.min(100,Math.round(g/Math.max(e.recordCount,1)*100)),S=`${v}: ${b.done} done, ${b.failed} refused`;_e(s,r,k,g,e.recordCount,S),p.progress(k,g,e.recordCount,S)},c.signal);await e.beforeEnd?.();let m=bl(h),y=c.signal.aborted;if(Y(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,...y?m.done+m.failed>0?{outcome:"cancelled"}:{outcome:"stopped",code:ot}:{outcome:m.status},...d?{guard:d}:{},objects:h.map(v=>kI(e.operation,v.objectApiName,v.counts))}),y)return s.infraServices?.backgroundRegistry?.abort(r),me(s,r,{aborted:!0,done:m.done,failed:m.failed}),p.cancel(),u(),{ran:!0,operationId:r,outcome:m,...d?{guard:d}:{},cancelled:!0,error:`Cancelled: ${m.done} record(s) ${e.operation==="delete"?"deleted":"overwritten"} before the cancel; the rest were left as they are.`};if(me(s,r,{status:m.status,done:m.done,failed:m.failed}),m.status==="failure"){let v=`The org refused the ${m.failed} record(s)`;p.fail(v),u(new Error(v))}else m.status==="partial"?p.partial():p.complete(),u();return{ran:!0,operationId:r,outcome:m,...d?{guard:d}:{}}}catch(h){await e.beforeEnd?.();let m=I(h);return Y(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,outcome:"failure",...d?{guard:d}:{},objects:f.map(y=>kI(e.operation,y.objectApiName,y.counts))}),Le(s,r,m,!0,{context:{module:"dataops",operation:e.origin,objectName:e.objectNames.join(", ")}}),p.fail(m),u(h),{ran:!0,operationId:r,outcome:{...bl(f),status:"failure"},...d?{guard:d}:{},error:m}}}async function OD(s,e,t,r,n){let o=t.fields.filter(cm).map(l=>l.name),i=await vn(s,t.name,o,r),a=lm(um(e,t.name,t.fields,i),t.fields,n?.fields),d=gm(t,a),c=new Map(a.flatMap(l=>l.orgClassification?[[l.field.name,l.orgClassification]]:[])),u=pm(t.fields,n?.fields);return{objectApiName:t.name,records:i,erased:d.fields,plan:{objectApiName:t.name,label:t.label,records:i.length,fields:d.fields.map(l=>{let p=c.get(l.field.name);return{fieldApiName:l.field.name,label:l.field.label,method:l.method,...p?{orgClassification:p}:{}}}),kept:d.kept.map(l=>({fieldApiName:l.name,label:l.label})),...n?.refused!==void 0?{classificationError:n.refused}:{},...u.length>0?{hiddenClassified:u}:{}}}}async function OI(s,e,t,r,n){let o=[],i,a=t==="anonymize"&&n?await pa(n,r.map(d=>d.objectApiName)):void 0;for(let d of r){let c=Vr.parse(await s.describe(Xe(d.objectApiName))),u=p=>({objectApiName:c.name,plan:{objectApiName:c.name,label:c.label,records:0,refused:p}});if(t==="anonymize"){if(c.updateable!==!0){o.push(u(`The connected user may not edit ${c.label} records: erase them with Delete instead, or have an admin grant Edit on ${c.label} in a permission set.`));continue}let p=a?.definitions?.get(d.objectApiName);o.push({...await OD(s,e,c,d.ids,a?.objects.get(d.objectApiName)),...p?{definitions:p}:{}});continue}if(c.deletable!==!0){o.push(u(`The connected user may not delete ${c.label} records: erase them with Anonymize in place instead, or have an admin grant Delete on ${c.label} in a permission set.`));continue}i??=await ma(s);let l=await ya(s,c,d.ids,i);o.push({objectApiName:c.name,ids:[...d.ids],plan:{objectApiName:c.name,label:c.label,records:d.ids.length,related:l.related,uncounted:l.uncounted}})}return o}function Rc(s){let e=new Map;for(let t of s)t.refused||t.records===0||e.set(t.objectApiName,(e.get(t.objectApiName)??0)+t.records);return[...e].map(([t,r])=>({objectApiName:t,records:r}))}function ID(s,e){return e.map(t=>({objectApiName:s,fieldApiName:t.field.name,method:t.method,config:{}}))}async function II(s,e,t,r,n){let o=[];for(let i of t){if(n?.aborted)break;if(i.plan.refused)continue;let a;if(i.ids)a=await wa(s,i.objectApiName,i.ids,n);else{let d=i.erased??[],c=i.records??[];if(d.length===0||c.length===0)continue;let u=e.anonymize(c,ID(i.objectApiName,d)),l=[],p=0;c.forEach((f,g)=>{let h={Id:f.Id};for(let m of d)dm(f[m.field.name])&&(h[m.field.name]=u[g][m.field.name]??null);Object.keys(h).length>1?l.push(h):p++}),a=await mm(s,i.objectApiName,l,n),a.done+=p}o.push({objectApiName:i.objectApiName,counts:a}),r?.(i.objectApiName,a)}return o}var AI="dataops:subject-requests",AD="audit",TD=K({objectApiName:L(),done:Te().int().nonnegative(),failed:Te().int().nonnegative()}),ED=Hi("kind",[K({kind:vt("searched"),at:L(),searchedBy:Re(Be(["email","phone","name"])),objects:Re(K({objectApiName:L(),found:Te().int().nonnegative(),truncated:Ve()}))}),K({kind:vt("exported"),at:L(),records:Te().int().nonnegative()}),K({kind:vt("erased"),at:L(),mode:Be(["anonymize","delete"]),outcome:Be(["success","partial","failure","stopped"]),operationId:L(),objects:Re(TD)})]),PD=K({requestId:L().min(1),orgId:L().min(1),openedAt:L(),events:Re(ED)}),vc=class{constructor(e,t=500){this.configStore=e;this.limit=t}configStore;limit;has(e,t){return this.read().some(r=>r.requestId===e&&r.orgId===t)}record(e,t,r){let n=this.read(),o=n.find(i=>i.requestId===e&&i.orgId===t);o||(o={requestId:e,orgId:t,openedAt:r.at,events:[]},n.push(o)),o.events.push(r),this.write(n)}list(){return this.read().reverse()}read(){let e=this.configStore.get(AI);return Array.isArray(e)?e.flatMap(t=>{let r=PD.safeParse(t);return r.success?[r.data]:[]}):[]}write(e){this.configStore.set(AI,e.slice(-this.limit),AD)}};function $D(s){return tl(s).slice(-8)}function xD(s){return`%${s.split("").join("%")}%`}function TI(s,e){return typeof s=="string"&&s.trim().toLowerCase()===e.trim().toLowerCase()}function DD(s,e,t){let r=Xe(s.name);if(e==="email"&&t.email){let n=t.email.trim();return{field:s,kind:e,soql:`${r} = '${tr(n)}'`,matches:o=>TI(o,n)}}if(e==="phone"&&t.phone){let n=$D(t.phone);return{field:s,kind:e,soql:`${r} LIKE '${xD(n)}'`,matches:o=>typeof o=="string"&&tl(o).includes(n)}}if(e==="name"&&t.name){let n=t.name.trim();return{field:s,kind:e,soql:`${r} = '${tr(n)}'`,matches:o=>TI(o,n)}}}async function ND(s,e,t){try{let r=Vr.parse(await s.describe(Xe(e))),n=Xe(r.name);if(r.queryable===!1)throw new Error(`${n} cannot be queried.`);let o=fm(r).flatMap(({field:f,kind:g})=>{let h=DD(f,g,t.identifiers);return h?[h]:[]});if(o.length===0)return{status:"skipped",objectApiName:e,label:r.label};let i=o.map(f=>({fieldApiName:f.field.name,label:f.field.label,kind:f.kind})),a=o.map(f=>f.soql).join(" OR "),d=(await s.query(`SELECT COUNT() FROM ${n} WHERE ${a}`)).totalSize;if(d===0)return{status:"searched",objectApiName:e,label:r.label,counted:d,records:[],truncated:!1,searched:i};let c=r.fields.find(f=>f.nameField===!0),u=[...new Set(["Id",...c?[c.name]:[],...o.map(f=>f.field.name)])].map(Xe),l=await s.query(`SELECT ${u.join(", ")} FROM ${n} WHERE ${a} ORDER BY Id LIMIT ${t.limit}`),p=[];for(let f of l.records){if(typeof f!="object"||f===null)continue;let g=f;if(!Xr(g.Id))continue;let h=[...new Set(o.filter(y=>y.matches(g[y.field.name])).map(y=>y.field.name))];if(h.length===0)continue;let m=c?g[c.name]:null;p.push({id:g.Id,name:typeof m=="string"?m:null,matchedBy:h})}return{status:"searched",objectApiName:e,label:r.label,counted:d,records:p,truncated:d>t.limit,searched:i}}catch(r){return{status:"failed",objectApiName:e,message:jD(I(r),t.identifiers)}}}function jD(s,e){let t=s;for(let r of[e.email,e.name,e.phone]){let n=r?.trim();n&&(t=t.replace(new RegExp(n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"gi"),"\u2026"))}return t}async function EI(s,e){let t=[];for(let r of e.objects)t.push(await ND(s,r,e));return t}function PI(s){return s.flatMap(e=>{if(e.plan.refused||e.ids||!e.erased||!e.records)return[];let t=e.erased.map(n=>n.field.name),r=e.records.flatMap(n=>typeof n.Id=="string"?[n.Id]:[]);return t.length===0||r.length===0?[]:[{objectApiName:e.objectApiName,fields:t,records:{ids:r}}]})}function CI(s){return new Map(s.flatMap(e=>e.definitions?[[e.objectApiName,e.definitions]]:[]))}function MD(s){return typeof s=="object"&&s!==null&&"success"in s&&s.success===!0}function $I(s,e){return{...s,update:async(t,r)=>{let n=await s.update(t,r),o=Array.isArray(n)?n:[n];return e.add(t,o.flatMap((i,a)=>{let d=r[a]?.Id;return MD(i)&&typeof d=="string"?[d]:[]})),n}}}var FD=6e4,_D=new Set(["dataops:pii-inventory","dataops:dsr:search","dataops:dsr:export","dataops:dsr:erase","dataops:dsr:log"]),UD=20;function HD(s){let e="payload"in s?s.payload:void 0;return typeof e=="object"&&e!==null&&"dryRun"in e?e.dryRun===!0:!1}function BD(s){return typeof s=="object"&&s!==null&&"success"in s&&s.success===!0}function qD(s,e){return{...s,update:async(t,r)=>{e.beforeWrite(t);try{let n=await s.update(t,r),o=Array.isArray(n)?n:[n];return e.wrote(t,o.flatMap((i,a)=>BD(i)?[r[a]?.Id]:[])),n}catch(n){throw Nb(n)==="may-have-written"&&e.wrote(t,r.map(o=>o.Id)),n}}}}function WD(s){return["email","name","phone"].filter(e=>s[e]!==void 0)}var Sc=class{constructor(e,t){this.deps=e;this.saveDialog=t??new An}deps;found=new Map;maskingKey=LD(32).toString("hex");saveDialog;writing=new jb;liveTracker;setLiveOperationTracker(e){this.liveTracker=e}targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;muteLeases={};setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}duplicatesSettleMs=_b;setDuplicatesSettle(e){this.duplicatesSettleMs=e}ownReader(){return this.reader??=import("./chunk-UK3QLBHW.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}isWritingTo(e){return this.writing.has(e)}get requestLog(){return new vc(this.deps.configStore)}get detector(){return this.deps.infraServices?.piiDetector??new ga}async session(e,t){return(await this.reads(e,t)).session}async reads(e,t){let r=await B(e,this.deps.orgRegistry,this.deps.orgManager);return{session:ha(r,t),tooling:fa(r)}}async handle(e){if(!_D.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"dataops:pii-inventory":return await this.handleInventory(e),!0;case"dataops:dsr:search":return await this.handleSearch(e),!0;case"dataops:dsr:export":return await this.handleExport(e),!0;case"dataops:dsr:erase":return await this.writing.during(HD(e)?void 0:Mb(e,"orgId"),()=>this.handleErase(e)),!0;default:return this.handleLog(e),!0}}async handleInventory(e){let t=x(vy,e,"dataops:error",this.deps);if(t)try{let{session:r,tooling:n}=await this.reads(t.orgId,"dataops:pii-inventory"),o=await hm(r,this.detector,t,void 0,n),i=A(this.deps,e,"dataops:pii-inventory:response",{...o});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} objects=${o.objects.length} classification requests=${o.classificationRequests??0}`)}catch(r){T(this.deps,"dataops:pii-inventory","dataops:error",e,r)}}async handleSearch(e){let t=x(Sy,e,"dataops:error",this.deps);if(!t)return;let{orgId:r,objects:n}=t,o={...t.email!==void 0?{email:t.email}:{},...t.name!==void 0?{name:t.name}:{},...t.phone!==void 0?{phone:t.phone}:{}};try{let i=await this.session(r,"dataops:dsr:search"),a=await EI(i,{objects:n,identifiers:o,limit:200}),d=this.requestLog,c=t.requestId!==void 0&&d.has(t.requestId,r)?t.requestId:crypto.randomUUID(),u=new Date().toISOString(),l={orgId:r,objects:new Map};for(let h of a)h.status==="searched"&&l.objects.set(h.objectApiName,new Set(h.records.map(m=>m.id)));this.hold(c,l),d.record(c,r,{kind:"searched",at:u,searchedBy:WD(o),objects:a.flatMap(h=>h.status==="searched"?[{objectApiName:h.objectApiName,found:h.records.length,truncated:h.truncated}]:[])});let p={requestId:c,orgId:r,searchedAt:u,limit:200,objects:a},f=A(this.deps,e,"dataops:dsr:search:response",{...p});this.deps.broker.postToWebview(f);let g=[...l.objects.values()].reduce((h,m)=>h+m.size,0);this.deps.log(`[TX] ${f.type} id=${f.id} records=${g}`)}catch(i){T(this.deps,"dataops:dsr:search","dataops:error",e,i)}}hold(e,t){for(this.found.delete(e),this.found.set(e,t);this.found.size>UD;){let r=this.found.keys().next().value;if(r===void 0)break;this.found.delete(r)}}heldFor(e,t){let r=this.found.get(e);if(!r||r.orgId!==t)throw new Error("This request has found nothing in this window. Search again: an export or an erasure only acts on the records a search found.");return r}async handleExport(e){let t=x(ky,e,"dataops:error",this.deps);if(t)try{let r=this.heldFor(t.requestId,t.orgId),n=await this.session(t.orgId,"dataops:dsr:export"),o={},i=0;for(let[l,p]of r.objects){if(p.size===0)continue;let f=Vr.parse(await n.describe(l)),g=await vn(n,f.name,f.fields.map(h=>h.name),[...p]);o[l]=g,i+=g.length}let a=new Date().toISOString(),d={sandforgeSubjectRequestVersion:1,requestId:t.requestId,orgId:t.orgId,exportedAt:a,objects:o},c=await this.saveDialog.save(`sandforge-subject-request-${t.requestId.slice(0,8)}.json`,JSON.stringify(d,null,2),["json"]);c.status==="saved"&&this.requestLog.record(t.requestId,t.orgId,{kind:"exported",at:a,records:i});let u=A(this.deps,e,"dataops:dsr:export:response",{requestId:t.requestId,records:i,saved:c});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id} ${c.status} records=${i}`)}catch(r){T(this.deps,"dataops:dsr:export","dataops:error",e,r)}}async handleErase(e){let t=x(Iy,e,"dataops:error",this.deps);if(!t)return;let{orgId:r,requestId:n,mode:o,dryRun:i}=t;try{let a=this.heldFor(n,r),d=t.records.reduce((F,ne)=>{let ke=a.objects.get(ne.objectApiName);return F+ne.ids.filter(de=>!ke?.has(de)).length},0);if(d>0)throw new Error(`${d} of the records to erase were not found by this request. Search again, and erase from what the search lists.`);let{session:c,tooling:u}=await this.reads(r,"dataops:dsr:erase"),l=await OI(c,this.detector,o,t.records,u),p=l.map(F=>F.plan),f=Rc(p),g=o==="anonymize"&&(i||t.purgeHistory===!0)?await this.erasureHistory(r,l,i):[];if(i){let F=A(this.deps,e,"dataops:dsr:erase:response",{requestId:n,mode:o,dryRun:i,plan:p,written:f,...g.length>0?{history:g.map(({parentField:ne,names:ke,...de})=>de)}:{}});this.deps.broker.postToWebview(F),this.deps.log(`[TX] ${F.type} id=${F.id} plan objects=${p.length}`);return}let h=p.filter(F=>!F.refused&&F.records>0),m=h.reduce((F,ne)=>F+ne.records,0);if(m===0){let F=p.flatMap(ne=>ne.refused?[ne.refused]:[]);throw new Error(F.length>0?`Nothing can be erased. ${F.join(" ")}`:"Nothing is left to erase: the records found are no longer in the org.")}let y=tb(g);if(y.length>0){let F=crypto.randomUUID();Y(this.deps,{action:"subject_erase",module:"dataops",operationId:F,orgId:r,outcome:"stopped",code:Pl}),this.requestLog.record(n,r,{kind:"erased",at:new Date().toISOString(),mode:o,outcome:"stopped",operationId:F,objects:[]}),T(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(rb(y)),{code:Pl});return}let v=we(this.deps.orgManager.getOrg(r),r),b=await B(r,this.deps.orgRegistry,this.deps.orgManager),k=this.targetAutomation,S=await Qr({act:o==="delete"?"cleanup":"masking",target:v,objects:f,org:Fo(b,F=>new pe(FD).withTimeout("dataops automation",()=>k.read(r,F)),Pe(this.deps.orgManager.getOrg(r))==="production"),accord:t,mayMute:!0,muteLeases:this.muteLeases,voice:"erasure"}),C=Tn(S.answer),R=C?{refused:C}:await io(S,e.id,t.acceptEmails===!0,"erasure");if("refused"in R){let F=crypto.randomUUID();Y(this.deps,{action:"subject_erase",module:"dataops",operationId:F,orgId:r,outcome:"stopped",code:R.refused.code}),this.requestLog.record(n,r,{kind:"erased",at:new Date().toISOString(),mode:o,outcome:"stopped",operationId:F,objects:[]}),T(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(R.refused.message),{code:R.refused.code,...C?La(C):{}});return}let w=R.held,P={},O=async()=>{if(!(!w||P.back)){P.back=await w.release();for(let F of Qt(P.back,v))this.deps.log(`[INFO] ${F}`)}},E=o==="anonymize"?Hb({query:async F=>b.query(F),serverTime:async()=>(await b.soap.getServerTimestamp()).timestamp},Ub(S.answer.automation,f.map(F=>F.objectApiName)),{settleMs:this.duplicatesSettleMs}):void 0,$={},H=async()=>{await O(),!$.read&&($.read=!0,$.duplicates=await E?.read())},J=()=>qb($.duplicates,v,"erasure"),W=()=>w?{mutedAutomation:P.back??w.outcome}:{},Z=new Yw(void 0,this.maskingKey),_=t.purgeHistory===!0&&o==="anonymize"&&g.length>0?new eb(Cl(b),g.filter(Zg)):void 0,Q=E?qD(c,E):c,N=await bc(this.deps,{orgId:r,operation:o==="delete"?"delete":"update",objectNames:h.map(F=>F.objectApiName),recordCount:m,action:"subject_erase",description:`Erase ${m} record(s) of a subject request`,origin:"dataops:dsr:erase",run:async(F,ne)=>{let ke=await II(_?$I(Q,_):Q,Z,l,F,ne);return await _?.flushAll(()=>ne?.aborted===!0),ke},beforeEnd:H},this.liveTracker).finally(O),z=new Date().toISOString();if(!N.ran){this.requestLog.record(n,r,{kind:"erased",at:z,mode:o,outcome:"stopped",operationId:N.operationId,objects:[]}),T(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(N.message),{...N.code?{code:N.code}:{},extraPayload:W()});return}let oe=p.reduce((F,ne)=>F+(ne.hiddenClassified?.length??0),0);this.requestLog.record(n,r,{kind:"erased",at:z,mode:o,outcome:N.outcome.status,operationId:N.operationId,objects:N.outcome.objects,...oe>0?{classifiedHidden:oe}:{}});let{duplicates:re}=$;if(N.error!==void 0){let F=J();T(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(F?`${N.error} ${F}`:N.error),{...N.cancelled?{code:ot}:{},extraPayload:{...W(),...re?{duplicates:re}:{}}});return}let q=A(this.deps,e,"dataops:dsr:erase:response",{requestId:n,mode:o,dryRun:i,plan:p,outcome:N.outcome,...W(),...re?{duplicates:re}:{},..._?{historyRun:{purge:!0,objects:_.result()}}:{}});this.deps.broker.postToWebview(q),this.deps.log(`[TX] ${q.type} id=${q.id} ${N.outcome.status} done=${N.outcome.done} failed=${N.outcome.failed}`),Bb(re)&&Ae(this.deps,"warning","Erase",J())}catch(a){T(this.deps,"dataops:dsr:erase","dataops:error",e,a)}}async erasureHistory(e,t,r){let n=PI(t);if(n.length===0)return[];try{let o=await B(e,this.deps.orgRegistry,this.deps.orgManager);return await Zw(Cl(o),n,{count:r,definitions:CI(t)})}catch(o){return this.deps.log("[WARN] dataops:dsr:erase: the field history of what it overwrites was not read: "+(o instanceof Error?o.message:String(o))),[]}}handleLog(e){try{let t=this.requestLog.list(),r=A(this.deps,e,"dataops:dsr:log:response",{entries:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} entries=${t.length}`)}catch(t){T(this.deps,"dataops:dsr:log","dataops:error",e,t)}}};var zD=new Set(["User","Group","RecordType","BusinessHours","Profile","UserRole"]);function MI(s){return s.type==="reference"&&yl(s)&&s.nillable===!0&&s.filterable===!0&&s.referenceTo?.length===1&&!zD.has(s.referenceTo[0])}function LI(s,e){return e>0&&s/e>=.9}async function GD(s,e,t){let r,n,o;try{if(r=Vr.parse(await s.describe(Xe(e.objectApiName))),n=Xe(r.name),r.queryable===!1)throw new Error(`${n} cannot be queried.`);o=(await s.query(`SELECT COUNT() FROM ${n}`)).totalSize}catch(f){return{status:"failed",objectApiName:e.objectApiName,message:I(f)}}let i=r.fields.filter(wl).sort((f,g)=>f.label.localeCompare(g.label)),a=r.fields.filter(MI),d=[...a,...r.fields.filter(f=>yl(f)&&!a.includes(f))],[c,u,l]=await Promise.all([om(s,n,d,o),sm(s,n,i,e.duplicateKey,o),am(s,n,r.fields,t,o)]),p=c.fields.filter(f=>a.some(g=>g.name===f.fieldApiName)&&LI(f.filled,o)&&f.filled<o).map(f=>{let g=a.find(h=>h.name===f.fieldApiName);return{fieldApiName:f.fieldApiName,label:f.label,referenceTo:g?.referenceTo?.[0]??"",filled:f.filled,empty:o-f.filled}}).sort((f,g)=>g.empty-f.empty||f.label.localeCompare(g.label));return{status:"scanned",objectApiName:e.objectApiName,label:r.label,totalRecords:o,fields:c.fields,unmeasured:c.unmeasured,stale:l.stale,orphans:p,duplicates:u.duplicates,keyFields:i.map(f=>({fieldApiName:f.name,label:f.label})),errors:[...c.errors,...u.errors,...l.errors],deletable:r.deletable===!0}}async function FI(s,e,t=()=>new Date){if(!Number.isInteger(e.staleDays)||e.staleDays<1)throw new Error(`A staleness threshold is a whole number of days, not ${e.staleDays}.`);let r=t().toISOString(),n=[];for(let o of e.objects)n.push(await GD(s,o,e.staleDays));return{orgId:e.orgId,staleDays:e.staleDays,scannedAt:r,orphanThreshold:.9,bounds:{duplicateGroupLimit:tm,duplicateSample:rm,singleFieldQueries:nm},objects:n}}function JD(s){let e=Date.parse(s.replace(/([+-]\d{2})(\d{2})$/,"$1:$2"));return Number.isNaN(e)?void 0:new Date(e).toISOString().replace(/\.\d{3}Z$/,"Z")}function mf(s,e,t,r){let n=(s?.skip??0)+e;return e>0&&n<t?{skip:n,...r}:void 0}function DI(s){return s.flatMap(e=>{let t=typeof e=="object"&&e!==null?e.Id:void 0;return Xr(t)?[t]:[]})}function VD(s,e){switch(s){case"int":case"long":case"double":case"currency":case"percent":return typeof e=="number"&&Number.isFinite(e)?String(e):void 0;case"boolean":return typeof e=="boolean"?String(e):void 0;case"date":return typeof e=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(e)?e:void 0;case"datetime":case"time":return;default:return typeof e=="string"?`'${tr(e)}'`:void 0}}function XD(s,e){let t=String(e??"");return typeof e=="string"&&s!=="date"?t.toLowerCase():t}var NI=100,KD=2e3;async function YD(s,e,t,r){let n=Xe(e.name),o=Xe(t.name),i=await im(s,n,t.name),a=i.rows.reduce((l,p)=>l+p.count-1,0),d=i.rows.map(l=>VD(t.type,l.value));if(d.some(l=>l===void 0))throw new Error(`Copies of ${e.label} records cannot be picked out by ${t.label}: its values are dates and times, which this cleanup does not compare.`);let c=e.fields.some(l=>l.name==="LastModifiedDate"),u=[];for(let l=0;l<d.length&&u.length<r;l+=NI){let p=d.slice(l,l+NI).join(", "),f=await s.query(`SELECT Id, ${o}${c?", LastModifiedDate":""} FROM ${n} WHERE ${o} IN (${p}) ORDER BY Id LIMIT ${KD}`),g=new Map;for(let h of f.records){if(typeof h!="object"||h===null)continue;let m=h;if(!Xr(m.Id))continue;let y=XD(t.type,m[t.name]),v=g.get(y)??[];v.push({id:m.Id,modified:typeof m.LastModifiedDate=="string"?m.LastModifiedDate:""}),g.set(y,v)}for(let h of g.values()){h.sort((m,y)=>y.modified.localeCompare(m.modified)||y.id.localeCompare(m.id));for(let m of h.slice(1)){if(u.length>=r)break;u.push(m.id)}}}return{total:a,ids:u}}async function yf(s,e,t,r,n){let o=Vr.parse(await s.describe(Xe(e))),i=Xe(o.name),a=f=>o.fields.find(g=>g.name.toLowerCase()===f.toLowerCase());if(t.kind==="stale"){if(!Number.isInteger(t.days)||t.days<1)throw new Error(`A staleness threshold is a whole number of days, not ${t.days}.`);if(!a("LastModifiedDate"))throw new Error(`${o.label} records carry no date of last modification.`);let f=`LastModifiedDate < LAST_N_DAYS:${t.days}`,g=(await s.query(`SELECT COUNT() FROM ${i} WHERE ${f}`)).totalSize,h=n?.modified!==void 0?JD(n.modified):void 0,m=h!==void 0&&n?.id!==void 0&&Xr(n.id)?` AND (LastModifiedDate > ${h} OR (LastModifiedDate = ${h} AND Id > '${n.id}'))`:"",y=await s.query(`SELECT Id, LastModifiedDate FROM ${i} WHERE ${f}${m} ORDER BY LastModifiedDate, Id LIMIT ${r}`),v=DI(y.records),b=y.records.at(-1),k=mf(n,v.length,g,{id:v.at(-1),...typeof b?.LastModifiedDate=="string"?{modified:b.LastModifiedDate}:{}});return{object:o,total:g,ids:v,truncated:(n?.skip??0)+v.length<g,...k?{next:k}:{}}}if(t.kind==="orphans"){let f=a(t.fieldApiName);if(!f||!MI(f))throw new Error(`${t.fieldApiName} is not a lookup of ${o.label} that can leave a record without its parent.`);let g=Xe(f.name),h=(await s.query(`SELECT COUNT() FROM ${i}`)).totalSize,m=(await s.query(`SELECT COUNT() FROM ${i} WHERE ${g} = null`)).totalSize;if(!LI(h-m,h))throw new Error(`${f.label} is filled on fewer than ${Math.round(.9*100)}% of ${o.label} records: the business does not rely on it, and a record without it is no orphan.`);let y=n?.id!==void 0&&Xr(n.id)?` AND Id > '${n.id}'`:"",v=await s.query(`SELECT Id FROM ${i} WHERE ${g} = null${y} ORDER BY Id LIMIT ${r}`),b=DI(v.records),k=mf(n,b.length,m,{id:b.at(-1)});return{object:o,total:m,ids:b,truncated:(n?.skip??0)+b.length<m,...k?{next:k}:{}}}let d=a(t.keyField);if(!d||!wl(d))throw new Error(`${t.keyField} is not a field ${o.label} records can be grouped by.`);let c=n?.skip??0,u=await YD(s,o,d,c+r),l=u.ids.slice(c),p=mf(n,l.length,u.total,{});return{object:o,total:u.total,ids:l,truncated:c+l.length<u.total,...p?{next:p}:{}}}var QD=6e4,ZD=new Set(["dataops:cleanup:scan","dataops:cleanup:export","dataops:cleanup:delete"]);function UI(s){switch(s.kind){case"stale":return`stale-${s.days}d`;case"orphans":return`orphans-${s.fieldApiName}`;default:return`duplicates-${s.keyField}`}}var kc=class{constructor(e,t){this.deps=e;this.saveDialog=t??new An}deps;saveDialog;liveTracker;setLiveOperationTracker(e){this.liveTracker=e}targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;muteLeases={};setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}ownReader(){return this.reader??=import("./chunk-UK3QLBHW.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async session(e,t){let r=await B(e,this.deps.orgRegistry,this.deps.orgManager);return ha(r,t)}async handle(e){if(!ZD.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"dataops:cleanup:scan":return await this.handleScan(e),!0;case"dataops:cleanup:export":return await this.handleExport(e),!0;default:return await this.handleDelete(e),!0}}async handleScan(e){let t=x(Ry,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:cleanup:scan"),n=await FI(r,t),o=A(this.deps,e,"dataops:cleanup:scan:response",{...n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} objects=${n.objects.length}`)}catch(r){T(this.deps,"dataops:cleanup:scan","dataops:error",e,r)}}async handleExport(e){let t=x(Ay,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:cleanup:export"),n=await yf(r,t.objectApiName,t.recommendation,1e3,t.after),o=await vn(r,n.object.name,n.object.fields.map(u=>u.name),n.ids),i=new Date().toISOString(),a={sandforgeCleanupVersion:1,orgId:t.orgId,objectApiName:n.object.name,recommendation:t.recommendation,exportedAt:i,recommended:n.total,records:o},d=await this.saveDialog.save(`sandforge-cleanup-${n.object.name}-${UI(t.recommendation)}.json`,JSON.stringify(a,null,2),["json"]),c=A(this.deps,e,"dataops:cleanup:export:response",{objectApiName:t.objectApiName,records:o.length,truncated:n.truncated,saved:d,exported:(t.after?.skip??0)+o.length,recommended:n.total,...n.next?{next:n.next}:{}});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id} ${d.status} records=${o.length}`)}catch(r){T(this.deps,"dataops:cleanup:export","dataops:error",e,r)}}async handleDelete(e){let t=x(Ty,e,"dataops:error",this.deps);if(!t)return;let{orgId:r,recommendation:n,dryRun:o}=t;try{let i=await this.session(r,"dataops:cleanup:delete"),a=await yf(i,t.objectApiName,n,1e3),{object:d,ids:c}=a;if(d.deletable!==!0)throw new Error(`The connected user may not delete ${d.label} records: Export keeps a copy of them, and an admin grants Delete on ${d.label} in a permission set. Nothing was deleted.`);if(o){let R=await ya(i,d,c,await ma(i)),w={objectApiName:d.name,label:d.label,records:c.length,related:R.related,uncounted:R.uncounted},P=A(this.deps,e,"dataops:cleanup:delete:response",{objectApiName:t.objectApiName,dryRun:o,plan:w,truncated:a.truncated,written:Rc([w])});this.deps.broker.postToWebview(P),this.deps.log(`[TX] ${P.type} id=${P.id} plan records=${c.length}`);return}if(c.length===0)throw new Error(`No ${d.label} record is left to delete for this recommendation.`);let u=await B(r,this.deps.orgRegistry,this.deps.orgManager),l=we(this.deps.orgManager.getOrg(r),r),p=this.targetAutomation,f=Ma(t),g=await Qr({act:"cleanup",target:l,objects:[{objectApiName:d.name,records:c.length}],org:Fo(u,R=>new pe(QD).withTimeout("dataops automation",()=>p.read(r,R)),Pe(this.deps.orgManager.getOrg(r))==="production"),accord:t,mayMute:!0,muteLeases:this.muteLeases,...f?{voice:f}:{}}),h=Tn(g.answer);if(h){T(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(h.message),{code:h.code,...La(h)});return}let m=await io(g,e.id,t.acceptEmails===!0,f);if("refused"in m){T(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(m.refused.message),{code:m.refused.code});return}let y=m.held,v={},b=async()=>{if(!(!y||v.back)){v.back=await y.release();for(let R of Qt(v.back,l))this.deps.log(`[INFO] ${R}`)}},k={objectApiName:d.name,label:d.label,records:c.length},S=await bc(this.deps,{orgId:r,operation:"delete",objectNames:[d.name],recordCount:c.length,action:"cleanup_delete",description:`Delete ${c.length} ${d.name} record(s): ${UI(n)}`,origin:"dataops:cleanup:delete",run:async(R,w)=>{let P=await wa(i,d.name,c,w);return R(d.name,P),[{objectApiName:d.name,counts:P}]},beforeEnd:b},this.liveTracker).finally(b);if(!S.ran){T(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(S.message),S.code?{code:S.code}:void 0);return}if(S.error!==void 0){T(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(S.error),S.cancelled?{code:ot}:void 0);return}let C=A(this.deps,e,"dataops:cleanup:delete:response",{objectApiName:t.objectApiName,dryRun:o,plan:k,truncated:a.truncated,outcome:S.outcome,...y?{mutedAutomation:v.back??y.outcome}:{}});this.deps.broker.postToWebview(C),this.deps.log(`[TX] ${C.type} id=${C.id} ${S.outcome.status} deleted=${S.outcome.done} failed=${S.outcome.failed}`)}catch(i){T(this.deps,"dataops:cleanup:delete","dataops:error",e,i)}}};import{join as rj}from"node:path";async function HI(s){let{permissions:e,objects:t}=s;if(e.viewAllData&&e.modifyAllData)return{kind:"org"};let r={kind:"perObject",viewAllData:e.viewAllData,modifyAllData:e.modifyAllData},n=await s.grants();if("unread"in n)return{...r,unseen:t.map(l=>({objectApiName:l,reason:"permissionsUnread",detail:n.unread}))};let o=await s.describe(t),i={grants:n.grants,describes:o,...s.customSettings?{customSettings:s.customSettings}:{}},a=wR(t,i),d=a.length>0?[...o,...await s.describe(a)]:o,c=bR(t,{...i,describes:d}),u=[];for(let[l,p]of c)"access"in p||u.push({objectApiName:l,reason:p.reason,...p.detail!==void 0?{detail:p.detail}:{}});return{...r,unseen:u}}function BI(s,e){if(e.kind==="org")return[];let t=new Set(s.kind==="org"?[]:s.unseen.map(r=>r.objectApiName));return e.unseen.map(r=>r.objectApiName).filter(r=>!t.has(r))}var eN=1e4,WI={bulkDestroy:()=>Promise.reject(new Error("an estimate sends no job"))};function wf(s){return Ws(WI,s,1,"hard")}var zI=9,tN=25;function GI(s,e,t){let r=e>0&&Ws(WI,s,e,t);if(!r&&t==="hard"&&e>0)return{objectApiName:s,records:e,restCalls:0,jobs:[],toTheBin:!1,notSent:!0};if(!r)return{objectApiName:s,records:e,restCalls:Math.ceil(e/qt),jobs:[],toTheBin:!0};let n=Math.ceil(e/qs),o=Math.ceil(e/n),i=[];for(let a=e;a>0;a-=o)i.push(Math.min(a,o));return{objectApiName:s,records:e,restCalls:0,jobs:i,toTheBin:t==="recycle"}}function Nr(s,e){return{apiRequests:s,seconds:s*e}}function vi(s){return s.reduce((e,t)=>({apiRequests:e.apiRequests+t.apiRequests,seconds:e.seconds+t.seconds}),{apiRequests:0,seconds:0})}function JI(s){return Math.max(1,Math.ceil(s/Ll))}function VI(s){return s.notSent?{apiRequests:0,seconds:0}:vi([Nr(JI(s.records),ao),Nr(1,Vs),Nr(s.restCalls,qa),...s.jobs.map(e=>({apiRequests:ab({stateReads:cb(e)}),seconds:db(e)}))])}function rN(s){return s<=0?{apiRequests:0,seconds:0}:vi([Nr(1,Vs),Nr(Math.ceil(s/Ll),ao),Nr(Math.ceil(s/qt),qa),Nr(Math.ceil(s/qt),ao)])}function nN(s){if(s<=0)return{apiRequests:0,seconds:0};let e=Math.ceil(s/qt);return vi([Nr(e,qa),Nr(e,ao)])}var oN=.05,qI={check:2,connect:3};function Oc(s,e,t,r=0){let n=t*qI.check+qI.connect,o=t*e+n+s.apiRequests+r,i=Math.ceil(o*oN);return{apiRequests:o+i,seconds:e*Vs+s.seconds,requests:{reads:e,readings:t,passes:s.apiRequests,margin:i,connecting:n,...r>0?{mute:r}:{}}}}function XI(s){let e=s.passes.map(({objectApiName:d,records:c})=>GI(d,Math.max(0,c),s.mode)),t=vi([rN(s.toDraft),Nr(s.draftReads??0,ao),...e.map(VI),...(s.refused??[]).map(nN)]),r=Oc(t,Math.max(0,s.reads),s.readings??2),n=e.reduce((d,c)=>d+c.jobs.reduce((u,l)=>u+Math.ceil(l/eN),0),0),o=s.mode==="recycle"?Math.max(0,s.deleted):e.filter(d=>d.toTheBin).reduce((d,c)=>d+c.records,0),i=s.dataStorageMB===void 0?void 0:s.dataStorageMB*tN,a=e.some(d=>d.jobs.length>0);return{...r,bulkBatches:n,passes:e,binRecords:o,...i===void 0?{}:{bin:{documentedCapacity:i,past:o>i}},api:Pn(r.apiRequests,s.apiBudget),...a?{batches:s.bulkBatches?Pn(n,s.bulkBatches):{verdict:"unread",estimate:n,unread:"the limits the org answered list no DailyBulkApiBatches"}}:{}}}function KI(s,e,t,r=0){let n=vi(e.map(o=>{let i=GI(o.objectApiName,Math.max(0,o.records),s),a=VI(i);if(!o.idsRead||i.notSent)return a;let d=JI(i.records);return{apiRequests:a.apiRequests-d,seconds:a.seconds-d*ao}}));return Oc(n,Math.max(0,t),1,Math.max(0,r)).apiRequests}var bf=3;function YI(s,e,t=0){return Oc({apiRequests:Math.max(0,s),seconds:0},Math.max(0,e),1,Math.max(0,t)).apiRequests}function QI(s,e,t,r=0){let n={apiRequests:s.requests.passes,seconds:s.seconds-s.requests.reads*Vs},o=Oc(n,Math.max(0,e),t,Math.max(0,r)),i=s.api.verdict==="unread"?{unread:s.api.unread}:{max:s.api.max,remaining:s.api.remaining};return{...s,...o,api:Pn(o.apiRequests,i)}}var sN=yR.extend({relationshipName:L().nullish(),polymorphicForeignKey:Ve().optional()}),ZI=za.extend({deletable:Ve().optional(),fields:Re(sN)});function Rf(s){return lR.has(s)}var eA={pricebook2:{field:"IsStandard",value:!0}};function tA(s){let e=eA[s.toLowerCase()];return e?`${e.field} = ${String(e.value)}`:void 0}function po(s){let e=eA[s.toLowerCase()];return e?`${e.field} = ${String(!e.value)}`:void 0}var iN=new Set(["pricebook2","product2"]);function rA(s,e){return e!==void 0&&s.childSObject!==void 0&&s.field!==void 0&&mR(s.childSObject,s.field,e)?"restricted":s.cascadeDelete===!0?"cascade":s.restrictedDelete===!0?"restricted":"lookup"}function vf(s,e=t=>t){let t=[];for(let[r,n]of s)for(let o of n.childRelationships??[]){let i=e(o.childSObject),a=s.get(i)?Ic(s,i,o.field):void 0;nA(a,r)||t.push({parent:r,child:e(o.childSObject),field:o.field,kind:rA(o,r)})}return t}var Si=5,aN=8;function nA(s,e){if(s?.polymorphicForeignKey===!0)return!1;let t=s?.referenceTo??[];return t.length>0&&!t.some(r=>r.toLowerCase()===e.toLowerCase())}function dN(s,e,t){let r=Ic(s,e,t);return(r?.referenceTo?.length??0)>1||r?.polymorphicForeignKey===!0}function Sf(s,e,t){let r=new Map;for(let g of[...e,...s,...t.keys()])r.set(g.toLowerCase(),g);let n=g=>r.get(g.toLowerCase())??g,o=g=>t.get(g)??t.get(n(g)),i=new Set(s.map(g=>g.toLowerCase())),a=new Set([...e,...s].map(g=>g.toLowerCase())),d=new Map,c=new Map,u=new Set,l=(g,h)=>{let m=c.get(g)??new Set;m.add(h),c.set(g,m)},p=s.map(g=>({top:g,from:g,above:[]}));for(;p.length>0;){let g=[];for(let{top:h,from:m,above:y}of p){let v=o(m);if(!v){u.add(m);continue}for(let b of v.childRelationships??[]){if(rA(b,m)!=="cascade")continue;let k=n(b.childSObject),C=o(k)?.fields.find(O=>O.name.toLowerCase()===b.field.toLowerCase());if(nA(C,m))continue;let R=k.toLowerCase();if(!a.has(R)||R===m.toLowerCase()||y.some(O=>O.object.toLowerCase()===R))continue;let w=[{object:k,field:b.field,parent:m},...y],P=d.get(k)??[];if(w.length>1&&P.length>=aN){l(k,m);continue}d.set(k,[...P,{object:k,steps:w,emptied:h}]),!(i.has(R)||w.length>=Si)&&g.push({top:h,from:k,above:w})}}p=g}for(let g=!0;g;){g=!1;for(let[h,m]of d)for(let y of m)for(let[v,b]of y.steps.entries())v===0||!c.has(b.object)||y.steps.slice(0,v).some(S=>dN(t,S.object,S.field))||c.get(h)?.has(b.object)||(l(h,b.object),g=!0)}let f=[...d.keys()].filter(g=>!i.has(g.toLowerCase())).sort();return{emptied:new Set(s),routes:d,along:f,routesCut:new Map([...c].map(([g,h])=>[g,[...h].sort()])),undescribed:[...u].filter(g=>!i.has(g.toLowerCase())).sort()}}function us(s,e){let t=new Set,r=new Set,n=o=>{if(!r.has(o)){r.add(o),e.emptied.has(o)&&t.add(o);for(let i of e.routes.get(o)??[])n(i.emptied)}};return n(s),t}function cN(s,e,t){if(t===void 0)return s;if(t==="unnamed")return{...s,exact:!1};if(t.length===0)return s;let r=t.map(n=>`'${n}'`).join(", ");return{soql:`${s.soql} AND ${e} NOT IN (${r})`,exact:s.exact}}function Ic(s,e,t){let r=t.toLowerCase();return s.get(e)?.fields.find(n=>n.name.toLowerCase()===r)}function Ac(s,e,t=po,r=()=>{}){let n=[],o=(i,a,d,c)=>cN({soql:i,exact:a},d,r(c));for(let[i,a]of s.entries()){if(!e.has(a.object)){let g=[...n,a.field].join(".");return o(`${g} != null`,!1,g,a.parent)}let d=Ic(e,a.object,a.field);if(!d){if(i===0)return;let g=s[i-1],h=[...n.slice(0,-1),g.field].join(".");return o(`${h} != null`,!1,h,g.parent)}let c=(d.referenceTo?.length??0)>1||d.polymorphicForeignKey===!0,u=d.relationshipName??void 0,l=i===s.length-1,p=u?[...n,u].join("."):void 0,f=[...n,d.name].join(".");if(c)return p?o(`${p}.Type = '${a.parent}'`,l,f,a.parent):o(`${f} != null`,!1,f,a.parent);if(l){let g=t(a.parent);if(g===void 0&&!iN.has(a.parent.toLowerCase()))return o(`${f} != null`,!0,f,a.parent);if(!p)return o(`${f} != null`,!1,f,a.parent);let h=g!==void 0?` AND ${p}.${g}`:"";return o(`${p}.Id != null${h}`,!0,f,a.parent)}if(!u||i+1>=Si)return o(`${f} != null`,!1,f,a.parent);n.push(u)}}function oA(s,e,t){let r=[];for(let[n,o]of s.entries()){let i=e.has(o.object)?Ic(e,o.object,o.field):void 0;if(!i)return;let a=[...r,i.name].join(".");if(n===s.length-1)return`${a} IN (${t.map(c=>`'${c}'`).join(", ")})`;if((i.referenceTo?.length??0)>1||i.polymorphicForeignKey===!0||!i.relationshipName||n+1>=Si)return;r.push(i.relationshipName)}}function ki(s,e,t=po,r){let n=s.map(a=>Ac(a.steps,e,t,r)).filter(a=>a!==void 0);if(n.length===0)return;if(n.length===1)return n[0];let o=n.every(a=>a.exact)&&n.length===s.length,i=[...new Set(n.map(a=>a.soql))];return i.length===1?{soql:i[0],exact:o}:{soql:i.map(a=>`(${a})`).join(" OR "),exact:o}}function sA(s,e,t,r,n,o=po,i){let a={object:s,field:e,parent:t};if(r.emptied.has(t))return Ac([a],n,o,i);let d=(r.routes.get(t)??[]).map(c=>({object:s,steps:[a,...c.steps],emptied:c.emptied}));return ki(d,n,o,i)}var dA=4,iA=100,uN=/^[A-Za-z0-9]+$/;function aA(s,e){let t=po(s);if(t!==void 0)return t;if(e&&s.toLowerCase()===hr.toLowerCase())return`${Xs} = false`}var mo="stopped before the org was asked";function cA(s,e,t="COUNT()"){let r=Rf(s),n=[...e,...r?["IsDeleted = false"]:[]],o=n.length===0?"":` WHERE ${n.map(i=>n.length>1?`(${i})`:i).join(" AND ")}`;return{soql:`SELECT ${t} FROM ${Xe(s)}${o}`,all:r}}var ho=class{statements=new Map;answers=new Map;ask(e,t){let r=cA(e,t.map(i=>typeof i=="string"?i:i.soql)),n=t.some(i=>typeof i!="string"&&!i.exact),o=this.statements.get(r.soql);return this.statements.set(r.soql,{...r,atMost:n||o?.atMost===!0}),r.soql}get size(){return this.statements.size}async run(e,t){let r=!1;return await Fs([...this.statements].map(([n,{soql:o,all:i,atMost:a}])=>async()=>{if(t()){r=!0,this.answers.set(n,{unread:mo});return}try{let d=await(i?e.countAll(o):e.count(o));this.answers.set(n,{records:d,...a?{atMost:!0}:{}})}catch(d){this.answers.set(n,{unread:I(d)})}}),dA),r}answer(e){return this.answers.get(e)??{unread:mo}}},Pc=class{statements=new Map;answers=new Map;ask(e,t){let r=cA(e,t,"Id");return this.statements.set(r.soql,r.all),r.soql}get size(){return this.statements.size}async run(e,t){let r=!1;return await Fs([...this.statements].map(([n,o])=>async()=>{if(t()){r=!0,this.answers.set(n,{counted:{unread:mo}});return}try{let i=await e.readIds(n,o),a=i.ids.filter(d=>uN.test(d));this.answers.set(n,{counted:{records:i.totalSize},...a.length===i.totalSize?{ids:a}:{}})}catch(i){this.answers.set(n,{counted:{unread:I(i)}})}}),dA),r}answer(e){return this.answers.get(e)??{counted:{unread:mo}}}};function If(s,e){return s.records===void 0?s:e.records===void 0?{unread:e.unread??mo}:{records:Math.max(0,s.records-e.records),...e.atMost?{atLeast:!0}:{}}}function kf(s,e){return s.records===void 0?s:e.records===void 0?{...s,atMost:!0}:{...s,records:Math.max(0,s.records-e.records),...e.atMost?{atLeast:!0}:{},...e.atLeast?{atMost:!0}:{}}}function Fn(s){return s.records===0&&s.atLeast!==!0}function fo(s){return s===void 0||s.records===void 0||s.records>0}function Ec(s){return{unread:`${s}: the lookup its records go by is hidden from the user`}}function Af(s){return s.records===void 0?s:{...s,atLeast:!0}}function Oi(s){return s.records===void 0?s:{...s,atMost:!0}}function Of(s,e){let t=e.key?s.answer(e.key):Ec(e.objectApiName),r=e.going?If(t,s.answer(e.going)):t,n=(r.records??0)>0;return e.more&&n&&(r={...r,atLeast:!0}),e.under&&n&&(r=Af(r)),e.over&&n&&(r=Oi(r)),r}function Tf(s,e){return s.every(t=>e.get(t.emptied)!=="unnamed"&&t.steps.every(r=>e.get(r.parent)!=="unnamed"))}function lN(s){let e=r=>typeof r=="string"?r:r.soql,t=[...new Set(s.map(r=>r.length===1?e(r[0]):r.map(n=>`(${e(n)})`).join(" AND ")))];return{soql:t.length===1?t[0]:t.map(r=>`(${r})`).join(" OR "),exact:s.every(r=>r.every(n=>typeof n=="string"||n.exact))}}function go(s){let e=s.filter(n=>n.records!==void 0);if(e.length===0)return s.length===0?{records:0}:{unread:s[0].unread??mo};let t=s.some(n=>n.records===void 0||n.atLeast),r=s.some(n=>n.atMost);return{records:e.reduce((n,o)=>n+(o.records??0),0),...r?{atMost:!0}:{},...t?{atLeast:!0}:{}}}var Tc="Pricebook2";function pN(s){let e=new Map,t=r=>r.records.records??Number.POSITIVE_INFINITY;for(let r of s){let n=[r.objectApiName,r.field??"",r.parent??""].join("\0"),o=e.get(n);(!o||t(r)>t(o))&&e.set(n,r)}return[...e.values()]}async function uA(s,e,t=()=>!1,r={undo:!0}){let{affected:n,order:o,relations:i,describes:a}=s,d=o.passes.map(D=>D.objectApiName),c=a.get(hr)?.fields.some(D=>D.name===Xs)===!0,u=D=>{let G=aA(D,c);if(!(D.toLowerCase()===hr.toLowerCase()&&n.emptied.has(Co)))return G},l=D=>{let G=u(D);return G===void 0?[]:[G]},p=new Map,f=D=>p.get(D),g=D=>f(D),h=D=>Ac(D,a,u,g),m=D=>ki(D,a,u,g),y=(D,G,ue)=>sA(D,G,ue,n,a,u,g),v=new ho,b=new Map;for(let D of d)b.set(D,v.ask(D,l(D)));let k=await v.run(e,t),S=new Map(d.map(D=>[D,v.answer(b.get(D)??"")])),C=D=>[...us(D,n)].some(G=>fo(S.get(G))),R=D=>D.filter(G=>fo(S.get(G.emptied))),w=D=>!n.emptied.has(D)&&n.routesCut.has(D),P=new ho,O=[];for(let{parent:D,child:G,field:ue,kind:j}of i){if(j!=="restricted"||G===D||n.emptied.has(G)||!C(D))continue;let se=y(G,ue,D),U=n.routes.has(G)?m(R(n.routes.get(G)??[])):void 0;O.push({objectApiName:G,field:ue,parent:D,...se?{key:P.ask(G,[se])}:{},...se&&U?{going:P.ask(G,[U,se])}:{},...U&&w(G)?{over:!0}:{},...n.emptied.has(D)&&!n.routes.has(G)?{naming:""}:{}})}for(let{child:D,field:G,parent:ue,rows:j}of _l){if(j===void 0||!C(ue)||n.emptied.has(D)||!n.routes.has(D))continue;let U=a.get(D)?.fields.some(Se=>Se.name===j.field)===!0?y(D,G,ue):void 0;if(!U)continue;let te=`${j.field} = ${String(j.value)}`;O.push({objectApiName:D,field:G,parent:ue,key:P.ask(D,[te,U]),along:!0,...n.emptied.has(ue)?{naming:te}:{}})}k=await P.run(e,t)||k;let E=new Pc,$=new Map,H=new Map;O.forEach((D,G)=>{if(D.naming===void 0||D.key===void 0||(Of(P,D).records??0)===0)return;let ue=`Id IN (SELECT ${Xe(D.field)} FROM ${Xe(D.objectApiName)}${D.naming!==""?` WHERE ${D.naming}`:""})`;$.set(G,E.ask(D.parent,[...l(D.parent),ue])),H.set(D.parent,[...H.get(D.parent)??[],ue])}),k=await E.run(e,t)||k;for(let D of H.keys()){let G=[...$].filter(([j])=>O[j].parent===D).map(([,j])=>E.answer(j));if(G.every(j=>j.counted.records===0))continue;let ue=new Set(G.flatMap(j=>j.ids??[]));p.set(D,G.every(j=>j.ids!==void 0)&&ue.size<=iA?[...ue]:"unnamed")}let J=D=>{let G={archived:new Map,kept:new Map,goneBefore:new Map,along:new Map,refusals:[],undoLost:[]};for(let U of o.passes){let te=U.objectApiName;if(!fo(S.get(te)))continue;let Se=l(te);Rf(te)&&G.archived.set(te,D.ask(te,[...Se,"IsArchived = true"]));let De=tA(te);De!==void 0&&G.kept.set(te,D.ask(te,[De]));let qe=R(U.goneBefore);if(qe.length>0){let Ee=m(qe);G.goneBefore.set(te,Ee?{key:D.ask(te,[...Se,Ee]),unreadable:!1}:{unreadable:!0})}let ce=r.undo?R(U.sentBeforeTheirParent):[];for(let Ee of ce){let Ne=h(Ee.steps),it=Ee.steps[0],nt=Ne?[...Se,Ne]:void 0;G.undoLost.push({objectApiName:te,field:it.field,parent:it.parent,reason:"unordered",...nt?{key:D.ask(te,nt),conditions:nt}:{}})}}for(let U of n.along){let te=R(n.routes.get(U)??[]);if(te.length===0)continue;let Se=te.map(qe=>{let ce=h(qe.steps);return{route:qe,...ce?{key:D.ask(U,[ce])}:{}}}),De=te.length>1?m(te):void 0;G.along.set(U,{...De?{total:D.ask(U,[De])}:Se[0].key?{total:Se[0].key}:{},via:Se})}let ue=U=>o.passes.findIndex(te=>te.objectApiName===U);for(let U of r.undo?o.beforeParent:[]){if(U.reason==="customPrices"){if(!C(Tc)||!C(U.parent)||ue(Tc)>ue(U.parent))continue;let qe=y(U.objectApiName,"Pricebook2Id",Tc),ce=y(U.objectApiName,U.field,U.parent),Ee=qe&&ce?[qe,ce]:void 0;G.undoLost.push({objectApiName:U.objectApiName,field:U.field,parent:U.parent,reason:"restricted",...Ee?{key:D.ask(U.objectApiName,Ee),conditions:Ee}:{},...w(Tc)||w(U.parent)?{under:!0}:{}});continue}if(!C(U.objectApiName)||!C(U.parent))continue;let te=y(U.objectApiName,U.field,U.parent),Se=[];if(!n.emptied.has(U.objectApiName)){let qe=m(R(n.routes.get(U.objectApiName)??[]));qe&&Se.push(qe)}let De=w(U.objectApiName)||w(U.parent);G.undoLost.push({objectApiName:U.objectApiName,field:U.field,parent:U.parent,reason:"restricted",...te?{key:D.ask(U.objectApiName,[...Se,te]),conditions:[...Se,te]}:{},...De?{under:!0}:{}})}for(let{child:U,field:te,parent:Se,rows:De}of _l){if(De===void 0||!C(Se)||!n.emptied.has(U))continue;let ce=a.get(U)?.fields.some(Ne=>Ne.name===De.field)===!0?y(U,te,Se):void 0;if(!ce||!r.undo||!fo(S.get(U)))continue;let Ee=`${De.field} = ${String(De.value)}`;G.undoLost.push({objectApiName:U,field:te,parent:Se,reason:"restricted",key:D.ask(U,[Ee,ce]),conditions:[Ee,ce],more:!0})}let j=(U,te,Se,De=!1)=>{G.refusals.push({code:U,objectApiName:te,key:D.ask(te,Se),...De?{under:!0}:{}})};for(let U of o.toDraft){if(!C(U))continue;let te="StatusCode != 'Draft'";if(n.emptied.has(U)){j("activatedOrder",U,[te]);continue}let Se=R(n.routes.get(U)??[]),De=m(Se);j(Tf(Se,p)?"activatedOrder":"activatedOrderLeft",U,De?[De,te]:[{soql:te,exact:!1}],De!==void 0&&w(U))}for(let[U,te]of G.kept)G.refusals.push({code:"standardPriceBook",objectApiName:U,key:te});n.emptied.has(ia)&&fo(S.get(ia))&&(n.emptied.has(hr)||j("directContactRelation",ia,[{soql:"IsDirect = true",exact:!n.routes.has(hr)}]));let se=a.get(hr);return n.emptied.has(hr)&&!n.emptied.has(Co)&&fo(S.get(hr))&&se?.fields.some(U=>U.name===Xs)===!0&&j("personAccountContact",hr,[`${Xs} = true`]),G},W=new Pc,Z=new Map;if(p.size>0){let D=new Set;f=G=>(n.emptied.has(G)||D.add(G),p.get(G)),J(new ho),f=G=>p.get(G);for(let G of[...D].sort()){let ue=R(n.routes.get(G)??[]),j=ue.filter(te=>p.has(te.emptied));if(j.length===0)continue;let se=p.get(j[0].emptied),U=ue.length===1&&Array.isArray(se)?oA(ue[0].steps,a,se):void 0;U===void 0?p.set(G,"unnamed"):Z.set(G,W.ask(G,[U]))}k=await W.run(e,t)||k;for(let[G,ue]of Z){let j=W.answer(ue);p.set(G,j.ids!==void 0&&j.ids.length<=iA?j.ids:"unnamed")}}let _=new ho,Q=J(_);k=await _.run(e,t)||k;let N=D=>Of(_,D),z=new ho,oe=new Map;for(let[D,G]of H)G.length===2&&p.get(D)==="unnamed"&&oe.set(D,z.ask(D,[...l(D),...G]));let re=new Map,q=new Map;for(let D of Q.undoLost)q.set(D.objectApiName,[...q.get(D.objectApiName)??[],D]);for(let[D,G]of q){let ue=G.filter(se=>!Fn(N(se)));if(ue.length<2)continue;let j=ue.map(se=>se.conditions);j.some(se=>se===void 0)||re.set(D,z.ask(D,[lN(j)]))}k=await z.run(e,t)||k;let F=O.map((D,G)=>{let ue=$.get(G);return{objectApiName:D.objectApiName,field:D.field,parent:D.parent,records:Of(P,D),...ue!==void 0?{keeps:E.answer(ue).counted}:{}}}).filter(D=>!Fn(D.records)),ne=D=>{let G=F.flatMap(U=>U.parent===D&&U.keeps!==void 0?[U.keeps]:[]);if(G.length===0)return;let ue=p.get(D);if(Array.isArray(ue))return{records:ue.length};let j=go(G),se=oe.get(D);return se!==void 0?kf(j,z.answer(se)):G.length>1&&(j.records??0)>0?Oi(j):j},ke=F.filter(D=>!Array.isArray(p.get(D.parent))&&O.some(G=>G.along===!0&&G.objectApiName===D.objectApiName&&G.field===D.field&&G.parent===D.parent)),de=F.filter(D=>O.some(G=>G.along===!0&&G.objectApiName===D.objectApiName&&G.field===D.field&&G.parent===D.parent)),Ze=o.passes.map(D=>{let G=D.objectApiName,ue=aA(G,c),j=S.get(G)??{unread:mo};if(!fo(j))return{objectApiName:G,...ue!==void 0?{rows:ue}:{},records:j,sent:j};let se=Q.goneBefore.get(G),U=se===void 0?j:se.unreadable||se.key===void 0?Ec(G):n.routesCut.has(G)?Oi(If(j,_.answer(se.key))):If(j,_.answer(se.key)),te=Q.archived.get(G),Se=Q.kept.get(G),De=ne(G);return{objectApiName:G,...ue!==void 0?{rows:ue}:{},records:j,sent:U,...te?{archived:_.answer(te)}:{},...Se?{kept:_.answer(Se)}:{},...De&&!Fn(De)?{blocked:De}:{}}}),xe=r.undo?Ze.filter(D=>a.get(D.objectApiName)?.undeletable===!1&&!Fn(D.sent)).map(D=>({objectApiName:D.objectApiName,reason:"notRestorable",records:D.sent})):[],Ue=[...Q.along].map(([D,{total:G,via:ue}])=>{let j=G?_.answer(G):Ec(D),se=n.routesCut.get(D),U=ke.filter(ce=>ce.objectApiName===D),te=de.filter(ce=>ce.objectApiName===D),Se=U.length>0?go(U.map(ce=>ce.records)):void 0,De=te.length>0?go(te.map(ce=>ce.records)):void 0,qe=Se?kf(j,Se):j;return{objectApiName:D,records:se?Af(qe):qe,via:ue.map(({route:ce,key:Ee})=>{let Ne=Ee?_.answer(Ee):Ec(D),it=ce.steps[0],nt=U.filter(Ce=>Ce.field===it.field&&Ce.parent===it.parent);return{field:it.field,parent:it.parent,emptied:ce.emptied,records:nt.length>0?kf(Ne,go(nt.map(Ce=>Ce.records))):Ne}}).filter(ce=>!Fn(ce.records)),...De&&!Fn(De)?{blocking:De}:{},...se?{routesNotRead:[...se]}:{}}}).filter(D=>!Fn(D.records)),V=(D,G)=>D.map(ue=>({...G(ue),records:N(ue)})).filter(ue=>!Fn(ue.records)),ae=pN([...V(Q.undoLost,D=>({objectApiName:D.objectApiName,...D.field!==void 0?{field:D.field}:{},...D.parent!==void 0?{parent:D.parent}:{},reason:D.reason})),...xe]),ee=new Map;for(let D of ae)ee.set(D.objectApiName,[...ee.get(D.objectApiName)??[],D]);let fe=go([...ee].map(([D,G])=>{let ue=re.get(D),j=G.filter(U=>U.reason==="notRestorable");if(ue===void 0){let U=go(G.map(te=>te.records));return G.length>1&&(U.records??0)>0?Oi(U):U}let se=z.answer(ue);return G.some(U=>U.reason!=="notRestorable"&&U.records.atLeast)&&(se.records??0)>0&&(se=Af(se)),j.length>0?Oi(go([se,...j.map(U=>U.records)])):se}));return{objects:Ze,along:Ue,refusals:V(Q.refusals,D=>({code:D.code,objectApiName:D.objectApiName})),blockers:F,undoLost:ae,undoLostRecords:fe,kept:p,statements:v.size+P.size+E.size+W.size+_.size+z.size,...k?{stopped:!0}:{}}}var fA={lookup:0,cascade:1,restricted:2,customPrices:2},lA="Pricebook2",Ef="Product2",pA="PricebookEntry";function fN(s,e){let t=[],r=[],n=o=>s.emptied.has(o)||s.routes.has(o);for(let o of s.emptied)for(let i of us(o,s))i!==o&&t.push({first:i,then:o,reason:"cascade"});for(let{parent:o,child:i,field:a,kind:d}of e){if(i===o||!n(i)||!n(o))continue;if(d==="lookup"){s.emptied.has(i)&&s.emptied.has(o)&&t.push({first:i,then:o,reason:"lookup"});continue}if(d!=="restricted")continue;let c=us(i,s),u=s.emptied.has(i)?[i]:[...c],l=!1;for(let p of us(o,s))if(!c.has(p))for(let f of u)f!==p&&(t.push({first:f,then:p,reason:"restricted"}),l=!0);l&&r.push({objectApiName:i,field:a,parent:o,reason:"restricted"})}return s.emptied.has(lA)&&s.emptied.has(Ef)&&(t.push({first:lA,then:Ef,reason:"customPrices"}),n(pA)&&r.push({objectApiName:pA,field:"Product2Id",parent:Ef,reason:"customPrices"})),{constraints:t,beforeParent:r}}function gN(s){return Object.hasOwn(fA,s)}function gA(s,e){let{constraints:t,beforeParent:r}=fN(s,e),n=[...s.emptied].sort(),o=new Map(n.map(l=>[l,[]]));for(let{first:l,then:p,reason:f}of t)f==="cascade"?o.get(l)?.push({childSObject:p,field:f,cascadeDelete:!0}):o.get(p)?.push({childSObject:l,field:f});let i=new Map(n.map(l=>[l,{name:l,fields:[],childRelationships:o.get(l)??[]}])),a=Kh(n,i,({field:l})=>{let p=gN(l)?l:"lookup";return{first:p==="cascade"?"parent":"child",firmness:fA[p]}}),d=new Map(a.map((l,p)=>[l,p])),c=(l,p)=>(d.get(l)??0)<(d.get(p)??0);return{passes:a.map(l=>{let p=s.routes.get(l)??[];return{objectApiName:l,goneBefore:p.filter(f=>c(f.emptied,l)),sentBeforeTheirParent:p.filter(f=>!c(f.emptied,l))}}),beforeParent:r,unordered:hN(t.filter(({first:l,then:p})=>!c(l,p))),toDraft:or([...n,...s.along])}}function hN(s){let e=new Set;return s.filter(({first:t,then:r,reason:n})=>{let o=`${t}\0${r}\0${n}`;return e.has(o)?!1:(e.add(o),!0)})}function mN(s){switch(s){case"configuration":case"excludedByUser":case"notFound":case"chatter":case"history":case"sharing":case"changeEvent":case"unsupportedKind":case"customSetting":case"heldWithFiles":case"setup":case"platformCreated":case"metadata":return s;case"notCustomSetting":return"notFound";case"files":return"documents";case"notWritable":return"notDeletable"}}var yN=(s,e,t)=>{let r=fR(s,e,"empty",t.customSettings?{customSettings:Vh}:{});return{candidates:r.candidates,leftOut:r.leftOut.map(({objectApiName:n,reason:o,detail:i})=>({objectApiName:n,reason:mN(o),...i===void 0?{}:{detail:i}}))}},wN=new Set([Gh,Jh].map(s=>s.toLowerCase()));function hA(s,e){return s.objectApiName<e.objectApiName?-1:s.objectApiName>e.objectApiName?1:0}function bN(s,e){if(s.customSetting===!0&&e.customSettings!==!0)return"customSetting";if(wN.has(s.name.toLowerCase())&&e.files!==!0)return"files";if(Xh(s.name)!==void 0&&e.managedPackages!==!0)return"managedPackage";if(s.undeletable===!1&&e.unrestorable!==!0)return"notRestorable"}function Cc(s,e,t,r=yN){let n=r(s,e,{customSettings:!0}),o=new Map(s.map(l=>[l.name.toLowerCase(),l])),i=new Set(n.candidates.map(l=>l.toLowerCase())),a=new Map(n.leftOut.map(l=>[l.objectApiName.toLowerCase(),l])),d=[],c=[],u=l=>{let p=a.get(l.name.toLowerCase());return p?{...p,objectApiName:l.name}:{objectApiName:l.name,reason:"notDeletable"}};if(t.mode==="objects"){let l=new Set;for(let p of t.objects??[]){let f=p.toLowerCase();if(l.has(f))continue;l.add(f);let g=o.get(f);g?i.has(f)?d.push(g.name):c.push(u(g)):c.push({objectApiName:p,reason:"notFound"})}}else{let l=new Set((t.excluded??[]).map(p=>p.toLowerCase()));for(let p of t.excluded??[])o.has(p.toLowerCase())||c.push({objectApiName:p,reason:"notFound"});for(let p of o.values()){let f=p.name.toLowerCase();if(l.has(f)){c.push({objectApiName:p.name,reason:"excludedByUser"});continue}if(!i.has(f)){c.push(u(p));continue}let g=bN(p,t);g===void 0?d.push(p.name):c.push({objectApiName:p.name,reason:g})}}return d.sort(),c.sort(hA),{mode:t.mode,objects:d,leftOut:c,worked:[...n.candidates].sort()}}function mA(s,e,t=new Map){let r=[],n=[...s.leftOut];for(let o of s.objects){let i=e.get(o);if(i)i.deletable===!1?n.push({objectApiName:o,reason:"notDeletable"}):i.fields.some(a=>a.name==="IsDeleted")?r.push(o):n.push({objectApiName:o,reason:"noRecycleBin"});else{let a=t.get(o);n.push({objectApiName:o,reason:"notDescribed",...a===void 0?{}:{detail:a}})}}return{...s,objects:r,leftOut:n.sort(hA)}}async function Pf(s,e,t,r){await Fs(e.map(n=>async()=>{try{t.set(n,ZI.parse(await s.describe(n)))}catch(o){r.set(n,I(o))}}),6)}function vN(s,e){if(e!=="hard")return s;let t=s.objects.filter(r=>!wf(r));return t.length===0?s:{...s,objects:s.objects.filter(wf),leftOut:[...s.leftOut,...t.map(r=>({objectApiName:r,reason:"notForGood"}))].sort((r,n)=>r.objectApiName<n.objectApiName?-1:r.objectApiName>n.objectApiName?1:0)}}function yo(s){return s.records}async function yA(s,e){let t=Cc(s.global,s.tooling,s.request,s.rule),r=new Map,n=new Map;await Pf(e,t.objects,r,n);let o=vN(mA(t,r,n),s.deleteMode),i=new Map([...t.worked,...s.global.map(w=>w.name)].map(w=>[w.toLowerCase(),w])),a=w=>i.get(w.toLowerCase())??w,d=Sf(o.objects,t.worked,r);for(let w=0;w<Si;w++){let P=d.undescribed.filter(O=>!r.has(O)&&!n.has(O));if(P.length===0)break;await Pf(e,P,r,n),d=Sf(o.objects,t.worked,r)}let c=w=>d.emptied.has(w)||d.routes.has(w),u=[...new Set(vf(r,a).filter(({kind:w,parent:P,child:O})=>w==="restricted"&&c(P)&&!c(O)).map(({child:w})=>w))].filter(w=>!r.has(w)&&!n.has(w));await Pf(e,u,r,n);let l=vf(r,a),p=gA(d,l),f=await uA({affected:d,order:p,relations:l,describes:r},e,s.stopped,{undo:s.deleteMode==="recycle"}),g=[...f.objects.filter(w=>yo(w.records)===void 0),...f.along.filter(w=>yo(w.records)===void 0)].map(w=>w.objectApiName),h=[...f.objects.map(w=>Math.max(0,(yo(w.records)??0)-(w.blocked?.records??0))),...f.along.map(w=>yo(w.records)??0)].filter(w=>w>0),m=h.reduce((w,P)=>w+P,0),y=f.along.some(w=>w.records.atLeast===!0)||f.objects.some(w=>w.blocked?.atMost===!0),v=f.refusals.filter(w=>w.code==="activatedOrder").reduce((w,P)=>w+(yo(P.records)??0),0),b=p.toDraft.filter(w=>!d.emptied.has(w)).map(w=>{let P=d.routes.get(w)??[];if(!Tf(P,f.kept))return{objectApiName:w};let O=ki(P,r,void 0,E=>f.kept.get(E));return{objectApiName:w,...O?{condition:O.soql}:{}}}),k=w=>w.records===void 0||w.records>0,S=f.objects.filter(w=>k(w.records)).length+f.along.filter(w=>k(w.records)).length,C=zI+r.size+n.size+f.statements+2*S,R=XI({mode:s.deleteMode,passes:f.objects.map(w=>({objectApiName:w.objectApiName,records:yo(or([w.objectApiName]).length>0?w.records:w.sent)??0})),toDraft:v,deleted:m,reads:C,draftReads:b.filter(w=>w.condition!==void 0).length,refused:f.blockers.map(w=>yo(w.records)??0),...s.apiBudget?{apiBudget:s.apiBudget}:{},...s.bulkBatches?{bulkBatches:s.bulkBatches}:{},...s.dataStorageMB===void 0?{}:{dataStorageMB:s.dataStorageMB}});return{mode:t.mode,deleteMode:s.deleteMode,passes:f.objects,along:f.along,leftOut:o.leftOut,refusals:f.refusals,blockers:f.blockers,beforeParent:p.beforeParent,unordered:p.unordered,undoLost:f.undoLost,undoLostRecords:f.undoLostRecords,undo:s.deleteMode==="recycle",affected:[...d.emptied,...d.along].sort(),toDraftAlong:b,cost:R,total:{records:m,objects:h.length,uncounted:g,...y?{atLeast:!0}:{}},statements:f.statements,...f.stopped?{stopped:!0}:{}}}var SN=5,kN=qs,$c=class{constructor(e,t){this.objectApiName=e;this.planned=t}objectApiName;planned;deleted=0;gone=0;refused=new Map;refusedUnkept=0;lockResent=new Map;notes=[];settle(e,t){e.forEach((r,n)=>{let o=t[n],i=r.slice(0,15);if((o.lockResends!==void 0||this.lockResent.has(i))&&this.lockResent.set(i,o.kind),o.kind!=="refused"){this.refused.delete(r),o.kind==="deleted"?this.deleted++:this.gone++;return}let a={reason:o.reason,dependency:o.dependency,again:o.limit===void 0&&o.reason!==fb};this.refused.has(r)||this.refused.size<kN?this.refused.set(r,a):(this.refusedUnkept++,this.note(o.reason))})}note(e){this.notes.includes(e)||this.notes.push(e)}toSendAgain(){return[...this.refused].filter(([,e])=>e.again).map(([e])=>e)}heldByDependents(){return[...this.refused].filter(([,e])=>e.again&&e.dependency).map(([e])=>e)}result(e,t){let r=this.refused.size+this.refusedUnkept,n=this.refusedUnkept>0?[`${this.refusedUnkept} more refused record(s) were counted, not kept for a second try: the reasons given are those of the records kept.`]:[],o=[...gb(this.objectApiName,e),...hb(this.lockResent.values()),...this.notes,...n,...[...this.refused.values()].map(a=>a.reason)],i=this.deleted+this.gone+r;return{objectApiName:this.objectApiName,planned:this.planned,deleted:this.deleted,gone:this.gone,refused:r,...t&&this.planned>i?{notReached:this.planned-i}:{},reasons:[...new Set(o)].slice(0,SN)}}};async function wA(s,e,t){let{mode:r}=t,n=()=>t.signal?.aborted===!0,o=t.splitting??Ia(),i=e.objects.reduce((h,m)=>h+m.count,0),a=[],d=0,c=[],u=h=>{let m=a.find(y=>y.objectApiName===h);if(!m){let y=e.objects.find(v=>v.objectApiName===h);m=new $c(h,y?.count??0),a.push(m)}return m},l=async(h,m)=>{await Ca(s,c,{note:(v,b,k,S)=>u(v).note(k?Pa(v,b,S,c):b)});let y=a.map(v=>v.result(o,h));if(h)for(let{objectApiName:v,count:b}of e.objects)y.some(k=>k.objectApiName===v)||y.push({...new $c(v,b).result(o,!1),...b>0?{notReached:b}:{}});return{hard:r==="hard",objects:y,cancelled:h,...m!==void 0?{hardRefused:m}:{}}},p=(h,m)=>mb(s,h.objectApiName,m,{mode:r,stopped:n,splitting:o,...t.signal?{signal:t.signal}:{},...t.wait?{wait:t.wait}:{},settle:(y,v)=>{let b=h.deleted+h.gone+h.refused.size+h.refusedUnkept;h.settle(y,v),t.onSettled?.(h.objectApiName,y,v),d+=h.deleted+h.gone+h.refused.size+h.refusedUnkept-b,t.onProgress?.(d,i,h.objectApiName)}});if(r==="hard"&&s.bulkHardDestroy===void 0)return l(!0,pb);if(t.toDraft!==!1){let h=await Ea(s,e.objects,e,()=>!0,n,async()=>new Set);if(c=h.drafted,h.cancelled)return l(!0)}for(let{objectApiName:h,count:m}of e.objects){if(n())return l(!0);let y=u(h),v=Ws(s,h,m,r),b=[],k=async()=>{let S=b;return b=[],p(y,S)};for await(let S of e.pages(h)){if(n())return l(!0);if(b.push(...S),v&&b.length<qs)continue;let C=await k();if(C.stopped)return l(!0,C.hardRefused)}if(b.length>0){if(n())return l(!0);let S=await k();if(S.stopped)return l(!0,S.hardRefused)}}let f;if(await yb(a,{stopped:n,idsOf:(h,m)=>m===0?h.toSendAgain():h.heldByDependents(),send:async(h,m)=>{let y=await p(h,[...m]);return f=y.hardRefused,y.stopped},deleted:h=>h.deleted}))return l(!0,f);for(let h of a){if(n())return l(!0);let{gone:m,unchecked:y,failure:v}=await wb([...h.refused.keys()],b=>vn(s,h.objectApiName,[],b),()=>!0);for(let b of m)h.refused.delete(b),h.gone++;y.length>0&&h.note(`Not checked: ${y.length} refused record(s) could not be read back once the rest had gone, to tell whether a parent deleted after them took them along`+(v?` \u2014 ${v}`:"."))}return l(!1)}function ON(s){let e=Math.floor(Date.parse(s)/1e3)*1e3;if(!Number.isFinite(e))throw new RangeError(`Not a date-time: ${s}`);return`CreatedDate < ${new Date(e).toISOString().replace(".000Z","Z")}`}function IN(s){return/CreatedDate/.test(I(s))}function Cf(s){let e=s.filter(t=>t!==void 0);if(e.length!==0)return e.length===1?e[0]:e.map(t=>`(${t})`).join(" AND ")}function AN(s,e,t,r){let n=e?.count??t??s.planned,o=s.deleted+s.gone+s.refused,i=r&&n>o?n-o:0;return{objectApiName:s.objectApiName,planned:n,deleted:s.deleted,gone:s.gone,refused:s.refused,...i>0?{notReached:i}:{},reasons:s.reasons}}function TN(s,e,t,r=!1){if(e&&t===void 0)return"cancelled";let n=s.reduce((i,a)=>i+a.deleted,0),o=s.reduce((i,a)=>i+a.refused+(a.notReached??0),0);return t!==void 0?n>0?"partial":"failure":o===0?"success":n>0||r||s.some(i=>i.gone>0)?"partial":"failure"}async function bA(s){let{journal:e,org:t}=s,r=e.head,n=s.now??(()=>new Date),o=await e.state();await e.attempt(s.resumed,n());let i=[],a=new Ha,d=new Map;if(s.resumed){for await(let _ of e.lines())if(_.kind==="settled"){for(let Q of[..._.deleted,..._.gone])a.add(Q);d.set(_.objectApiName,(d.get(_.objectApiName)??0)+_.deleted.length+_.gone.length)}}let c=new AbortController,u=s.signal?AbortSignal.any([s.signal,c.signal]):c.signal,l=()=>u.aborted,p,f=!1,g=ON(r.readAt),h=new Map(r.passes.map(_=>[_.objectApiName,_])),m=_=>h.get(_)?.rows??po(_),y=new Map,v=new Map,b=()=>r.passes.reduce((_,Q)=>_+Math.max(0,(v.get(Q.objectApiName)??Q.sent??Q.records??0)-(d.get(Q.objectApiName)??0)),0),k=async(_,Q)=>{let N=async z=>{let oe=await pR(t.ids,_,[{objectApiName:Q.objectApiName,...z!==void 0?{filter:z}:{}}],{signal:u});return oe.stopped?void 0:oe.spool};try{let z=await N(Cf([Q.filter,Q.own,g]));return z?{spool:z,sinceRead:!0}:void 0}catch(z){if(!IN(z))throw z;i.push(`${Q.objectApiName} has no CreatedDate: its records were read whole, those made after the simulation among them.`);let oe=await N(Cf([Q.filter,Q.own]));return oe?{spool:oe,sinceRead:!1}:void 0}},S=_=>{let Q=y.get(_);if(Q)return Q;let N=(async()=>{let z=r.passes.findIndex(de=>de.objectApiName===_),oe=e.idsDirOf(z,_),re=o.spooled.get(_);if(s.resumed&&re)return v.set(_,re.count),{spool:await Ba.open(oe,Wa),count:re.count,sinceRead:re.sinceRead};if(l())return;let q=m(_),F=await k(oe,{objectApiName:_,...q!==void 0?{own:q}:{}});if(!F)return;let ne=F.spool.count,ke=h.get(_)?.records;if(ke!==void 0&&ne>ke){p={code:"ORG_CHANGED",message:`${_} now holds ${ne.toLocaleString("en-US")} records to delete, where the simulation counted ${ke.toLocaleString("en-US")}: the org changed beyond what was confirmed, and the emptying stopped before deleting any of them. Simulate it again, then resume or undo it.`},c.abort();return}return await e.spooled({objectApiName:_,place:z,count:ne,sinceRead:F.sinceRead}),v.set(_,ne),{spool:F.spool,count:ne,sinceRead:F.sinceRead}})();return y.set(_,N),N},C={objects:r.passes.map(_=>({objectApiName:_.objectApiName,count:_.sent??_.records??0})),pages:_=>({async*[Symbol.asyncIterator](){let Q=await S(_);if(Q)for await(let N of Q.spool.pages(_)){let z=a.size>0?N.filter(oe=>!a.has(oe)):N;z.length>0&&(yield z)}}})},R=Promise.resolve(),w,P=(_,Q,N)=>{let z=[],oe=[];Q.forEach((re,q)=>{let F=N[q]?.kind;F==="deleted"?z.push(re):F==="gone"&&oe.push(re)}),z.length>0&&(f=!0),z.length+oe.length!==0&&(R=R.then(async()=>{if(w===void 0)try{await e.settled(_,z,oe)}catch(re){w=I(re),c.abort()}}))},O=[];for(let[_,Q]of r.toDraftAlong.entries()){if(Q.condition===void 0||l())continue;let N=e.idsDirOf(r.passes.length+_,Q.objectApiName),z=await k(N,{objectApiName:Q.objectApiName,filter:Q.condition});if(!z)break;let{drafted:oe}=await Ea(t.deletion,[{objectApiName:Q.objectApiName}],z.spool,()=>!0,l,async()=>new Set);O.push(...oe)}let E=await wA(t.deletion,C,{mode:r.deleteMode,signal:u,...s.splitting?{splitting:s.splitting}:{},...s.wait?{wait:s.wait}:{},onSettled:P,onProgress:(_,Q,N)=>{let z=Math.max(_,b());s.onProgress?.({percentage:z>0?Math.min(99,Math.round(_/z*100)):99,step:`${N}: ${_.toLocaleString("en-US")} of about ${z.toLocaleString("en-US")} settled`})}}).finally(async()=>{await R,await Ca(t.deletion,O,{note:(_,Q,N,z)=>i.push(Pa(_,Q,z,O))})});w!==void 0&&i.push(`The journal of this emptying could not be written (${w}): it stopped there, so that its Undo misses nothing it deleted.`);let $=new Map;for(let[_,Q]of y)$.set(_,await Q.catch(()=>{}));let H=E.objects.map(_=>AN(_,$.get(_.objectApiName),h.get(_.objectApiName)?.records,E.cancelled));if(!E.cancelled)for(let _ of H){if(!$.get(_.objectApiName)?.sinceRead)continue;let N=m(_.objectApiName),z=g.replace("CreatedDate <","CreatedDate >=");try{let oe=await t.deletion.query(`SELECT COUNT() FROM ${Xe(_.objectApiName)} WHERE ${Cf([N,z])}`);oe.totalSize>0&&(_.madeSince=oe.totalSize)}catch(oe){i.push(`Whether ${_.objectApiName} records were made after the simulation could not be read: `+I(oe))}}let J=E.cancelled&&p===void 0&&w===void 0,W=p!==void 0||w!==void 0?f?"partial":"failure":TN(H,J,E.hardRefused,s.resumed&&o.deletedAny),Z=H.reduce((_,Q)=>_+Q.refused,0);return s.resumed&&W==="partial"&&!f&&Z>0&&i.push(`The org refused again the ${Z.toLocaleString("en-US")} record(s) this emptying had left, each said with its words above: they stay, and the emptying is closed. Undo brings back what it deleted.`),{status:W,hard:E.hard,passes:H,...E.hardRefused!==void 0?{hardRefused:E.hardRefused}:{},...p!==void 0?{changed:p}:{},deletedAny:f,notes:i}}var EN=/Entity is not in the recycle bin/,PN=/INSUFFICIENT_ACCESS/,CN=5,RA=5e4;function xc(s){return s.slice(0,15)}function $f(s){let e=new Set;for(let t of s){let r=t?.Id;typeof r=="string"&&e.add(xc(r))}return e}function $N(s){let e=s?.errors?.[0];if(e===void 0)return"The org gave no reason.";if(typeof e=="string")return e;let t=e.statusCode??"",r=e.message??"";return t&&r?`${t}: ${r}`:t||r||"The org gave no reason."}function xN(s){return{objectApiName:s,planned:0,undeleted:0,alreadyBack:0,notInBin:0,othersDeletion:0,refused:0,reasons:[]}}function Ii(s,e){s.reasons.length<CN&&!s.reasons.includes(e)&&s.reasons.push(e)}async function*DN(s,e,t){let r=t?new Ha:void 0;for await(let o of s.settledOf(e)){if(r)for(let i of[...o.deleted,...o.gone])r.add(i);o.deleted.length>0&&(yield[...o.deleted])}if(!t||!r)return;let n=await Ba.open(s.idsDirOf(t.place,e),Wa);for await(let o of n.pages(e)){let i=o.filter(a=>!r.has(a));i.length>0&&(yield i)}}async function vA(s){let e=0,t=0,r,n=new Map;for await(let o of s.lines())o.kind==="attempt"?(e++,r=void 0):o.kind==="end"?(t++,r=o.status):o.kind==="spooled"&&n.set(o.objectApiName,{place:o.place,count:o.count,attempt:e});return{spooledIn:n,...e>t?{unendedAttempt:e}:{},wentThrough:r==="success"||r==="partial"}}function SA(s,e){let t=s.spooledIn.get(e);return t!==void 0&&s.unendedAttempt!==void 0&&t.attempt===s.unendedAttempt?t:void 0}function NN(s){return(s.head.undoLost??[]).filter(e=>e.records===void 0||e.records>0).map(e=>({objectApiName:e.objectApiName,...e.field!==void 0?{field:e.field}:{},...e.parent!==void 0?{parent:e.parent}:{},reason:e.reason,records:{...e.records!==void 0?{records:e.records}:{unread:"not counted"},...e.atLeast===!0?{atLeast:!0}:{}}}))}async function kA(s){let e=await vA(s),t=0;for(let{objectApiName:r}of s.head.passes){let n=0;for await(let a of s.settledOf(r))a.deleted.length!==0&&(n+=a.deleted.length,t+=Math.ceil(a.deleted.length/qt)*bf);let o=SA(e,r);o&&(n+=o.count,t+=Math.ceil(o.count/qt)*bf);let i=(s.head.undoLost??[]).filter(a=>a.objectApiName===r).reduce((a,d)=>a+(d.records??0),0);t+=Math.ceil(Math.min(i,n)/qt)}return t}async function OA(s){let{journal:e,org:t}=s,r=e.head,n=[],o=()=>s.signal?.aborted===!0,i=await vA(e),a=[],d=new Map,c=!1,u=[...r.passes].reverse();for(let[h,{objectApiName:m}]of u.entries()){let y=xN(m);a.push(y);let v=Xe(m),b=SA(i,m);for await(let k of DN(e,m,b)){y.planned+=k.length;for(let S=0;S<k.length;S+=qt){let C=k.slice(S,S+qt);if(c||o()){c=!0,y.notReached=(y.notReached??0)+C.length;continue}let[R]=Ls(C,qt),w,P;try{w=$f((await t.queryDeleted(`SELECT Id FROM ${v} WHERE Id IN (${R}) AND IsDeleted = true`)).records),P=$f((await t.query(`SELECT Id FROM ${v} WHERE Id IN (${R})`)).records)}catch($){y.refused+=C.length,Ii(y,`The recycle bin could not be read: ${I($)}`);continue}let O=C.filter($=>w.has(xc($)));for(let $ of C)w.has(xc($))||(P.has(xc($))?y.alreadyBack++:(y.notInBin++,Ii(y,"No longer in the recycle bin, nor in the org: emptied from the bin, or pushed out of it.")));if(O.length===0)continue;let E;try{let $=await s.undelete(O),H=Array.isArray($)?$:[$];E=O.map((J,W)=>H[W]??{success:!1})}catch($){let H=I($);E=O.map(()=>({success:!1,errors:[H]}))}E.forEach(($,H)=>{if($.success===!0){y.undeleted++;return}let J=$N($);if(EN.test(J)){y.notInBin++;let W=d.get(m)??[];W.length<RA&&W.push(O[H]),d.set(m,W),Ii(y,"Salesforce still lists it as deleted but will not bring it back: emptied from the recycle bin, or kept there for good \u2014 deleted on its own before a record it hangs from was deleted after it (the org answers 'Entity is not in the recycle bin')")}else PN.test(J)?(y.othersDeletion++,Ii(y,`Deleted by another user than the one bringing it back: only Modify All Data brings back another's deletions (${J})`)):(y.refused++,Ii(y,J))})}s.onProgress?.({percentage:Math.round((h+1)/Math.max(1,u.length)*100),step:`${m}: ${y.undeleted.toLocaleString("en-US")} brought back`})}}if(!c)for(let h of a){let m=d.get(h.objectApiName)??[];if(m.length===0)continue;h.notInBin>m.length&&n.push(`${h.objectApiName}: past ${RA.toLocaleString("en-US")} records answered not in the recycle bin, whether a parent brought back later took them back was not read: they are counted as not back.`);let y=Xe(h.objectApiName);try{let v=0;for(let k of Ls(m,qt)){let S=await t.query(`SELECT Id FROM ${y} WHERE Id IN (${k})`);v+=$f(S.records).size}let b=Math.min(v,h.notInBin);h.notInBin-=b,h.alreadyBack+=b}catch(v){n.push(`Whether the ${h.objectApiName} records the org answered were not in the recycle bin came back with their parent could not be read (${I(v)}): they are counted as not back.`)}}let l=i.wentThrough?NN(e):[],p=a.reduce((h,m)=>h+m.undeleted+m.alreadyBack,0),f=a.reduce((h,m)=>h+m.notInBin+m.othersDeletion+m.refused+(m.notReached??0),0)+l.length;return{status:c?"cancelled":f===0?"success":p>0?"partial":"failure",objects:a.filter(h=>h.planned>0),notes:n,...l.length>0?{previewedLost:l}:{}}}var lr="Nothing was deleted.";function Nc(s){return{query:e=>s.query(e),queryMore:e=>s.queryMore(e)}}var xf=K({Max:Te(),Remaining:Te()}).loose(),jN=K({DailyApiRequests:xf.optional(),DailyBulkApiBatches:xf.optional(),DataStorageMB:xf.optional()}).loose();async function MN(s){try{let e=jN.parse(await s.limits()),t=o=>o?{max:o.Max,remaining:o.Remaining}:void 0,r=t(e.DailyApiRequests),n=t(e.DailyBulkApiBatches);return{apiBudget:r??{unread:"the limits the org answered list no DailyApiRequests"},...n?{bulkBatches:n}:{},...e.DataStorageMB?{dataStorageMB:e.DataStorageMB.Max}:{}}}catch(e){return{apiBudget:{unread:I(e)}}}}async function AA(s){try{return(await s.query("SELECT Id FROM User WHERE UserType = 'AutomatedProcess'")).records.map(t=>t.Id).filter(t=>typeof t=="string")}catch{return[]}}function jf(s){let e=t=>t.records===void 0||t.records>0;return[...s.passes.filter(t=>e(t.records)).map(t=>t.objectApiName),...s.along.filter(t=>e(t.records)).map(t=>t.objectApiName)]}function LN(s){let e=s.passes.map(n=>({objectApiName:n.objectApiName,records:n.sent.records??0})).filter(n=>n.records>0),t=s.refusals.filter(n=>n.code==="activatedOrder"&&(n.records.records??0)>0).map(n=>({objectApiName:n.objectApiName,records:n.records.records??0})),r=[...e];for(let n of t)r.some(o=>o.objectApiName===n.objectApiName)||r.push(n);return{objects:r,steps:{delete:e.map(n=>n.objectApiName),...t.length>0?{setToDraft:t.map(n=>n.objectApiName)}:{}},written:[...e.map(n=>({...n,write:"delete"})),...t.map(n=>({...n,write:"update"}))]}}async function FN(s,e){let t=[];for(let r of e)try{let n=za.safeParse(await s.describe(r));n.success&&t.push(n.data)}catch{}return t}function TA(s,e){return{code:"RUN_WRITING",message:`${e.operation==="take"?`A checkpoint of ${s} is being taken`:e.operation==="rewind"?`A rewind is writing to ${s}`:e.operation==="undo"?`An undo is writing to ${s}`:e.operation==="empty"?`An emptying of its objects, or its undo, is writing to ${s}`:`SandForge is deleting checkpoints of ${s}`} (process ${e.pid} on ${e.host}): empty once it has ended. ${lr}`}}function ls(s,e={}){let[t,...r]=s;return{ran:!1,refusal:t,...r.length>0?{alsoRefused:r}:{},...e}}async function Df(s,e){let t=await s.lastOf(e);if(!t)return;let r;try{r=await s.open(e,t.runId)}catch(o){if(o instanceof Tr)return;throw o}let n=await r.state();return n.open?{runId:t.runId,startedAt:n.head.startedAt,journal:r}:void 0}function EA(s,e){return{code:"OPEN_RUN",message:`The last emptying of ${s} (${e}) stopped part way: resume it, or undo it, before another one starts, so that its Undo still reaches the org as it was. ${lr}`}}function _N(s){return s.reason==="notRestorable"?`${s.objectApiName}, which Salesforce does not bring back`:`${s.objectApiName} before ${s.parent??"their parent"}`}function PA(s){let e=s.undoLostRecords;return e?.records!==void 0?{records:e.records,atLeast:e.atLeast===!0}:{records:s.undoLost.reduce((t,r)=>t+(r.records.records??0),0),atLeast:s.undoLost.some(t=>t.records.records===void 0||t.records.atLeast===!0)}}function UN(s){if(s.deleteMode!=="recycle")return;let e=s.undoLost.filter(i=>i.records.records===void 0||i.records.records>0);if(e.length===0)return;let t=PA(s),r=`${t.atLeast?"at least ":""}${t.records.toLocaleString("en-US")}`,n=[...new Set(e.map(_N))],o=e.some(i=>i.reason==="restricted"||i.reason==="unordered");return{code:"NO_UNDO",message:`${r} record(s) would stay gone after Undo (${n.slice(0,5).join(", ")}${n.length>5?", \u2026":""})`+(o?": some go before a record they name, as Salesforce requires, and once both have gone, Undo cannot bring them back":"")+". Accept it to empty all the same, or leave those objects out. "+lr}}function HN(s,e){let t=[],{api:r,batches:n}=s.cost;return r.verdict==="exceeds"&&t.push({code:"API_BUDGET",message:`The emptying takes about ${r.estimate.toLocaleString("en-US")} API requests, and ${e} has ${r.remaining.toLocaleString("en-US")} left today. Empty fewer objects, or tomorrow. ${lr}`}),n?.verdict==="exceeds"&&t.push({code:"BULK_BATCHES",message:`The emptying's Bulk API jobs take about ${n.estimate.toLocaleString("en-US")} batches, and ${e} has ${n.remaining.toLocaleString("en-US")} left today. Empty fewer records, or tomorrow. ${lr}`}),t}function Dc(s){return s.records}function BN(s,e){let t=[],r=new Map(s.passes.map(o=>[o.objectApiName,o]));for(let o of e.passes){let i=r.get(o.objectApiName),a=Dc(o.records);if(!i){(a===void 0||a>0)&&t.push(`${o.objectApiName} is now emptied too`);continue}a===void 0&&Dc(i.records)!==void 0&&t.push(`${o.objectApiName} could not be counted again (${o.records.unread??""})`)}let n=new Map(s.along.map(o=>[o.objectApiName,o]));for(let o of e.along){let i=n.get(o.objectApiName),a=Dc(o.records),d=i?Dc(i.records):0;if(a===void 0){d!==void 0&&t.push(`what goes along of ${o.objectApiName} could not be counted again`);continue}d!==void 0&&a>d&&t.push(`${a.toLocaleString("en-US")} ${o.objectApiName} record(s) now go along, where the simulation counted ${d.toLocaleString("en-US")}`)}if(e.deleteMode==="recycle"){let o=c=>PA(c).records,i=c=>new Set(c.undoLost.map(u=>`${u.objectApiName}.${u.field??""}.${u.reason}`)),a=i(s);([...i(e)].filter(c=>!a.has(c)).length>0||o(e)>o(s))&&t.push("more records would go beyond what Undo brings back")}return t}function IA(s,e){return{code:"ORG_CHANGED",message:`${s} changed since the simulation, beyond what was confirmed: ${e.slice(0,5).join("; ")}${e.length>5?"; \u2026":""}. Simulate the emptying again. ${lr}`}}function Nf(s,e,t){let r=t.automation?gr(t.automation,t.mutePlan,zr(t.steps)):{firing:[]};return{module:"empty",written:jf(e),running:{firing:r.firing},request:{},orgId:s.orgId,operationId:s.operationId}}async function CA(s,e){let{org:t,orgName:r}=s,n=s.requestsSent?.()??0,o=Nc(t),i=await co(o,{orgName:r,registered:s.registered,mode:e.request.mode});if(!i.allowed)return{previewed:!1,refusal:i.refusal};let a=await DA(s,e.request,e.deleteMode),d=await Qr({act:"empty",target:r,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{},...xA(a.preview)}),c=await Df(s.store,i.org.id),u=e.checkpointFirst===!0&&s.checkpoints?await s.checkpoints.scope(Nf(s,a.preview,d.answer),{operationId:s.operationId}):void 0,l=s.requestsSent!==void 0?s.requestsSent()-n:void 0,p=$A(a,l,2,br(d.mute?.plan)),f={previewId:qN(s.now?.()??new Date),readAt:p.readAt,orgName:r,tier:i.tier,preview:p.preview,request:e.request,organizationId:i.org.id,access:p.access,hardDelete:{permitted:p.permissions.hardDelete,...p.permissions.unread!==void 0?{unread:p.permissions.unread}:{}},peopleActive:WN(p.people),...u?{checkpoint:u}:{},...c?{openRun:{runId:c.runId,startedAt:c.startedAt}}:{}},g=await jA(s,i.org.id,p,{deleteMode:e.deleteMode,acceptNoUndo:e.acceptNoUndo===!0,...e.acceptPeopleActive===!0?{peopleAccepted:!0}:{},automation:d.answer,...u?{checkpoint:u}:{},...c?{open:c.runId}:{}});return{previewed:!0,kept:f,automation:d.answer,refusals:g,...l!==void 0?{requestsSent:l}:{}}}function $A(s,e,t,r){let n=e??s.preview.cost.requests.reads;return{...s,preview:{...s.preview,cost:QI(s.preview.cost,n,t,r)}}}function qN(s){return mp(s).replace(/^em-/,"ep-")}function xA(s){let e=LN(s);return{objects:e.objects,writes:{steps:e.steps,written:e.written}}}async function DA(s,e,t){let{org:r}=s,n=Nc(r),o=await r.serverTime(),i=K({sobjects:Re(ca)}).loose().parse(await r.describeGlobal()).sobjects,a=await r.toolingObjects(),d=await MN(r),c=await yA({global:i,tooling:a,request:e,deleteMode:t,apiBudget:d.apiBudget,...d.bulkBatches?{bulkBatches:d.bulkBatches}:{},...d.dataStorageMB!==void 0?{dataStorageMB:d.dataStorageMB}:{},stopped:()=>s.signal?.aborted===!0},r),u=await ei(n),l=jf(c),p=new Set(i.filter(v=>v.customSetting===!0).map(v=>v.name)),f=await HI({permissions:u,objects:l,customSettings:l.filter(v=>p.has(v)),grants:async()=>RR(n,()=>r.userId()),describe:v=>FN(r,v)}),g=await r.userId(),h=new Date(Date.parse(o)-cp).toISOString(),m=await up(r,l,[g,...await AA(r)],h),y=s.voice==="page"?await GS(r,m):m;return{readAt:o,preview:c,permissions:u,access:f,people:y}}function WN(s){return{people:s.people.length,...s.atLeast?{atLeast:!0}:{},...s.who.length>0?{who:s.who.map(e=>({...e}))}:{},...s.unread.length>0?{unread:s.unread}:{}}}function NA(s){return s.voice==="page"?"page":"flags"}async function jA(s,e,t,r){let n=[],o=await s.runWriting?.(e);o!==void 0&&n.push({code:"RUN_WRITING",message:o}),r.open!==void 0&&n.push(EA(s.orgName,r.open)),t.preview.stopped&&n.push({code:"PREVIEW_STOPPED",message:`The simulation was stopped before every count was in: simulate again. ${zS}`}),r.deleteMode==="hard"&&!t.permissions.hardDelete&&n.push(dp(t.permissions));let i=lp(s.orgName,t.people,{...r.peopleAccepted!==void 0?{accepted:r.peopleAccepted}:{},voice:NA(s)});i&&n.push(i);let a=r.acceptNoUndo?void 0:UN(t.preview);a&&n.push(a),n.push(...HN(t.preview,s.orgName)),r.checkpoint?.refusal&&n.push({...r.checkpoint.refusal});let d=Tn(r.automation);return d&&n.push({code:d.code,message:d.message},...d.alsoRefused),n}function zN(s){let e=s.toISOString();return{runId:"",status:"success",hard:!1,passes:[],totals:{deleted:0,gone:0,refused:0,notReached:0},undo:{offered:!1,why:"nothingDeleted"},notes:["The org holds nothing the simulation would delete any more: nothing was sent."],startedAt:e,finishedAt:e}}function GN(s){return{mode:s.mode,...s.objects?{objects:[...s.objects]}:{},...s.excluded?{excluded:[...s.excluded]}:{},...s.customSettings!==void 0?{customSettings:s.customSettings}:{},...s.files!==void 0?{files:s.files}:{},...s.managedPackages!==void 0?{managedPackages:s.managedPackages}:{},...s.unrestorable!==void 0?{unrestorable:s.unrestorable}:{}}}function JN(s){return s.undoLost.filter(e=>e.records.records===void 0||e.records.records>0).map(e=>({objectApiName:e.objectApiName,...e.field!==void 0?{field:e.field}:{},...e.parent!==void 0?{parent:e.parent}:{},reason:e.reason,...e.records.records!==void 0?{records:e.records.records}:{},...e.records.atLeast===!0?{atLeast:!0}:{}}))}async function VN(s){let e=new Map,t=new Map;for await(let r of s.lines())if(r.kind==="spooled")e.set(r.objectApiName,r.count);else if(r.kind==="settled"){let n=t.get(r.objectApiName)??0;t.set(r.objectApiName,n+r.deleted.length+r.gone.length)}return s.head.passes.map(r=>{let n=e.get(r.objectApiName);return n===void 0?{objectApiName:r.objectApiName,records:r.sent??r.records??0,idsRead:!1}:{objectApiName:r.objectApiName,records:Math.max(0,n-(t.get(r.objectApiName)??0)),idsRead:!0}})}function XN(s){return s.reduce((e,t)=>({deleted:e.deleted+t.deleted,gone:e.gone+t.gone,refused:e.refused+t.refused,notReached:e.notReached+(t.notReached??0)}),{deleted:0,gone:0,refused:0,notReached:0})}async function MA(s,e){let{org:t,orgName:r}=s,n=s.now??(()=>new Date);if(!e.confirmed&&e.resumeRunId===void 0)throw new Error("An emptying acts on the simulation it was confirmed on, or takes up a run.");let o=s.requestsSent?.()??0,i=Nc(t),a=await co(i,{orgName:r,registered:s.registered,mode:e.confirmed?.request.mode??"objects"});if(!a.allowed)return{ran:!1,refusal:a.refusal};let d=a.org.id,c,u=await Df(s.store,d);if(e.resumeRunId!==void 0){if(!u||u.runId!==e.resumeRunId)return{ran:!1,refusal:{code:"RUN_GONE",message:`${e.resumeRunId} is not the last emptying of ${r} stopped part way: there is nothing of it to take up. ${lr}`}};if(c=u.journal,c.head.mode==="org"&&a.tier==="staging"){let O=await co(i,{orgName:r,registered:s.registered,mode:"org"});if(!O.allowed)return{ran:!1,refusal:O.refusal}}}else if(e.confirmed&&e.confirmed.organizationId.slice(0,15)!==d.slice(0,15))return{ran:!1,refusal:IA(r,["it is another org than the one the simulation read \u2014 a refreshed sandbox is a new org"])};let l=e.confirmed,p=c?c.head.deleteMode:l?.preview.deleteMode??"recycle",f=[],g,h,m,y;if(l){g=await DA(s,l.request,p);let O=[...BN(l.preview,g.preview),...BI(l.access,g.access).map(E=>`the user is no longer proven to see every record of ${E}`)];if(O.length>0&&f.push(IA(r,O)),g.preview.total.records===0&&g.preview.total.uncounted.length===0&&O.length===0)return{ran:!0,result:zN(n())};h=await Qr({act:"empty",target:r,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{},...xA(g.preview)}),e.checkpointFirst===!0&&(m=s.checkpoints?await s.checkpoints.scope(Nf(s,g.preview,h.answer),{operationId:s.operationId}):void 0,m||f.push({code:"CHECKPOINT_REFUSED",message:`Checkpoints cannot be taken from here: run without Checkpoint first. ${lr}`})),g=$A(g,s.requestsSent!==void 0?s.requestsSent()-o:void 0,1,br(h.mute?.plan)),f.push(...await jA(s,d,g,{deleteMode:p,acceptNoUndo:e.acceptNoUndo===!0,...e.acceptPeopleActive===!0?{peopleAccepted:(l.peopleActive.who??[]).map(E=>E.userId)}:{},automation:h.answer,...m?{checkpoint:m}:{},...u?{open:u.runId}:{}}))}else{let O=c.head,E=await ei(i);p==="hard"&&!E.hardDelete&&f.push(dp(E));let $=await s.runWriting?.(d);$!==void 0&&f.push({code:"RUN_WRITING",message:$});let H=O.passes.map(z=>z.objectApiName),J=await t.userId(),W=await t.serverTime(),Z=await up(t,H,[J,...await AA(t)],new Date(Date.parse(W)-cp).toISOString()),_=lp(r,Z,{...e.acceptPeopleActive===!0?{accepted:!0}:{},voice:NA(s)});_&&f.push(_);let Q=O.passes.map(z=>({objectApiName:z.objectApiName,records:z.sent??z.records??0})).filter(z=>z.records>0);h=await Qr({act:"empty",target:r,objects:Q,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{}});let N=Tn(h.answer);N&&f.push({code:N.code,message:N.message},...N.alsoRefused),y=KI(p,await VN(c),s.requestsSent!==void 0?s.requestsSent()-o:0,br(h.mute?.plan))}if(f.length>0)return ls(f);let v=l&&g?g.preview:void 0,b=v?v.total.records:c.head.passes.reduce((O,E)=>O+(E.records??0),0),k=v?jf(v):c.head.passes.map(O=>O.objectApiName),S=await s.askGuard({operation:p==="hard"?"hardDelete":"delete",objectNames:k,recordCount:b});if(S.decision==="refused"||S.decision==="declined")return ls([{code:"GUARD",message:S.decision==="refused"?`Production Guard refused the emptying: ${S.reason??"no reason given"}. ${lr}`:`The emptying was declined at Production Guard's confirmation. ${lr}`}],{guard:S.decision});let C=S.decision,R;if(m&&s.checkpoints&&v){let O=await s.checkpoints.take(Nf(s,v,h.answer),{operationId:s.operationId},{planned:m,...s.signal?{signal:s.signal}:{},onProgress:({percentage:E})=>s.onProgress?.(Math.round(E/10),`Taking the checkpoint first (${Math.round(E)}%)`)});if(!O.taken)return ls(["stopped"in O?{code:"CANCELLED",message:`The emptying was stopped while its checkpoint was taken. ${lr}`}:{code:O.refusal.code,message:O.refusal.message}],{guard:C});R=O.checkpoint}let w=async O=>{if(!R||R.state!=="taken"||!s.checkpoints)return R;try{return await s.checkpoints.settle(R,O)}catch{return R}},P=s.lock(d);if("busy"in P)return await w(!1),ls([TA(r,P.busy)],{guard:C});try{let O=await Df(s.store,d);if(!c&&O)return await w(!1),ls([EA(r,O.runId)],{guard:C});let E=await io(h,s.operationId,e.accord.acceptEmails===!0,s.voice);if("refused"in E)return await w(!1),ls([{code:E.refused.code,message:E.refused.message}],{guard:C});let $=E.held,H=n(),J=c??await s.store.begin(d,{runId:mp(H),orgName:r,startedAt:H.toISOString(),readAt:l.readAt,previewId:l.previewId,mode:v.mode,deleteMode:p,request:GN(l.request),passes:v.passes.map(ne=>({objectApiName:ne.objectApiName,...ne.records.records!==void 0?{records:ne.records.records}:{},...ne.sent.records!==void 0?{sent:ne.sent.records}:{},...ne.rows!==void 0?{rows:ne.rows}:{}})),toDraftAlong:v.toDraftAlong,beforeParent:v.beforeParent,...p==="recycle"?{undoLost:JN(v)}:{}}),W=v&&v.cost.api.verdict!=="unread"?Aa(v.cost.api).splitAllowance:void 0,Z,_,Q=[];try{Z=await bA({org:{deletion:t,ids:t},journal:J,resumed:c!==void 0,...s.signal?{signal:s.signal}:{},splitting:Ia(W),now:n,onProgress:({percentage:ne,step:ke})=>s.onProgress?.(ne,ke)})}catch(ne){throw await J.ended("failure",[],n()).catch(()=>{}),ne}finally{let ne=t.lostJobs?.()??[];if(ne.length>0&&t.stillRunning){let ke=await t.stillRunning(ne);ke.length>0&&Q.push(`${ke.length} Bulk API job(s) the org was still running after ten minutes: the mute was given back all the same, and what they delete from now on runs the org's automation.`)}$&&(_=await $.release(),Q.push(...Qt(_,r).map(ke=>ke.trim())))}let N=Z.passes,z=n();await J.ended(Z.status,N,z,Z.hardRefused);let oe=await w(Z.deletedAny),re=[];if(Z.status==="success"||Z.status==="partial")for(let ne of await s.store.runsOf(d))ne.runId>=J.head.runId||(await s.store.remove(d,ne.runId),re.push(ne.runId));let q=await J.state();return{ran:!0,result:{runId:J.head.runId,status:Z.status,hard:Z.hard,passes:N,totals:XN(N),...Z.hardRefused!==void 0?{hardRefused:Z.hardRefused}:{},undo:Z.hard?{offered:!1,why:"hard"}:q.deletedAny?{offered:!0}:{offered:!1,why:"nothingDeleted"},...c?{resumed:!0}:{},notes:[...Z.notes,...Z.changed?[Z.changed.message]:[],...Q],..._?{mutedAutomation:_}:{},...oe?{checkpoint:oe}:{},...re.length>0?{removedRuns:re}:{},...s.requestsSent!==void 0?{requestsSent:s.requestsSent()-o}:{},...y!==void 0?{requestsEstimate:y}:{},startedAt:H.toISOString(),finishedAt:z.toISOString()},guard:C}}finally{P.lock.release()}}async function LA(s,e){let{org:t,orgName:r}=s,n=s.now??(()=>new Date),o=s.requestsSent?.()??0,i=Nc(t),a=await co(i,{orgName:r,registered:s.registered,mode:"objects"});if(!a.allowed)return{ran:!1,refusal:a.refusal};let d=a.org.id,c=(k,S)=>({ran:!1,refusal:{code:k,message:`${S} Nothing was brought back.`}}),u;try{u=await s.store.open(d,e.runId)}catch(k){if(k instanceof Tr)return c("RUN_GONE",k.message);throw k}if((await s.store.lastOf(d))?.runId!==e.runId)return c("NOT_LAST_RUN",`${e.runId} is not the last emptying of ${r}: Undo reaches the last one alone, as what a later emptying deleted may hang from what this one did.`);let p=await u.state();if(u.head.deleteMode==="hard")return c("UNDO_UNAVAILABLE",`${e.runId} deleted for good: Salesforce brings back nothing a hard delete took, what went along included.`);if(p.undone)return c("UNDO_UNAVAILABLE",`${e.runId} was undone already.`);let f=await s.runWriting?.(d),g=[];f!==void 0&&g.push({code:"RUN_WRITING",message:f});let h=u.head.passes.map(k=>({objectApiName:k.objectApiName,records:k.records??0})),m=await Qr({act:"emptyUndo",target:r,objects:h,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{},writes:{steps:{bringBack:h.map(k=>k.objectApiName)},written:[]}}),y=Tn(m.answer);if(y&&g.push({code:y.code,message:y.message},...y.alsoRefused),g.length>0){let[k,...S]=g;return{ran:!1,refusal:k,...S.length>0?{alsoRefused:S}:{}}}let v=YI(await kA(u),s.requestsSent!==void 0?s.requestsSent()-o:0,br(m.mute?.plan)),b=s.lock(d);if("busy"in b)return{ran:!1,refusal:TA(r,b.busy)};try{let k=await io(m,s.operationId,e.accord.acceptEmails===!0,s.voice);if("refused"in k)return{ran:!1,refusal:{code:k.refused.code,message:k.refused.message}};let S,C;try{C=await OA({org:t,undelete:w=>t.undelete(w),journal:u,...s.signal?{signal:s.signal}:{},onProgress:({percentage:w,step:P})=>s.onProgress?.(w,P)})}finally{k.held&&(S=await k.held.release())}let R=n();return C.status!=="cancelled"&&await u.undone(C.status,R),{ran:!0,result:{runId:e.runId,status:C.status,objects:C.objects,notes:[...C.notes,...S?Qt(S,r).map(w=>w.trim()):[]],...S?{mutedAutomation:S}:{},...s.requestsSent!==void 0?{requestsSent:s.requestsSent()-o}:{},requestsEstimate:v,...C.previewedLost?{previewedLost:C.previewedLost}:{},finishedAt:R.toISOString()}}}finally{b.lock.release()}}function KN(s){let e=to(s),t={closed:!1};return{bulk:{bulk2:{createJob:r=>{let n=e.bulk2.createJob(r);return t={closed:!1},{get id(){return n.id},open:async()=>{await n.open();let o=ib(n);t={...o!==void 0?{jobId:o}:{},closed:!1}},uploadData:o=>n.uploadData(o),close:async()=>{await n.close(),t={...t,closed:!0}},abort:()=>n.abort(),check:()=>n.check(),getAllResults:()=>n.getAllResults()}}}},last:()=>t}}function FA(s,e,t){let r=oa(s),n=lb(s,t),o=KN(s),i=[],a=new jv(async(u,l)=>(await to(s).bulk2.job("ingest",{id:l}).check()).state),d=u=>async(l,p,f)=>{try{return await ub(o.bulk,l,p,f,u)}catch(g){let h=o.last();throw h.closed&&i.push({orgId:e,objectApiName:l,...h.jobId?{jobId:h.jobId}:{}}),g}},c=u=>({totalSize:u.totalSize,done:u.done,records:u.records,...u.nextRecordsUrl?{nextRecordsUrl:u.nextRecordsUrl}:{}});return{describe:u=>s.describe(u),count:async u=>(await s.query(u)).totalSize,countAll:async u=>(await s.query(u,{scanAll:!0})).totalSize,readIds:async(u,l)=>{let p=await s.query(u,{scanAll:l});return{totalSize:p.totalSize,ids:p.records.flatMap(f=>typeof f.Id=="string"?[f.Id]:[])}},query:async(u,l)=>c(await s.query(u,{scanAll:l?.scanAll===!0})),queryMore:async u=>c(await s.queryMore(u)),queryDeleted:u=>n.queryDeleted(u),describeGlobal:()=>s.describeGlobal(),toolingObjects:async()=>{try{return(await s.tooling.describeGlobal()).sobjects.map(u=>u.name)}catch{return[]}},serverTime:async()=>(await s.soap.getServerTimestamp()).timestamp,userId:async()=>(await s.soap.getUserInfo()).userId,limits:()=>s.request({method:"GET",url:"/limits"}),update:(u,l)=>n.update(u,l),destroy:(u,l)=>n.destroy(u,l),bulkDestroy:d("delete"),bulkHardDestroy:d("hardDelete"),undelete:u=>s.soap.undelete(u),lostJobs:()=>[...i],stillRunning:u=>a.stillRunning(u),requestsSent:r}}import{readdir as YN,readFile as QN,rm as _A,stat as UA,writeFile as ZN}from"node:fs/promises";import{join as jc}from"node:path";var BA=/^ep-\d{8}-\d{6}-[a-z0-9]{4}$/,ej=50;function Mc(s){return BA.test(s)}var HA=K({records:Te().optional(),unread:L().optional()}).loose(),tj=K({v:vt(1),orgId:L().min(1),kept:K({previewId:L().regex(BA),readAt:L(),orgName:L(),organizationId:L().min(15).max(18),request:K({mode:Be(["objects","org"])}).loose(),preview:K({mode:Be(["objects","org"]),deleteMode:Be(["recycle","hard"]),passes:Re(K({objectApiName:L(),records:HA}).loose()),along:Re(K({objectApiName:L(),records:HA}).loose()),undoLost:Re(K({objectApiName:L()}).loose()),total:K({records:Te()}).loose()}).loose(),access:K({kind:Be(["org","perObject"])}).loose(),peopleActive:K({people:Te(),who:Re(K({userId:L()}).loose()).optional()}).loose()}).loose()}),Lc=class{constructor(e,t=_a){this.root=e;this.keepMs=t}root;keepMs;async keep(e,t,r=Date.now()){if(!Mc(t.previewId))throw new Error(`Not a preview's id: ${t.previewId}`);await Ua(this.root),await ZN(jc(this.root,`${t.previewId}.json`),JSON.stringify({v:1,orgId:e,kept:t}),{mode:Fa}),await this.sweep(r)}async read(e,t=Date.now()){if(!Mc(e))return;let r=jc(this.root,`${e}.json`);try{if((await UA(r)).mtimeMs+this.keepMs<=t)return;let n=tj.safeParse(JSON.parse(await QN(r,"utf8")));return!n.success||n.data.kept.previewId!==e?void 0:{orgId:n.data.orgId,kept:n.data.kept}}catch{return}}async remove(e){Mc(e)&&await _A(jc(this.root,`${e}.json`),{force:!0})}async sweep(e){let t;try{t=await YN(this.root)}catch{return}let r=t.filter(o=>o.endsWith(".json")&&Mc(o.slice(0,-5))).sort(),n=Math.max(0,r.length-ej);for(let[o,i]of r.entries()){let a=jc(this.root,i);try{(o<n||(await UA(a)).mtimeMs+this.keepMs<=e)&&await _A(a,{force:!0})}catch{}}}};var nj=6e4,oj=20,ps="dataops",sj=new Set(["dataops:empty:scope","dataops:empty:preview","dataops:empty:run","dataops:empty:cancel","dataops:empty:undo"]),un=class extends Error{constructor(t,r=[],n){super(t.message);this.refusal=t;this.alsoRefused=r;this.mutedAutomation=n;this.name="EmptyRefused"}refusal;alsoRefused;mutedAutomation};function ij(s){return s.passes.filter(e=>e.deleted+e.refused+(e.notReached??0)>0).map(e=>({...bt(e.objectApiName),deleted:e.deleted,failed:e.refused,...(e.notReached??0)>0?{notSent:e.notReached}:{}}))}function aj(s){return s.objects.filter(e=>e.undeleted+e.notInBin+e.othersDeletion+e.refused>0).map(e=>({...bt(e.objectApiName),created:e.undeleted,failed:e.notInBin+e.othersDeletion+e.refused,...(e.notReached??0)>0?{notSent:e.notReached}:{}}))}function dj(s){return{previewId:s.previewId,readAt:s.readAt,orgName:s.orgName,tier:s.tier,preview:s.preview,access:s.access,hardDelete:s.hardDelete,peopleActive:s.peopleActive,...s.checkpoint?{checkpoint:s.checkpoint}:{},...s.openRun?{openRun:s.openRun}:{}}}var Fc=class{constructor(e){this.deps=e}deps;liveTracker;previews=new Map;running=new Map;writing=new Map;targetAutomation;muteLeases={};checkpoints;runWriting;stores;orgOf=(e,t)=>FA(e,t,"dataops:empty");setLiveOperationTracker(e){this.liveTracker=e}setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}setBeforeRunCheckpoints(e){this.checkpoints=e}setRunWriting(e){this.runWriting=e}setStores(e){this.stores=e}setOrgOf(e){this.orgOf=e}isWritingTo(e,t){for(let[r,n]of this.writing)if(n===e&&r!==t)return!0;return!1}async handle(e){if(!sj.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"dataops:empty:scope":return await this.handleScope(e),!0;case"dataops:empty:preview":return await this.handlePreview(e),!0;case"dataops:empty:run":return await this.handleRun(e),!0;case"dataops:empty:cancel":return this.handleCancel(e),!0;default:return await this.handleUndo(e),!0}}async countingReader(e){let{TargetAutomationReader:t,targetAutomationQueries:r}=await import("./chunk-UK3QLBHW.mjs");return new t(r(async n=>{let o=await B(n,this.deps.orgRegistry,this.deps.orgManager);return e(o),o}))}ownStores(){if(this.stores)return this.stores;let e=nR({root:tR()});if("refusal"in e)throw new un({code:"RUN_WRITING",message:`The lock of the org cannot be kept in ${e.refusal.path}. Nothing was read or deleted.`});let t=e.store;return this.stores={journals:new kd(yp()),previews:new Lc(rj(yp(),"previews")),lock:r=>t.lock(r,"empty")},this.stores}async contextOf(e,t,r,n,o){let i=this.deps.orgManager.getOrg(e),a=await B(e,this.deps.orgRegistry,this.deps.orgManager),d=we(i,e),c=this.ownStores(),u=this.orgOf(a,e),l=[],p,f=()=>this.targetAutomation?Promise.resolve(this.targetAutomation):(p??=this.countingReader(m=>l.push(oa(m))),p),g=Ma(r),h=this.runWriting?.(e,d,t);return{org:u,...u.requestsSent?{requestsSent:()=>(u.requestsSent?.()??0)+l.reduce((m,y)=>m+y(),0)}:{},orgId:e,orgName:d,username:i?.username??d,registered:i,store:c.journals,lock:c.lock,...h?{runWriting:h}:{},automation:Fo(a,async m=>{let y=await f();return new pe(nj).withTimeout("dataops automation",()=>y.read(e,m,{undeletes:!0}))},!1),muteLeases:this.muteLeases,...g?{voice:g}:{},...this.checkpoints?{checkpoints:this.checkpoints}:{},askGuard:async m=>{let y=this.deps.infraServices?.productionGuard;if(!y)return{decision:"refused",reason:ve.message};let{check:v,decision:b}=await et(y,{orgId:e,orgTier:Pe(i),operation:m.operation,objectName:m.objectNames.join(", "),recordCount:m.recordCount,module:ps});return{decision:b,...b==="refused"?{reason:v.blockedReason??v.impactSummary}:{}}},operationId:t,tool:"panel",...n?{signal:n}:{},...o?{onProgress:o}:{}}}fail(e,t,r){if(t instanceof un){T(this.deps,e.type,"dataops:error",e,t,{code:t.refusal.code,retryable:!1,...t.alsoRefused.length>0||t.mutedAutomation?{extraPayload:{...t.alsoRefused.length>0?{alsoRefused:[...t.alsoRefused]}:{},...t.mutedAutomation?{mutedAutomation:t.mutedAutomation}:{}}}:{}});return}T(this.deps,e.type,"dataops:error",e,t,{code:r})}respond(e,t,r){let n=A(this.deps,e,t,r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}async handleScope(e){let t=x(Ey,e,"dataops:error",this.deps);if(t)try{let{orgId:r,...n}=t,o=await this.contextOf(r,e.id,{}),i={query:l=>o.org.query(l)},a=await co(i,{orgName:o.orgName,registered:o.registered,mode:n.mode});if(!a.allowed)throw new un(a.refusal);let d=K({sobjects:Re(ca)}).loose().parse(await o.org.describeGlobal()).sobjects,c=Cc(d,await o.org.toolingObjects(),n),u=await ei(i);this.respond(e,"dataops:empty:scope:response",{mode:c.mode,objects:c.objects,leftOut:c.leftOut,candidates:c.worked,tier:a.tier,hardDelete:{permitted:u.hardDelete,...u.unread!==void 0?{unread:u.unread}:{}}})}catch(r){this.fail(e,r,"EMPTY_SCOPE_ERROR")}}previewStore(){return this.ownStores().previews}async keep(e,t){for(this.previews.set(t.previewId,{orgId:e,kept:t,at:Date.now()});this.previews.size>oj;){let r=this.previews.keys().next().value;if(r===void 0)break;this.previews.delete(r)}try{await this.previewStore()?.keep(e,t)}catch(r){this.deps.log(`[WARN] dataops:empty:preview: ${t.previewId} kept in this window alone (${r instanceof Error?r.message:String(r)})`)}}async keptPreview(e,t){let r=this.previews.get(t),n=r&&Date.now()-r.at<=_a?r:await this.previewStore()?.read(t);return n?.orgId===e?n.kept:void 0}async letGo(e){this.previews.delete(e),await this.previewStore()?.remove(e).catch(()=>{})}async handlePreview(e){let t=x(Py,e,"dataops:error",this.deps);if(!t)return;let r=new AbortController;this.running.set(e.id,r);try{let n=await this.contextOf(t.orgId,e.id,t,r.signal),o=await CA(n,{request:t.request,deleteMode:t.deleteMode,accord:t,...t.acceptNoUndo!==void 0?{acceptNoUndo:t.acceptNoUndo}:{},...t.acceptPeopleActive!==void 0?{acceptPeopleActive:t.acceptPeopleActive}:{},...t.checkpointFirst!==void 0?{checkpointFirst:t.checkpointFirst}:{}});if(!o.previewed)throw new un(o.refusal);await this.keep(t.orgId,o.kept),this.respond(e,"dataops:empty:preview:response",{...dj(o.kept),automation:o.automation,refusals:o.refusals,...o.requestsSent!==void 0?{requestsSent:o.requestsSent}:{}})}catch(n){this.fail(e,n,"EMPTY_PREVIEW_ERROR")}finally{this.running.delete(e.id)}}handleCancel(e){let t=x($y,e,"dataops:error",this.deps);if(!t)return;let r=this.running.get(t.operationId);r&&(this.deps.infraServices?.backgroundRegistry?.abort(t.operationId),r.abort()),this.respond(e,"dataops:empty:cancel:response",{operationId:t.operationId,cancelled:r!==void 0})}async writeAct(e,t,r,n,o,i,a){let d=e.id,c=this.deps.infraServices?.backgroundRegistry,u=new AbortController;this.running.set(d,u),this.writing.set(d,t);let l=()=>{},p=new Promise((h,m)=>{l=y=>y===void 0?h():m(y)});p.catch(()=>{}),Ge(this.deps,d,ps,r),c?.register(d,ps,r,p,u);let f=sr(this.liveTracker,d,ps,r),g=(h,m)=>{_e(this.deps,d,h,0,0,m),u.signal.aborted||c?.updateProgress(d,h),f.progress(h,0,0,m)};try{let h=await this.contextOf(t,d,a,u.signal,g),m=await n(h);if(!m.ran)throw o("stopped",{code:m.refusal.code,...m.guard?{guard:m.guard}:{}}),me(this.deps,d,{status:"refused",code:m.refusal.code}),f.fail(m.refusal.message),l(new Error(m.refusal.message)),new un(m.refusal,m.alsoRefused??[],m.mutedAutomation);let{result:y}=m;if(o(y.status,{result:y,...m.guard?{guard:m.guard}:{}}),await i(y),y.status==="cancelled")c?.abort(d),me(this.deps,d,{aborted:!0}),f.cancel(),l();else if(y.status==="failure"){let v="Nothing the emptying set out to do went through: its result says why.";me(this.deps,d,{status:y.status}),f.fail(v),l(new Error(v))}else me(this.deps,d,{status:y.status}),y.status==="success"?f.complete():f.partial(),l()}catch(h){throw h instanceof un||(o("failure",{}),me(this.deps,d,{status:"failure"}),f.fail(h instanceof Error?h.message:String(h)),l(h)),h}finally{this.running.delete(d),this.writing.delete(d)}}async handleRun(e){let t=x(Cy,e,"dataops:error",this.deps);if(t)try{let r;if(t.previewId!==void 0&&(r=await this.keptPreview(t.orgId,t.previewId),!r))throw new un({code:"PREVIEW_GONE",message:"The simulation this emptying was confirmed on is no longer kept on this machine \u2014 a simulation is kept a day: simulate again, then empty. Nothing was read or deleted."});let n=o=>({empty:"run",...r?{mode:r.preview.mode,deleteMode:r.preview.deleteMode}:{},...t.resumeRunId!==void 0?{resumes:t.resumeRunId}:{},...o?{runId:o.runId,hard:o.hard,gone:o.totals.gone,...o.status==="cancelled"?{cancelled:!0}:{}}:{}});await this.writeAct(e,t.orgId,t.resumeRunId!==void 0?`Taking up the emptying ${t.resumeRunId}`:`Emptying ${r?.preview.total.objects??0} object(s) of ${r?.orgName??t.orgId}`,o=>MA(o,{...r?{confirmed:r}:{},...t.resumeRunId!==void 0?{resumeRunId:t.resumeRunId}:{},accord:t,...t.acceptNoUndo!==void 0?{acceptNoUndo:t.acceptNoUndo}:{},...t.acceptPeopleActive!==void 0?{acceptPeopleActive:t.acceptPeopleActive}:{},...t.checkpointFirst!==void 0?{checkpointFirst:t.checkpointFirst}:{}}),(o,i)=>Y(this.deps,{action:"cleanup_delete",module:ps,operationId:e.id,orgId:t.orgId,outcome:o,...i.guard?{guard:i.guard}:{},...i.code!==void 0?{code:i.code}:{},...i.result?{objects:ij(i.result)}:{},...i.result?.mutedAutomation?{muted:ft(i.result.mutedAutomation)}:{},...i.result?.checkpoint?.state==="taken"?{checkpointId:i.result.checkpoint.checkpointId}:{},details:n(i.result)}),async o=>{t.previewId!==void 0&&await this.letGo(t.previewId),this.respond(e,"dataops:empty:run:response",{operationId:e.id,result:o})},t)}catch(r){this.fail(e,r,"EMPTY_RUN_ERROR")}}async handleUndo(e){let t=x(xy,e,"dataops:error",this.deps);if(t)try{await this.writeAct(e,t.orgId,`Undoing the emptying ${t.runId}`,r=>LA(r,{runId:t.runId,accord:t}),(r,n)=>Y(this.deps,{action:"empty_undo",module:ps,operationId:e.id,orgId:t.orgId,outcome:r,...n.code!==void 0?{code:n.code}:{},...n.result?{objects:aj(n.result)}:{},...n.result?.mutedAutomation?{muted:ft(n.result.mutedAutomation)}:{},details:{empty:"undo",runId:t.runId}}),r=>this.respond(e,"dataops:empty:undo:response",{operationId:e.id,result:r}),t)}catch(r){this.fail(e,r,"EMPTY_UNDO_ERROR")}}};import{userInfo as hj}from"node:os";var qA=6e4,cj=2*6e4,uj=50,lj=2880*6e4,pj=60*6e4,fj=250,WA="pipeline-triggers",gj=K({cron:L().optional(),timezone:L().optional(),nextRunAt:Te().optional(),lastFiredAt:Te().optional(),lastOutcome:Be(["started","missed"]).optional()});function Ai(s,e){return`pipeline-trigger:${s}:${e}`}var _c=class{constructor(e){this.deps=e;this.now=e.now??(()=>Date.now()),this.newId=e.newId??(()=>globalThis.crypto.randomUUID())}deps;engine=new YS;now;newId;timer;started=!1;firstLook=!0;looking;lookAgain=!1;lastPrune=0;soonest;busyMisses=new Map;refusedMisses=new Map;unscheduled=new Map;start(){this.started||(this.started=!0,this.firstLook=!0,this.deps.log("[pipeline-triggers] started"),this.look())}stop(){this.started&&(this.started=!1,clearTimeout(this.timer),this.timer=void 0,this.deps.log("[pipeline-triggers] stopped"))}reload(){return this.started?this.look():Promise.resolve()}async onSandboxRefresh(e){if(!this.started)return;let t=this.deps.org(e.orgId);for(let r of this.deps.pipelines())for(let n of this.triggersOf(r)){if(!this.engine.firesOnRefreshOf(n,e.orgId)||this.engine.idleReason(n,t)||!this.deps.claims.claim(`refresh:${r.id}:${n.id}:${e.key}`))continue;let o=this.now(),i=await this.problemsOf(r);if(i.length>0){this.refuseStart(r,n,"sandbox_refresh",o,i,{sandboxName:t?.name});continue}this.fire(r,n,"sandbox_refresh",o,t?.name)}}async statuses(){let e=[],t=this.now();for(let r of this.deps.pipelines()){let n=this.triggersOf(r),o;for(let i of n){let a=this.read(r.id,i.id),d=i.type,c={pipelineId:r.id,triggerId:i.id,type:d,armed:!1,...a.lastFiredAt!==void 0?{lastFiredAt:new Date(a.lastFiredAt).toISOString(),...a.lastOutcome?{lastOutcome:a.lastOutcome}:{}}:{},...d==="schedule"?{timezone:this.engine.timezoneOf(i)}:{}},u=this.engine.idleReason(i,this.orgOf(i),t);u||(o??=await this.problemsOf(r),o.length>0&&(u={idle:"cannotRun",detail:o.join(" ")})),!u&&!this.started&&(u={idle:"stopped"});let l;if(!u&&d==="schedule"){let p=this.planOf(i,a)??this.engine.nextRun(i,t);typeof p=="number"?l=p:u=p}e.push(u?{...c,idle:u.idle,...u.detail?{detail:u.detail}:{}}:{...c,armed:!0,...l!==void 0?{nextRunAt:new Date(l).toISOString()}:{}})}}return e}look(){return this.looking?(this.lookAgain=!0,this.looking):(this.looking=this.lookNow().catch(e=>{this.deps.log(`[pipeline-triggers] a look failed: ${I(e)}`)}).finally(()=>{this.looking=void 0,this.lookAgain?(this.lookAgain=!1,this.look()):this.arm()}),this.looking)}async lookNow(){if(!this.started)return;let e=this.now(),t=this.firstLook;this.firstLook=!1,e-this.lastPrune>=pj&&(this.lastPrune=e,this.deps.claims.prune(lj));let r=new Set,n=new Set,o;for(let i of this.deps.pipelines()){n.add(i.id);let a;for(let d of this.triggersOf(i)){r.add(Ai(i.id,d.id));let c=this.engine.idleReason(d,this.orgOf(d),e);if(c||(a??=await this.problemsOf(i)),d.type!=="schedule")continue;let u=c?this.unplan(i,d):this.lookAt(i,d,e,t,a??[]);u!==void 0&&(o===void 0||u<o)&&(o=u)}this.sayWhyUnscheduled(i,a)}for(let i of[...this.unscheduled.keys()])n.has(i)||this.unscheduled.delete(i);this.soonest=o,this.forgetAllBut(r)}sayWhyUnscheduled(e,t){if(t===void 0)return;let r=this.unscheduled.get(e.id);if(t.length===0){if(r===void 0)return;this.unscheduled.delete(e.id),this.deps.log(`[pipeline-triggers] "${e.name}" can run again: its triggers start it`);return}let n=t.join(" ");r!==n&&(this.unscheduled.set(e.id,n),this.deps.log(`[pipeline-triggers] "${e.name}" is not scheduled: its triggers start nothing while a step cannot run. ${n}`))}lookAt(e,t,r,n,o){let i=this.read(e.id,t.id),a=this.planOf(t,i);if(a===void 0)return this.plan(e,t,i,r);if(a>r)return a;let d=this.engine.dueBetween(t,a,r,uj),c=[a,...d.times],u=c[c.length-1],l=!n&&r-u<=cj?u:void 0,p=l===void 0?c:c.slice(0,-1),f=this.plan(e,t,i,r),g=p.filter(h=>this.deps.claims.claim(this.dueKey(e,t,h)));if(g.length>0){let h={reason:n?"closed":"asleep",count:g.length,...g.length>1?{lastDueAt:new Date(g[g.length-1]).toISOString()}:{},...d.more?{atLeast:!0}:{}};this.recordMissed(e,"schedule",g[0],h),this.remember(e,t,{lastFiredAt:g[g.length-1],lastOutcome:"missed"}),this.deps.report({kind:"missed",pipelineName:e.name,triggeredBy:"schedule",dueAt:new Date(g[0]).toISOString(),missed:h,...f!==void 0?{nextRunAt:new Date(f).toISOString()}:{}})}return l!==void 0&&this.deps.claims.claim(this.dueKey(e,t,l))&&(o.length>0?this.refuseStart(e,t,"schedule",l,o,{...f!==void 0?{nextRunAt:new Date(f).toISOString()}:{}}):this.fire(e,t,"schedule",l)),f}refuseStart(e,t,r,n,o,i){let a=o.join(" "),d=Ai(e.id,t.id),c=r==="schedule"?this.refusedMisses.get(d):void 0,u=c&&c.detail===a?{...c,count:c.count+1}:{runId:`missed-${this.newId()}`,detail:a,firstDueAt:n,count:1};r==="schedule"&&this.refusedMisses.set(d,u);let l={reason:"cannotRun",count:u.count,...u.count>1?{lastDueAt:new Date(n).toISOString()}:{},detail:a};this.recordMissed(e,r,u.firstDueAt,l,u.runId),this.remember(e,t,{lastFiredAt:n,lastOutcome:"missed"}),!(u.count>1)&&this.deps.report({kind:"missed",pipelineName:e.name,triggeredBy:r,dueAt:new Date(n).toISOString(),missed:l,...i})}dueKey(e,t,r){return`due:${e.id}:${t.id}:${r}`}fire(e,t,r,n,o){let i=Ai(e.id,t.id);this.refusedMisses.delete(i);let a=this.deps.start(e,r);if(a.started){this.busyMisses.delete(i),this.remember(e,t,{lastFiredAt:n,lastOutcome:"started"}),this.deps.log(`[pipeline-triggers] started "${e.name}" (${r})`),a.run.then(l=>{l?.status==="failed"&&this.deps.report({kind:"failed",pipelineName:e.name,triggeredBy:r,error:l.error??"the run failed",...o?{sandboxName:o}:{}})},l=>{this.deps.report({kind:"failed",pipelineName:e.name,triggeredBy:r,error:I(l),...o?{sandboxName:o}:{}})});return}let d=this.busyMisses.get(i),c=d&&d.busySince===a.busy.startedAt?{...d,count:d.count+1,lastDueAt:n}:{runId:`missed-${this.newId()}`,busySince:a.busy.startedAt,firstDueAt:n,count:1,lastDueAt:n};this.busyMisses.set(i,c);let u={reason:"busy",count:c.count,busySince:c.busySince,...c.count>1?{lastDueAt:new Date(c.lastDueAt).toISOString()}:{}};this.recordMissed(e,r,c.firstDueAt,u,c.runId),this.remember(e,t,{lastFiredAt:n,lastOutcome:"missed"}),this.deps.log(`[pipeline-triggers] "${e.name}" not started (${r}): a run started at ${a.busy.startedAt} is going`),c.count===1&&this.deps.report({kind:"missed",pipelineName:e.name,triggeredBy:r,dueAt:new Date(n).toISOString(),missed:u,...o?{sandboxName:o}:{}})}recordMissed(e,t,r,n,o=`missed-${this.newId()}`){this.deps.record({runId:o,pipelineId:e.id,pipelineName:e.name,status:"missed",triggeredBy:t,startTime:new Date(r).toISOString(),duration:0,stepCount:0,errorCount:0,missed:n})}planOf(e,t){return t.cron===(e.config.cron??"").trim()&&t.timezone===this.engine.timezoneOf(e)?t.nextRunAt:void 0}plan(e,t,r,n){let o=this.engine.nextRun(t,n),i=typeof o=="number"?o:void 0;return this.write(e.id,t.id,{...r,cron:(t.config.cron??"").trim(),timezone:this.engine.timezoneOf(t),nextRunAt:i}),i}unplan(e,t){let r=this.read(e.id,t.id);(r.nextRunAt!==void 0||r.cron!==void 0)&&this.write(e.id,t.id,{...r.lastFiredAt!==void 0?{lastFiredAt:r.lastFiredAt}:{},...r.lastOutcome?{lastOutcome:r.lastOutcome}:{}})}remember(e,t,r){this.write(e.id,t.id,{...this.read(e.id,t.id),...r})}forgetAllBut(e){for(let t of Object.keys(this.deps.store.getByCategory(WA)))e.has(t)||this.deps.store.delete(t)}arm(){if(clearTimeout(this.timer),this.timer=void 0,!this.started)return;let e=this.soonest===void 0?qA:this.soonest-this.now(),t=Math.min(Math.max(e,fj),qA);this.timer=setTimeout(()=>{this.look()},t),this.timer.unref?.()}triggersOf(e){return(Array.isArray(e.triggers)?e.triggers:[]).flatMap(r=>{let n=KS.safeParse(r);if(!n.success)return[];let o=n.data;return o.type==="schedule"||o.type==="sandbox_refresh"?[o]:[]})}orgOf(e){let t=e.config.orgId;return e.type==="sandbox_refresh"&&t?this.deps.org(t):void 0}async problemsOf(e){try{return await this.deps.problems(e)}catch(t){return[`The saved pipeline cannot be read: ${I(t)}.`]}}read(e,t){let r=gj.safeParse(this.deps.store.get(Ai(e,t)));return r.success?r.data:{}}write(e,t,r){this.deps.store.set(Ai(e,t),r,WA)}};function fs(){let s=new Map,e=new Map;return{claim(t){return s.has(t)?!1:(s.set(t,Date.now()),!0)},hold(t,r){let n=e.get(t);return n?{busy:n}:(e.set(t,r),{release:()=>{e.delete(t)}})},prune(t){let r=Date.now()-t;for(let[n,o]of s)o<r&&s.delete(n)}}}var NJ=65*6e4;var zA=[{id:"tpl-sandbox-refresh",name:"Sandbox Refresh",description:"Full sandbox refresh: backup data, seed test data, verify deployment.",category:"environment",steps:[{name:"Backup Target Data",type:"dataops:backup",description:"Export current target data before refresh."},{name:"Seed Test Data",type:"seed:execute",description:"Generate and insert test data from templates."},{name:"Verify Deployment",type:"compare:execute",description:"Compare metadata between source and target."}]},{id:"tpl-data-migration-dry",name:"Migration Pre-flight Check",description:"Describe source objects, deltas, field mappings and conflicts for a migration (steps do not run yet).",category:"migration",steps:[{name:"Describe Source Objects",type:"sync:describe-global",description:"List all queryable objects in source."},{name:"Detect Deltas",type:"sync:delta",description:"Identify new, modified, and deleted records."},{name:"Validate Field Mappings",type:"sync:describe-fields",description:"Verify field compatibility between orgs."},{name:"List Conflicts",type:"sync:preview",description:"List conflicts between source and target records."}]},{id:"tpl-nightly-cleanup",name:"Nightly Cleanup",description:"Scheduled cleanup: anonymize stale data, archive old records, refresh monitoring.",category:"maintenance",steps:[{name:"Anonymize PII",type:"dataops:anonymize",description:"Apply GDPR anonymization rules to sensitive data."},{name:"Archive Old Records",type:"dataops:backup",description:"Backup and archive records older than 90 days."},{name:"Refresh Monitor",type:"monitor:refresh",description:"Refresh org health and limit data."}]}];function Mf(s,e){return`${s}\0${e}`}var Uc=class{constructor(e){this.deps=e}deps;waiting=new Map;get canAsk(){return this.deps.ask!==void 0}ask(e,t){let r=this.deps.now??(()=>new Date),n=Mf(e.operationId,e.stepId),o={...e,expiresAt:new Date(r().getTime()+e.timeoutMs).toISOString()};return new Promise(i=>{let a=u=>{this.waiting.get(n)?.settle===a&&(this.waiting.delete(n),clearTimeout(c),t?.removeEventListener("abort",d),i(u))},d=()=>a({decision:"cancelled",at:r().toISOString()}),c=setTimeout(()=>a({decision:"timedOut",at:r().toISOString()}),e.timeoutMs);if(this.waiting.set(n,{question:o,settle:a}),t?.aborted){d();return}t?.addEventListener("abort",d,{once:!0}),this.deps.announce?.(o),this.deps.ask?.(o).then(u=>{if(u===void 0)return;let l=typeof u=="string"?{decision:u,via:void 0}:u,p=l.decision==="approve"?"approved":"rejected",f=l.via??"notification";this.answer(e.operationId,e.stepId,p,f)||this.deps.tooLate?.(o)},()=>{})})}answer(e,t,r,n){let o=this.waiting.get(Mf(e,t));if(!o)return!1;let i=this.deps.now??(()=>new Date),a=this.deps.who?.();return o.settle({decision:r,via:n,at:i().toISOString(),...a?{by:a}:{}}),!0}isWaiting(e,t){return this.waiting.has(Mf(e,t))}};var GA=50,KA={manual:"by hand",schedule:"by its schedule",sandbox_refresh:"by a sandbox refresh",event:"by an event",webhook:"by a webhook",deployment_complete:"by a deployment"};function mj(s,e){return`Pipeline "${s}" is already running: the run started ${KA[e.triggeredBy]} at ${e.startedAt} has not ended. A pipeline runs once at a time.`}function yj(s){return{stepName:s.stepName,stepType:s.stepType,status:s.status,...s.duration!==void 0?{duration:s.duration}:{},...s.summary!==void 0?{summary:s.summary}:{},...s.error!==void 0?{error:s.error}:{},...s.approval!==void 0?{approval:s.approval}:{}}}var wj={approved:"success",rejected:"stopped",timedOut:"stopped",cancelled:"cancelled"};function JA(){try{return Zh(hj().username)}catch{return}}function bj(s,e){let t=s,r=0,n=!1,o=!1,i,a=()=>{o||(o=!0,e())},d=()=>{r=Date.now(),i=setTimeout(a,t)};return{start(){n||(n=!0,d())},hold(){i!==void 0&&(clearTimeout(i),i=void 0,t=Math.max(0,t-(Date.now()-r)))},resume(){!n||o||i!==void 0||d()},end(){o=!0,clearTimeout(i),i=void 0}}}var VA="A simulation of a pipeline is not available here: nothing ran. Run it, or simulate it again once SandForge has finished starting.",XA={release:()=>{}};function Lf(s){return s.flatMap(e=>e.type==="rewind"&&typeof e.id=="string"&&e.id!==""?[{id:e.id,config:typeof e.config=="object"&&e.config!==null?e.config:{}}]:[])}var Rj=new Set(["pipeline:execute","pipeline:templates","pipeline:list","pipeline:history","pipeline:save","pipeline:delete","pipeline:approval","pipeline:sync-configs","pipeline:seed-templates","pipeline:masking-templates","pipeline:rewind-steps","pipeline:rewind-grant","pipeline:rewind-revoke","pipeline:export","marketplace:list","marketplace:install"]),Hc=class{constructor(e){this.deps=e}deps;pipelineMarketplace;stepRunners;claims=fs();scheduler;reportTrigger=()=>{};approvalGate;unreadableSaid=new Map;liveTracker;dryRunApplier;pipelinesRootOverride;commandLineHistory;sandforgeVersion;setDryRunApplier(e){this.dryRunApplier=e}setPipelinesRoot(e){this.pipelinesRootOverride=e,this.commandLineHistory=void 0}setSandforgeVersion(e){this.sandforgeVersion=e}pipelinesRoot(){return this.pipelinesRootOverride??hk()}takeRunLock(e,t,r){if(typeof e.id!="string"||e.id==="")return XA;try{let n=yk(this.pipelinesRoot(),e.id,{pipelineName:e.name,ranFrom:this.deps.services?.runsFrom==="commandLine"?"commandLine":"editor",triggeredBy:t,...r?{dryRun:!0}:{}});return"busy"in n?n:(n.tookOver&&this.deps.log(`[INFO] ${bk(n.tookOver)}`),n.lock)}catch(n){return this.deps.log(`[WARN] the run lock of pipeline "${e.name}" could not be taken (${I(n)}): a run from the command line is not kept apart from this one.`),XA}}setLiveOperationTracker(e){this.liveTracker=e}approvals(){let e=this.deps.services;return this.approvalGate??=new Uc({...e?.askApproval?{ask:e.askApproval}:{},announce:t=>this.postStepUpdate({operationId:t.operationId,stepId:t.stepId,status:"running",approval:{...t.message?{message:t.message}:{},expiresAt:t.expiresAt}}),tooLate:t=>e?.approvalTooLate?.(t),who:JA}),this.approvalGate}async askApproval(e,t,r){r.holdBudget(!0);try{let n=await this.approvals().ask({...e,operationId:r.operationId},t);return r.dryRun||this.recordApproval(e,n,r.operationId),n}finally{r.holdBudget(!1)}}async untimed(e,t){t.holdBudget(!0);try{return await e()}finally{t.holdBudget(!1)}}rewindGrants(){return new ti(this.deps.configStore)}async runSyncUntimed(e,t,r,n,o){o.holdBudget(!0);try{return await e(t,r,n)}finally{o.holdBudget(!1)}}recordApproval(e,t,r){try{if(!(this.deps.services?.getSandforgeSetting?.("safety.auditLogging",!0)!==!1))return;new $o(this.deps.configStore).append({id:crypto.randomUUID(),action:"pipeline_approval",module:"automation",operationId:r,outcome:wj[t.decision],objects:[],details:{pipeline:e.pipelineName??"",step:e.stepName,decision:t.decision,...t.via?{via:t.via}:{},...t.by?{answeredBy:t.by}:{}},timestamp:t.at})}catch(n){this.deps.log(`[WARN] audit trail: approval of run ${r} was not recorded \u2014 ${I(n)}`)}}setPipelineMarketplace(e){this.pipelineMarketplace=e}setStepRunners(e){this.stepRunners=e}startTriggers(e){e.claims&&(this.claims=e.claims),this.reportTrigger=e.report,this.triggerScheduler().start()}stopTriggers(){this.scheduler?.stop()}noticeSandboxRefresh(e){return this.scheduler?.onSandboxRefresh(e)??Promise.resolve()}triggerScheduler(){return this.scheduler??=new _c({pipelines:()=>this.savedPipelines(),problems:e=>this.pipelineProblems(e),org:e=>{let t=this.deps.orgManager.getOrg(e);return t?{name:we(t,t.id),sandbox:t.orgType==="Sandbox"}:void 0},start:(e,t)=>this.startTriggeredRun(e,t),record:e=>this.recordEntry(e),store:this.deps.configStore,claims:{claim:e=>this.claims.claim(e),hold:(e,t)=>this.claims.hold(e,t),prune:e=>this.claims.prune(e)},report:e=>this.reportTrigger(e),log:this.deps.log}),this.scheduler}savedPipelines(){let e=this.deps.configStore.getByCategory("pipelines"),t=new Map,r=Object.entries(e).flatMap(([n,o])=>{let i=Oa.safeParse(o);return i.success?[i.data]:(t.set(n,El(i.error)),[])});for(let[n,o]of t){if(this.unreadableSaid.get(n)===o)continue;let i=e[n]?.name;this.deps.log(`[pipeline-triggers] saved pipeline ${typeof i=="string"?`"${i}"`:n} is not scheduled: it does not read as a pipeline (${o}).`)}this.unreadableSaid.clear();for(let[n,o]of t)this.unreadableSaid.set(n,o);return r}async pipelineProblems(e){return(await this.buildOrchestrator(void 0,e)).check(e)}startTriggeredRun(e,t){let r=this.claims.hold(e.id,{startedAt:new Date().toISOString(),triggeredBy:t});if("busy"in r)return{started:!1,busy:r.busy};let n=this.takeRunLock(e,t,!1);if("busy"in n)return r.release(),this.deps.log(`[pipeline-triggers] ${Rp(n.busy,e.name)}`),{started:!1,busy:{startedAt:n.busy.acquiredAt,triggeredBy:n.busy.triggeredBy}};let o=`${Qg}${crypto.randomUUID()}`;return{started:!0,run:this.runPipeline(e,{},t,o).catch(a=>{throw this.deps.log(`[ERR] ${t} run of "${e.name}": ${I(a)}`),Le(this.deps,o,I(a),!1,{context:{module:"automation",operation:"pipeline:execute"}}),a}).finally(()=>{n.release(),r.release()})}}async handle(e){if(!Rj.has(e.type))return!1;switch(e.type){case"pipeline:execute":return await this.handlePipelineRun(e),!0;case"pipeline:templates":return this.handlePipelineTemplates(e),!0;case"pipeline:list":return await this.handlePipelineList(e),!0;case"pipeline:history":return this.handlePipelineHistory(e),!0;case"pipeline:save":return this.handlePipelineSave(e),!0;case"pipeline:delete":return this.handlePipelineDelete(e),!0;case"pipeline:approval":return this.handlePipelineApproval(e),!0;case"pipeline:sync-configs":return this.handleSyncConfigs(e),!0;case"pipeline:seed-templates":return this.handleSeedTemplates(e),!0;case"pipeline:masking-templates":return this.handleMaskingTemplates(e),!0;case"pipeline:rewind-steps":return await this.handleRewindSteps(e),!0;case"pipeline:rewind-grant":return await this.handleRewindGrant(e),!0;case"pipeline:rewind-revoke":return this.handleRewindRevoke(e),!0;case"pipeline:export":return await this.handlePipelineExport(e),!0;case"marketplace:list":return this.handleMarketplaceList(e),!0;case"marketplace:install":return this.handleMarketplaceInstall(e),!0;default:return!1}}async handlePipelineRun(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Uw,e,"pipeline:error",this.deps);if(!t)return;let r=t,n=e.id,o={module:"automation",operation:e.type},i=r.pipeline,a=r.dryRun===!0;if(a&&(!this.dryRunApplier||!this.stepRunners)){T(this.deps,"pipeline:execute","pipeline:error",e,new Error(VA),{code:"DRY_RUN_UNAVAILABLE",retryable:!0});return}let d=typeof i.id=="string"&&i.id!==""?this.claims.hold(i.id,{startedAt:new Date().toISOString(),triggeredBy:"manual"}):{release:()=>{}};if("busy"in d){T(this.deps,"pipeline:execute","pipeline:error",e,new Error(mj(i.name,d.busy)),{code:"PIPELINE_RUNNING",retryable:!0});return}let c=this.takeRunLock(i,"manual",a);if("busy"in c){d.release(),T(this.deps,"pipeline:execute","pipeline:error",e,new Error(Rp(c.busy,i.name)),{code:"PIPELINE_RUNNING",retryable:!0});return}try{let u=await this.runPipeline(i,r.variables??{},"manual",n,{dryRun:a}),l=A(this.deps,e,"pipeline:run:response",{...u,...a?{dryRun:!0}:{}});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`)}catch(u){T(this.deps,"pipeline:execute","pipeline:error",e,u),Le(this.deps,n,I(u),!1,{context:o})}finally{c.release(),d.release()}}handlePipelineApproval(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(zw,e,"pipeline:error",this.deps);if(!t)return;this.approvals().answer(t.operationId,t.stepId,t.decision,"page")||this.deps.log(`[WARN] pipeline:approval for a step that no longer waits: ${t.stepId}`)}async checkpointsOf(e){let t=new Map,r=this.stepRunners?.readCheckpoint;if(!e||!r)return t;for(let n of Lf(e.steps)){let o=xt.safeParse(n.config);if(!(!o.success||t.has(o.data.checkpointId)))try{t.set(o.data.checkpointId,await r(o.data.checkpointId))}catch(i){this.deps.log(`[WARN] checkpoint ${o.data.checkpointId} not read for a check: ${I(i)}`)}}return t}async revokeVoidGrants(){try{let e=this.stepRunners?.readCheckpoint,t=await this.rewindGrants().revokeVoid(e?async r=>(await e(r)).kept:void 0);for(let r of t)this.deps.log(`[INFO] the confirmation of Rewind step ${r.stepId} of pipeline ${r.pipelineId} was taken back: its pipeline is no longer saved, or its checkpoint ${r.checkpointId} is no longer kept`)}catch(e){this.deps.log(`[WARN] confirmations of Rewind steps not checked: ${I(e)}`)}}savedPipeline(e){let t=Oa.safeParse(this.deps.configStore.get(`pipeline:saved:${e}`));return t.success?t.data:void 0}async describeRewindStep(e,t){let r=this.stepRunners,n=xt.safeParse(t.config),o=n.success&&r?.readCheckpoint?await r.readCheckpoint(n.data.checkpointId):void 0,i=this.rewindGrants().get(e,t.id),a=i?{grantedAt:i.grantedAt,matches:i.takenBackAt===void 0&&ri(t.config)===i.digest}:void 0;return r?{info:nO(r,t,o,a),...o?{checkpoint:o}:{}}:{info:{stepId:t.id,valid:!1,why:"missing",...a?{granted:{at:a.grantedAt,digestMatches:a.matches}}:{}}}}async handleRewindSteps(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Gw,e,"pipeline:error",this.deps);if(t)try{let r=this.savedPipeline(t.pipelineId),n=[];for(let i of Lf(r?.steps??[]))n.push((await this.describeRewindStep(t.pipelineId,i)).info);let o=A(this.deps,e,"pipeline:rewind-steps:response",{pipelineId:t.pipelineId,steps:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} (${n.length} Rewind steps)`)}catch(r){T(this.deps,"pipeline:rewind-steps","pipeline:error",e,r)}}async handleRewindGrant(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Jw,e,"pipeline:error",this.deps);if(!t)return;let{pipelineId:r,stepId:n,typed:o}=t,i=d=>{let c=A(this.deps,e,"pipeline:rewind-grant:response",d);this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} ${d.granted?"granted":`refused ${d.code}`}`)},a=(d,c={})=>i({granted:!1,pipelineId:r,stepId:n,code:d,...c.why!==void 0?{why:c.why}:{},...c.reason!==void 0?{reason:c.reason}:{}});try{let d=this.savedPipeline(r),c=Lf(d?.steps??[]).find(h=>h.id===n);if(!c)return a("NOT_SAVED");let u=xt.safeParse(c.config);if(!u.success)return a("CONFIG_INVALID",{reason:u.error.issues[0]?.message??""});let l=this.deps.orgManager.getOrg(u.data.orgId);if(!l)return a("ORG_UNKNOWN");if(o!==we(l))return a("TYPED_MISMATCH");let{info:p,checkpoint:f}=await this.describeRewindStep(r,c);if(!p.valid)return a("CHECKPOINT_INVALID",{why:p.why??"missing"});if(!f?.kept||f.organizationId===void 0)return a("CHECKPOINT_INVALID",{why:"missing"});let g=JA();this.rewindGrants().write({pipelineId:r,stepId:n,organizationId:f.organizationId,checkpointId:u.data.checkpointId,digest:ri(c.config)??"",grantedAt:new Date().toISOString(),...g!==void 0?{grantedBy:g}:{}}),this.deps.log(`[INFO] pipeline:rewind-grant: Rewind step ${n} of pipeline ${r} confirmed for ${we(l)}, to checkpoint ${u.data.checkpointId}`),i({granted:!0,pipelineId:r,stepId:n,step:(await this.describeRewindStep(r,c)).info})}catch(d){T(this.deps,"pipeline:rewind-grant","pipeline:error",e,d)}}handleRewindRevoke(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Vw,e,"pipeline:error",this.deps);if(t)try{let r=this.rewindGrants().revoke(t.pipelineId,t.stepId),n=A(this.deps,e,"pipeline:rewind-revoke:response",{pipelineId:t.pipelineId,stepId:t.stepId,revoked:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} revoked=${r}`)}catch(r){T(this.deps,"pipeline:rewind-revoke","pipeline:error",e,r)}}handleSeedTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.stepRunners?eO(this.stepRunners):[],r=A(this.deps,e,"pipeline:seed-templates:response",{templates:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} (${t.length} templates)`)}catch(t){T(this.deps,"pipeline:seed-templates","pipeline:error",e,t)}}handleMaskingTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.stepRunners?tO(this.stepRunners):[],r=A(this.deps,e,"pipeline:masking-templates:response",{templates:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} (${t.length} templates)`)}catch(t){T(this.deps,"pipeline:masking-templates","pipeline:error",e,t)}}handleSyncConfigs(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.stepRunners?Kk(this.stepRunners):[],r=A(this.deps,e,"pipeline:sync-configs:response",{configs:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} (${t.length} configurations)`)}catch(t){T(this.deps,"pipeline:sync-configs","pipeline:error",e,t)}}async buildOrchestrator(e,t){return(await this.buildRunParts(e,t)).orchestrator}async buildRunParts(e,t){let{PipelineBuilder:r}=await import("./chunk-4HW535YJ.mjs"),{TriggerEngine:n}=await import("./chunk-MIDBQ7SD.mjs"),{StepLibrary:o}=await import("./chunk-GEV2DCMK.mjs"),{StepExecutor:i}=await import("./chunk-HDWB4ZOG.mjs"),{ConditionalRouter:a}=await import("./chunk-LG466Q5H.mjs"),{PipelineHistory:d}=await import("./chunk-ZHJP7L3K.mjs"),c=new i,u=e??{operationId:"",holdBudget:()=>{}};c.wrapHandler("delay",f=>(g,h)=>this.untimed(()=>f(g,h),u));let l;if(this.stepRunners){let{runSync:f,seed:g,anonymize:h,verifyMasking:m,takeCheckpoint:y,rewind:v,backup:b}=this.stepRunners,{simulateSync:k,previewSeed:S,previewMasking:C,estimateTake:R,previewRewind:w}=this.stepRunners,P=await this.checkpointsOf(t),O=this.rewindGrants();l={...this.stepRunners,...t?.id?{pipelineId:t.id}:{},...u.triggeredBy?{trigger:u.triggeredBy}:{},rewindGrant:(E,$)=>O.verify(E,$),checkpointKept:E=>P.get(E),...f?{runSync:(E,$,H)=>this.runSyncUntimed(f,E,$,H,u)}:{},backup:(E,$)=>this.untimed(()=>b(E,$),u),...g?{seed:(E,$)=>this.untimed(()=>g(E,$),u)}:{},...h?{anonymize:(E,$)=>this.untimed(()=>h(E,$),u)}:{},...m?{verifyMasking:(E,$)=>this.untimed(()=>m(E,$),u)}:{},...y?{takeCheckpoint:(E,$)=>this.untimed(()=>y(E,$),u)}:{},...v?{rewind:(E,$)=>this.untimed(()=>v(E,$),u)}:{},...k?{simulateSync:(E,$)=>this.untimed(()=>k(E,$),u)}:{},...S?{previewSeed:(E,$)=>this.untimed(()=>S(E,$),u)}:{},...C?{previewMasking:(E,$)=>this.untimed(()=>C(E,$),u)}:{},...R?{estimateTake:(E,$)=>this.untimed(()=>R(E,$),u)}:{},...w?{previewRewind:(E,$)=>this.untimed(()=>w(E,$),u)}:{},...this.approvals().canAsk?{askApproval:(E,$)=>this.askApproval(E,$,u)}:{}},oO(c,l)}if(u.dryRun){if(!this.dryRunApplier||!l)throw new Error(VA);await this.dryRunApplier(c,l)}if(!this.deps.services)throw new Error("AutomationHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");return{orchestrator:this.deps.services.automationOrchestrator({builder:new r,triggerEngine:new n,stepLibrary:new o,stepExecutor:c,conditionalRouter:new a,history:new d,services:this.deps.services}),stepExecutor:c}}async runPipeline(e,t,r,n,o={}){let i=o.dryRun===!0,a={module:"automation",operation:"pipeline:execute"},d=this.deps.services?.getSandforgeSetting?.("pipeline.timeout",3e5)??3e5,c=new AbortController,u=!1,l=bj(d,()=>{u=!0,c.abort()}),p=await this.buildOrchestrator({operationId:n,holdBudget:R=>R?l.hold():l.resume(),triggeredBy:r,...i?{dryRun:!0}:{}},e);this.deps.infraServices?.performanceTracker?.start(n,"automation");let f=`${i?"Pipeline simulation":"Pipeline"}: ${e.name}`;Ge(this.deps,n,"automation",f);let g=sr(this.liveTracker,n,"automation",f,e.steps.length),h=R=>u&&R.status==="stopped"?{...R,status:"failed"}:R,m=(R,w)=>{let P=w,O=p.getActiveRuns(),E=e.steps.length,$=O[0]?.stepResults.length??0,H=Math.round($/E*100),J=`Step: ${P.stepResult.stepName} (${P.stepResult.status})`;_e(this.deps,n,H,$,E,J),g.progress(H,$,E,J)},y=(R,w)=>{let{stepId:P}=w;this.postStepUpdate({operationId:n,stepId:P,status:"running"})},v=(R,w)=>{let P=h(w.stepResult);this.postStepUpdate({operationId:n,stepId:P.stepId,status:P.status==="failed"||P.status==="skipped"||P.status==="stopped"?P.status:"completed",...P.duration!==void 0?{duration:P.duration}:{},...P.summary!==void 0?{summary:P.summary}:{},...P.error!==void 0?{error:P.error}:{}})};p.on("stepCompleted",m),p.on("stepStarted",y),p.on("stepCompleted",v),p.on("stepSkipped",v),l.start();let b=()=>{};this.deps.infraServices?.backgroundRegistry?.register(n,"automation",f,new Promise((R,w)=>{b=P=>P?w(P):R()}),c);let k;try{k=await p.execute(e,t,r,c.signal)}catch(R){throw b(new Error(I(R))),g.fail(I(R)),R}finally{l.end(),p.off?.("stepCompleted",m),p.off?.("stepStarted",y),p.off?.("stepCompleted",v),p.off?.("stepSkipped",v)}let S=u&&k.status==="cancelled",C=S?{...k,status:"failed",error:`Pipeline ran out of time: sandforge.pipeline.timeout stopped it after ${d} ms.`,stepResults:k.stepResults.map(h)}:k;return b(C.status==="failed"?new Error(C.error??"Pipeline failed"):void 0),C.status==="failed"?g.fail(C.error??"Pipeline failed"):C.status==="cancelled"?g.cancel():C.status==="completed_with_warnings"?g.partial():g.complete(),this.deps.infraServices?.performanceTracker?.complete(n),i||this.recordRun(C,e),C.status==="failed"?Le(this.deps,n,C.error??"Pipeline failed",S,{context:a}):me(this.deps,n,{status:C.status,stepResults:C.stepResults.length}),C}postStepUpdate(e){let t={id:this.deps.nextId(),type:"pipeline:step",timestamp:Date.now(),payload:e};this.deps.broker.postToWebview(t)}recordRun(e,t){this.writeHistory({runId:e.id,pipelineId:e.pipelineId,pipelineName:e.pipelineName,status:e.status,triggeredBy:e.triggeredBy,startTime:e.startTime,duration:e.duration??0,stepCount:e.stepResults.filter(r=>r.status!=="skipped").length,errorCount:e.stepResults.filter(r=>r.status==="failed").length,steps:e.stepResults.map(yj)},{pipeline:t})}recordEntry(e){this.writeHistory(e)}writeHistory(e,t={}){try{let r=new Date(e.startTime).getTime();this.deps.configStore.set(`pipeline:history:${e.runId}`,{...e,timestamp:Number.isNaN(r)?Date.now():r,...t},"pipeline-history"),this.trimHistory()}catch(r){this.deps.log(`[ERR] pipeline history write: ${I(r)}`)}}trimHistory(){let e=Object.entries(this.deps.configStore.getByCategory("pipeline-history"));if(e.length<=GA)return;let t=e.map(([r,n])=>{let o=n.timestamp;return{key:r,timestamp:typeof o=="number"?o:0}}).sort((r,n)=>r.timestamp-n.timestamp);for(let{key:r}of t.slice(0,e.length-GA))this.deps.configStore.delete(r)}exportInput(e,t){let r=this.deps.configStore,n=this.deps.services;return{pipeline:e,org:o=>this.deps.orgManager.getOrg(o),syncConfig:o=>new Pt(r).load(o),seedTemplate:o=>new dn(r).load(o),maskingTemplate:o=>new Na(r).load(o),setting:(o,i)=>n?.getSandforgeSetting?n.getSandforgeSetting(o,i):i,sandforgeVersion:t,exportedAt:new Date().toISOString(),machineTimezone:Intl.DateTimeFormat().resolvedOptions().timeZone,now:Date.now()}}outsideStatuses(e){let t=[];for(let r of e){let n=Oa.safeParse(r);if(!n.success||n.data.runsOutside===void 0)continue;let o=n.data;try{let i=Dk(this.exportInput(o,"0.0.0"));t.push({pipelineId:o.id,matches:i===n.data.runsOutside.digest,...i!==void 0?{digest:i}:{}})}catch(i){this.deps.log(`[WARN] pipeline "${o.name}": whether its exported file is up to date was not read: ${I(i)}`),t.push({pipelineId:o.id,matches:!1})}}return t}async exportPipeline(e){let t=this.savedPipeline(e);if(!t)return{exported:!1,pipelineId:e,code:"NOT_SAVED",message:"No pipeline is saved under this id: save the pipeline, then export it. An export takes the pipeline as saved."};let r=this.sandforgeVersion??this.deps.infraServices?.checkpointFiles?.sandforgeVersion;if(r===void 0)return{exported:!1,pipelineId:e,code:"VERSION_UNKNOWN",message:"This SandForge does not say which release it is, which the file and its launchers name: nothing was exported."};let{stepExecutor:n,orchestrator:o}=await this.buildRunParts(void 0,t),i=new Set((t.variables??[]).map(a=>a.name));return xk({...this.exportInput(t,r),stepRefusal:(a,d)=>n.check(a,{steps:t.steps,index:d,declared:i}),problems:o.check(t),checkedWhereItRuns:this.deps.services?.runsFrom==="commandLine"})}async handlePipelineExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Bw,e,"pipeline:error",this.deps);if(t)try{let r=await this.exportPipeline(t.pipelineId),n=A(this.deps,e,"pipeline:export:response",r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} ${r.exported?`exported ${r.fileName}`:`refused ${r.code}`}`)}catch(r){T(this.deps,"pipeline:export","pipeline:error",e,r)}}handlePipelineTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=A(this.deps,e,"pipeline:templates:response",{templates:zA});this.deps.broker.postToWebview(t),this.deps.log("[TX] pipeline:templates:response")}async handlePipelineList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.deps.configStore.getByCategory("pipelines"),r=Object.entries(t).map(([a,d])=>({key:a,...d})),n=await this.triggerScheduler().statuses();await this.revokeVoidGrants();let o=this.outsideStatuses(Object.values(t)),i=A(this.deps,e,"pipeline:list:response",{pipelines:r,triggers:n,...o.length>0?{outside:o}:{}});this.deps.broker.postToWebview(i),this.deps.log(`[TX] pipeline:list:response (${r.length} pipelines)`)}catch(t){T(this.deps,"pipeline:list","pipeline:error",e,t)}}commandLineRuns(){try{return this.commandLineHistory??=Ok(this.pipelinesRoot(),this.deps.log),this.commandLineHistory.read()}catch(e){return this.deps.log(`[WARN] the pipeline runs of the command line are not listed: ${I(e)}`),[]}}handlePipelineHistory(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.deps.configStore.getByCategory("pipeline-history"),n=[...Object.values(t).map(i=>{let a={...i};return delete a.pipeline,a}),...this.commandLineRuns()].sort((i,a)=>{let d=typeof i.timestamp=="number"?i.timestamp:0;return(typeof a.timestamp=="number"?a.timestamp:0)-d}),o=A(this.deps,e,"pipeline:history:response",{history:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] pipeline:history:response (${n.length} entries)`)}catch(t){T(this.deps,"pipeline:history","pipeline:error",e,t)}}handlePipelineSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=x(qw,e,"pipeline:error",this.deps);if(!t)return;let r=t,n=r.config.runsOutside;if(n!==void 0){let u=Hw.safeParse(n);if(!u.success){T(this.deps,"pipeline:save","pipeline:error",e,new Error(`The pipeline was not saved: runsOutside.${El(u.error)}`),{code:"INVALID_PAYLOAD",retryable:!1});return}}let o=r.id||crypto.randomUUID(),i=`pipeline:saved:${o}`;this.deps.configStore.set(i,{...r.config,id:o,savedAt:new Date().toISOString()},"pipelines");let a=Array.isArray(r.config.steps)?r.config.steps:[],d=this.rewindGrants().revokeChanged(o,a.map(u=>({...typeof u.id=="string"?{id:u.id}:{},...u.type==="rewind"?{type:"rewind"}:{},config:typeof u.config=="object"&&u.config!==null?u.config:{}})));for(let u of d)this.deps.log(`[INFO] pipeline:save ${o}: the confirmation of Rewind step ${u} was taken back, since the save changed what it does`);this.scheduler?.reload();let c=A(this.deps,e,"pipeline:save:response",{success:!0,id:o});this.deps.broker.postToWebview(c),this.deps.log(`[TX] pipeline:save:response id=${o}`)}catch(t){T(this.deps,"pipeline:save","pipeline:error",e,t)}}handlePipelineDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=x(Ww,e,"pipeline:error",this.deps);if(!t)return;let{id:r}=t,n=this.claims.hold(r,{startedAt:new Date().toISOString(),triggeredBy:"manual"});if("busy"in n){let a=this.deps.configStore.get(`pipeline:saved:${r}`),d=typeof a?.name=="string"?a.name:r;T(this.deps,"pipeline:delete","pipeline:error",e,new Error(`Pipeline "${d}" is running: the run started ${KA[n.busy.triggeredBy]} at ${n.busy.startedAt} has not ended. Delete it once that run has ended.`),{code:"PIPELINE_RUNNING",retryable:!0});return}let o;try{o=this.deps.configStore.delete(`pipeline:saved:${r}`);let a=this.rewindGrants().revokePipeline(r);a.length>0&&this.deps.log(`[INFO] pipeline:delete ${r}: the confirmations of Rewind steps ${a.join(", ")} were taken back`)}finally{n.release()}this.scheduler?.reload();let i=A(this.deps,e,"pipeline:delete:response",{id:r,deleted:o});this.deps.broker.postToWebview(i),this.deps.log(`[TX] pipeline:delete:response id=${r} deleted=${o}`)}catch(t){T(this.deps,"pipeline:delete","pipeline:error",e,t)}}handleMarketplaceList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{if(!this.pipelineMarketplace)throw new Error("Pipeline Marketplace not available.");let t=x(Xw,e,"pipeline:error",this.deps);if(t===null)return;let r;t?.query?r=this.pipelineMarketplace.search(t.query):t?.category?r=this.pipelineMarketplace.getByCategory(t.category):r=this.pipelineMarketplace.getTemplates();let n=A(this.deps,e,"marketplace:list:response",{success:!0,templates:r.map(o=>({id:o.id,name:o.name,description:o.description,category:o.category,author:"SandForge",stepTypes:o.steps.map(i=>i.type),steps:o.steps.map(i=>({name:i.name,type:i.type,config:i.config,...i.condition?{condition:i.condition}:{}}))}))});this.deps.broker.postToWebview(n)}catch(t){this.deps.log(`[ERR] marketplace:list: ${I(t)}`);let r=A(this.deps,e,"marketplace:list:response",{success:!1,error:I(t)});this.deps.broker.postToWebview(r)}}handleMarketplaceInstall(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Kw,e,"pipeline:error",this.deps);if(!t)return;let{templateId:r}=t;try{if(!this.pipelineMarketplace)throw new Error("Pipeline Marketplace not available.");if(!this.pipelineMarketplace.getById(r))throw new Error(`Template "${r}" not found.`);let o=this.pipelineMarketplace.exportTemplate(r),i;try{i=JSON.parse(o)}catch{throw new Error(`Template "${r}" contains invalid JSON.`)}let a=i.id;typeof a=="string"&&a!==""&&this.rewindGrants().revokePipeline(a);let d=A(this.deps,e,"marketplace:install:response",{success:!0,pipeline:i});this.deps.broker.postToWebview(d)}catch(n){this.deps.log(`[ERR] marketplace:install: ${I(n)}`);let o=A(this.deps,e,"marketplace:install:response",{success:!1,error:I(n)});this.deps.broker.postToWebview(o)}}};var gs=class{calls=new Map;begin(e){let t=new AbortController;return this.calls.has(e)||this.calls.set(e,t),{signal:t.signal,end:()=>{this.calls.get(e)===t&&this.calls.delete(e)}}}abort(e){let t=this.calls.get(e);return t?.abort(),t!==void 0}};function wo(s,e){return e.aborted?(s.catch(()=>{}),Promise.reject(YA())):new Promise((t,r)=>{let n=()=>r(YA());e.addEventListener("abort",n,{once:!0}),s.then(o=>{e.removeEventListener("abort",n),t(o)},o=>{e.removeEventListener("abort",n),r(o)})})}function YA(){return Object.assign(new Error("Stopped before its answer came."),{code:"CANCELLED"})}var QA=200,Ff=50,_f="ai.enabled",Uf="ai.errorResolution",ZA="ai:conversations:index",eT="ai",Bc="ai.anthropic.key",vj=new Set(["ai:chat","ai:chat:cancel","ai:conversation:create","ai:conversation:load","ai:conversation:delete","ai:conversation:delete-all","ai:conversation:list","ai:status","ai:save-key","ai:settings","ai:remove-key"]),qc=class{constructor(e){this.deps=e}deps;aiAssistant;asking=new gs;setAIAssistant(e){this.aiAssistant=e}async handle(e){if(!vj.has(e.type))return!1;switch(e.type){case"ai:chat":return await this.handleChat(e),!0;case"ai:chat:cancel":return this.handleChatCancel(e),!0;case"ai:conversation:create":return this.handleConversationCreate(e),!0;case"ai:conversation:load":return this.handleConversationLoad(e),!0;case"ai:conversation:list":return this.handleConversationList(e),!0;case"ai:conversation:delete":return this.handleConversationDelete(e),!0;case"ai:conversation:delete-all":return this.handleConversationDeleteAll(e),!0;case"ai:status":return await this.handleStatus(e),!0;case"ai:save-key":return await this.handleSaveKey(e),!0;case"ai:settings":return await this.handleSettings(e),!0;case"ai:remove-key":return await this.handleRemoveKey(e),!0;default:return!1}}conversationKey(e){return`ai:conversation:${e}`}loadIndex(){return this.deps.configStore.get(ZA)??[]}saveIndex(e){this.deps.configStore.set(ZA,e,eT)}loadConversation(e){return this.deps.configStore.get(this.conversationKey(e))}saveConversation(e){this.deps.configStore.set(this.conversationKey(e.id),e,eT),this.updateIndexEntry(e)}updateIndexEntry(e){let t=this.loadIndex(),r=t.findIndex(o=>o.id===e.id),n={id:e.id,title:e.title,createdAt:e.createdAt,messageCount:e.messages.length,updatedAt:e.updatedAt};r>=0?t[r]=n:t.push(n),this.saveIndex(this.withinTheBound(t,e.id))}withinTheBound(e,t){if(e.length<=Ff)return e;let r=o=>o.updatedAt??o.createdAt,n=new Set([...e].filter(o=>o.id!==t).sort((o,i)=>r(o).localeCompare(r(i))).slice(0,e.length-Ff).map(o=>o.id));for(let o of n)this.forgetConversation(o);return this.deps.log(`[INFO] ai: ${n.size} conversation(s) written to least recently deleted (${Ff} are kept).`),e.filter(o=>!n.has(o.id))}forgetConversation(e){this.asking.abort(e),this.aiAssistant?.deleteConversation(e),this.deps.configStore.delete(this.conversationKey(e))}deleteAllConversations(){let e=this.conversationKey(""),t=new Set(this.loadIndex().map(r=>r.id));for(let r of this.deps.configStore.getKeysByPrefix(e))t.add(r.slice(e.length));for(let r of t)this.forgetConversation(r);return this.saveIndex([]),t.size}pruneMessages(e){if(e.length<=QA)return e;let t=e.filter(o=>o.role==="system"),r=e.filter(o=>o.role!=="system"),n=QA-t.length;return[...t,...r.slice(-n)]}isChatRole(e){return e==="user"||e==="assistant"||e==="system"}toConversation(e){let t=e.messages.filter(r=>this.isChatRole(r.role)).map(r=>({id:r.id,role:r.role,content:r.content,timestamp:r.timestamp,tokenCount:r.tokenCount}));return{id:e.id,title:e.title,messages:t,createdAt:e.createdAt,updatedAt:e.updatedAt,totalTokens:t.reduce((r,n)=>r+(n.tokenCount??0),0)}}restoreConversationIfNeeded(e){let t=this.aiAssistant;if(!t||t.getConversation(e))return;let r=this.loadConversation(e);r&&(t.restoreConversation(this.toConversation(r)),this.deps.log(`Restored conversation ${e} from store.`))}async handleChat(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(aw,e,"ai:error",this.deps);if(!t)return;let r=t,n=this.aiAssistant;if(!n){let i=A(this.deps,e,"ai:error",{message:"AI is not configured. Set your API key in Settings > AI."});this.deps.broker.postToWebview(i);return}this.restoreConversationIfNeeded(r.conversationId);let o=this.asking.begin(r.conversationId);try{let i=await n.chat(r.conversationId,r.message,{signal:o.signal}),a=n.getConversation(r.conversationId);a&&this.persistConversationFromMemory(a);let d=A(this.deps,e,"ai:chat:response",{conversationId:r.conversationId,message:{id:i.id,role:i.role,content:i.content,timestamp:i.timestamp,tokenCount:i.tokenCount},...a?{title:a.title}:{}});this.deps.broker.postToWebview(d),this.deps.log("[TX] ai:chat:response")}catch(i){if(o.signal.aborted){let c=A(this.deps,e,"ai:chat:response",{conversationId:r.conversationId,code:"CANCELLED"});this.deps.broker.postToWebview(c),this.deps.log("[TX] ai:chat:response cancelled");return}let a=I(i),d=A(this.deps,e,"ai:error",{message:a});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ai:error: ${a}`)}finally{o.end()}}handleChatCancel(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ka,e,"ai:error",this.deps);t&&this.asking.abort(t.conversationId)}handleConversationCreate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(dw,e,"ai:error",this.deps);if(!t)return;let r=t;if(!this.aiAssistant){let i=A(this.deps,e,"ai:error",{message:"AI is not configured. Set your API key in Settings > AI."});this.deps.broker.postToWebview(i);return}let n=this.aiAssistant.createConversation(r.title);this.persistConversationFromMemory(n);let o=A(this.deps,e,"ai:conversation:created",{conversation:{id:n.id,title:n.title,createdAt:n.createdAt}});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ai:conversation:created id=${n.id}`)}handleConversationLoad(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ka,e,"ai:error",this.deps);if(!t)return;let r=t;if(this.aiAssistant){let i=this.aiAssistant.getConversation(r.conversationId);if(i){let a=A(this.deps,e,"ai:conversation:loaded",{conversation:{id:i.id,title:i.title,messages:i.messages.map(d=>({id:d.id,role:d.role,content:d.content,timestamp:d.timestamp}))}});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ai:conversation:loaded id=${i.id} (memory)`);return}}let n=this.loadConversation(r.conversationId);if(!n){let i=A(this.deps,e,"ai:error",{message:`Conversation ${r.conversationId} not found.`});this.deps.broker.postToWebview(i);return}let o=A(this.deps,e,"ai:conversation:loaded",{conversation:{id:n.id,title:n.title,messages:n.messages.map(i=>({id:i.id,role:i.role,content:i.content,timestamp:i.timestamp}))}});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ai:conversation:loaded id=${n.id} (store)`)}handleConversationList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.loadIndex(),r=A(this.deps,e,"ai:conversation:list:response",{conversations:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ai:conversation:list:response count=${t.length}`)}handleConversationDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ka,e,"ai:error",this.deps);if(!t)return;let r=t;this.aiAssistant&&this.aiAssistant.deleteConversation(r.conversationId),this.deps.configStore.delete(this.conversationKey(r.conversationId));let n=this.loadIndex().filter(i=>i.id!==r.conversationId);this.saveIndex(n);let o=A(this.deps,e,"ai:conversation:deleted",{conversationId:r.conversationId});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ai:conversation:deleted id=${r.conversationId}`)}handleConversationDeleteAll(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.deleteAllConversations(),r=A(this.deps,e,"ai:conversation:deleted-all",{count:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ai:conversation:deleted-all count=${t}`)}async handleStatus(e){this.deps.log(`[RX] ${e.type} id=${e.id}`),await this.postStatus(e)}async postStatus(e){let t=await this.deps.secretVault.hasSecret(Bc),r=A(this.deps,e,"ai:status:response",{enabled:!!this.aiAssistant&&t,provider:this.aiAssistant?Wg:"none",model:this.aiAssistant?Gg(this.deps.services?.getSandforgeSetting?.("ai.model",zg.MODEL)):"",budget:this.aiAssistant?this.deps.services?.sessionBudget?.getState():void 0,hasKey:t,errorResolution:this.deps.services?.getSandforgeSetting?.(Uf,!0)??!0});this.deps.broker.postToWebview(r),this.deps.log("[TX] ai:status:response")}async enableAIFeature(){await this.writeSetting("ai:save-key",_f,!0)}async writeSetting(e,t,r){if(!this.deps.services?.setSandforgeSetting)return this.deps.log(`[WARN] ${e}: no settings backend \u2014 sandforge.${t} left as-is.`),!1;try{return await this.deps.services.setSandforgeSetting(t,r),!0}catch(n){return this.deps.log(`[ERR] ${e}: writing sandforge.${t} failed: ${I(n)}`),!1}}async rebuildAIStack(e="ai:save-key"){let t=this.deps.services?.reinitAI;if(!t){this.deps.log(`[WARN] ${e}: no AI rebuild wired \u2014 the change applies after a reload.`);return}try{await t()}catch(r){this.deps.log(`[ERR] ${e}: rebuilding the AI stack failed: ${I(r)}`)}}async handleSaveKey(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(cw,e,"ai:error",this.deps);if(!t)return;let{apiKey:r,errorResolution:n}=t;try{let o=await this.deps.secretVault.hasSecret(Bc);await this.deps.secretVault.storeSecret(Bc,r),(!o||n!==void 0)&&await this.writeSetting("ai:save-key",Uf,n===!0),await this.enableAIFeature(),await this.rebuildAIStack();let i=A(this.deps,e,"ai:save-key:response",{success:!0});this.deps.broker.postToWebview(i),this.deps.log("[TX] ai:save-key:response success"),await this.postStatus(e)}catch(o){let i=I(o);this.deps.log(`[ERR] ai:save-key: ${i}`);let a=A(this.deps,e,"ai:save-key:response",{success:!1,error:i});this.deps.broker.postToWebview(a)}}async handleSettings(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(uw,e,"ai:error",this.deps);if(!t)return;let r=[];t.errorResolution!==void 0&&r.push([Uf,t.errorResolution]),t.enabled!==void 0&&r.push([_f,t.enabled]);let n=!0;for(let[i,a]of r)await this.writeSetting("ai:settings",i,a)||(n=!1);await this.rebuildAIStack("ai:settings");let o=A(this.deps,e,"ai:settings:response",{success:n,...n?{}:{error:"The setting could not be written: the SandForge log says why."}});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ai:settings:response success=${n}`),await this.postStatus(e)}async handleRemoveKey(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{await this.deps.secretVault.deleteSecret(Bc);let t=this.deleteAllConversations();await this.writeSetting("ai:remove-key",_f,!1),await this.rebuildAIStack("ai:remove-key");let r=A(this.deps,e,"ai:remove-key:response",{success:!0,conversationsDeleted:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ai:remove-key:response conversations=${t}`),await this.postStatus(e)}catch(t){let r=I(t);this.deps.log(`[ERR] ai:remove-key: ${r}`);let n=A(this.deps,e,"ai:remove-key:response",{success:!1,error:r});this.deps.broker.postToWebview(n)}}persistConversationFromMemory(e){let t=e.messages.map(n=>({id:n.id,role:n.role,content:n.content,timestamp:n.timestamp,tokenCount:n.tokenCount})),r={id:e.id,title:e.title,messages:this.pruneMessages(t),createdAt:e.createdAt,updatedAt:e.updatedAt};this.saveConversation(r)}};var Sj=new Set(["ai:anomaly-scan"]),Wc=class{constructor(e){this.deps=e}deps;ruleModules;setRuleModules(e){this.ruleModules=e}async handle(e){return Sj.has(e.type)&&e.type==="ai:anomaly-scan"?(await this.handleAnomalyScan(e),!0):!1}async handleAnomalyScan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(lw,e,"ai:error",this.deps);if(!t)return;let{orgId:r,objectName:n,sampleSize:o}=t;try{if(!this.ruleModules?.anomalyDetector)throw new Error("Anomaly scan is still starting up. Try again in a moment.");let i=await B(r,this.deps.orgRegistry,this.deps.orgManager),a=St(n),d=o??mn.anomalyScan,c=`SELECT FIELDS(ALL) FROM ${a} LIMIT ${d}`,u=await Sm(i,a,c),l=u.records,p={records:l,fields:Object.keys(l[0]??{})},f=this.ruleModules.anomalyDetector.detectAnomalies(p,n),g=A(this.deps,e,"ai:anomaly-scan:response",{success:!0,anomalies:f.anomalies.map(h=>({field:h.field,type:h.type,description:h.description,severity:h.severity})),sample:{read:l.length,limit:u.limit??d}});this.deps.broker.postToWebview(g)}catch(i){this.deps.log(`[ERR] ai:anomaly-scan: ${I(i)}`);let a=A(this.deps,e,"ai:anomaly-scan:response",{success:!1,error:I(i)});this.deps.broker.postToWebview(a)}}};function tT(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"")}function kj(s){let e=[s];return s.endsWith("ies")&&s.length>3&&e.push(`${s.slice(0,-3)}y`),(s.endsWith("ses")||s.endsWith("xes")||s.endsWith("ches"))&&e.push(s.slice(0,-2)),s.endsWith("s")&&!s.endsWith("ss")&&e.push(s.slice(0,-1)),e}function Oj(s){let e=new Map;for(let t of s)if(t.queryable!==!1)for(let r of[t.name,t.label,t.labelPlural]){if(!r)continue;let n=tT(r);n&&!e.has(n)&&e.set(n,t.name)}return e}function rT(s,e,t=5){if(t<=0)return[];let r=Oj(e),n=s.split(/[^A-Za-z0-9_]+/).filter(Boolean),o=[],i=new Set;for(let a=0;a<n.length;a++){let d=Math.min(4,n.length-a);for(let c=d;c>=1;c--){let u=n.slice(a,a+c).join(""),l=kj(tT(u)).map(p=>r.get(p)).find(p=>p!==void 0);if(l){if(!i.has(l)&&(i.add(l),o.push(l),o.length>=t))return o;a+=c-1;break}}}return o}var Ij={sync:"Sync",seed:"Seed",dataops:"DataOps"};function nT(s){if(s.code==="STEP_NOT_RUNNABLE")return`A pipeline cannot run a ${s.stepType} step, so the draft leaves it out.`;let e=Ij[s.page];return`The draft leaves out the ${e} work, which writes to an org: run it from the ${e} page, where Production Guard can stop or ask first.`}var Aj=new Set(["WHERE","USING","WITH","GROUP","ORDER","LIMIT","OFFSET","FOR","UPDATE"]),Tj=new Set(["WITH","GROUP","ORDER","LIMIT","OFFSET","FOR","UPDATE"]),Ej=new Set(["AND","OR","NOT","WHERE"]),Pj=/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/,Cj=/^([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)(?:\s+[A-Za-z_]\w*)?$/,$j=/^[A-Za-z_]\w*\s*\(([^()]*)\)(?:\s+[A-Za-z_]\w*)?$/,xj=/([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*(?:!=|<>|<=|>=|=|<|>|\bNOT\s+IN\b|\bIN\b|\bLIKE\b|\bINCLUDES\b|\bEXCLUDES\b)/gi;function Dj(s){let e="",t=0;for(;t<s.length;){if(s[t]!=="'"){e+=s[t],t++;continue}for(t++;t<s.length&&s[t]!=="'";)t+=s[t]==="\\"?2:1;t++,e+="''"}return e}var oT=/\(\s*SELECT\b/iy;function Nj(s){let e="",t=0;for(;t<s.length;){if(oT.lastIndex=t,s[t]!=="("||!oT.test(s)){e+=s[t],t++;continue}let r=0,n=t;for(;n<s.length;n++)if(s[n]==="(")r++;else if(s[n]===")"&&--r===0)break;e+="()",t=n+1}return e}function jj(s){let e=[],t=0,r=0;for(;r<s.length;){let n=s[r];if(n==="(")t++,r++;else if(n===")")t=Math.max(0,t-1),r++;else if(/\w/.test(n)){let o=r;for(;r<s.length&&/\w/.test(s[r]);)r++;t===0&&e.push({word:s.slice(o,r),start:o,end:r})}else r++}return e}function Mj(s){let e=[],t=0,r=0;for(let n=0;n<s.length;n++)s[n]==="("?t++:s[n]===")"?t=Math.max(0,t-1):s[n]===","&&t===0&&(e.push(s.slice(r,n)),r=n+1);return e.push(s.slice(r)),e}function Lj(s){let e=Cj.exec(s);if(e)return e[1];let t=$j.exec(s);if(t){let r=t[1].trim();return Pj.test(r)?r:null}return null}function Fj(s){let e=Nj(Dj(s)).replace(/\bTYPEOF\b[\s\S]*?\bEND\b/gi,"()"),t=jj(e),r=h=>t[h]?.word.toUpperCase();if(r(0)!=="SELECT")return null;let n=t.findIndex(h=>h.word.toUpperCase()==="FROM");if(n<1||n+1>=t.length)return null;let o=t[n+1].word,i=new Set([o.toUpperCase()]),a=r(n+2)==="AS"?n+3:n+2,d=r(a),c=e.slice(t[n+1].end,t[a]?.start);d&&!Aj.has(d)&&!c.includes(",")&&i.add(d);let u=[],l=e.slice(t[0].end,t[n].start);for(let h of Mj(l)){let m=Lj(h.trim());m&&u.push(m)}let p=t.findIndex((h,m)=>m>n+1&&h.word.toUpperCase()==="WHERE");if(p>=0){let h=t.findIndex((y,v)=>v>p&&Tj.has(r(v)??"")),m=e.slice(t[p].end,h<0?e.length:t[h].start);for(let y of m.matchAll(xj))Ej.has(y[1].toUpperCase())||u.push(y[1])}let f=new Set,g=[];for(let h of u){let[m,...y]=h.split("."),v=y.length>0&&i.has(m.toUpperCase())?y.join("."):h,b=v.toUpperCase();f.has(b)||(f.add(b),g.push(v))}return{objectApiName:o,fieldRefs:g}}async function sT(s,e){let t=Fj(s);if(!t)return{fieldsChecked:0,problems:[{kind:"no-from"}]};let r=t.objectApiName.toLowerCase(),n=e.catalog.find(u=>u.name.toLowerCase()===r);if(!n)return{rootObject:t.objectApiName,fieldsChecked:0,problems:[{kind:"object-missing",object:t.objectApiName}]};let o;try{o=await e.describe(n.name)}catch(u){return{rootObject:n.name,rootLabel:n.label,fieldsChecked:0,problems:[{kind:"describe-failed",object:n.name,detail:I(u)}]}}let i=new Set(o.fields.map(u=>u.name.toLowerCase())),a=new Set(o.fields.flatMap(u=>u.relationshipName?[u.relationshipName.toLowerCase()]:[])),d=[],c=new Set;for(let u of t.fieldRefs){let[l,...p]=u.split(".");p.length===0?i.has(l.toLowerCase())||d.push({kind:"field-missing",object:n.name,field:l}):!a.has(l.toLowerCase())&&!c.has(l.toLowerCase())&&(c.add(l.toLowerCase()),d.push({kind:"relationship-missing",object:n.name,relationship:l}))}if(d.length===0)try{await e.explain(s)}catch(u){d.push({kind:"org-refused",detail:I(u)})}return{rootObject:n.name,rootLabel:o.label||n.label,fieldsChecked:t.fieldRefs.length,problems:d}}function Hf(s){return Hj().text(s)}var Uj=new Set;function Hj(){let s=$S(),e=new Map,t=o=>{let i=e.get(o);if(i!==void 0)return i;let a=s(o);return e.set(o,a),a},r=o=>{let i=xS({text:o},Uj,t).text;return typeof i=="string"?i:o},n=o=>typeof o=="string"?r(o):Array.isArray(o)?o.map(n):o!==null&&typeof o=="object"?Object.fromEntries(Object.entries(o).map(([i,a])=>[i,n(a)])):o;return{text:r,deep:o=>n(o)}}var Bt=Yu,Kt=Yu.text,iT="{firstName}, {lastName}, {company}, {email} and {caseSubject}";var FV=[`- "id" and each topic's "key": lower-case letters and digits in words joined by single hyphens, starting with a letter, ${Bt.maxKeyLength} characters at most.`,`- "name": at most ${Kt.name} characters. "businessContext": what the company does and who its customers are, in two or three sentences, at most ${Kt.businessContext} characters.`,`- "customers": "count" is 10 unless the scenario asks for another number, at least the number of topics and at most ${Bt.maxCustomers}; "industry" is the customers' industry as an Account Industry value of Salesforce (Retail, Telecommunications, Technology...), at most ${Kt.industry} characters.`,`- "topics": ${Bt.topics.min} to ${Bt.topics.max}, five unless the scenario calls for more or fewer: the subjects customers write to support about. "label": at most ${Kt.label} characters.`,`- "utterances": ${Bt.utterances.min} to ${Bt.utterances.max} a topic, two unless it needs more: what a customer whose case on the topic is still open says to the agent ("text"), and what the agent should do, in plain words ("expectedOutcome"), each at most ${Kt.utterance} characters. They may name the customer and the case with ${iT}, filled in when the pack is seeded.`,`- "decoy": an article close to the topic it "resembles", by its key, that does not answer it, so that a test tells the right article from the nearest. "title" at most ${Kt.articleTitle} characters, "summary" at most ${Kt.articleSummary}, "body" plain-text paragraphs of 600 to 1,500 characters. No placeholder.`,`- "outOfScope": ${Bt.outOfScope.min} to ${Bt.outOfScope.max}, three unless more are useful: what a customer may say that no topic covers, and that the agent should decline ("expectedOutcome"), each at most ${Kt.utterance} characters. No placeholder.`,"- No word in braces but the placeholders named here, where they are allowed."];var _V=[`- "article": what the agent answers the topic from. "title" at most ${Kt.articleTitle} characters and none of the titles above; "summary" at most ${Kt.articleSummary}; "body" plain-text paragraphs of 1,200 to 3,000 characters, at most ${Kt.articleBody}: the policy or the procedure, with the figures, delays and conditions customers ask about. No placeholder in the article.`,`- "facts": ${Bt.facts.min} to ${Bt.facts.max}, each a sentence of the body copied word for word, at most ${Kt.fact} characters: what an answer drawn from the article has to say.`,`- "caseTemplates": ${Bt.caseTemplates.min} to ${Bt.caseTemplates.max}, two unless the topic needs more: cases customers open on the topic. "subject" at most ${Kt.caseSubject} characters, and may name {firstName}, {lastName}, {company} and {email}; "description" what the customer writes, under 600 characters; "priority" is High, Medium or Low; "origin" is Phone, Email or Web; "followUp" what the customer writes again while the case is open, under 300 characters; "resolution" ${Bt.resolutionSteps.min} to ${Bt.resolutionSteps.max} steps, each a comment of the agent who resolved the case, under 400 characters. "description", "followUp" and "resolution" may name ${iT}.`,"- No word in braces but the placeholders named here, where they are allowed."];var Bj=new Set(["ai:forge-plan","ai:generate-pipeline","ai:scenario-draft","ai:tool:cancel"]),Bf={success:!1,code:"CANCELLED"},aT="AI not configured. Set your API key in Settings > AI.";function qj(s){switch(s){case"Production":return"production";case"Sandbox":return"sandbox";case"Developer":return"developer";case"Scratch":return"scratch";default:return"production"}}var zc=class{constructor(e){this.deps=e}deps;aiModules;drafting=new gs;describeGlobalCache=new Zs({defaultTtl:5*6e4,maxSize:16,maxSizeBytes:50*1024*1024});describeCache=new Zs({defaultTtl:5*6e4,maxSize:50,maxSizeBytes:20*1024*1024});setAIModules(e){this.aiModules=e}forgetOrg(e){this.describeGlobalCache.invalidate(e),this.describeCache.invalidateByPrefix(`${e}::`)}async handle(e){if(!Bj.has(e.type))return!1;switch(e.type){case"ai:forge-plan":return await this.handleForgePlan(e),!0;case"ai:generate-pipeline":return await this.handleGeneratePipeline(e),!0;case"ai:scenario-draft":return await this.handleScenarioDraft(e),!0;case"ai:tool:cancel":return this.handleCancel(e),!0;default:return!1}}handleCancel(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(gw,e,"ai:error",this.deps);t&&this.drafting.abort(t.requestId)}async handleForgePlan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(pw,e,"ai:error",this.deps);if(!t)return;let{orgId:r,prompt:n}=t,o=this.drafting.begin(e.id);try{let i=this.aiModules?.nl2soql;if(n!==void 0&&!i){this.deps.broker.postToWebview(A(this.deps,e,"ai:forge-plan:response",{success:!1,code:"AI_NOT_CONFIGURED",error:aT}));return}let a=await wo(this.connect(r),o.signal),d=await wo(this.loadCatalog(r,a),o.signal),c=t.soql??"",u;if(n!==void 0&&i){let{result:p}=await this.draft(i,n,r,a,d,o.signal);c=p.soql,u=p.explanation}let l=await wo(sT(c,{catalog:d,describe:async p=>{let f=await this.describeObject(r,a,p);return{name:f.apiName,label:f.label,fields:f.fields.map(g=>({name:g.apiName,relationshipName:g.relationshipName}))}},explain:p=>a.request(`/query/?explain=${encodeURIComponent(p)}`)}),o.signal);this.deps.broker.postToWebview(A(this.deps,e,"ai:forge-plan:response",{success:l.problems.length===0,soql:c,...u?{explanation:u}:{},...l.rootObject?{rootObject:l.rootObject}:{},...l.rootLabel?{rootLabel:l.rootLabel}:{},fieldsChecked:l.fieldsChecked,problems:l.problems}))}catch(i){if(o.signal.aborted){this.deps.broker.postToWebview(A(this.deps,e,"ai:forge-plan:response",{...Bf})),this.deps.log("[TX] ai:forge-plan:response cancelled");return}this.deps.log(`[ERR] ai:forge-plan: ${I(i)}`),this.deps.broker.postToWebview(A(this.deps,e,"ai:forge-plan:response",{success:!1,error:I(i)}))}finally{o.end()}}async connect(e){return await B(e,this.deps.orgRegistry,this.deps.orgManager)}async draft(e,t,r,n,o,i){let a=rT(t,o),d=await wo(this.describeObjects(r,n,a),i),c={objects:d.length>0?d:o.map(l=>({apiName:l.name,label:l.label,fields:[]}))};return{result:await wo(e.generateSOQL(t,c,{signal:i}),i),described:d}}async loadCatalog(e,t){let r=this.describeGlobalCache.get(e);if(r)return r;let o=(await t.describeGlobal()).sobjects.filter(i=>i.queryable!==!1).map(i=>({name:i.name,label:i.label,labelPlural:i.labelPlural,queryable:i.queryable}));return this.describeGlobalCache.set(e,o),o}async describeObjects(e,t,r){let n=[];for(let o of r)try{n.push(await this.describeObject(e,t,o))}catch(i){this.deps.log(`[WARN] ai:nl2soql describe ${o}: ${I(i)}`)}return n}async describeObject(e,t,r){let n=`${e}::${r}`,o=this.describeCache.get(n);if(o)return o;let i=await t.describe(r),a={apiName:i.name,label:i.label??i.name,fields:i.fields.map(d=>({apiName:d.name,label:d.label??d.name,type:d.type,...d.relationshipName?{relationshipName:d.relationshipName}:{}}))};return this.describeCache.set(n,a),a}async handleGeneratePipeline(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(fw,e,"ai:error",this.deps);if(!t)return;let{description:r,orgIds:n}=t,o=this.drafting.begin(e.id);try{if(!this.aiModules?.pipelineGenerator)throw new Error("AI not configured. Set your API key in Settings > AI to enable this feature.");let i=(n??[]).map(u=>{let l=this.deps.orgManager.getOrg(u);return{orgId:u,alias:l?.alias??u,type:qj(l?.orgType)}}),{suggestions:a=[],...d}=await wo(this.aiModules.pipelineGenerator.generatePipeline(r,i,{signal:o.signal}),o.signal);if(d.steps.length===0&&a.length>0){let u=a.map(nT).join(" ");this.deps.log(`[ERR] ai:generate-pipeline: ${u}`),this.deps.broker.postToWebview(A(this.deps,e,"ai:generate-pipeline:response",{success:!1,error:u,suggestions:a}));return}if(d.steps.length===0)throw new Error("The AI returned a pipeline with no steps, so there is nothing to load. Name the operations it should run, for example: back up Account daily, then compare dev with uat.");let c=A(this.deps,e,"ai:generate-pipeline:response",{success:!0,pipeline:d,...a.length>0?{suggestions:a}:{}});this.deps.broker.postToWebview(c)}catch(i){if(o.signal.aborted){this.deps.broker.postToWebview(A(this.deps,e,"ai:generate-pipeline:response",{...Bf})),this.deps.log("[TX] ai:generate-pipeline:response cancelled");return}this.deps.log(`[ERR] ai:generate-pipeline: ${I(i)}`);let a=A(this.deps,e,"ai:generate-pipeline:response",{success:!1,error:I(i)});this.deps.broker.postToWebview(a)}finally{o.end()}}async handleScenarioDraft(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(hw,e,"ai:error",this.deps);if(!t)return;let r=i=>this.deps.broker.postToWebview(A(this.deps,e,"ai:scenario-draft:response",i));if(t.maskOnly){r({success:!0,sentText:Hf(t.text)});return}let n=this.aiModules?.scenarioDrafter;if(!n){r({success:!1,code:"AI_NOT_CONFIGURED",error:aT,sentText:Hf(t.text)});return}let o=this.drafting.begin(e.id);try{let i=await n.draft({text:t.text,language:t.language,...t.casePicklists?{casePicklists:t.casePicklists}:{},...t.agent?{agent:t.agent}:{},...t.draft?{from:t.draft}:{}},{signal:o.signal});i.kind==="failed"?this.deps.log(`[ERR] ai:scenario-draft (${i.failedAt.call}): ${i.error}`):i.kind==="stopped"&&this.deps.log("[TX] ai:scenario-draft:response cancelled"),r(Wj(i))}catch(i){this.deps.log(`[ERR] ai:scenario-draft: ${I(i)}`),r({success:!1,error:I(i)})}finally{o.end()}}};function Wj(s){switch(s.kind){case"complete":return{success:!0,sentText:s.sentText,pack:s.pack};case"stopped":return{...Bf,sentText:s.sentText,...s.draft?{draft:s.draft}:{}};case"failed":return{success:!1,error:s.error,failedAt:s.failedAt,sentText:s.sentText,...s.issues?{issues:s.issues}:{},...s.draft?{draft:s.draft}:{}}}}var zj=new Set(["ai:chat","ai:chat:cancel","ai:conversation:create","ai:conversation:load","ai:conversation:list","ai:conversation:delete","ai:conversation:delete-all","ai:status","ai:save-key","ai:settings","ai:remove-key","ai:tool:cancel","ai:forge-plan","ai:anomaly-scan","ai:generate-pipeline","ai:scenario-draft"]),Gc=class{chatHandler;analysisHandler;toolsHandler;subHandlers;constructor(e){this.chatHandler=new qc(e),this.analysisHandler=new Wc(e),this.toolsHandler=new zc(e),this.subHandlers=[this.chatHandler,this.analysisHandler,this.toolsHandler]}setAIAssistant(e){this.chatHandler.setAIAssistant(e)}setAIModules(e){this.toolsHandler.setAIModules(e)}setRuleModules(e){this.analysisHandler.setRuleModules(e)}forgetOrg(e){this.toolsHandler.forgetOrg(e)}async handle(e){if(!zj.has(e.type))return!1;for(let t of this.subHandlers)if(await t.handle(e))return!0;return!1}};function Gj({org:s,check:e,readBefore:t}){return{org:s,estimate:e.estimate,verdict:e.verdict,...e.verdict==="unread"?{unread:e.unread}:{remaining:e.remaining,max:e.max},...t?{readBefore:{...t}}:{}}}function dT(s,e,t,r){return{records:s.totalRows,estimateMB:e.estimateMB,verdict:e.verdict,...e.verdict==="unread"?{unread:e.unread}:{remainingMB:e.remainingMB,maxMB:e.maxMB},...t.verdict==="unread"?{}:{apiRequests:{estimate:t.estimate,remaining:t.remaining,max:t.max,verdict:t.verdict}},...r?{source:Gj(r)}:{}}}function cT(s,e,t){let{mode:r,share:n}=s,o=r.all!==void 0||Object.keys(r.caps??{}).length>0;return{module:"autopilot",...n!==void 0?{share:n}:{},...o?{capped:!0}:{},...r.withinMB!==void 0?{withinMB:r.withinMB}:{},kept:e,inSource:t}}var Jj=new Set(["autopilot:list-objects","autopilot:count-objects","autopilot:scan-schema","autopilot:generate-plan","autopilot:fit-plan","autopilot:fit-undo","autopilot:execute","autopilot:pause","autopilot:resume","autopilot:skip-node","autopilot:compliance-report"]),Vj=10,qf=3e4,Wf=6e4;function lT(s){return`autopilot:${s}`}var zf=(s,e)=>e==="insert"||e==="update",Jc={code:"AUTOPILOT_NOT_READY",message:"Autopilot module is not initialized."},hs={code:"AUTOPILOT_RUNNING",message:"An Autopilot run is still writing to this target org: Monitor's Live Operations shows where it is. Start another once it has ended."},Xj=new Set(["autopilot:pause","autopilot:resume","autopilot:skip-node"]),Vc=class{constructor(e){this.deps=e}deps;operations=new Map;currentOperationId;executingOperations=new Set;runningRequests=new Set;writingTargets=new Map;beforeRunCheckpoints;orchestrator;registry;liveTracker;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-UK3QLBHW.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}setOrchestrator(e){this.orchestrator=e}setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}isWritingTo(e,t){let r=this.writingTargets.get(e);return r!==void 0&&(t===void 0||t!==lT(r))}async handle(e){if(!Jj.has(e.type))return!1;switch(e.type){case"autopilot:list-objects":return await this.handleListObjects(e),!0;case"autopilot:count-objects":return await this.handleCountObjects(e),!0;case"autopilot:scan-schema":return await this.handleScanSchema(e),!0;case"autopilot:generate-plan":return await this.handleGeneratePlan(e),!0;case"autopilot:fit-plan":return await this.handleFitPlan(e),!0;case"autopilot:fit-undo":return await this.handleFitUndo(e),!0;case"autopilot:execute":return await this.handleExecute(e),!0;case"autopilot:pause":return this.handlePause(e),!0;case"autopilot:resume":return this.handleResume(e),!0;case"autopilot:skip-node":return this.handleSkipNode(e),!0;case"autopilot:compliance-report":return this.handleComplianceReport(e),!0;default:return!1}}refuseNotReady(e){T(this.deps,e.type,"autopilot:error",e,new Error(Jc.message),{code:Jc.code}),Xj.has(e.type)&&Ae(this.deps,"error","Autopilot",Jc.message,{code:Jc.code})}resolveCurrentOperation(){return this.currentOperationId!==void 0?this.operations.get(this.currentOperationId):void 0}evictOldOperations(){for(;this.operations.size>Vj;){let e=this.operations.keys().next();if(e.done||this.executingOperations.has(e.value))return;this.operations.delete(e.value),this.currentOperationId===e.value&&(this.currentOperationId=[...this.operations.keys()].pop())}}async handleListObjects(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=x(Ky,e,"autopilot:error",this.deps);if(t)try{let r=await B(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await this.orchestrator.listObjects(r,n,t.includeStandardObjects),i=A(this.deps,e,"autopilot:objects-listed",{objects:o});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} count=${o.length}`)}catch(r){T(this.deps,"autopilot:list-objects","autopilot:error",e,r)}}async handleCountObjects(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=x(Yy,e,"autopilot:error",this.deps);if(t)try{let r=await B(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await this.orchestrator.countObjects(r,t.objectApiNames),o=A(this.deps,e,"autopilot:objects-counted",{counts:Object.fromEntries(n)});this.deps.broker.postToWebview(o)}catch(r){T(this.deps,"autopilot:count-objects","autopilot:error",e,r)}}async handleScanSchema(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=x(Qy,e,"autopilot:error",this.deps);if(!t)return;let r=t,n=this.currentOperationId,o={id:e.id,targetOrgId:r.targetOrgId,sourceOrgId:r.sourceOrgId};this.operations.set(e.id,o),this.currentOperationId=e.id,this.evictOldOperations();try{let i=await B(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),a=await B(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),d=await this.orchestrator.scanSchemas(i,a,{selectedObjects:r.selectedObjects,includeStandardObjects:r.includeStandardObjects,...r.maxDepth!==void 0?{maxDepth:r.maxDepth}:{},...r.maxObjects!==void 0?{maxObjects:r.maxObjects}:{},maxRecordsPerObject:this.maxRecordsPerObject()});o.scanResult=d;let c=this.orchestrator.buildGraph(d);o.graph=c;let u=A(this.deps,e,"autopilot:schema-result",{graph:c});this.deps.broker.postToWebview(u)}catch(i){this.operations.delete(e.id),this.currentOperationId===e.id&&(this.currentOperationId=n),T(this.deps,"autopilot:scan-schema","autopilot:error",e,i),Ae(this.deps,"error","Autopilot",`Schema scan failed: ${I(i)}`)}}async readClassificationOf(e,t){try{let r=await B(e,this.deps.orgRegistry,this.deps.orgManager);return await pa(fa(r),t)}catch(r){let n=I(r);return{requests:0,objects:new Map(t.map(o=>[o,{fields:new Map,refused:n}]))}}}async handleGeneratePlan(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=this.resolveCurrentOperation();if(!t?.graph){Ae(this.deps,"error","Autopilot","No schema scan result available. Run scan-schema first.");return}let r=x(Zy,e,"autopilot:error",this.deps);if(!r)return;let n=r;try{let o=n.complianceFramework!=="none"&&t.scanResult?await this.readClassificationOf(t.sourceOrgId,[...t.scanResult.objectDescribes.keys()]):void 0,i=n.complianceFramework!=="none"&&t.scanResult?XR(this.deps.infraServices?.piiDetector??new ga,t.scanResult.objectDescribes,o?.objects,n.complianceFramework==="every_personal_field"):[],{profile:a,rules:d}=this.orchestrator.buildCompliance(n.complianceFramework,[],i);t.profile=a,t.rules=d;let c=Vl(this.orchestrator.generatePlan(t.graph,n.complianceFramework,d,t.scanResult?.scope),o,t.scanResult?.objectDescribes);t.plan=c,t.fit&&(t.fit={...t.fit,plan:Vl(this.orchestrator.generatePlan(t.fit.graph,n.complianceFramework,d,t.fit.scan.scope),o,t.scanResult?.objectDescribes)}),await this.sendPlanReady(e,t)}catch(o){T(this.deps,"autopilot:generate-plan","autopilot:error",e,o),Ae(this.deps,"error","Autopilot",`Plan generation failed: ${I(o)}`)}}async sendPlanReady(e,t,r,n){let{plan:o,graph:i}=t.fit??t,a=t.fit?.scan??t.scanResult;if(!o||!i)return;let d=async()=>{try{return a?await this.planWriteGate(t,Xl(o,a.recordCounts,a.personAccounts),r??await this.readTargetDataStorage(t.targetOrgId)):void 0}catch(p){this.deps.log(`[WARN] ${e.type}: what the plan comes to against the target could not be told (${I(p)})`);return}},[c,u]=await Promise.all([d(),this.planValidationRules(t,o,a).catch(p=>{this.deps.log(`[WARN] ${e.type}: the target's validation rules could not be listed (${I(p)})`)})]);if((t.fit??t).plan!==o)return;let l=A(this.deps,e,"autopilot:plan-ready",{plan:o,graph:i,...c?{writeGate:c}:{},...u?{validationRules:u}:{},...n?{fitNotApplied:n}:{}});this.deps.broker.postToWebview(l)}async planValidationRules(e,t,r){let n=e.scanResult;if(!e.plan||!n||!r)return;let o=(c,u)=>Qs(c).filter(l=>(u.get(l)??0)>0),i=await import("./chunk-STQ2JMIZ.mjs"),a=e.validationRules??=this.readPlanRules(e.targetOrgId,o(e.plan,n.recordCounts)),d=await a;return d.unread!==void 0&&e.validationRules===a&&(e.validationRules=void 0),i.planValidationRulesFor(d,o(t,r.recordCounts))}async readPlanRules(e,t){try{let{planRulesReadsOver:r,readPlanValidationRules:n}=await import("./chunk-STQ2JMIZ.mjs"),o=await B(e,this.deps.orgRegistry,this.deps.orgManager);return await new pe(Wf).withTimeout("autopilot:validation-rules",()=>n(r(o),t))}catch(r){return{rules:[],unread:I(r)}}}async planWriteGate(e,t,r,n){let{targetOrgId:o,sourceOrgId:i}=e,[a,d]=await Promise.all([iv(t,r,()=>this.readApiBudgetOf(o),n),t.totalRows>0?dv(t,()=>this.readApiBudgetOf(i)):void 0]),c=this.sourceReadBefore(e);return dT(t,Sr(t,r),a,d&&{org:we(this.deps.orgManager.getOrg(i),i),check:d,...c?{readBefore:c}:{}})}sourceReadBefore(e){return av(e.scanResult?.sourceRequests,e.fit?.report)}refuseFit(e,t,r,n){T(this.deps,e.type,"autopilot:error",e,new Error(r),{code:t,...n?{extraPayload:n}:{}})}async handleFitPlan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let{orchestrator:t}=this;if(!t){this.refuseNotReady(e);return}let r=x(tw,e,"autopilot:error",this.deps);if(!r)return;let n=this.resolveCurrentOperation(),{plan:o,graph:i,rules:a,scanResult:d}=n??{};if(!n||!o||!i||!a||!d){this.refuseFit(e,qo.NO_PLAN,"No execution plan available. Run generate-plan first.");return}let{targetOrgId:c}=n;if(this.writingTargets.has(c)){this.refuseFit(e,hs.code,hs.message);return}try{let u=await this.readTargetAutomation(c,o),l=r.muteAutomation===!0?await this.planMute(c,u).catch(v=>{if(!jt(v))throw v}):void 0,p=await this.readTargetDataStorage(c),f=r.checkpointFirst!==void 0?await this.checkpointFirstOf(e,c,o,r.checkpointFirst,{read:u,...l?{mute:l}:{}},new AbortController().signal):void 0,g=VR({storage:p,...r.mode.withinMB!==void 0?{withinMB:r.mode.withinMB}:{},api:"unread"in p?await this.readApiBudgetOf(c).catch(v=>({unread:I(v)})):p.dailyApiRequests??{unread:"the target's /limits did not list them"},otherRequests:Bo(f&&"estimate"in f?f.estimate:void 0)});if("unread"in g){this.refuseFit(e,qo.STORAGE_UNREAD,`The plan cannot be fitted: the target's data storage left could not be read (${g.unread}). Give the most MB it may use to fit it to that.`,{reason:g.unread});return}let h=await B(n.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),m=await B(c,this.deps.orgRegistry,this.deps.orgManager),y;try{y=await t.fitPlan(h,{scan:d,graph:i,plan:o,rules:a,mode:r.mode,budget:g,automation:u,...l?.plan?{mutePlan:l.plan}:{},describeLookups:async v=>nv((await m.describe(v)).fields)})}catch(v){let b=I(v);this.refuseFit(e,qo.READ_REFUSED,`The plan could not be fitted: the source refused a read of it (${b}).`,{reason:b});return}if(n.plan!==o||this.currentOperationId!==n.id||this.writingTargets.has(c)){this.refuseFit(e,qo.STALE,"The plan changed while it was fitted: fit it again.");return}if(y.fitted){n.fit={...y.fitted,report:y.report},await this.sendPlanReady(e,n,p);return}y.report.cannotFit===void 0&&(n.fit=void 0),await this.sendPlanReady(e,n,p,y.report)}catch(u){T(this.deps,"autopilot:fit-plan","autopilot:error",e,u)}}async handleFitUndo(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=this.resolveCurrentOperation();if(!t?.plan){this.refuseFit(e,qo.NO_PLAN,"No execution plan available. Run generate-plan first.");return}if(this.writingTargets.has(t.targetOrgId)){this.refuseFit(e,hs.code,hs.message);return}t.fit=void 0;try{await this.sendPlanReady(e,t)}catch(r){T(this.deps,"autopilot:fit-undo","autopilot:error",e,r)}}async handleExecute(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=this.resolveCurrentOperation();if(!t?.plan||!t.graph||!t.rules||!t.scanResult){Ae(this.deps,"error","Autopilot","No execution plan available. Run generate-plan first.");return}let r=x(ew,e,"autopilot:error",this.deps);if(!r)return;let n=r,{rules:o,fit:i}=t,a=i?.plan??t.plan,d=i?.graph??t.graph,c=i?.scan??t.scanResult,u=this.deps.infraServices?.productionGuard;if(!u){Y(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:ve.code}),T(this.deps,"autopilot:execute","autopilot:error",e,new Error(ve.message),{code:ve.code});return}if(this.writingTargets.has(t.targetOrgId)){T(this.deps,"autopilot:execute","autopilot:error",e,new Error(hs.message),{code:hs.code});return}this.writingTargets.set(t.targetOrgId,e.id),this.runningRequests.add(e.id);try{await this.executeRun(e,t,{plan:a,graph:d,rules:o,scanResult:c,...i?{fit:i}:{}},n,u)}finally{this.writingTargets.delete(t.targetOrgId),this.runningRequests.delete(e.id)}}async executeRun(e,t,{plan:r,graph:n,rules:o,scanResult:i,fit:a},d,c){if(!this.orchestrator)return;let u=Array.from(i.recordCounts.values()).reduce((q,F)=>q+F,0),l=a?cT(a.report,u,[...t.scanResult?.recordCounts.values()??[]].reduce((q,F)=>q+F,0)):void 0,p=new AbortController,f=()=>{},g=new Promise((q,F)=>{f=ne=>ne===void 0?q():F(ne)});g.catch(()=>{}),this.registry?.register(e.id,"autopilot","Autopilot run",g,p);let h=this.deps.orgManager.getOrg(t.targetOrgId),m={orgId:t.targetOrgId,orgTier:Pe(h),operation:"insert",objectName:r.waves[0]?.objects[0]??"AutopilotData",recordCount:u,module:"autopilot"},{check:y,decision:v}=await et(c,m),b=v;if((v==="refused"||v==="declined")&&Y(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:v,...l?{fit:l}:{}}),v==="refused"){let q=bn(y.blockedReason??y.impactSummary);T(this.deps,"autopilot:execute","autopilot:error",e,q,{code:Dt.blocked}),f(q);return}if(v==="declined"){let q="Operation cancelled by user (confirmation declined).";T(this.deps,"autopilot:execute","autopilot:error",e,new Error(q),{code:Dt.declined}),f(new Error(q));return}let k=Xl(r,i.recordCounts,i.personAccounts),S,C;if(d.muteAutomation===!0)try{({mute:S,read:C}=await this.runMute(t.targetOrgId,r))}catch(q){if(!jt(q))throw q;Y(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:b,...l?{fit:l}:{},code:q.code}),T(this.deps,"autopilot:execute","autopilot:error",e,q,{code:q.code}),f(q);return}let R;if(d.checkpointFirst!==void 0&&k.totalRows>0){C??=await this.readTargetAutomation(t.targetOrgId,r);let q=await this.checkpointFirstOf(e,t.targetOrgId,r,d.checkpointFirst,{read:C,mute:S},p.signal);if("refused"in q){Y(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:b,...l?{fit:l}:{},code:Ys.CHECKPOINT_REFUSED});let F=new Error(q.refused);T(this.deps,"autopilot:execute","autopilot:error",e,F,{code:Ys.CHECKPOINT_REFUSED}),f(F);return}R=q}k.totalRows>0&&(C??=await this.readTargetAutomation(t.targetOrgId,r));let w=await this.targetEmails(t.targetOrgId,r,k,S?S.automation:C),P=new Set(k.objects.map(({objectApiName:q})=>q)),O=(q,F)=>P.has(q)&&zf(q,F),E=we(h,t.targetOrgId),$=we(this.deps.orgManager.getOrg(t.sourceOrgId),t.sourceOrgId),H=C?await ir({read:C,...S?.plan?{plan:S.plan}:{},writes:O,readDeliverability:async()=>m.orgTier==="production"?Gt:Jt(await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager)),accepted:!1,target:E,run:"autopilot",keepsAddresses:d.keepContactPoints===!0}):void 0,J=this.sourceReadBefore(t),W=await cv({plan:k,storage:await this.readTargetDataStorage(t.targetOrgId),readApiBudget:()=>this.readApiBudgetOf(t.targetOrgId),confirmAboveRecords:this.confirmAboveRecords(),emails:w.checks,...w.unread!==void 0?{emailsUncounted:w.unread}:{},org:E,orgTier:m.orgTier,confirm:q=>c.confirmRun(q),...R?{checkpointFirst:R}:{},readBack:sv(k),mute:br(S?.plan),...H?{runEmails:H}:{},source:{org:$,readApiBudget:()=>this.readApiBudgetOf(t.sourceOrgId),...J?{readBefore:J}:{}}});if(!W.go){Y(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:b,...l?{fit:l}:{},code:W.code,details:so(W.emails)});let q=new Error(W.message),F="source"in W?W.source:void 0;T(this.deps,"autopilot:execute","autopilot:error",e,q,{code:Ys[W.code],...F?{extraPayload:{source:{org:$,...F}}}:await this.fitOffer(t,W,k,R)}),f(q);return}this.liveTracker?.register(e.id,"autopilot","Autopilot run",u),Tt({action:"autopilot_execute",orgId:t.targetOrgId,operationId:e.id},{mb:W.check.estimateMB,rowBytes:Ga(k)}),this.executingOperations.add(t.id);let Z=new Map,_=!1,Q=S?.muted,N=W.checkpoint,z,oe=!1,re=(q,F)=>{_||(_=!0,Y(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:q,guard:b,objects:[...Z.values()],source:{origin:"org",orgId:t.sourceOrgId},...q==="stopped"?{code:ot}:{},...Q?{muted:ft(Q)}:{},...z?.state==="taken"?{checkpointId:z.checkpointId}:{},...l?{fit:l}:{},details:{...so(W.emails),...Kr(F).details}}))};try{d.grappeThreshold&&this.deps.log(`[GRAPPE] autopilot threshold set to ${d.grappeThreshold}`);for(let j of r.waves)for(let se of j.objects)this.sendNodeProgress(e,String(se),"processing",j.order);let q=new Map;for(let j of r.waves)for(let se of j.objects)q.set(String(se),j.order);let F=S?.prepared?await S.prepared.acquire(e.id).catch(j=>{if(!jt(j))throw j;return j}):void 0;if(jt(F)){N&&(z=await this.settleCheckpoint(N,!1)),_=!0,Y(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:b,...l?{fit:l}:{},code:F.code}),this.liveTracker?.fail(e.id,F.message),T(this.deps,"autopilot:execute","autopilot:error",e,F,{code:F.code,...z?{extraPayload:{checkpoint:z}}:{}}),f(F);return}F&&(Q=F.outcome);let ne=F?H?.afterLease(F.outcome,W.emails?.accepted===!0):void 0;if(F&&ne){Q=await F.release(),N&&(z=await this.settleCheckpoint(N,!1)),_=!0,Y(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:b,code:ne.code,muted:ft(Q),details:so(W.emails)});let j=Kb(ne.message,"autopilot","Untick Mute automation to be asked about them and run it all the same"),se=new Error(j);this.liveTracker?.fail(e.id,j),T(this.deps,"autopilot:execute","autopilot:error",e,se,{code:Ys.EMAILS_NOT_ACCEPTED,...z?{extraPayload:{checkpoint:z}}:{}}),f(se);return}oe=!0;let de=await this.orchestrator.executePlan(r,n,o,i.recordCounts,j=>{let se=String(j.objectApiName);Z.set(se,{...bt(se),...j.type==="node-completed"?{created:j.successCount,failed:j.failureCount}:{created:j.partialSuccessCount,failed:j.failureCount??0}});let U=[...Z.values()].reduce((te,Se)=>te+Se.created+Se.failed,0);this.liveTracker?.updateProgress(e.id,u>0?Math.round(U/u*100):0,U,u,se),j.type==="node-completed"?this.sendNodeProgress(e,se,"completed",q.get(se)??0,{recordCount:j.successCount,failureCount:j.failureCount,linkedCount:j.linkedCount,refusals:j.refusals,apiCallsUsed:j.apiCallsUsed}):this.sendNodeProgress(e,se,"failed",q.get(se)??0,{recordCount:j.partialSuccessCount,failureCount:j.failureCount,linkedCount:j.linkedCount,refusals:j.refusals,error:j.errors[0]??`Execution failed for ${se}`})},p.signal,i.parentIds,{...d.keepContactPoints===!0?{keepContactPoints:!0}:{},...F?{lease:{assigned:F.outcome.assigned.length,giveBack:()=>F.release()}}:{},...a?{fit:a.run}:{}}).finally(async()=>{F&&(Q=await F.release())});N&&(z=await this.settleCheckpoint(N,de.totalSuccess>0));let Ze=new Set(de.completedObjects),xe=new Set(de.failedObjects),Ue=new Set(de.skippedObjects),V=new Set(de.stoppedObjects??[]),ae=[],ee=0,fe=[],D=[];for(let j of r.waves)for(let se of j.objects){let U=String(se),te=de.objectOutcomes?.[U],Se=de.statuses?.[U],De=de.lookups?.[U],qe=(te?.leftToThePlatform??[]).reduce((Ce,zn)=>Ce+zn.count,0),ce={...te?{recordCount:te.written,failureCount:te.failed,linkedCount:te.linked,refusals:te.refusals,...qe>0?{leftToThePlatform:qe}:{},...te.currenciesReplaced?{currenciesReplaced:te.currenciesReplaced}:{},...te.pricesSettled?{pricesSettled:te.pricesSettled}:{},...te.recordTypeGiven?{recordTypeGiven:te.recordTypeGiven}:{},...te.cutSinceFit!==void 0?{cutSinceFit:te.cutSinceFit}:{},...te.sentAgainForALock?{sentAgainForALock:te.sentAgainForALock}:{}}:{},...Se?{statusesApplied:Se.applied,statusRefusals:Se.refusals}:{},...De?{lookupsFilled:De.filled,lookupRefusals:De.refusals}:{}};if(Ze.has(U))this.sendNodeProgress(e,U,"completed",j.order,{recordCount:i.recordCounts.get(U)??0,failureCount:0,...ce});else if(xe.has(U))this.sendNodeProgress(e,U,"failed",j.order,{...ce,error:de.nodeErrors?.[U]??`Execution failed for ${U}`});else if(Ue.has(U)){let Ce=i.recordCounts.get(U)??0;Z.set(U,{...bt(U),skipped:"counted",...Ce>0?{notSent:Ce}:{}}),this.sendNodeProgress(e,U,"skipped",j.order,{recordCount:0,failureCount:0,...Ce>0?{notSent:Ce}:{}})}else if(V.has(U)){let Ce=te?.notSent??0;ee+=te?.heldForTheirTask??0,Z.set(U,{...bt(U),created:te?.written??0,failed:te?.failed??0,...Ce>0?{notSent:Ce}:{}}),this.sendNodeProgress(e,U,"stopped",j.order,{...ce,recordCount:te?.written??0,failureCount:te?.failed??0,...Ce>0?{notSent:Ce}:{}})}let Ee=()=>Z.get(U)??{...bt(U),created:te?.written??0,failed:te?.failed??0},Ne=te?.lookupsLeftEmpty??0,it=te?.statusesNotGivenBack??0;if(Ne+it>0){let Ce={...Ne>0?{lookupsLeftEmpty:Ne}:{},...it>0?{statusesNotGivenBack:it}:{}};ae.push({objectApiName:U,...Ce}),Z.set(U,{...Ee(),...Ce})}De?.leftEmpty!==void 0&&(fe.push({objectApiName:U,records:De.leftEmpty,refusals:De.refusals}),Z.set(U,{...Ee(),lookupsNotFilled:De.leftEmpty}));let nt=Se?.leftDraft??0;Se&&nt>0&&(D.push({objectApiName:U,records:nt,refusals:Se.refusals}),Z.set(U,{...Ee(),statusesNotApplied:nt}))}let G=rv(de);re(de.stopped?de.totalSuccess+de.totalFailure>0?"cancelled":"stopped":G,de.contactPoints);let ue=A(this.deps,e,"autopilot:completed",{status:G,totalRecords:de.totalSuccess+de.totalFailure+de.totalSkipped,totalSuccessCount:de.totalSuccess,totalFailureCount:de.totalFailure,totalElapsedMs:de.elapsedMs,totalApiCalls:0,...Q?{mutedAutomation:Q}:{},...z?{checkpoint:z}:{},...de.cutSinceFit!==void 0?{cutSinceFit:de.cutSinceFit}:{},...fe.length>0?{lookupsNotFilled:fe}:{},...D.length>0?{statusesNotApplied:D}:{},...de.stopped?{stopped:!0,notWritten:de.stoppedObjects??[],...ae.length>0?{leftByStop:ae}:{},...ee>0?{emailsHeldForTheirTask:ee}:{}}:{}});this.deps.broker.postToWebview(ue),de.stopped?this.liveTracker?.cancel(e.id):G==="failure"?this.liveTracker?.fail(e.id,de.fatalError??"No record could be written."):G==="partial"?this.liveTracker?.partial(e.id):this.liveTracker?.complete(e.id),f()}catch(q){this.liveTracker?.fail(e.id,I(q)),f(q),N&&z===void 0&&(z=await this.settleCheckpoint(N,oe)),re("failure"),T(this.deps,"autopilot:execute","autopilot:error",e,q,z?{extraPayload:{checkpoint:z}}:void 0),Ae(this.deps,"error","Autopilot",`Execution failed: ${I(q)}`)}finally{this.executingOperations.delete(t.id)}}maxRecordsPerObject(){let e=this.deps.services?.getSandforgeSetting?.("forge.maxRecordsPerObject",5e4);return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.floor(e),Wi):5e4}confirmAboveRecords(){let e=this.deps.services?.getSandforgeSetting?.("safety.confirmAboveRecords",en);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):en}async readTargetDataStorage(e){try{let t=await B(e,this.deps.orgRegistry,this.deps.orgManager);return await new pe(qf).withTimeout("autopilot:limits",()=>vr(Vt(t,e)))}catch(t){return{unread:I(t)}}}setMuteLeases(e){this.muteLeases=e}muteLeases={};async runMute(e,t){let r=await this.readTargetAutomation(e,t);return{mute:await this.planMute(e,r),read:r}}planMute(e,t){return Et(async()=>_t(await B(e,this.deps.orgRegistry,this.deps.orgManager)),t,{...this.muteLeases,writes:zf})}async readTargetAutomation(e,t){let r=this.targetAutomation;return new pe(Wf).withTimeout("autopilot:automation",()=>r.read(e,Qs(t))).catch(n=>({unread:I(n)}))}async checkpointFirstOf(e,t,r,n,o,i){let a=this.beforeRunCheckpoints;if(!a)return{refused:Rr(new Error("SandForge's checkpoints are not set up in this window"))};let{read:d,mute:c}=o,u="objects"in d?gr(d,c?.plan,zf):{firing:[]},l={module:"autopilot",orgId:t,operationId:e.id,written:Qs(r),running:u,request:n},p={operationId:lT(e.id)};try{return{estimate:await a.scope(l,p),take:g=>a.take(l,p,{planned:g,signal:i})}}catch(f){return{refused:Rr(f)}}}async settleCheckpoint(e,t){let r=this.beforeRunCheckpoints;if(!r)return e;try{return await r.settle(e,t)}catch(n){return this.deps.log(`[WARN] autopilot:execute: the checkpoint '${e.name}' taken before the run is kept, as it could not be settled (${I(n)})`),e}}async fitOffer(e,t,r,n){if(t.code!=="STORAGE_EXCEEDED"&&t.code!=="API_BUDGET_EXCEEDED")return{};let{targetOrgId:o}=e,{check:i}=t,a=this.deps.orgManager.getOrg(o),d={org:we(a,o),estimateMB:i.estimateMB,...i.verdict==="unread"?{}:{remainingMB:i.remainingMB,maxMB:i.maxMB,...kr(i)}};try{let c=await this.planWriteGate(e,r,await this.readTargetDataStorage(o),n?.estimate);return{extraPayload:{...d,writeGate:c}}}catch(c){return this.deps.log(`[WARN] autopilot:execute: what the plan comes to could not be read again (${I(c)})`),{extraPayload:d}}}async readApiBudgetOf(e){let t=await B(e,this.deps.orgRegistry,this.deps.orgManager);return new pe(qf).withTimeout("autopilot:limits",()=>ar(t))}async targetEmails(e,t,r,n){let o=this.targetAutomation,i=await ov({plan:r,objects:Qs(t),readAutomation:a=>n?"objects"in n?Promise.resolve(n):Promise.reject(new Error(n.unread)):new pe(Wf).withTimeout("autopilot:automation",()=>o.read(e,a)),readLimits:async()=>{let a=await B(e,this.deps.orgRegistry,this.deps.orgManager);return new pe(qf).withTimeout("autopilot:limits",()=>Or(a))}});i.unread!==void 0&&this.deps.log(`[WARN] autopilot:execute: the emails the target's flows send were not counted: ${i.unread} could not be read`);for(let a of i.checks.filter(d=>d.verdict==="unread"))this.deps.log(`[WARN] autopilot:execute: about ${a.emails} ${a.limit} from the target's flows, against a limit that could not be read: ${a.unread??""}`);return i}sendNodeProgress(e,t,r,n,o){let i=A(this.deps,e,"autopilot:node-progress",{nodeId:t,objectName:t,status:r,wave:n,...o??{}});this.deps.broker.postToWebview(i)}hasExecutingOperation(){return this.executingOperations.size>0}handlePause(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}if(!this.hasExecutingOperation()){Ae(this.deps,"warning","Autopilot","No autopilot execution in progress.");return}try{this.orchestrator.pause();for(let t of this.runningRequests)this.liveTracker?.pause(t);Ae(this.deps,"info","Autopilot","Execution paused.")}catch(t){T(this.deps,"autopilot:pause","autopilot:error",e,t),Ae(this.deps,"error","Autopilot",`Pause failed: ${I(t)}`)}}handleResume(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}if(!this.hasExecutingOperation()){Ae(this.deps,"warning","Autopilot","No autopilot execution in progress.");return}try{this.orchestrator.resume();for(let t of this.runningRequests)this.liveTracker?.resume(t);Ae(this.deps,"info","Autopilot","Execution resumed.")}catch(t){T(this.deps,"autopilot:resume","autopilot:error",e,t),Ae(this.deps,"error","Autopilot",`Resume failed: ${I(t)}`)}}handleSkipNode(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=x(rw,e,"autopilot:error",this.deps);if(!t)return;let r=t;if(!this.hasExecutingOperation()){Ae(this.deps,"warning","Autopilot","No autopilot execution in progress.");return}try{this.orchestrator.skip(r.objectApiName),Ae(this.deps,"info","Autopilot",`Skipped node: ${r.objectApiName}`)}catch(n){T(this.deps,"autopilot:skip-node","autopilot:error",e,n),Ae(this.deps,"error","Autopilot",`Skip failed: ${I(n)}`)}}handleComplianceReport(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=this.resolveCurrentOperation();if(!t?.profile||!t.rules||!t.scanResult){Ae(this.deps,"error","Autopilot","No compliance data available. Run generate-plan first.");return}try{let r=t.fit?.scan??t.scanResult,n=this.orchestrator.generateReport(t.profile,t.rules,r.recordCounts,"","",r.totalObjectsScanned),o=A(this.deps,e,"autopilot:compliance-report",{report:n});this.deps.broker.postToWebview(o)}catch(r){T(this.deps,"autopilot:compliance-report","autopilot:error",e,r),Ae(this.deps,"error","Autopilot",`Report generation failed: ${I(r)}`)}}};import{dirname as Xf}from"node:path";import{AsyncLocalStorage as Kj}from"node:async_hooks";var Yj=new Kj;async function pT(s){let e=new Map;return{result:await Yj.run(e,s),sent:e}}function fT(s,e){let t=s.get(e.sourceOrgId)??0,r=e.targetOrgId===e.sourceOrgId?0:s.get(e.targetOrgId)??0;return t+r>0?{source:t,target:r}:void 0}import*as Gf from"node:path";var Xc="forge:imported-templates",Qj=10,gT="forge",Zj=K({folder:L().min(1),templates:Re(hn()),replacing:Re(L())});function ln(s){if(typeof s!="object"||s===null||Array.isArray(s))return!1;let{id:e}=s;return typeof e=="string"&&e.length>0}function Ti(s,e,t){let r=new Map;for(let i of e)r.has(i.id)||r.set(i.id,i);let n=s.map(i=>t.has(i.id)?r.get(i.id)??i:i),o=new Set(s.map(i=>i.id));for(let[i,a]of r)o.has(i)||n.push(a);return n}function Jf(s,e){return Gf.resolve(s)===Gf.resolve(e)}function Vf(s){let e=s.get(Xc);if(!Array.isArray(e))return[];let t=[];for(let r of e){let n=Zj.safeParse(r);if(!n.success)continue;let{folder:o,templates:i,replacing:a}=n.data;t.push({folder:o,templates:i.filter(ln),replacing:a})}return t}function Kc(s,e){return Vf(s).find(t=>Jf(t.folder,e))}function hT(s,e,t,r){if(t.length===0)return;let n=Vf(s),o=n.findIndex(d=>Jf(d.folder,e)),i=o>=0?n.splice(o,1)[0]:void 0,a=new Map((i?.templates??[]).map(d=>[d.id,d]));for(let d of t)a.set(d.id,d);n.push({folder:i?.folder??e,templates:[...a.values()],replacing:[...new Set([...i?.replacing??[],...r])]}),s.set(Xc,n.slice(-Qj),gT)}function mT(s,e){let t=Vf(s).filter(r=>!Jf(r.folder,e));t.length>0?s.set(Xc,t,gT):s.delete(Xc)}function eM(s){return{...s.window?{window:{field:s.window.field,...s.window.from!==void 0?{from:s.window.from}:{},...s.window.to!==void 0?{to:s.window.to}:{},...s.window.lastDays!==void 0?{lastDays:s.window.lastDays}:{}}}:{},...s.whereObjects?{whereObjects:[...s.whereObjects]}:{},...s.strataFields?{strataFields:[...s.strataFields]}:{}}}function tM(s){return{seed:s.seed,draw:s.draw,share:s.share,sha256:s.sha256,drawnAt:s.drawnAt,...s.drawnBy?{drawnBy:s.drawnBy}:{},...s.drawnAgain?{drawnAgain:s.drawnAgain}:{},...s.ofTheRunRetried?{ofTheRunRetried:!0}:{},...s.roots?{roots:eM(s.roots)}:{},objects:s.objects.map(e=>({objectApiName:e.objectApiName,sourceRows:e.sourceRows,kept:e.kept,roots:e.roots,below:e.below,asParents:e.asParents,...e.whole?{whole:e.whole}:{},...e.childrenCut?{childrenCut:e.childrenCut.map(({field:t,rows:r})=>({field:t,rows:r}))}:{},...e.rootsInTheSource!==void 0?{rootsInTheSource:e.rootsInTheSource}:{},...e.rootsInTheDraw!==void 0?{rootsInTheDraw:e.rootsInTheDraw}:{},written:e.written,goneSinceTheSample:e.goneSinceTheSample,changedSinceTheSample:e.changedSinceTheSample})),...s.leftEmpty?{leftEmpty:s.leftEmpty.map(({objectApiName:e,field:t,rows:r})=>({objectApiName:e,field:t,rows:r}))}:{}}}function yT(s){let{leftOut:e,...t}=s.graph,r=new Map;for(let l of e??[])r.set(l.reason,(r.get(l.reason)??0)+1);let n=[...r].map(([l,p])=>({reason:l,count:p})).sort((l,p)=>p.count-l.count||l.reason.localeCompare(p.reason)),{idRemapWithTheirRecord:o,sample:i,config:a,...d}=s,c=s.remapInJournal?void 0:o,u=a?.sample?{...a.sample}:void 0;return u&&delete u.plan,{...d,graph:{...t,edges:[],withoutEdges:!0},...a?{config:u?{...a,sample:u}:a}:{},...i?{sample:tM(i)}:{},...n.length>0?{leftOutCounts:n}:{},...c?{idRemapWithTheirRecord:c}:{}}}var wT="SELECT Id, Name, Username FROM User WHERE IsActive = true AND UserType = 'Standard' ORDER BY Name LIMIT 2001";function bT(s,e){let t=s.flatMap(r=>{let{Id:n,Name:o,Username:i}=r;return typeof n!="string"||typeof o!="string"?[]:[{id:n,name:o,username:typeof i=="string"?i:""}]});return{users:t.slice(0,2e3),truncated:e||t.length>2e3}}var eg=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/,Bn=L().min(1).max(128),nM=K({recordId:L().regex(eg,"Invalid Salesforce record ID"),orgId:Bn}),qn=Dg.superRefine((s,e)=>{if(s.inputMode!=="org"&&s.depth!=="all"&&s.sample===void 0)return;let t=Vu(s);t!==void 0&&e.addIssue({code:"custom",message:t,path:["inputMode"]});let r=oM(s.sample);r!==void 0&&e.addIssue({code:"custom",message:r.message,path:r.path})});function oM(s){if(s?.plan!==void 0)return{message:"The panel names no plan of a sample: a run takes up the plan of its last simulation of itself. plan must be left out",path:["sample","plan"]};if(s?.maxTotal!==void 0)return{message:"The panel bounds a sample by the data storage it may take, not by its records (the command line\u2019s --max-total). maxTotal must be left out",path:["sample","maxTotal"]}}var sM=K({config:qn}),iM=K({graph:Hr,config:qn,anonymizationRules:zi.optional(),files:jg.optional(),retryOf:L().min(1).max(200).optional(),reviewSkipped:Ve().optional(),muteAutomation:Ve().optional(),checkpointFirst:Mm.optional()}).superRefine((s,e)=>{let t=Ng(s.config,s.files);t!==void 0&&e.addIssue({code:"custom",message:t,path:["files"]})});function aM(s,e){let t=s.check(e);return{check:t,decision:t.allowed?"allowed":"refused"}}var RT="FILES_NOT_ACCEPTED",vT="RETRY_UNAVAILABLE",dM="GRAPH_WITHOUT_EDGES",cM="This graph is the one the history keeps of a clone of the whole org, without the relations between its objects, and cannot be run as it is. Discover the org again from the Forge panel. Nothing was read or written.",uM="WHOLE_ORG_DIRECT",lM="A clone of the whole org is not started by Clone directly: Review lists what it leaves out and the personal fields it copies as they are. Open Review and execute it from there. Nothing was read or written.",pM="WHOLE_ORG_REHEARSAL",fM="A clone of the whole org is not rehearsed: a rehearsal holds every row it prepares. Simulate it, which stops at its gate, and its confirmation lists what it writes. Nothing was read or sent.",gM="A clone of the whole org keeps its journal on disk, which could not be opened. Nothing was written.",Kf="JOURNAL_UNAVAILABLE",hM="RESUME_TARGET_UNREAD",pn=class extends Error{constructor(t,r){super(r);this.code=t;this.name="ForgeRunRefusal"}code};function ST(s){let e=s!==null&&typeof s=="object"&&"code"in s?String(s.code):void 0,t=e==="ENOSPC"||e==="EDQUOT"?"Free some space on that disk":e==="EACCES"||e==="EPERM"||e==="EROFS"?"Let your user write in that folder":"Free some space on that disk, or let your user write in that folder";return{reason:I(s),lift:t}}function mM(s,e){let t=o=>o.catch(i=>{throw e.err??=i,i}),{serverTime:r,readJob:n}=s;return{queryPages:o=>(async function*(){try{yield*s.queryPages(o)}catch(a){throw e.err??=a,a}})(),userId:()=>t(s.userId()),...r?{serverTime:()=>t(r.call(s))}:{},...n?{readJob:o=>t(n.call(s,o))}:{}}}var Qc="A checkpoint taken before the run takes the org back (Checkpoints \u2192 Rewind\u2026); without one, DataOps \u2192 Emptying \u2192 Empty objects empties its objects, every record of them.",ms="JOURNAL_GONE",_n=`The ids of this run's records were kept in its journal, which is gone: they can no longer be removed, verified, retried against or exported from here. ${Qc}`,ys="RUN_NOT_IN_HISTORY",Yf="REMOVAL_RUNNING",Ei="RUN_WRITING",yM="VERIFY_RUNNING",kT="The org this run wrote to is no longer registered. Add the same org again on Organizations, then try again; a sandbox refreshed since is another org, and holds nothing this run wrote.",wM="RESUME_UNAVAILABLE",OT="remove the records it created (Forge \u2192 History), then run the clone again. Nothing was read or written.",IT="RESUME_TARGET_CHANGED",Qf="RESUME_CHANGED",bM=K({forgeId:L().min(1).max(200),graph:Hr.optional(),config:qn.optional(),muteAutomation:Ve().optional()}).strict(),AT=new Set(["cancelled","failure","interrupted"]),Un="Forge execution was aborted before it started. Nothing was written.",Zf="FORGE_RUNNING",RM="FORGE_STOP_AMBIGUOUS",vM={stopped:{code:"DISCOVERY_STOPPED",message:"The discovery was stopped before it finished. Discover again to see the graph."},superseded:{code:"DISCOVERY_SUPERSEDED",message:`The discovery was stopped to make way for a newer one: ${3} discoveries at most are walked at once in this window. Discover again to see the graph.`}},SM=K({requestId:L().min(1).max(200).optional()}).optional(),kM=K({template:Xu}),OM=K({forgeId:L().min(1).max(200),includeChanged:Ve().optional(),sweep:Ve().optional(),again:Ve().optional(),muteAutomation:Ve().optional(),sweepLate:Ve().optional(),sweepUntied:Ve().optional()}),IM=K({forgeId:L().min(1).max(200),again:Ve().optional(),sweptObjects:jm.optional()}),AM=K({forgeId:L().min(1).max(200)}),TM=K({forgeId:L().min(1).max(200),recordId:L().regex(eg,"Invalid Salesforce record ID")}).strict(),EM=K({forgeId:L().min(1).max(200)}).strict(),PM=K({forgeId:L().min(1).max(200)}).strict(),CM=5e3,$M=K({templateId:L().min(1).max(200)}),xM=K({graph:Hr,config:qn}),DM=K({sourceOrgId:Bn,objects:Re(L().regex(/^[A-Za-z][A-Za-z0-9_]*$/).max(80)).max(2e3)}),NM=K({framework:L().min(1).max(50),graph:Hr,config:qn,anonymizationRules:zi.optional()}),jM=K({sourceOrgId:Bn,targetOrgId:Bn,objectApiNames:Re(L().regex(/^[A-Za-z][A-Za-z0-9_]*$/).max(80)).max(100)}),MM=K({graph:Hr,config:qn,anonymizationRules:zi.optional()}),LM=K({targetOrgId:Bn,graph:Hr}),FM=K({graph:Hr,config:qn}),_M=K({orgId:Bn}),UM=K({targetOrgId:Bn,objectApiNames:Re(L().min(1).max(255)).max(5e3)}),HM=K({graph:Hr,config:qn,muteAutomation:Ve().optional()}).refine(s=>s.config.inputMode==="org",{message:"A sample is drawn from a clone of the whole org alone (inputMode org, depth all)",path:["config","inputMode"]}),BM=K({sourceOrgId:Bn,soqlQuery:L().min(1).max(2e4),maxRoots:Te().int().min(1).max($g).optional()}),qM=[[/Give the most it may take \(--fit-within <MB>\) or the most records \(--max-total <n>\)/g,"Set the MB it may take under Sample settings, on Review,"],[/Lower the bound \(--fit-within or --max-total\), or leave objects out \(--exclude-object\) or narrow them \(--filter\)\./g,"Let it take fewer MB under Sample settings, or leave objects out on Review or narrow them by their filter in Review \u2192 Controls."],[/ Or draw among fewer roots: a window of dates \(--fit-window\) or a filter on the roots of the large objects \(--fit-where\)\./g," Or draw among fewer roots, under Which roots: a window of dates, or a filter on the roots of the large objects."],[/ instead: --fit-where "[^"=]+=([^"]*)"/g," instead, under Which roots: $1"],[/ \(--fit-(?:window|where|strata)\b[^)]*\)/g," (under Which roots)"],[/ \(--exclude-object\)/g," (left out on Review)"],[/--filter leaves records of it out of the copy\./g,"Its filter, in Review \u2192 Controls, leaves records of it out of the copy."]],WM=[[/raise --max-roots \(the sandforge\.forge\.maxRoots setting\)/g,"raise the sandforge.forge.maxRoots setting"],[/raise --max-roots/g,"raise the sandforge.forge.maxRoots setting"]],HT=new Set(["SAMPLE_DRAW_INVALID","SAMPLE_DRAW_EMPTY"]),zM=new Set([...HT,"SAMPLE_STORAGE_UNREAD","SAMPLE_TOO_LARGE"]);function GM(s){if(s.code==="ROOTS_EXCEEDED")return new gt(s.code,WM.reduce((t,[r,n])=>t.replace(r,n),s.message));if(!zM.has(s.code))return s;let e=qM.reduce((t,[r,n])=>t.replace(r,n),s.message);return new gt(s.code,e,void 0,void 0,void 0,{...s.sample?{sample:s.sample}:{}})}var JM="The run to retry cloned the records its query chose, and neither its journal nor its entry in the history keeps them any more: retried, it would write the records its query chooses now, which may be others. Run the clone again from Review.",VM="A sample of the whole org keeps its plan on disk, in the extension\u2019s storage, which this window has none of. Nothing was read or written.",XM=16;function TT(s){let e=s.fit();return e?{fit:e}:{}}function Yc(s,e){let t=0,r=null,n=null,o=a=>{s(...a),t=Date.now(),r=null},i=((...a)=>{r=a;let d=e-(Date.now()-t);d<=0?(n&&(clearTimeout(n),n=null),o(a)):n||(n=setTimeout(()=>{n=null,r&&o(r)},d))});return i.flush=()=>{n&&(clearTimeout(n),n=null),r&&o(r)},i}function KM(){let s=new Map;return e=>{let t=s.get(e.objectName)??{},r={...t,...typeof e.recordCount=="number"?{recordCount:(t.recordCount??0)+e.recordCount}:{},...typeof e.fieldCount=="number"?{fieldCount:e.fieldCount}:{},...typeof e.createableFieldCount=="number"?{createableFieldCount:e.createableFieldCount}:{}};return s.set(e.objectName,r),{...e,...r}}}function st(s,e,t,r){return x(s,e,t,r)}var YM={holder:s=>Gv(s),take:(s,e)=>{let t=zv(s,{...e,ranFrom:"editor"});return"busy"in t?t:{release:()=>t.lock.release()}}};function Pi(s){return s.charAt(0).toUpperCase()+s.slice(1)}function Hn(s,e=1){s.requests+=e,s.target!==void 0&&(s.target+=e)}function QM(s,e){let t=new Set,r=e.find(n=>n.forgeId===s);for(;r&&!t.has(r.forgeId);){if(t.add(r.forgeId),r.checkpoint?.state==="taken")return r.checkpoint;let n=r.retryOf;r=n===void 0?void 0:e.find(o=>o.forgeId===n)}}function ET(s){return s.successCount+s.updatedCount>0}function PT(s,e){let t=new Set,r=s;for(;r&&!t.has(r.forgeId);){if(t.add(r.forgeId),r.undo)return r;let n=r.retryOf;r=n===void 0?void 0:e.find(o=>o.forgeId===n)}}function ZM(s,e=s){let t=new Set([...e.created,...e.unattributed??[]].flatMap(({ids:n})=>n.map(o=>o.slice(0,15)))),r=new Set(s.remap.withTheirRecord??[]);return s.remap.linked.filter(n=>{let o=s.remap.table[n];return!r.has(n)&&o!==void 0&&t.has(o.slice(0,15))}).length}function e0(s,e,t){let r=s.remap.createdByObject.reduce((c,u)=>c+u.sourceIds.length,0),n=Object.keys(s.remap.table).length,o=ZM(s,t),i=new Set(s.remap.withTheirRecord??[]),a=s.remap.linked.filter(c=>i.has(c)),d=n>ed?{idRemapTable:{},idRemapExisting:[],idRemapCreated:[],idRemapByObject:s.remap.createdByObject.map(({objectApiName:c,sourceIds:u})=>({objectApiName:c,created:u.length,linked:0})),remapInJournal:!0,...a.length>0?{withTheirRecordCount:a.length}:{}}:{idRemapTable:s.remap.table,idRemapExisting:s.remap.linked,idRemapCreated:s.remap.createdByObject,...a.length>0?{idRemapWithTheirRecord:a}:{}};return{forgeId:s.parts>1?`${s.journalId}-${s.parts-1}`:s.journalId,status:"partial",interrupted:!0,graph:e,duration:0,timestamp:s.partStartedAt,idRemapCount:n,...d,createdCount:r,linkedExistingCount:s.remap.linked.length,...o>0?{linkedToCreatedCount:o}:{},...ym(s),journalId:s.journalId,journalPart:Math.max(0,s.parts-1),...s.endBefore?{retryOf:s.endBefore.forgeId,resumed:!0}:{},...s.runUserId?{runUserId:s.runUserId}:{},...s.checkpoint?{checkpoint:s.checkpoint}:{}}}var t0=new Set(["forge:preview","forge:discover","forge:execute","forge:pause","forge:resume","forge:abort","forge:templates:list","forge:templates:save","forge:templates:delete","forge:history:list","forge:undo","forge:resume-run","forge:open-record","forge:verify:request","forge:export-ids:request","forge:plan:request","forge:classification:request","forge:compliance:request","forge:metadata-diff:request","forge:rehearse:request","forge:automation:request","forge:undo-automation:request","forge:undo-sweep:request","forge:gaps:request","forge:users:request","forge:target-records:request","forge:sample-budget:request","forge:previewRoots"]),CT=3e4,r0=6e4,n0=18e4,o0=3e4,s0=6e4,Ci=6e4,i0=12e4;function $T(s){let e=Date.parse(s.writtenBetween?.first??""),t=Date.parse(s.writtenBetween?.last??"");if(Number.isFinite(e)&&Number.isFinite(t))return{from:e,to:t};let r=Date.parse(s.timestamp);return{from:r-Math.max(0,s.duration),to:r}}var xT="The history no longer holds this run: what its id map holds cannot be told from what the target\u2019s automation created, and nothing is swept. Remove its records without the sweep.",a0=6e4,d0=10*6e4,c0=8,u0=8,ws=3e4,l0=3e4,DT="forge:templates",NT="forge:history";function jT(s){return s.runUserId!==void 0&&s.undo!==void 0&&!rh(s.undo)}function p0(s,e,t){let r=new Set([s]),n=new Set;for(let o=!0;o;){o=!1;let i=a=>{r.has(a)||(r.add(a),o=!0)};for(let a of e)a.journalId!==void 0&&r.has(a.forgeId)&&!n.has(a.journalId)&&(n.add(a.journalId),o=!0);for(let a of n)for(let d of t.get(a)??[])i(d);for(let a of e){a.journalId!==void 0&&n.has(a.journalId)&&i(a.forgeId);let d=a.retryOf;d!==void 0&&(r.has(a.forgeId)?i(d):r.has(d)&&i(a.forgeId))}}return{inLine:r,journals:n}}function f0(s,e,t,r){let n=new Map;for(let i of[...e,...t])i.retryOf!==void 0&&!n.has(i.forgeId)&&n.set(i.forgeId,i.retryOf);let o=i=>{let a=new Set;for(let d=n.get(i);d!==void 0;d=n.get(d)){if(d===s)return!0;if(a.has(d))return!1;a.add(d)}return!1};return e.flatMap(i=>{if(!i.resumed||i.remapInJournal||i.targetOrgId!==r)return[];if(!o(i.forgeId))return[];let a=i.idRemapTable??{},d=(i.idRemapExisting??[]).flatMap(u=>{let l=a[u];return l!==void 0?[l]:[]}),c=i.wroteToEarlierParts??[];return c.length===0&&d.length===0?[]:[{span:BT(i.writtenBetween,i),...c.length>0?{wrote:c}:{},...d.length>0?{linked:d}:{}}]})}function BT(s,e){return s?{runStartedAt:new Date(s.first),runEndedAt:new Date(s.last)}:{runDurationMs:e.duration,runRecordedAt:new Date(e.timestamp)}}function g0(s,e){let t=[...new Set(s.flatMap(r=>r.keptDependents>0?r.heldBy:[]))];return e.flatMap(r=>{if(r.undo)return[];let n=[...s.map(a=>a.objectApiName),...e.flatMap(a=>a===r?[]:a.objects)],o=$a(r.objects,n),i=t.filter(a=>o.includes(a));return i.length>0?[{forgeId:r.forgeId,objects:i}]:[]})}function h0(s){return s.map(e=>({objectApiName:e.objectApiName,jobId:e.jobId,rows:e.rows,...e.state!==void 0?{state:e.state}:{},...e.processed!==void 0?{processed:e.processed}:{},...e.graceLeftMs!==void 0?{minutesLeft:Math.max(1,Math.ceil(e.graceLeftMs/6e4))}:{}}))}function m0(s){return(s.mayHaveBeenWritten??[]).reduce((e,{sourceIds:t})=>e+t.length,0)}function y0(s,e){if(!e||e.calls===0)return m0({mayHaveBeenWritten:s});let t=e.lookedFor??new Set,r=(s??[]).reduce((n,{sourceIds:o})=>n+o.filter(i=>!t.has(i)).length,0);return Zl(e)+r}function w0(s,e){if(!e.journalRead)return;let t=e.callsNotLookedFor??0,r=e.reconciled?.lookedFor??new Set,n=t>0?0:(s??[]).reduce((o,{sourceIds:i})=>o+i.filter(a=>!r.has(a)).length,0);if(!(t===0&&n===0))return{...t>0?{callsAfterRemoval:t}:{},...n>0?{notJournaled:n}:{}}}function b0(s,e){if(!s)return;let t=s.map(r=>({...r}));for(let{objectApiName:r,rows:n}of e){let o=t.find(i=>i.objectApiName===r);o?o.created+=n:t.push({objectApiName:r,created:n,linked:0})}return t}var MT="forge";function R0(s){let e={...s};return delete e.sourceOrgId,delete e.targetOrgId,e}function v0(s){let e=(s.errors??[]).filter(r=>!r.objectApiName.startsWith("__")),t=[...new Set(e.filter(r=>r.failedCount>0||r.skipped).map(r=>r.objectApiName))];return{status:s.status,created:s.createdCount??s.idRemapCount-(s.linkedExistingCount??0),linked:s.linkedExistingCount??0,updated:s.updatedCount??0,failed:e.reduce((r,n)=>r+n.failedCount,0),durationMs:s.duration,...t.length>0?{objectsWithFailures:t.slice(0,20),why:S0(e)}:{},...s.failedReads?.length?{failedReads:s.failedReads}:{}}}function S0(s){let e=new Map;for(let t of s){if(t.failedCount===0&&!t.skipped)continue;let r=e.get(t.objectApiName)??new Set;e.set(t.objectApiName,r);let n=t.samples.flatMap(o=>o.messages).map(o=>/^([A-Z][A-Z0-9_]+):/.exec(o)?.[1]).filter(o=>o!==void 0);n.length===0&&r.add(t.stage);for(let o of n)r.add(o)}return Object.fromEntries([...e].slice(0,20).map(([t,r])=>[t,[...r].slice(0,5)]))}function k0(s,e){let t=s.nodes.filter(d=>d.included),r=t.map(d=>d.objectApiName).join(", ")||"ForgeData",n=Db,o=e.inputMode==="org"?void 0:e.maxRecordsPerObject,i=Ju(e),a=0;for(let d of t)if(d.recordCountUnknown===!0){if(o===void 0)return{objectName:r,recordCount:"unknown",alsoWrites:n};a+=o,i=!0}else a+=o===void 0?d.recordCount:Math.min(d.recordCount,o);return{objectName:r,recordCount:i?{atMost:a}:a,alsoWrites:n}}function O0(s,e,t){return{forgeId:`forge-${Date.now()}`,status:t.wouldBeRefused.length>0?"failure":"success",graph:s,duration:Date.now()-e,timestamp:new Date().toISOString(),idRemapCount:0,createdCount:0,dryRun:!0,wouldInsertCount:t.totalRows}}function LT(s,e){let t=e.nodes.map(n=>`${n.objectApiName}:${n.included||n.leftOutByUser===!0?1:0}`).sort(),r=e.edges.map(n=>`${n.sourceObject}>${n.targetObject}:${n.required===!0?1:0}`).sort();return JSON.stringify([s,t,r])}function FT(s,e){let t=(e.nodes??[]).map(r=>r.objectApiName).sort();return JSON.stringify([s.sourceOrgId,s.targetOrgId,t])}function I0(s,e){return e.size===0?s:{...s,objectsRead:s.objectsRead.filter(t=>!e.has(t)),objects:s.objects.filter(t=>!e.has(t.objectApiName))}}function _T(s,e){return s.apiCalls===void 0?s:{...s,apiCalls:s.apiCalls+e}}function UT(s,e){return!s.sample||!e||!e.drawnAgain&&!e.ofTheRunRetried?s:{...s,sample:{...s.sample,...e.drawnAgain?{drawnAgain:e.drawnAgain}:{},...e.ofTheRunRetried?{ofTheRunRetried:!0}:{}}}}function A0(s){return s instanceof Error&&s.name==="ForgeAbortedError"}var Zc=class extends Error{constructor(t,r){super(r);this.code=t;this.name="RehearsalStoppedError"}code};function T0(s){return{sampled:s.sampled,judged:s.judged,passed:s.passed,linked:s.linked??0,refused:s.judged-s.passed-(s.linked??0),notJudged:s.notJudged,updatesJudged:s.updatesJudged,updatesRefused:s.updatesJudged-s.updatesPassed,updatesNotRehearsed:s.updatesNotRehearsed,calls:s.calls}}var eu=class s{constructor(e,t,r){this.deps=e;this.externalBrowser=t??new jn,this.saveDialog=r??new An}deps;abortController=null;stops=new Mv;executeOperationId=null;writingTo=null;orchestrator;planGenerator;complianceService;metadataDiff;targetAutomation;targetGaps;requestsSent;requestsSentTo;muteOrgOf;muteLeases;lostBulkJobs;beforeRunCheckpoints;rehearser;rehearseOperationId=null;templateStore;removalPlans;runJournal;otherModuleRuns=()=>Promise.resolve([]);journalsRunning=new Set;journalLocks=YM;describeGlobalCache=new Zs({defaultTtl:5*6e4,maxSize:16,maxSizeBytes:50*1024*1024});dmlTracker=new ba;removing=new Set;trials=new Bv;simulations=new OR;sampleSimulations=new Map;samplePlansSwept=new Set;rootPlansSwept=new Map;verifying=new Set;automationReads=new Map;automationReadAgain=new Set;discoverySent=new Map;liveTracker;lastWriteAt=new Map;static DUPLICATE_COOLDOWN_MS=6e4;static MAX_HISTORY=20;externalBrowser;saveDialog;forgetOrg(e){this.describeGlobalCache.invalidate(e),this.orchestrator?.clearDiscoveryCache([e]);for(let[t,r]of this.automationReads)r.orgId===e&&this.automationReads.delete(t)}setForgeOrchestrator(e,t){this.orchestrator=e,t&&(this.planGenerator=t.planGenerator,this.complianceService=t.complianceService,this.metadataDiff=t.metadataDiff,this.targetAutomation=t.targetAutomation,this.targetGaps=t.targetGaps,this.templateStore=t.templateStore,this.removalPlans=t.removalPlans,this.runJournal=t.runJournal,this.requestsSent=t.requestsSent,this.requestsSentTo=t.requestsSentTo,this.muteOrgOf=t.muteOrg,this.muteLeases=t.muteLeases,this.lostBulkJobs=t.lostBulkJobs,this.rehearser=t.rehearser,t.journalLocks&&(this.journalLocks=t.journalLocks))}setLiveOperationTracker(e){this.liveTracker=e}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}trackRun(e,t,r,n=!1){let o=this.deps.infraServices?.backgroundRegistry;if(!o)return()=>{};let i=()=>{},a=new Promise((c,u)=>{i=l=>{l===void 0?c():u(l instanceof Error?l:new Error(String(l)))}}),d=new AbortController;return d.signal.addEventListener("abort",()=>{r.abort(),n&&this.orchestrator?.abort()},{once:!0}),o.register(e,"forge",t,a,d),i}isWritingTo(e,t){return this.writingTo===e&&(t===void 0||t!==this.executeOperationId)}async handle(e){if(!t0.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"forge:preview":return await this.handleForgePreview(e),!0;case"forge:discover":return await this.handleDiscover(e),!0;case"forge:execute":return await this.handleExecute(e),!0;case"forge:pause":return this.handlePause(e),!0;case"forge:resume":return this.handleResume(e),!0;case"forge:abort":return this.handleAbort(e),!0;case"forge:templates:list":return await this.handleTemplatesList(e),!0;case"forge:templates:save":return await this.handleSaveTemplate(e),!0;case"forge:templates:delete":return await this.handleDeleteTemplate(e),!0;case"forge:history:list":return await this.handleHistoryList(e),!0;case"forge:undo":return await this.handleUndo(e),!0;case"forge:resume-run":return await this.handleResumeRun(e),!0;case"forge:open-record":return await this.handleOpenRecord(e),!0;case"forge:verify:request":return await this.handleVerify(e),!0;case"forge:export-ids:request":return await this.handleExportIds(e),!0;case"forge:plan:request":return await this.handlePlanRequest(e),!0;case"forge:classification:request":return await this.handleClassificationRequest(e),!0;case"forge:compliance:request":return await this.handleComplianceRequest(e),!0;case"forge:metadata-diff:request":return await this.handleMetadataDiffRequest(e),!0;case"forge:rehearse:request":return await this.handleRehearseRequest(e),!0;case"forge:automation:request":return await this.handleAutomationRequest(e),!0;case"forge:undo-automation:request":return await this.handleUndoAutomation(e),!0;case"forge:undo-sweep:request":return await this.handleUndoSweep(e),!0;case"forge:gaps:request":return await this.handleGapsRequest(e),!0;case"forge:users:request":return await this.handleUsersRequest(e),!0;case"forge:target-records:request":return await this.handleTargetRecordsRequest(e),!0;case"forge:sample-budget:request":return await this.handleSampleBudgetRequest(e),!0;case"forge:previewRoots":return await this.handlePreviewRoots(e),!0;default:return!1}}async loadTemplates(){if(!this.templateStore){let e=this.deps.configStore.get(DT);return{templates:Array.isArray(e)?e.filter(ln):[]}}return this.withImportedTemplates(this.templateStore)}async withImportedTemplates(e){let t=Kc(this.deps.configStore,e.workspacePath);if(!t)return{templates:await e.list()};let r;try{r=await e.merge(t.templates,new Set(t.replacing))}catch(n){let o=I(n);return ie.warn(`Imported forge templates not written into .sandforge/: ${o}`),{templates:await e.list(),importNotMerged:o}}return mT(this.deps.configStore,e.workspacePath),ie.info("Merged an imported set of forge templates into .sandforge/"),{templates:r}}async saveTemplates(e){if(!this.templateStore){this.deps.configStore.set(DT,e,MT);return}let t=await this.templateStore.list();for(let r of t.filter(n=>!e.some(o=>o.id===n.id)))await this.templateStore.delete(r.id);for(let r of e)await this.templateStore.save(r)}loadHistory(){return this.deps.configStore.get(NT)??[]}saveHistory(e){this.deps.configStore.set(NT,e,MT)}noteForgeWrite(e){let t=Date.now();for(let[r,n]of this.lastWriteAt)t-n>=s.DUPLICATE_COOLDOWN_MS&&this.lastWriteAt.delete(r);this.lastWriteAt.set(e,t)}async handleForgePreview(e){let t=st(nM,e,"forge:preview:error",this.deps);if(!t)return;let{recordId:r,orgId:n}=t;try{let o=await B(n,this.deps.orgRegistry,this.deps.orgManager),i=r.substring(0,3),a=this.describeGlobalCache.get(n);if(!a){let k=await o.describeGlobal();$e(o.limitInfo,"forge:preview describeGlobal"),a=k.sobjects.map(S=>({name:S.name,label:S.label,keyPrefix:S.keyPrefix??null})),this.describeGlobalCache.set(n,a)}let d=a.find(k=>k.keyPrefix===i),c=we(this.deps.orgManager.getOrg(n),n),u=(k,S)=>{this.deps.broker.postToWebview(A(this.deps,e,"forge:preview:error",{code:k,orgName:c,message:S}))};if(!d){u("UNKNOWN_KEY_PREFIX",`No object of ${c} has ids starting "${i}": the record is read from the source org picked.`);return}let l=await vm(o,d.name,`SELECT FIELDS(STANDARD) FROM ${d.name} WHERE Id = '${tr(r)}' LIMIT 1`);if($e(o.limitInfo,`forge:preview query ${d.name}`),!l||l.length===0){u("RECORD_NOT_FOUND",`Record ${r} is not in ${c}, or the user connected there cannot see it: the record is read from the source org picked.`);return}let p=l[0],f=new Set(["attributes","Id"]),g=Object.entries(p).filter(([k])=>!f.has(k)).filter(([,k])=>k!=null&&String(k)!=="").slice(0,8).map(([k,S])=>({name:k,value:String(S)})),h=await o.describe(d.name);$e(o.limitInfo,`forge:preview describe ${d.name}`);let m=h.fields.length,y=0;try{y=(await o.query(`SELECT COUNT() FROM ${d.name}`)).totalSize}catch{}let v=y*.001,b=A(this.deps,e,"forge:preview:response",{objectApiName:d.name,objectLabel:d.label,recordId:r,fields:g,estimatedRecordCount:y,totalFieldCount:m,estimatedSize:v});this.deps.broker.postToWebview(b)}catch(o){T(this.deps,"forge:preview","forge:preview:error",e,o,{code:"PREVIEW_ERROR"})}}async handleDiscover(e){if(!this.orchestrator){T(this.deps,"forge:discover","forge:discover:error",e,new Error("Forge module is not initialized"),{code:"NOT_INITIALIZED"});return}let t=st(sM,e,"forge:discover:error",this.deps);if(!t)return;let r=this.withMaxRoots(t.config),n=new AbortController,o=`forge-discover-${this.deps.nextId()}`,{discovery:i,superseded:a}=this.stops.beginDiscovery(e.id,n,o);for(let l of a)this.stopDiscovery(l);Ge(this.deps,o,"forge","Discovering object graph");let d=this.trackRun(o,"Discovering object graph",n),c,u=Yc(l=>{let p=A(this.deps,e,"forge:discover:progress",l);this.deps.broker.postToWebview(p)},100);try{ie.info("Forge discover started");let l=this.orchestrator,{result:p,sent:f}=await pT(()=>l.discover(r,{...r.inputMode==="org"?{}:{maxNodes:r.maxNodes},signal:n.signal,onProgress:y=>{u(y)}}));if(u.flush(),n.signal.aborted){me(this.deps,o,{aborted:!0}),this.answerStoppedDiscovery(e,i);return}let g=fT(f,r),h=FT(r,p);this.discoverySent.delete(h),g&&this.discoverySent.set(h,g);for(let y of this.discoverySent.keys()){if(this.discoverySent.size<=u0)break;this.discoverySent.delete(y)}let m=A(this.deps,e,"forge:discover:response",{graph:g?{...p,discoveryRequests:g}:p});this.deps.broker.replyToRequester(m),me(this.deps,o,{nodeCount:p.nodes?.length??0}),ie.info("Forge discover finished",{objects:p.nodes?.length??0,records:p.totalRecords})}catch(l){if(u.flush(),n.signal.aborted){me(this.deps,o,{aborted:!0}),this.answerStoppedDiscovery(e,i);return}c=l,T(this.deps,"forge:discover","forge:discover:error",e,l,{code:"DISCOVER_ERROR",retryable:!0}),Le(this.deps,o,I(l),!0)}finally{d(c),this.stops.endDiscovery(i)}}stopDiscovery(e){this.deps.infraServices?.backgroundRegistry?.abort(e.operationId),e.controller.abort()}answerStoppedDiscovery(e,t){let{code:r,message:n}=vM[t.stop??"stopped"];T(this.deps,"forge:discover","forge:discover:error",e,new Error(n),{code:r,retryable:!0})}async handleExecute(e,t){if(!this.orchestrator){T(this.deps,"forge:execute","forge:execute:error",e,new Error("Forge module is not initialized"),{code:"NOT_INITIALIZED"});return}let r=t?t.startedWith:st(iM,e,"forge:execute:error",this.deps);if(!r)return;let{graph:n,anonymizationRules:o,files:i,reviewSkipped:a,muteAutomation:d}=r,c=this.withMaxRoots(r.config),u=t?t.forgeId:r.retryOf,l=u!==void 0?QM(u,this.loadHistory()):void 0,p=u===void 0?r.checkpointFirst:void 0;u!==void 0&&r.checkpointFirst!==void 0&&ie.info("Forge run: no checkpoint taken for a retry or a resume, which takes up a run that wrote",{checkpoint:l?.checkpointId??"none"});let f=c.dryRun===!0,g=rp(n,c),h=kR(c),m=new qv(c,{reviewSkipped:a===!0,...this.trials.before(g)}),y=c.inputMode==="org",v=y&&c.sample!==void 0,b=(je,ze)=>{f||Y(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:je,context:m.context()}),T(this.deps,"forge:execute","forge:execute:error",e,new Error(ze),{code:je})};if(n.withoutEdges===!0){b(dM,cM);return}if(y&&a===!0){b(uM,lM);return}let k=y?xv(n):void 0;if(k){b(k.code,k.message);return}let S=i?Eg(c.anonymizePII,i.acceptedAsIs):null;if(S){Y(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:RT,context:m.context()}),T(this.deps,"forge:execute","forge:execute:error",e,new Error(S),{code:RT});return}let C,R,w;if(u!==void 0&&!t){let je=await this.runToRetry(u,c.targetOrgId);if("refused"in je){Y(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:vT,context:m.context()}),T(this.deps,"forge:execute","forge:execute:error",e,new Error(je.refused),{code:vT});return}C=je.written,R=je.journalId!==void 0?{journalId:je.journalId}:{},w=je.roots}let P=this.deps.infraServices?.productionGuard;if(!P){Y(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:ve.code,context:m.context()}),T(this.deps,"forge:execute","forge:execute:error",e,new Error(ve.message),{code:ve.code});return}let O=this.deps.orgManager.getOrg(c.targetOrgId),E=Pe(O),$=we(O,c.targetOrgId);if(E==="production"){this.refuseAtGate(e,c.targetOrgId,new gt("PRODUCTION_TARGET",`${$} is a production org, or an org SandForge cannot tell is a sandbox, a scratch org or a Developer Edition org: Forge writes to those only. Nothing was read or written.`),void 0,m.context());return}let H=await this.ownerMapRefusal(c);if(H){f||Y(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:H.code,context:m.context()}),T(this.deps,"forge:execute","forge:execute:error",e,H,{code:H.code,retryable:!0});return}let J={orgId:c.targetOrgId,orgTier:E,operation:"insert",...k0(n,c),module:"forge"},W=new AbortController,Z=this.stops.awaitGuard(e.id,W),{check:_,decision:Q}=f?aM(P,J):await et(P,J).finally(Z);f&&Z();let N=Q;if(_.warnings.length>0&&ie.warn("Forge run: Production Guard warnings",{warnings:_.warnings}),(Q==="refused"||Q==="declined")&&Y(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",guard:Q,context:m.context()}),Q==="refused"){T(this.deps,"forge:execute","forge:execute:error",e,new Error(`Operation blocked by Production Guard: ${_.blockedReason??_.impactSummary}`),{code:"GUARD_BLOCKED"});return}if(Q==="declined"){T(this.deps,"forge:execute","forge:execute:error",e,new Error("Operation cancelled by user (confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}if(W.signal.aborted){Y(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",guard:Q,code:ht,context:m.context()}),T(this.deps,"forge:execute","forge:execute:error",e,new Error(Un),{code:ht,retryable:!0});return}let z=`${c.sourceOrgId}:${c.targetOrgId}:${c.recordId??""}`,oe=n.nodes?.map(je=>je.objectApiName).join(",")??"",re=`forge:${z}:${oe}:${n.totalRecords??0}`+(u!==void 0?`:${t?"resume":"retry"}:${u}`:""),q=this.dmlTracker.isDuplicate(re)?this.dmlTracker.get(re):void 0,F=this.lastWriteAt.get(re),ne=F!==void 0&&Date.now()-F<s.DUPLICATE_COOLDOWN_MS;if(q?.status==="pending"||ne){ie.warn("Duplicate forge execution detected",{operationId:re}),T(this.deps,"forge:execute","forge:execute:error",e,new Error(`Duplicate forge operation: ${re}`),{code:"DUPLICATE"});return}if(this.executeOperationId!==null){Y(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",guard:Q,code:Zf,context:m.context()}),T(this.deps,"forge:execute","forge:execute:error",e,new Error("Another Forge run is still under way in this window: start this one once it has ended. A run asked to stop ends once the step under way is done."),{code:Zf,retryable:!0});return}let ke=n.totalRecords??0;q?(q.status="pending",q.recordCount=ke,q.registeredAt=new Date().toISOString()):this.dmlTracker.register(re,"forge","upsert",ke),this.abortController=W;let de=`forge-execute-${this.deps.nextId()}`,Ze=f?"Simulating forge operation":"Executing forge operation";Ge(this.deps,de,"forge",Ze);let xe=this.trackRun(de,Ze,W,!0);this.liveTracker?.register(de,"forge",Ze),this.executeOperationId=de,this.writingTo=f?null:c.targetOrgId,this.stops.beginRun(e.id,W);let Ue=Date.now(),V,ae,ee,fe,D,G=!1,ue=()=>{G||!ae||(G=!0,ae.close())},j={keep:!1},se=!1,U,te=async()=>{if(!V||se)return;se=!0;let je=V,ze=j;ue(),await(ze.keep?this.runJournal?.stop(je,ze.status,ze.forgeId):this.runJournal?.end(je))?.catch(Ye=>{ie.warn(`Forge run journal not ${ze.keep?"kept":"dropped"}: ${I(Ye)}`)}),this.journalsRunning.delete(je),U?.release(),U=void 0},Se={requests:0,target:0},De,qe,ce=()=>{let je=this.requestsSent?.();return je===void 0||De===void 0?void 0:Se.requests+je-De},Ee,Ne=!1,it=[],nt,Ce=0,zn=()=>{let je=this.requestsSentTo?.(c.targetOrgId),ze=je===void 0||qe===void 0?0:je-qe;return Ce+(this.discoverySent.get(FT(c,n))?.target??0)+(Se.target??0)+ze},Gn,fn,Ct,Mi,pr=[],Li,bo=()=>(Li??=this.jobsStillRunning(c.targetOrgId,Mi,Se).then(je=>{pr=je}),Li),Ro,Mr={firing:[]},vo,$t,So,Lr,Fi,Fr,Ss=!1,pt,Jn,_r=Yc(je=>{let ze=A(this.deps,e,"forge:progress",je);this.deps.broker.postToWebview(ze)},100),Vn=Yc(je=>{this.deps.broker.postToWebview(A(this.deps,e,"forge:sampling:progress",{...je}))},100),_i=this.liveProgressOf(de,n),Xn=KM(),Ui=this.orchestrator.on("forge:progress",je=>{let ze=Xn(je),Ye=ce(),dt=Ye===void 0?ze:{...ze,apiCalls:Ye};_i(dt);let ct=dt.status;if(ct==="done"||ct==="error"||ct==="skipped"||ct==="stopped"){_r.flush();let Qe=A(this.deps,e,"forge:progress",dt);this.deps.broker.postToWebview(Qe);return}_r(dt)});try{ie.info("Forge execute started",{source:we(this.deps.orgManager.getOrg(c.sourceOrgId),"unknown org"),target:we(this.deps.orgManager.getOrg(c.targetOrgId),"unknown org")});let je=this.maxRecordsPerObject(),ze=zl(n,{leftOut:new Set(n.nodes.filter(qi).map(ye=>ye.objectApiName)),retry:u!==void 0}),Ye=new Set(ze.map(ye=>ye.objectApiName)),dt=(ye,Fe)=>Fe==="insert"||Fe==="update"&&Ye.has(ye),ct=dt;if(f){if(p!==void 0||y||v){let ye=await this.automationBeforeTheRun(c.targetOrgId,n);if("automation"in ye){let Fe=d===!0?await Et(()=>this.muteOrg(c.targetOrgId),ye.automation,{...this.muteLeases,writes:dt}).then(be=>($t=be,be.plan),be=>{ie.warn(`Forge simulation: the mute could not be planned (${I(be)})`)}):void 0;So=ye.automation,Mr=gr(ye.automation,Fe,dt),vo=Fe}}}else{let ye=await this.automationBeforeTheRun(c.targetOrgId,n);Ce=$n("automation"in ye?ye.automation:ye);let Fe=ye,be;if(d===!0){let at=await Et(()=>this.muteOrg(c.targetOrgId),"automation"in ye?ye.automation:ye,{...this.muteLeases,writes:dt});$t=at,fn=at.prepared,Ct=at.muted,be=at.plan,"automation"in ye&&at.automation&&(Fe={...ye,automation:at.automation})}if("automation"in ye&&(So=ye.automation,Mr=gr(ye.automation,be,dt)),nt=Fe,"automation"in Fe&&(it=dh(Fe.automation)),W.signal.aborted)throw Ne=!0,new Error(Un);if(m.automationRead(Fe,ze),Fr=await ir({read:"automation"in ye?ye.automation:ye,...be?{plan:be}:{},writes:dt,applyAssignmentRules:c.applyAssignmentRules===!0,readDeliverability:()=>this.readDeliverability(c.targetOrgId,W.signal),accepted:!1,target:$,run:"clone",keepsAddresses:c.keepContactPoints===!0}),Se.requests+=Fr.ofRun.read?.requests??0,W.signal.aborted)throw Ne=!0,new Error(Un);m.emailsRead(Fr.gate.audit);let He=await this.confirmAutomation(P,{orgId:c.targetOrgId,org:$,orgTier:E,username:O?.username},Fe,ze,a===!0,Fr.gate.confirmation);He==="confirmed"&&(m.confirm("automation"),Fr.gate.verdict==="asks"&&(Ss=!0,m.confirm("emails"))),N=oo(N,He);let Me=y?[]:vR(n,c.maxRecordsPerObject,je);if(Me.length>0){if(W.signal.aborted)throw Ne=!0,new Error(Un);let at=await this.confirmReadCeiling(P,{org:$,orgTier:E,source:we(this.deps.orgManager.getOrg(c.sourceOrgId),c.sourceOrgId)},Me,je);at==="confirmed"&&m.confirm("volume"),N=oo(N,at)}}if(W.signal.aborted)throw Ne=!0,new Error(Un);let Qe=f?void 0:this.runUserOf(c.targetOrgId),Ur=await this.loadRecordTypeMappings(c,W.signal,Se);if(W.signal.aborted)throw Ne=!0,new Error(Un);ee=await Qe,Ue=Date.now(),De=this.requestsSent?.(),qe=this.requestsSentTo?.(c.targetOrgId),Mi=this.lostBulkJobs?.count;let wt=f?void 0:this.runJournal,fr;if(wt){let ye=t?.journalId??`forge-run-${Ue}`,Fe;try{Fe=this.journalLocks.take(wt.pathOf(ye),{journalId:ye,target:$,...t?{resumes:!0}:{}})}catch(Me){ie.warn(`Forge run journal: its lock not taken (${I(Me)})`)}if(Fe&&"busy"in Fe)throw new pn(Ei,`${Pi(td(Fe.busy))}: taken up now, two runs would write it; ${rd(Fe.busy)}, then resume it. Nothing was written.`);U=Fe,V=ye,this.journalsRunning.add(ye);let be=Me=>new pn(hM,`${$} could not be read for the insert calls the run had under way when it stopped (${I(Me)}): taken up without them, the run would write their records twice. Reconnect ${$} on Organizations if its session expired, then resume the run again. Nothing was written.`);if(ae=await(t?wt.resuming(ye).then(async()=>{let Me=await B(c.targetOrgId,this.deps.orgRegistry,this.deps.orgManager).catch(Yn=>{throw be(Yn)}),at={},Kn=await wt.reconcile(ye,mM(Yl(Me),at)).catch(Yn=>{throw at.err!==void 0?be(at.err):Yn});for(let Yn of Ql(Kn,$))ie.info(`Forge resume: ${Yn.trim()}`);fe=Kn.uncertain,D=Kn.underway;let mg=this.loadHistory().find(Yn=>Yn.forgeId===t.forgeId);mg&&Kn.found.length>0&&await this.withRowsFoundAfterStop(mg,Kn.found)}):wt.begin(ye,c.targetOrgId,new Date(Ue),{...this.resumeHeadOf(n,c,o,je),...d===!0?{muteAutomation:!0}:{},...i?{files:i}:{}},ee)).then(()=>wt.open(ye)).catch(Me=>{ie.warn(`Forge run journal not started: ${I(Me)}`),fr={err:Me}}),t&&!ae){let Me=fr?.err;if(Me instanceof pn)throw Me;let{reason:at,lift:Kn}=ST(Me);throw new pn(Kf,`The journal of the run to resume, in ${Xf(wt.pathOf(ye))}, could not be opened (${at}). ${Kn}, then resume it again. Nothing was written.`)}}if(y&&!f&&!ae){if(!wt||!V||fr===void 0)throw new pn(Kf,gM);let{reason:ye,lift:Fe}=ST(fr.err);throw new pn(Kf,`A clone of the whole org keeps its journal on disk, in ${Xf(wt.pathOf(V))}, which could not be opened (${ye}). ${Fe}, then run it again. Nothing was written.`)}v&&(pt=await this.sampleOf({graph:n,config:c,anonymizationRules:o,readCeiling:je,dryRun:f,...V!==void 0?{journalId:V}:{},resumes:t!==void 0,...R?{retried:R}:{},volumeCase:h,target:$,lookup:Se,room:()=>Jl(Mr,dt).perRecord,sentBefore:zn,updatedAfterInsert:[...Ye],onProgress:Vn}));let Yt=await this.rootsOfTheRun({graph:n,config:c,anonymizationRules:o,readCeiling:je,dryRun:f,resumes:t!==void 0,...w?{retried:w}:{},lookup:Se});if(W.signal.aborted)throw Ne=!0,new Error(Un);let M,X=y?Cv(c):void 0,le=this.writeGate({guard:P,targetOrgId:c.targetOrgId,operationId:de,org:$,source:we(this.deps.orgManager.getOrg(c.sourceOrgId),c.sourceOrgId),orgTier:E,lookup:Se,emailsPerInsert:it,...nt!==void 0?{automation:nt}:{},...xn(Fr?.ofRun),sentBefore:zn,mute:br(fn?.plan??vo),atTheRows:(ye,Fe)=>(ct=Wv(ye.objects,Fe,dt),$t&&($t=Xb($t,ct),f?vo=$t.plan:M||(fn=$t.prepared,Ct=$t.muted)),So&&(Mr=gr(So,$t?.plan,ct)),{running:Mr,mute:br($t?.plan)}),mayBeInTarget:fe,...D&&D.length>0?{jobsUnderway:D}:{},...f?{}:{simulated:this.simulations.of(h)},updatedAfterInsert:[...Ye],automationRoom:()=>Jl(Mr,ct).perRecord,...y?{wholeOrg:{source:we(this.deps.orgManager.getOrg(c.sourceOrgId),c.sourceOrgId),sourceOrgId:c.sourceOrgId,graph:n,anonymizePII:c.anonymizePII,...X?{carried:X}:{}}}:{},...p!==void 0?{checkpoint:{ask:{module:"forge",orgId:c.targetOrgId,operationId:de,running:Mr,request:p},own:{operationId:de},signal:W.signal,onEstimate:ye=>{Fi=ye},onTaken:ye=>{Lr=ye,wt&&V&&ae&&wt.keepCheckpoint(V,ye).catch(Fe=>{ie.warn(`Forge run journal: the checkpoint taken first not named (${I(Fe)})`)})},onProgress:ye=>{let Fe=_o(ye);_e(this.deps,de,ye,0,0,Fe),this.liveTracker?.updateProgress(de,ye,0,0,Fe)}}}:{},onSimulated:ye=>{Gn=ye},...v?{sampled:ye=>{Vn.flush();let Fe=pt?.drawnAgain,be=Fe||pt?.ofTheRunRetried?{...ye,plan:{...ye.plan,...Fe?{drawnAgain:Fe}:{},...pt?.ofTheRunRetried?{ofTheRunRetried:!0}:{}}}:ye;return m.sampled(be),be}}:y?{onSampleOffer:ye=>{Jn=ye}}:{},onConfirmed:()=>{N=oo(N,"confirmed"),m.confirm("volume")}}),Oe=await this.orchestrator.execute(n,c,{recordTypeMappings:Ur,anonymizationRules:o,files:i,writtenBefore:C,stream:{ceiling:je,...ae?{store:ae,summaryBound:ed}:{},...pt?{sample:pt.stream}:{}},...ee?{runUserId:ee}:{},...Yt?{roots:Yt}:{},beforeWrite:async ye=>{let Fe=await le(ye);if(!fn||ye.dryRun||M)return Fe;let be=await fn.acquire(de);M=be,Ct=be.outcome;let He=Fr?.afterLease(be.outcome,Ss,$t?.plan?{plan:$t.plan,writes:ct}:void 0);if(He)throw new gt(He.code,He.message);return{...Fe,lease:{assigned:be.outcome.assigned.length,giveBack:async()=>(await bo(),be.release())}}}}).catch(ye=>{if(!Dv(ye))throw ye;return Ro=ye.dryRun,O0(n,Ue,ye.dryRun)}).finally(ue).finally(async()=>{M&&(await bo(),Ct=await M.release())}),ge=UT(_T(Oe,Se.requests),pt),he=(ge.remapInJournal===!0||pt!==void 0&&ge.status!=="success")&&ae&&V?{journalId:V,journalPart:Math.max(0,ae.partCount-1)}:{},Ke=Ct?{mutedAutomation:Ct,...pr.length>0?{bulkJobsPastMute:pr,errors:[...ge.errors??[],...tp(pr)]}:{}}:{},Je=f?Fi:Lr?await this.settleCheckpoint(Lr,(ge.createdCount??ge.idRemapCount-(ge.linkedExistingCount??0))+(ge.updatedCount??0)>0):l,Lt=Je?{checkpoint:Je}:{},At=t&&!f&&ae&&V?await this.wroteToEarlierPartsOf(ge,V,ae.partCount-1):{},rt=u!==void 0?{...ge,...he,...Ke,...Lt,retryOf:u,...t?{resumed:!0}:{},...At}:{...ge,...he,...Ke,...Lt};"journalId"in he&&!f&&(j={keep:!0,status:"success",forgeId:rt.forgeId});let gn=rt.createdCount??rt.idRemapCount-(rt.linkedExistingCount??0);rt.status!=="failure"&&gn>0&&this.noteForgeWrite(re),rt.status==="failure"&&(Ee=new Error("Forge execution finished with a failure status.")),f?(this.trials.note("simulation",g),Gn&&this.simulations.note(h,Gn),pt&&Ro?.sample&&this.noteSampleSimulation(h,pt.fingerprint)):(Y(this.deps,{action:"forge_execute",module:"forge",operationId:de,orgId:c.targetOrgId,outcome:rt.status,guard:N,objects:Rl(rt),source:{origin:"org",orgId:c.sourceOrgId},carried:vl(rt),...Kr(rt.contactPoints),...TT(m),context:m.context(rt.decisionsApplied),...Ct?{muted:ft(Ct)}:{},...Je?.state==="taken"?{checkpointId:Je.checkpointId}:{}}),this.addToHistory(rt,c)),ie.info("Forge execute finished",v0(rt)),await te(),Vn.flush();let ks=A(this.deps,e,"forge:execute:response",{result:rt,operationId:de,...Ro?{wholeOrgDryRun:Ro}:{},...Jn?{sampleOffer:Jn}:{}});this.deps.broker.postToWebview(ks),this.dmlTracker.markCompleted(re),me(this.deps,de,{status:rt.status}),rt.status==="failure"?this.liveTracker?.fail(de,"Forge execution finished with a failure status."):rt.status==="partial"?this.liveTracker?.partial(de):this.liveTracker?.complete(de)}catch(je){Vn.flush();let ze=jR(je,t?"resume":"draw")??je,Ye=Ya(ze)?ze:GR(ze),dt=jt(ze)?ze:void 0;(Ye?.code==="AUTOMATION_DECLINED"||Ye?.code==="READ_DECLINED"||Ye?.code==="WRITE_DECLINED")&&(N=oo(N,"declined"));let ct=Ne||A0(ze)||Ye!==void 0||dt!==void 0;ct||(Ee=ze);let Qe=Ye||dt?void 0:fv(ze),Ur=Qe?bm(Qe):void 0,wt=Ur?Rl(Ur):[],fr=Ne||Ye||dt?"stopped":ct?Rm(Qe,wt):"failure",Yt=Ye?Ye.code:dt?dt.code:Ne?ht:fr==="stopped"?ot:ze instanceof pn?ze.code:void 0,M=Lr?await this.settleCheckpoint(Lr,Qe?ET(Qe):!(Ne||Ye||dt)):l;ie.info("Forge execute stopped",{outcome:fr,...Yt?{code:Yt}:{},...Qe?{created:Qe.successCount,linked:Qe.linkedCount,failed:Qe.failedCount}:{}});let X=Qe&&!f?this.keepStoppedRun(UT(Qe,pt),n,c,{startedAt:Ue,cancelled:ct,retryOf:u,resumed:t!==void 0,callsBefore:Se.requests,...ae&&V?{journalId:V,journalPart:Math.max(0,ae.partCount-1)}:{},...M?{checkpoint:M}:{},...ee?{runUserId:ee}:{},...pr.length>0?{bulkJobsPastMute:pr}:{},...t&&ae&&V?await this.wroteToEarlierPartsOf({idRemapTable:Qe.remapTable,idRemapCreated:Qe.createdByObject,...Qe.remapInJournal?{remapInJournal:!0}:{}},V,ae.partCount-1):{}}):void 0;ae&&V&&X?j={keep:!0,status:ct?"cancelled":"failure",forgeId:X.forgeId}:t&&(j={keep:!0,...t.end}),f||Y(this.deps,{action:"forge_execute",module:"forge",operationId:de,orgId:c.targetOrgId,outcome:fr,...Yt?{code:Yt}:{},guard:N,...Ur?{objects:wt,source:{origin:"org",orgId:c.sourceOrgId},carried:vl(Ur)}:{},...Kr(Qe?.contactPoints),...TT(m),context:m.context(Qe?.decisionsApplied),...Ct?{muted:ft(Ct)}:{},...M?.state==="taken"?{checkpointId:M.checkpointId}:{}}),this.dmlTracker.markFailed(re),this.lastWriteAt.delete(re),pt?.adoptedFrom!==void 0&&V!==void 0&&!j.keep&&!(Qe&&ET(Qe))&&await this.giveThePlanBack(V,pt.adoptedFrom),await te();let le=Lr&&M?{checkpoint:M}:{},Oe=Ye&&Ya(Ye)?GM(Ye):ze;T(this.deps,"forge:execute","forge:execute:error",e,Oe,{code:Yt??(ct?ot:"EXECUTE_ERROR"),retryable:!(Ye&&Ya(Ye)&&HT.has(Ye.code)),...X?{extraPayload:{result:j.keep?{...X,resumable:!0}:X}}:Ye?.stop?{extraPayload:{gate:Ye.stop,...le,...Jn?{sampleOffer:Jn}:{}}}:Lr?{extraPayload:le}:{}}),ct?(this.deps.infraServices?.backgroundRegistry?.abort(de),me(this.deps,de,{aborted:!0}),this.liveTracker?.cancel(de)):(Le(this.deps,de,I(ze),!0),this.liveTracker?.fail(de,I(ze))),j.keep&&this.liveTracker?.offerResume(de,j.forgeId)}finally{await te(),U?.release(),xe(Ee),this.executeOperationId===de&&(this.executeOperationId=null,this.writingTo=null),this.stops.endRun(e.id),Ui(),_r.flush(),this.abortController=null}}addToHistory(e,t){let r={...t.inputMode==="org"?yT(e):e,config:R0(t),targetOrgId:t.targetOrgId,sourceOrgId:t.sourceOrgId},n=[r,...this.loadHistory()];this.saveHistory(n.slice(0,s.MAX_HISTORY)),this.keepRemovalPlans(r,n.slice(s.MAX_HISTORY))}keepStoppedRun(e,t,r,n){if(!(e.remapInJournal?e.successCount>0:e.createdByObject.some(d=>d.sourceIds.length>0)))return;let i=_T(wm(e,t,{startedAt:n.startedAt,status:n.cancelled?"partial":"failure"}),n.callsBefore),a={...i,...n.cancelled?{cancelled:!0}:{},...n.retryOf!==void 0?{retryOf:n.retryOf}:{},...n.retryOf!==void 0&&n.resumed?{resumed:!0}:{},...n.journalId?{journalId:n.journalId}:{},...n.journalId&&n.journalPart!==void 0?{journalPart:n.journalPart}:{},...n.checkpoint?{checkpoint:n.checkpoint}:{},...n.runUserId?{runUserId:n.runUserId}:{},...n.wroteToEarlierParts?{wroteToEarlierParts:n.wroteToEarlierParts}:{},...n.bulkJobsPastMute?{bulkJobsPastMute:n.bulkJobsPastMute,errors:[...i.errors??[],...tp(n.bulkJobsPastMute)]}:{}};return this.addToHistory(a,r),a}async wroteToEarlierPartsOf(e,t,r){let n=this.runJournal;if(!n||e.remapInJournal||r<1)return{};let o=new Set(qr(e).flatMap(({ids:i})=>i.map(a=>a.slice(0,15))));try{let i=(await n.wroteIn(t,r)).filter(a=>!o.has(a.slice(0,15)));return i.length>0&&i.length<=ed?{wroteToEarlierParts:i}:{}}catch(i){return ie.warn(`Forge run journal not read for what the part wrote: ${I(i)}`),{}}}async ownerMapRefusal(e){let t=e.ownerMappings??{};if(Object.keys(t).length!==0)try{let r=await B(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager);return await pv(t,async n=>(await r.query(n)).records)}catch(r){ie.warn(`Forge run: the users its owners are mapped to could not be read first (${I(r)})`);return}}runUserOf(e){return _v(async()=>(await B(e,this.deps.orgRegistry,this.deps.orgManager)).identity(),"forge:execute")}async settleCheckpoint(e,t){let r=this.beforeRunCheckpoints;if(!r)return e;try{return await r.settle(e,t)}catch(n){return ie.warn(`Forge run: the checkpoint '${e.name}' taken before it is kept, as it could not be settled (${I(n)})`),e}}async runToRetry(e,t){let r=this.loadHistory(),n=r.find(c=>c.forgeId===e);if(!n)return{refused:"The run to retry is no longer in the history, so what it wrote is not known. Run the clone again from Review."};if(n.targetOrgId!==t)return{refused:"The run to retry wrote to another org than this one."};if(!n.idRemapTable)return{refused:"The run to retry kept no record of what it wrote. Run the clone again from Review."};let o=new Set,i=n;for(;i&&!o.has(i.forgeId);){if(o.add(i.forgeId),i.undo)return{refused:`The records ${i===n?"the run to retry created":"a run it was built on created"} were removed on ${i.undo.removedAt}: there is nothing to retry against. Run the clone again from Review.`};let c=i.retryOf;i=c===void 0?void 0:r.find(u=>u.forgeId===c)}let a=await this.withIdsOf(n);if("gone"in a)return{refused:a.gone};let d=n.roots?await this.rootsOfTheRunRetried(n):void 0;return n.roots&&!d?{refused:JM}:{written:a.entry.idRemapTable??{},...n.journalId!==void 0?{journalId:n.journalId}:{},...d?{roots:d}:{}}}async rootsOfTheRunRetried(e){let t=e.roots;if(!t)return;let r=this.runJournal;if(e.journalId!==void 0&&r){let i=(await r.read(e.journalId).catch(a=>{ie.warn(`Forge retry: the journal of the run retried could not be read (${I(a)})`)}))?.roots;if(i&&i.objectApiName.toLowerCase()===t.objectApiName.toLowerCase()&&Fl(i.ids)===i.sha256)return i}if(!t.ids||t.idsLeftOut!==void 0||t.ids.length!==t.asked)return;let n=cR(t.ids.map(o=>o.source));if(Fl(n)===t.sha256)return{objectApiName:t.objectApiName,ids:n,sha256:t.sha256,readAt:t.readAt,...t.query?{query:{...t.query}}:{}}}liveProgressOf(e,t){let r=t.nodes.filter(i=>i.included).length,n=new Set,o=0;return i=>{(i.status==="done"||i.status==="error"||i.status==="skipped")&&!n.has(i.objectName)&&(n.add(i.objectName),o+=i.recordCount??0);let d=r>0?Math.min(100,Math.round(n.size/r*100)):0;this.liveTracker?.updateProgress(e,d,o,0,i.message)}}handlePause(e){this.orchestrator?.pause(),this.executeOperationId&&this.liveTracker?.pause(this.executeOperationId),ie.info("Forge paused")}handleResume(e){this.orchestrator?.resume(),this.executeOperationId&&this.liveTracker?.resume(this.executeOperationId),ie.info("Forge resumed")}handleAbort(e){let t=st(SM,e,"forge:abort:error",this.deps);if(t===null)return;let r=this.stops.stop(t?.requestId,{discovery:n=>this.stopDiscovery(n),run:()=>{this.executeOperationId&&this.deps.infraServices?.backgroundRegistry?.abort(this.executeOperationId),this.abortController?.abort(),this.abortController=null,this.orchestrator?.abort()}});if("refused"in r){if(r.refused==="none"){ie.info("Forge stop: no operation under way answers it");return}T(this.deps,"forge:abort","forge:abort:error",e,new Error(`${r.live} Forge operations are under way in this window, and the stop did not say which one it was for: nothing was stopped. Stop it from its own screen, or from Live Operations.`),{code:RM});return}ie.info("Forge stopped",{what:r.stops.kind})}refuseAtGate(e,t,r,n,o){Y(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:t,outcome:"stopped",...n?{guard:n}:{},code:r.code,...o?{context:o}:{}}),T(this.deps,"forge:execute","forge:execute:error",e,r,{code:r.code,retryable:!0,...r.stop?{extraPayload:{gate:r.stop}}:{}})}keepAutomationRead(e,t,r){let n=LT(e,t);this.automationReads.delete(n),this.automationReads.set(n,{orgId:e,at:Date.now(),read:r});for(let o of this.automationReads.keys()){if(this.automationReads.size<=c0)break;this.automationReads.delete(o)}r.catch(()=>{this.automationReads.get(n)?.read===r&&this.automationReads.delete(n)})}readAutomationAgain(e){for(let[t,r]of this.automationReads)r.orgId===e&&this.automationReads.delete(t);this.automationReadAgain.add(e)}async removalMute(e,t,r,n=[],o=!1){let i=this.targetAutomation,a=[...new Set([...$a(t,n,{userKept:o}),...r])],d=i?await new pe(Ci).withTimeout("forge:undo-automation",()=>i.read(e,a)).catch(u=>({unread:I(u)})):{unread:"no reader of the target org's automation is set up"},c=new Set(or(t));return Et(()=>this.muteOrg(e),d,{...this.muteLeases,writes:(u,l)=>l==="delete"||l==="update"&&c.has(u)})}async muteOrg(e){return this.muteOrgOf?this.muteOrgOf(e):_t(await B(e,this.deps.orgRegistry,this.deps.orgManager))}async automationBeforeTheRun(e,t){let r=new Set(t.nodes.filter(d=>!d.included).map(d=>d.objectApiName)),o=this.automationReadAgain.delete(e)?void 0:this.automationReads.get(LT(e,t));if(o&&Date.now()-o.at<d0)try{return{automation:I0(await o.read,r),reused:!0}}catch{}let i=this.targetAutomation;if(!i)return{unread:"no reader of the target org's automation is set up"};let a=new Set(t.nodes.filter(qi).map(d=>d.objectApiName));try{return{automation:await new pe(Ci).withTimeout("forge:automation",()=>i.readForGraph(e,t,a)),reused:!1}}catch(d){return{unread:I(d)}}}async confirmAutomation(e,t,r,n,o,i={}){let a="automation"in r?r.automation:void 0,d=n.map(y=>y.objectApiName),c=a?ql(a):[],u=a?Wl(a,d):[],l=a?Gl(a):[{part:"automation",reason:"unread"in r?r.unread:""}];ie.info("Forge target automation before the run",{..."reused"in r?{reused:r.reused}:{},firedOnInsert:c.length,firedOnUpdate:u.length,unread:l.map(y=>y.part)});let p=c.length===0&&u.length===0&&l.length===0,f=a?ch(a):[],g=i.deliverability!==void 0;if(p&&!g&&!(o&&f.length>0))return"allowed";let h=a&&!p?WR(a,d):[],m=await e.confirmRun({stage:"automation",org:t.org,orgTier:t.orgTier,fired:c,firedOnUpdate:u,updateSteps:qR(n.filter(y=>u.some(v=>v.objectApiName===y.objectApiName))),unread:l,bypass:h,assign:a&&!p?zR(a,h,t.username?{alias:t.org,username:t.username}:void 0):[],...f.length>0?{removal:f}:{},...i});if(m==="confirmed")return"confirmed";throw this.readAutomationAgain(t.orgId),m==="declined"?new gt("AUTOMATION_DECLINED",p&&!g?"Forge execution was cancelled at the confirmation of what may refuse a removal of the records it creates. Nothing was read or written.":"Forge execution was cancelled at the confirmation of what the target org runs as it inserts and updates the records. Nothing was read or written."):new gt("CONFIRMATION_UNAVAILABLE","Forge execution needed a confirmation of what the target org runs as it inserts and updates the records, and there was no one to ask. Nothing was read or written.")}async confirmReadCeiling(e,t,r,n){ie.info("Forge read past the ceiling",{ceiling:n,objects:Object.fromEntries(r.slice(0,20).map(i=>[i.objectApiName,i.rows]))});let o=await e.confirmRun({stage:"read",org:t.org,orgTier:t.orgTier,source:t.source,objects:r,ceiling:n});if(o==="confirmed")return"confirmed";throw o==="declined"?new gt("READ_DECLINED","Forge execution was cancelled at the confirmation of the tables it reads with no cap per object. Nothing was read or written.",void 0,n):new gt("CONFIRMATION_UNAVAILABLE","Forge execution needed a confirmation of the tables it reads with no cap per object, and there was no one to ask. Nothing was read or written.")}maxRecordsPerObject(){let e=this.deps.services?.getSandforgeSetting?.("forge.maxRecordsPerObject",Ul);return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.floor(e),Wi):Ul}confirmAboveRecords(){let e=this.deps.services?.getSandforgeSetting?.("safety.confirmAboveRecords",en);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):en}async readTargetEmailLimits(e){try{let t=await B(e,this.deps.orgRegistry,this.deps.orgManager);return await new pe(ws).withTimeout("forge:limits",()=>Or(t))}catch(t){return{unread:I(t)}}}async readTargetDataStorage(e){try{let t=await B(e,this.deps.orgRegistry,this.deps.orgManager);return await new pe(ws).withTimeout("forge:limits",()=>vr(Vt(t,e)))}catch(t){return{unread:I(t)}}}async readTargetApiBudget(e){try{let t=await B(e,this.deps.orgRegistry,this.deps.orgManager);return await new pe(ws).withTimeout("forge:limits",()=>ar(t))}catch(t){return{unread:I(t)}}}async readSourceApiBudget(e,t){t.requests++;try{let r=await B(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager);return await new pe(ws).withTimeout("forge:limits",()=>ar(r))}catch(r){return{unread:I(r)}}}limitsTransportOf(e,t){return{request:async r=>{t();let n=await B(e,this.deps.orgRegistry,this.deps.orgManager);return new pe(ws).withTimeout("forge:limits",()=>n.request(r))}}}async jobsStillRunning(e,t,r){let n=this.lostBulkJobs;if(!n||t===void 0)return[];let o=n.since(t,e);if(o.length===0)return[];ie.info("Forge execute: waiting for the Bulk API jobs the run lost before the mute is given back",{jobs:o.map(a=>`${a.objectApiName} ${a.jobId??"(no id)"}`)});let i=await n.stillRunning(o,()=>{Hn(r)});return i.length>0&&ie.warn("Forge execute: Bulk API jobs still running as the mute is given back; what they write now goes in with the target\u2019s automation",{jobs:i.map(a=>`${a.objectApiName} ${a.jobId??"(no id)"}`)}),i.map(({objectApiName:a,jobId:d})=>({objectApiName:a,...d?{jobId:d}:{}}))}async sampleOf(e){let{config:t}=e,r=this.runJournal?.storagePath;if(r===void 0)throw new Error(VM);let n=this.setupFingerprintOf(e.graph,t,e.anonymizationRules,e.readCeiling),o=new Date,i,a,d,c=!1,u,l=h=>{if(!(h instanceof gv))throw h};if(e.dryRun||e.journalId===void 0)i=mv(r,n);else if(e.retried&&!e.resumes){i=Qa(r,e.journalId);let h=e.retried.journalId,m=h!==void 0?await Kl.open(Qa(r,h),{fingerprint:n}).catch(l):void 0;m?(a=await Rv(m,r,e.journalId),c=!0):d="planGone"}else if(i=Qa(r,e.journalId),!e.resumes){let h=await yv(r,n,o);if(h instanceof Kl)a=await wv(h,r,e.journalId).catch(l),a?u=h.dir:d="planTaken";else if(h==="tooOld"||this.samplePlansSwept.has(n))d="tooOld";else{let m=this.sampleSimulations.get(e.volumeCase);m!==void 0&&(d=m===n?"planTaken":"setUpOtherwise")}}await this.sweepSamplePlansOf(r,o);let p;if(!a&&!e.resumes){let h=await this.readSourceApiBudget(t,e.lookup);"unread"in h||(p=h.remaining)}let f=t.sample?.withinMB;return{stream:{options:t.sample??{},budget:async()=>{Hn(e.lookup);let h=await this.readTargetDataStorage(t.targetOrgId),m=DR({storage:h,bounds:f!==void 0?{withinMB:f}:{},target:e.target});if(m)throw gt.of(m);let y;"unread"in h?(Hn(e.lookup),y=await this.readTargetApiBudget(t.targetOrgId)):y=h.dailyApiRequests;let v="unread"in h?void 0:h.dailyBulkApiBatches,b=Za({storage:h,...f!==void 0?{withinMB:f}:{},automation:e.room(),allowances:{...y?{requests:y}:{},...v?{bulkBatches:v}:{},...e.sentBefore?{sentBefore:e.sentBefore()}:{},...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{}}});if(!b)throw new Error("No budget of the sample could be read. Nothing was written.");return b},keepAt:i,fingerprint:n,...a?{plan:a}:{},...p!==void 0?{sourceRequestsLeft:p}:{},onProgress:e.onProgress},fingerprint:n,...d?{drawnAgain:d}:{},...c?{ofTheRunRetried:!0}:{},...u!==void 0?{adoptedFrom:u}:{}}}async giveThePlanBack(e,t){let r=this.runJournal?.storagePath;r!==void 0&&await bv(r,e,t).catch(n=>{ie.warn(`Forge sample: the plan of the simulation was not put back (${I(n)})`)})}async sweepSimulationPlans(e=new Date){let t=this.runJournal?.storagePath;t!==void 0&&(await this.sweepSamplePlansOf(t,e),await this.sweepRootPlansOf(t,e))}async sweepRootPlansOf(e,t){await Tv(e,t,(r,n)=>this.rootPlansSwept.set(r,n)).catch(r=>{ie.warn(r instanceof Ov?`Forge roots: the roots of past simulations were not all swept: ${r.removed} removed, ${r.left.length} left (${I(r)})`:`Forge roots: the roots of past simulations were not swept (${I(r)})`)})}async sweepSamplePlansOf(e,t){try{for(let r of await vv(e,t))this.samplePlansSwept.add(r)}catch(r){if(r instanceof hv)for(let n of r.removed)this.samplePlansSwept.add(n);ie.warn(`Forge sample: the plans of past simulations were not all swept (${I(r)})`)}}noteSampleSimulation(e,t){this.samplePlansSwept.delete(t),this.sampleSimulations.delete(e),this.sampleSimulations.set(e,t);for(let r of this.sampleSimulations.keys()){if(this.sampleSimulations.size<=XM)break;this.sampleSimulations.delete(r)}}writeGate(e){let t=e.checkpoint,r=(n,o)=>t&&{...t.ask,...o?{running:o.running}:{},written:n.objects.filter(({rows:i})=>i>0).map(i=>i.objectApiName)};return async n=>{let o=e.wholeOrg,i=n.wholeOrg;if(o&&!i)throw new Error("A clone of the whole org reached its write gate without what it measured of both orgs, which its gate weighs it on. Nothing was written.");let a=i?.sample?e.sampled?.(i.sample.report)??i.sample.report:void 0;if(n.dryRun&&o&&i){let{sentBefore:N}=e,z=Bl(n.objects,i);e.onSimulated?.(z);let oe=e.atTheRows?.(n,z),re=r(z,oe),q;t&&re&&this.beforeRunCheckpoints&&z.totalRows>0&&(q=await this.beforeRunCheckpoints.scope(re,t.own).then(ne=>(t.onEstimate(ne),ne),ne=>{ie.warn(`Forge simulation: ${Rr(ne)}`)}));let F=await xR({objects:n.objects,measures:i,graph:o.graph,anonymizePII:o.anonymizePII,...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{},...q?{checkpoint:q}:{},...n.readBack!==void 0?{readBack:n.readBack}:{},...(oe?.mute??e.mute)!==void 0?{mute:oe?.mute??e.mute}:{},...e.deliverability!==void 0?{deliverability:e.deliverability}:{},...N?{sentBefore:()=>({target:N()})}:{},target:{org:e.org,limits:Vt(this.limitsTransportOf(e.targetOrgId,()=>Hn(e.lookup)),e.targetOrgId)},source:{org:o.source,limits:this.limitsTransportOf(o.sourceOrgId,()=>{e.lookup.requests++})},...a?{sample:a}:{},...e.automationRoom?{automation:e.automationRoom()}:{}});if(!a&&F.storage.verdict==="exceeds"){let ne=Za({storage:F.storage});ne&&e.onSampleOffer?.(ne.budget)}throw ie.info("Forge write gate: the dry run of a clone of the whole org",{records:F.totalRows,objects:F.wouldInsert.length,targetRequests:F.targetRequests.estimate,sourceRequests:F.sourceRequests.estimate,...F.bulkBatches?{bulkBatches:F.bulkBatches.estimate}:{},wouldBeRefused:F.wouldBeRefused.map(ne=>ne.code)}),new $v(F)}if(n.dryRun){let N=Hl(n.objects);e.onSimulated?.(N);let z=r(N,e.atTheRows?.(n,N));return t&&z&&this.beforeRunCheckpoints&&N.totalRows>0&&await this.beforeRunCheckpoints.scope(z,t.own).then(t.onEstimate,oe=>{ie.warn(`Forge simulation: ${Rr(oe)}`)}),{}}let d=i?ER(i.readWholeOver):void 0;if(d)throw gt.of(d);let c=i?Bl(n.objects,i):Hl(n.objects),u=e.atTheRows?.(n,c),l=u?.mute??e.mute;if(c.totalRows===0)return{};Hn(e.lookup);let p=await this.readTargetDataStorage(e.targetOrgId),f=Sr(c,p,e.automationRoom?$R(c,e.automationRoom()):0);if(a){let N=NR({sample:a,storage:p,target:e.org});if(N)throw gt.of(N)}let g=this.confirmAboveRecords(),h=g>0&&c.totalRows>g?g:void 0,m=Cb(e.orgTier),y=m!==void 0&&c.totalRows>m?m:void 0;ie.info("Forge write gate",{records:c.totalRows,objects:Object.fromEntries(c.objects.slice(0,20).map(N=>[N.objectApiName,N.rows])),storageEstimateMB:Ks(f.estimateMB),...f.verdict==="unread"?{storageUnread:f.unread}:{storageRemainingMB:f.remainingMB,storageMaxMB:f.maxMB},storage:f.verdict});let v=JR(f,e.org);if(v&&f.verdict==="exceeds"){if(o&&!a&&!("unread"in p)){let z=Za({storage:p});z&&e.onSampleOffer?.(z.budget)}let N=n.roots&&!o?dR(f,e.org,n.roots):void 0;throw N?gt.of(N):new gt("STORAGE_EXCEEDED",`${v} Nothing was written.`,{estimateMB:Number(Ks(f.estimateMB)),remainingMB:f.remainingMB,...kr(f)})}f.verdict==="near"?ie.warn("Forge write gate: the records take more than 80 % of the data storage the target has left"):f.verdict==="unread"&&ie.warn("Forge write gate: the data storage the target has left could not be read"),y!==void 0&&ie.warn(`Forge write gate: more than ${y} records, a large volume`);let b=i?PR(i.files,p,e.org):void 0;if(b?.stop)throw gt.of(b.stop);let k;"unread"in p?(Hn(e.lookup),k=await this.readTargetApiBudget(e.targetOrgId)):k=p.dailyApiRequests;let S=r(c,u),C;if(t&&S){let N=this.beforeRunCheckpoints;if(!N)throw new gt(Cn,Rr(new Error("SandForge's checkpoints are not set up in this window")));C=await N.scope(S,t.own).catch(z=>{throw new gt(Cn,Rr(z))})}let R=o?await this.readSourceApiBudget(o,e.lookup):void 0,w=CR({plan:c,...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{},...n.readBack!==void 0?{readBack:n.readBack}:{},...C?{checkpoint:C}:{},...l!==void 0?{mute:l}:{},...e.deliverability!==void 0?{deliverability:e.deliverability}:{},...e.sentBefore?{sentBefore:e.sentBefore()}:{},budget:k,target:e.org,...o&&i?{wholeOrg:{measures:i,bulkBatches:"unread"in p?p:p.dailyBulkApiBatches,sourceBudget:R,source:o.source}}:{}});if(ie.info("Forge write gate: API requests",{estimate:w.api.estimate,verdict:w.api.verdict,...w.api.verdict==="unread"?{unread:w.api.unread}:{remaining:w.api.remaining,max:w.api.max},...w.api.parts?{parts:w.api.parts}:{}}),w.stop)throw gt.of(w.stop);let P=Aa(w.api),O=o&&i&&w.wholeOrg?Nv({run:o,measures:i,plan:c,budget:{api:w.api,wholeOrg:w.wholeOrg},...b?.files?{files:b.files}:{},...a?{sample:a,now:Date.now()}:{}}):void 0;O&&ie.info("Forge write gate: a clone of the whole org",{sourceRequests:w.wholeOrg?.source.estimate,sourceApi:w.wholeOrg?.source.verdict,jobs:O.bulk?.jobs??0,...w.wholeOrg?.bulkBatches?{bulkBatches:w.wholeOrg.bulkBatches.estimate}:{},durationSeconds:Math.round(O.durationSeconds),managedPackages:O.managedPackages?.length??0,personalAsIs:O.personalAsIs?.length??0});let E=async()=>{let N=this.beforeRunCheckpoints;if(!t||!S||!C||!N)return;let z=C,oe=await Xa(()=>N.take(S,t.own,{planned:z,signal:t.signal,onProgress:({percentage:re})=>t.onProgress?.(re)}));if("stop"in oe)throw oe.stop.code===Cn?gt.of({...oe.stop,code:Cn}):Object.assign(new Error(oe.stop.message),{name:"ForgeAbortedError"});t.onTaken(oe.checkpoint)},$=()=>Tt({action:"forge_execute",orgId:e.targetOrgId,operationId:e.operationId},{mb:f.estimateMB,rowBytes:Ga(c)}),H=[],J=[];if(e.emailsPerInsert.length>0){Hn(e.lookup);for(let N of MR(c,e.emailsPerInsert,await this.readTargetEmailLimits(e.targetOrgId)))N.verdict==="exceeds"?H.push(_R(N)):N.verdict==="unread"&&J.push(UR(N));J.length>0&&ie.warn("Forge write gate: a daily email limit of the target could not be read",{limits:J.map(({limit:N,emails:z})=>({limit:N,emails:z}))}),H.length>0&&ie.warn("Forge write gate: the records take the target past a daily email limit",{limits:H.map(({limit:N,emails:z,remaining:oe})=>({limit:N,emails:z,remaining:oe}))})}let W=e.automation===void 0?void 0:"automation"in e.automation?FR(e.automation.automation,LR(c)):`the target's automation: ${e.automation.unread}`;W!==void 0&&ie.warn("Forge write gate: what of the target sends emails could not all be read, and its emails were not counted");let Z=(e.mayBeInTarget??[]).filter(({rows:N})=>N>0),_=e.simulated?IR(e.simulated,c.totalRows):void 0;if(_?.farAbove&&ie.warn("Forge write gate: far more records than the last simulation of the case",{records:c.totalRows,simulated:_.total}),h===void 0&&f.verdict==="fits"&&H.length===0&&J.length===0&&W===void 0&&Z.length===0&&_?.farAbove!==!0&&!w.asks)return await E(),$(),P;let Q=await e.guard.confirmRun({stage:"write",...n.roots?{roots:{...n.roots,source:e.source}}:{},org:e.org,orgTier:e.orgTier,objects:c.objects.map(({objectApiName:N,rows:z})=>({objectApiName:N,rows:z})),total:c.totalRows,...h!==void 0?{aboveRecords:h}:{},...y!==void 0?{largeVolume:y}:{},storage:Dn(f),...c.leftOut?{leftOut:c.leftOut}:{},...n.objects.some(N=>N.counted)?{counted:!0}:{},...H.length>0?{emails:H}:{},...J.length>0?{emailsUnread:J}:{},...W!==void 0?{emailsUncounted:W}:{},...AR(c),...TR(c),...Z.length>0?{mayBeInTarget:Z.map(({objectApiName:N,rows:z})=>({objectApiName:N,rows:z}))}:{},...Z.length>0&&e.jobsUnderway&&e.jobsUnderway.length>0?{jobsUnderway:h0(e.jobsUnderway)}:{},...n.capped?{capped:n.capped}:{},..._?{simulated:_}:{},...O?{wholeOrg:O,...w.confirmation.checkpoint?{checkpoint:w.confirmation.checkpoint}:{}}:w.confirmation});if(Q==="confirmed")return e.onConfirmed(),await E(),$(),P;throw Q==="declined"?new gt("WRITE_DECLINED","Forge execution was cancelled before it wrote the records it had read. Nothing was written."):new gt("CONFIRMATION_UNAVAILABLE","Forge execution needed a confirmation before it wrote the records it had read, and there was no one to ask. Nothing was written.")}}async loadRecordTypeMappings(e,t,r){let n=()=>{},o=new Promise(i=>{n=()=>i(void 0),t.addEventListener("abort",n,{once:!0})});try{let i=new pe(l0).withTimeout("forge:record-types",()=>this.readRecordTypeMappings(e,r));return await Promise.race([i,o])}catch(i){ie.warn(`[forge] Record types could not be read from both orgs (${I(i)}); cloned records keep their source RecordTypeId.`);return}finally{t.removeEventListener("abort",n)}}async readRecordTypeMappings(e,t){let[r,n]=await Promise.all([e.sourceOrgId,e.targetOrgId].map(async o=>{let i=await B(o,this.deps.orgRegistry,this.deps.orgManager),a=()=>{o===e.targetOrgId?Hn(t):t.requests++},{records:d}=await nr({query:async c=>(a(),i.query(c)),queryMore:async c=>(a(),i.queryMore(c))},YR);return QR(d)}));for(let o of ZR(r,n))ie.warn(`[forge] ${ev(o)}`);return new tv().buildMapping(r,n)}async handleTemplatesList(e){let{templates:t,importNotMerged:r}=await this.loadTemplates(),n=A(this.deps,e,"forge:templates:list:response",{templates:t.filter(o=>Xu.safeParse(o).success),...r===void 0?{}:{importNotMerged:r}});this.deps.broker.postToWebview(n)}async handleSaveTemplate(e){let t=st(kM,e,"forge:templates:save:error",this.deps);if(!t)return;let{template:r}=t;try{let o=[r,...(await this.loadTemplates()).templates.filter(i=>i.id!==r.id)];await this.saveTemplates(o)}catch(o){T(this.deps,"forge:templates:save","forge:templates:save:error",e,o);return}let n=A(this.deps,e,"forge:templates:save:response",{success:!0});this.deps.broker.postToWebview(n)}async handleDeleteTemplate(e){let t=st($M,e,"forge:templates:delete:error",this.deps);if(!t)return;let{templateId:r}=t;try{let o=(await this.loadTemplates()).templates.filter(i=>i.id!==r);await this.saveTemplates(o)}catch(o){T(this.deps,"forge:templates:delete","forge:templates:delete:error",e,o);return}let n=A(this.deps,e,"forge:templates:delete:response",{success:!0});this.deps.broker.postToWebview(n)}async handleHistoryList(e){await this.keepRunsLeftOver();let t=this.loadHistory(),r=await this.resumableRuns(t),n=[];try{n=await this.removalPlans?.list()??[]}catch(u){ie.warn(`Forge removal plans could not be read: ${I(u)}`)}let o=await this.journalsPresent([...t.flatMap(u=>u.remapInJournal&&u.journalId?[u.journalId]:[]),...n.flatMap(u=>u.inJournal?[u.inJournal.journalId]:[])]),i=t.map(u=>({...u,...r.has(u.forgeId)?{resumable:!0}:{},...u.remapInJournal&&!(u.journalId&&o.has(u.journalId))?{journalGone:!0}:{}})),a=new Set(i.map(u=>u.forgeId)),d=n.filter(u=>!a.has(u.forgeId)&&Wr(u).length>0).map(u=>u.inJournal&&!o.has(u.inJournal.journalId)?{...u,journalGone:!0}:u);await this.dropJournalsNoLongerNamed(t,n);let c=A(this.deps,e,"forge:history:list:response",{history:i,...d.length>0?{olderRuns:d}:{}});this.deps.broker.postToWebview(c)}async handleUndo(e){let t={};try{await this.undoUnderItsLock(e,t)}finally{t.lock?.release()}}async undoUnderItsLock(e,t){let r=st(OM,e,"forge:undo:error",this.deps);if(!r)return;let{forgeId:n}=r,o=r.includeChanged===!0,i=r.sweep===!0,a=r.again===!0,d=r.muteAutomation===!0,c=i&&r.sweepLate===!0,u=i&&r.sweepUntied===!0,l=(S,C)=>this.refuseUndo(e,S,C),p=this.loadHistory().find(S=>S.forgeId===n),f=p?void 0:await this.keptRemovalPlan(n),g,h={},m=p?.targetOrgId??f?.targetOrgId,y=p?p.journalId:f?.inJournal?.journalId;if(y){let S=this.journalBusy(y,"remove");if(S){l(S,Ei);return}if(this.removing.has(n)){l("The records of this run are being removed already: its result shows under the run once it ends.",Yf);return}let C=this.lockToRemove(y,m);if(C&&"busy"in C){l(C.busy,Ei);return}C&&(t.lock=C)}if(m&&y&&(!p||p.idRemapCreated)){if(this.removing.has(n)){l("The records of this run are being removed already: its result shows under the run once it ends.",Yf);return}this.removing.add(n);try{let S=await this.callsLookedForBeforeRemoval({forgeId:n,targetOrgId:m,journalId:y,removedBefore:(p??f)?.undo!==void 0});if("unread"in S){l(S.unread,"IN_FLIGHT_UNREAD");return}g=S.reconciled,h=S,g&&g.found.length>0&&(p?p=await this.withRowsFoundAfterStop(p,g.found):f&&(f=await this.planWithRowsFoundAfterStop(f,g.found)))}finally{this.removing.delete(n)}}let v,b,k=()=>{};if(p){let S=Date.parse(p.timestamp);if(!p.idRemapCreated||!p.targetOrgId||Number.isNaN(S)){l(`This run was recorded before Forge kept what a run created: its records cannot be removed from the history. ${Qc}`,"NOT_RECORDED");return}let C=p.remapInJournal&&p.journalId&&p.journalPart!==void 0?{journalId:p.journalId,part:p.journalPart}:void 0,R=w0(p.mayHaveBeenWritten,{...h,reconciled:g});if(v={...p,targetOrgId:p.targetOrgId,unreachable:y0(p.mayHaveBeenWritten,g),...R?{notLookedFor:R}:{},...C?{inJournal:C}:{}},p.remapInJournal){if(b=[],a||yn(p).length>0){let w=await this.journalRecordsOf(C,p.undo,a);if("gone"in w){l(w.gone,ms);return}b=w.records,k=w.close}}else b=a?qr(p):Ts(p)}else if(f){if(i){l(xT,"SWEEP_UNAVAILABLE");return}v={...f,unreachable:g&&g.calls>0?Zl(g):f.mayHaveBeenWritten??0,...h.callsNotLookedFor?{notLookedFor:{callsAfterRemoval:h.callsNotLookedFor}}:{}};let{inJournal:S}=f;if(S&&(a||Wr(f).length>0)){let C=await this.journalRecordsOf(S,f.undo,a);if("gone"in C){l(C.gone,ms);return}b=C.records,k=C.close}else b=a?f.objects.map(({objectApiName:C,ids:R})=>({objectApiName:C,ids:[...R]})):sl(f)}else{l("This run is no longer in the Forge history.",ys);return}try{let S=$l(b),C=i&&v.undo!==void 0,R=S===0&&jT(v),w=R&&o;if(S===0&&!C&&!w){v.undo?l(`The records this run created were already removed, on ${v.undo.removedAt}.`+(R?" What that removal kept as changed since the run, the duplicate record sets the target's rules made of them, goes once the records changed since are included.":""),"ALREADY_REMOVED"):l("This run created no record to remove.","NOTHING_TO_REMOVE");return}if(this.removing.has(n)){l("The records of this run are being removed already: its result shows under the run once it ends.",Yf);return}this.removing.add(n);let P=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(e.id);try{await this.removeRun(e,v,b,{includeChanged:o,again:a,muteAutomation:d,sweepLate:c,sweepUntied:u,...w?{setsAgain:!0}:{},...!i&&p?.config?.inputMode==="org"?{wholeOrgNotSwept:!0}:{}},i?p:void 0,P)}finally{this.removing.delete(n),P?.release()}}finally{k()}}async journalRecordsOf(e,t,r=!1){let n=this.runJournal;if(!n||!e)return{gone:_n};try{let o=await n.recordsOf(e.journalId,e.part,r);if(o)return o;let i=await this.planRecordsOf({inJournal:e,...t?{undo:t}:{}},r);return"gone"in i?i:{records:i.records,close:()=>{}}}catch(o){return ie.warn(`Forge run journal could not be read: ${I(o)}`),{gone:_n}}}async journalsPresent(e){let t=this.runJournal;if(e.length===0)return new Set;if(!t)return new Set;try{return await t.present(e)}catch(r){return ie.warn(`Forge run journals could not be listed: ${I(r)}`),new Set(e)}}async dropJournalsNoLongerNamed(e,t){let r=this.runJournal;if(r)try{let n=new Set([...e.map(o=>o.journalId),...t.map(o=>o.inJournal?.journalId),...this.journalsRunning].filter(o=>o!==void 0).map(o=>r.fileNameOf(o)));for(let o of await r.endedFiles())n.has(o)||await r.forgetFile(o)}catch(n){ie.warn(`Forge run journals could not be dropped: ${I(n)}`)}}async withIdsOf(e,t=!1){if(!e.remapInJournal)return{entry:e};let r=this.runJournal;if(!r||!e.journalId||e.journalPart===void 0)return{gone:_n};try{let n=await r.idsOf(e.journalId,e.journalPart);if(!n)return{gone:_n};let o=await r.leftOf(e.journalId,e.journalPart),i={...e.removalStamps,...await r.stampsOf(e.journalId,e.journalPart)};return{entry:{...e,idRemapTable:n.table,idRemapExisting:n.existing,idRemapCreated:n.createdByObject,...o?{removalLeft:o}:{},...Object.keys(i).length>0?{removalStamps:i}:{},...t&&n.withTheirRecord?{idRemapWithTheirRecord:n.withTheirRecord}:{}}}}catch(n){return ie.warn(`Forge run journal could not be read: ${I(n)}`),{gone:_n}}}async planRecordsOf(e,t=!1){let r=this.runJournal;if(!r)return{gone:_n};try{let{journalId:n,part:o}=e.inJournal,i=await r.idsOf(n,o);if(!i)return{gone:_n};let a={idRemapTable:i.table,idRemapExisting:i.existing,idRemapCreated:i.createdByObject};if(t)return{records:qr(a)};let d=await r.leftOf(n,o);return{records:Ts({...a,...e.undo?{undo:e.undo}:{},...d?{removalLeft:d}:{}})}}catch(n){return ie.warn(`Forge run journal could not be read: ${I(n)}`),{gone:_n}}}async keptRemovalPlan(e){try{return await this.removalPlans?.get(e)}catch(t){ie.warn(`Forge removal plans could not be read: ${I(t)}`);return}}async callsLookedForBeforeRemoval(e){let t=this.runJournal,{forgeId:r,journalId:n}=e;if(!t||this.journalsRunning.has(n))return{};try{if((await t.lastEnd(n))?.forgeId!==r)return{};let a=t.callsInFlight(n);if(e.removedBefore)return a>0?{journalRead:!0,callsNotLookedFor:a}:{};if(a===0)return{journalRead:!0}}catch{return{}}let o=we(this.deps.orgManager.getOrg(e.targetOrgId),e.targetOrgId);try{let i=await B(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=await t.reconcile(n,Yl(i));for(let d of Ql(a,o,"removal"))ie.info(`Forge removal: ${d.trim()}`);return{reconciled:a,journalRead:!0}}catch(i){return{unread:`${o} could not be read for the insert calls this run had under way when it stopped (${I(i)}): removed without them, the records those calls wrote would stay behind. Nothing was deleted. Reconnect ${o} on Organizations if its session expired, then remove the run again.`}}}async datedByItsJournal(e,t){let r=this.runJournal,{journalId:n,part:o,scope:i}=e;if(!(!r||!n))try{return(await r.present([n])).has(n)?await r.writtenBetween(n,t,o,i):void 0}catch(a){ie.warn(`Forge run not dated from its journal: ${I(a)}`);return}}async withRowsFoundAfterStop(e,t){let r=this.runJournal,{journalId:n,journalPart:o}=e;if(!r||!n||o===void 0)return e;let i=t.reduce((u,{rows:l})=>u+l,0),a=b0(e.idRemapByObject,t),d;if(e.remapInJournal)d={...e,idRemapCount:e.idRemapCount+i,createdCount:(e.createdCount??0)+i,...a?{idRemapByObject:a}:{}};else{let u=await r.idsOf(n,o).catch(()=>{});if(!u)return e;d={...e,idRemapTable:u.table,idRemapExisting:u.existing,idRemapCreated:u.createdByObject,idRemapCount:Object.keys(u.table).length,createdCount:u.createdByObject.reduce((l,{sourceIds:p})=>l+p.length,0),...a?{idRemapByObject:a}:{}}}this.saveHistory(this.loadHistory().map(u=>u.forgeId===d.forgeId?d:u));let c=Qi(d);return c&&await this.removalPlans?.put(c).catch(u=>{ie.warn(`Forge removal plan not kept: ${I(u)}`)}),d}async planWithRowsFoundAfterStop(e,t){let{inJournal:r}=e;if(!r)return e;let n=r.left.map(i=>({...i}));for(let{objectApiName:i,rows:a}of t){let d=n.find(c=>c.objectApiName===i);d?d.count+=a:n.unshift({objectApiName:i,count:a})}let o={...e,inJournal:{...r,left:n}};return await this.removalPlans?.put(o).catch(i=>{ie.warn(`Forge removal plan not kept: ${I(i)}`)}),o}async keepRunsLeftOver(){let e=this.runJournal;if(e)try{let t=new Set(this.journalsRunning);for(let r of await e.leftOver(t)){if(this.journalBusy(r.journalId,"remove")!==void 0)continue;let n=r.resume?.startedWith;if(!n){let o=kv.planOf(r),i=this.removalPlans;o&&i&&await i.putIfAbsent(o),(!o||i)&&await e.forget(r.journalId);continue}if(r.created.length>0||e.callsInFlight(r.journalId)>0){let o=r.parts>1?await e.readAt(e.pathOf(r.journalId),"all"):void 0,i=e0(r,n.graph,o);this.addToHistory(i,n.config),await e.stop(r.journalId,"interrupted",i.forgeId)}else r.endBefore?await e.stop(r.journalId,r.endBefore.status,r.endBefore.forgeId):await e.forget(r.journalId)}}catch(t){ie.warn(`Forge run journals could not be read: ${I(t)}`)}}async resumableRuns(e){let t=new Set,r=this.runJournal;if(!r)return t;for(let n of e)if(!(!n.journalId||this.journalsRunning.has(n.journalId))){try{let o=await r.lastEnd(n.journalId);if(o?.forgeId!==n.forgeId||!AT.has(o.status))continue}catch{continue}PT(n,e)===void 0&&t.add(n.forgeId)}return t}async runToResume(e){let t=this.loadHistory(),r=t.find(l=>l.forgeId===e);if(!r)return{refused:"The run to resume is no longer in the history: what it wrote and where it stopped are not known. Run the clone again from Review. Nothing was read or written."};let n=r.targetOrgId,o=this.runJournal;if(!r.journalId||!o)return{refused:`This run kept no journal to take it up from: ${OT}`,targetOrgId:n};if(this.journalsRunning.has(r.journalId))return{refused:"This run is being taken up already.",targetOrgId:n};let i=this.journalBusy(r.journalId,"resume");if(i)return{refused:i,targetOrgId:n};let a=await o.lastEnd(r.journalId);if(!a||a.forgeId!==r.forgeId||!AT.has(a.status))return{refused:"This run was taken up already, or its run ended: only the last part of a run that stopped can be resumed.",targetOrgId:n};let d=PT(r,t);if(d!==void 0)return{refused:`The records ${d===r?"this run created":"a part of this run created"} were removed on ${d.undo?.removedAt}: there is nothing to resume against.`,targetOrgId:n};let c=await o.head(r.journalId),u=c?.resume?.startedWith;return!c?.resume||!u||c.targetOrgId!==n?{refused:`The journal of this run does not say how it was set up: ${OT}`,targetOrgId:n}:{entry:r,journalId:r.journalId,head:{...c.resume,startedWith:u},targetOrgId:c.targetOrgId,end:a}}async handleResumeRun(e){let t=st(bM,e,"forge:execute:error",this.deps);if(!t)return;let r=(y,v,b)=>{b&&Y(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:b,outcome:"stopped",code:y}),T(this.deps,"forge:execute","forge:execute:error",e,new Error(v),{code:y})},n=await this.runToResume(t.forgeId);if("refused"in n){r(wM,n.refused,n.targetOrgId);return}let{entry:o,journalId:i,head:a,targetOrgId:d,end:c}=n,u=this.deps.orgManager.getOrg(d);if(!u){r(IT,"The org this run wrote to is no longer registered in SandForge: add the same org again on Organizations, then resume \u2014 the run checks it is the org it wrote to. Refreshed since, it holds nothing the run wrote: run the clone again. Nothing was read or written.",d);return}if(a.targetSalesforceOrgId!==void 0&&u.orgId&&u.orgId.slice(0,15)!==a.targetSalesforceOrgId.slice(0,15)){r(IT,`${we(u,d)} is no longer the org this run wrote to \u2014 refreshed or replaced since: what the run wrote is not there. Run the clone again from Review into it as it is now. Nothing was read or written.`,d);return}let{graph:l,config:p,anonymizationRules:f}=a.startedWith,g=Vu(p);if(g!==void 0){r(Qf,`${g}. Nothing was read or written.`,d);return}let h=this.maxRecordsPerObject(),m=y=>Pv(a.fingerprint,y.graph,this.runSetupOf(y.config,f,h,a.targetSalesforceOrgId));if(!m({graph:l,config:p})){r(Qf,"This run would now be set up otherwise than the part it resumes (sandforge.forge.maxRecordsPerObject changed since): put the setting back to take it up, or retry it.",d);return}if(t.graph&&t.config&&!m({graph:t.graph,config:this.withMaxRoots(t.config)})){r(Qf,"The clone on this page is set up otherwise than the run to resume: its objects, filters or decisions changed since.",d);return}await this.handleExecute(e,{forgeId:o.forgeId,journalId:i,head:a,end:c,startedWith:{graph:l,config:p,...f?{anonymizationRules:f}:{},...t.muteAutomation===!0||a.muteAutomation===!0?{muteAutomation:!0}:{},...a.files?{files:a.files}:{}}})}resumeHeadOf(e,t,r,n){let o=this.targetSalesforceOrgIdOf(t);return{sourceOrgId:t.sourceOrgId,fingerprint:this.setupFingerprintOf(e,t,r,n),...o?{targetSalesforceOrgId:o}:{},startedWith:{graph:e,config:t,...r?{anonymizationRules:r}:{}}}}targetSalesforceOrgIdOf(e){let t=this.deps.orgManager.getOrg(e.targetOrgId)?.orgId;return t&&eg.test(t)?t:void 0}setupFingerprintOf(e,t,r,n){return this.fingerprintOf(e,t,r,n,this.targetSalesforceOrgIdOf(t))}fingerprintOf(e,t,r,n,o){return Ev(e,this.runSetupOf(t,r,n,o))}runSetupOf(e,t,r,n){return{config:{...e,dryRun:void 0},anonymizationRules:t??{},ceiling:e.inputMode==="org"?null:r,targetSalesforceOrgId:n?.slice(0,15)??null}}keepRemovalPlans(e,t){let r=this.removalPlans;if(!r)return;let n=Qi(e),o=[...n?[r.put(n)]:[],...t.flatMap(i=>{let a=Qi(i);return a&&Wr(a).length>0?[r.putIfAbsent(a)]:[]})];Promise.all(o).catch(i=>{ie.warn(`Forge removal plan not kept: ${I(i)}`)})}refuseUndo(e,t,r){T(this.deps,"forge:undo","forge:undo:error",e,new Error(t),{code:r})}async handleOpenRecord(e){let t=st(TM,e,"forge:open-record:error",this.deps);if(!t)return;let r=(u,l)=>{T(this.deps,"forge:open-record","forge:open-record:error",e,new Error(u),{code:l})},n=this.loadHistory().find(u=>u.forgeId===t.forgeId);if(!n){r("This run is no longer in the Forge history.",ys);return}if(!n.targetOrgId){r("This run was recorded before Forge kept the org it wrote to.","NOT_RECORDED");return}let o=await this.withIdsOf(n);if("gone"in o){r(o.gone,ms);return}let i=t.recordId.slice(0,15),a;for(let{objectApiName:u,ids:l}of qr(o.entry)){let p=l.find(f=>f.slice(0,15)===i);if(p){a={objectApiName:u,id:p};break}}if(!a){r("This record is not one this run created.","NOT_CREATED");return}let d=this.deps.orgManager.getOrg(n.targetOrgId);if(!d){r(kT,"ORG_NOT_FOUND");return}let c=bd(d.instanceUrl,a.objectApiName,a.id);if(!c.ok){let u=c.reason==="not-https"?`its instance URL must use HTTPS, got "${c.protocol}"`:c.reason==="invalid"?"its instance URL is not a valid URL":"the record is not one an address can be built for";r(`Cannot open the record in "${we(d)}": ${u}.`,c.reason==="not-a-record"?"NOT_CREATED":"INVALID_INSTANCE_URL");return}try{let u=await this.externalBrowser.open(c.url),l=A(this.deps,e,"forge:open-record:response",u);this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id} status=${u.status}`)}catch(u){T(this.deps,"forge:open-record","forge:open-record:error",e,u)}}async handleVerify(e){let t=st(EM,e,"forge:verify:error",this.deps);if(!t)return;let{forgeId:r}=t,n=(u,l)=>{T(this.deps,"forge:verify:request","forge:verify:error",e,new Error(u),{code:l})},o=this.loadHistory().find(u=>u.forgeId===r);if(!o){n("This run is no longer in the Forge history.",ys);return}if(o.dryRun===!0){n("A simulation wrote nothing: there is nothing of it to verify.","SIMULATION");return}let i=o.targetOrgId;if(!o.idRemapCreated||!o.idRemapTable||!i){n(`This run was recorded before Forge kept what a run created: its records cannot be verified. ${Qc}`,"NOT_RECORDED");return}let a=o;if(o.remapInJournal&&yn(o).length>0){let u=await this.withIdsOf(o,!0);if("gone"in u){n(u.gone,ms);return}a=u.entry}let d=o.remapInJournal&&a===o?[]:Ts(a);if(d.length===0){o.undo?n(`The records this run created were removed, on ${o.undo.removedAt}: there is nothing of it to verify.`,"ALREADY_REMOVED"):n("This run created no record to verify.","NOTHING_TO_VERIFY");return}if(!this.deps.orgManager.getOrg(i)){n(kT,"ORG_NOT_FOUND");return}if(this.verifying.has(r)){n("The records of this run are being verified already: its verdict shows under the run once it ends.",yM);return}this.verifying.add(r);let c=`forge-verify-${this.deps.nextId()}`;try{let u=await B(i,this.deps.orgRegistry,this.deps.orgManager),l=new Xv({target:np(u,"forge:verify"),source:await this.verificationSource(o.sourceOrgId)}),p=o.writtenBetween??await this.datedByItsJournal({journalId:o.journalId,part:o.journalPart,scope:"part"},u),f=await l.verify({records:d,remapTable:a.idRemapTable??{},...p?{runStartedAt:new Date(p.first),runEndedAt:new Date(p.last)}:{runRecordedAt:new Date(o.timestamp)},...a.removalStamps?{removalStamps:a.removalStamps}:{},...o.config?.fieldExclusions?{fieldExclusions:o.config.fieldExclusions}:{},...o.config?.fieldMappings?{fieldMappings:o.config.fieldMappings}:{},writtenWithout:Qv(o.writtenWithoutFields??[]),...o.lookupsLeftEmptyByFilter?{leftEmptyByFilter:o.lookupsLeftEmptyByFilter}:{},leftEmptyByTheRun:Yv(o.config?.inputMode==="org"),...a.idRemapWithTheirRecord?{withTheirRecord:a.idRemapWithTheirRecord}:{}});this.saveHistory(this.loadHistory().map(h=>h.forgeId===r?{...h,verification:f}:h)),Y(this.deps,{action:"forge_verify",module:"forge",operationId:c,orgId:i,outcome:f.verdict==="verified"?"success":"partial",verdict:f.verdict,details:{forgeId:r,...Kv(f)}});let g=A(this.deps,e,"forge:verify:response",{verification:f});this.deps.broker.postToWebview(g),this.deps.log(`[TX] ${g.type} id=${g.id} verdict=${f.verdict}`)}catch(u){Y(this.deps,{action:"forge_verify",module:"forge",operationId:c,orgId:i,outcome:"failure",details:{forgeId:r}}),T(this.deps,"forge:verify:request","forge:verify:error",e,u,{code:"VERIFY_ERROR",retryable:!0})}finally{this.verifying.delete(r)}}async handleExportIds(e){let t=st(PM,e,"forge:export-ids:error",this.deps);if(!t)return;let r=(c,u)=>{T(this.deps,"forge:export-ids:request","forge:export-ids:error",e,new Error(c),{code:u})},n=this.loadHistory().find(c=>c.forgeId===t.forgeId);if(!n){r("This run is no longer in the Forge history.",ys);return}if(!n.remapInJournal){r("This run keeps its ids in its results: save its Id map from there.","NOT_IN_JOURNAL");return}let o=await this.idMapRowsInJournal(n),i,a=()=>{};if(o)i=o.rows,a=o.close;else{let c=await this.withIdsOf(n);if("gone"in c){r(c.gone,ms);return}i=oh(c.entry)}let d=new Date().toISOString().slice(0,10);try{let c=await this.saveDialog.saveStream(`sandforge-forge-id-map-${d}.csv`,async p=>{await p(sh([]));let f=0,g=[];for(let h of i)g.push(h),!(g.length<CM)&&(await p(`
18
+ ${il(g)}`),f+=g.length,g=[]);return g.length>0&&await p(`
19
+ ${il(g)}`),f+g.length},["csv"]),u=c.status==="saved"?{status:"saved",path:c.path,rows:c.result}:c,l=A(this.deps,e,"forge:export-ids:response",u);this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id} status=${c.status}`)}finally{a()}}async idMapRowsInJournal(e){let t=this.runJournal;if(!(!t||!e.journalId||e.journalPart===void 0))try{return await t.idMapRowsOf(e.journalId,e.journalPart)}catch(r){ie.warn(`Forge run journal could not be read: ${I(r)}`);return}}async verificationSource(e){if(!e)return{unavailable:"This run was recorded before Forge kept the org it read from."};if(!this.deps.orgManager.getOrg(e))return{unavailable:"The org this run read from is no longer registered."};try{let t=await B(e,this.deps.orgRegistry,this.deps.orgManager);return np(t,"forge:verify source")}catch(t){return{unavailable:`The org this run read from could not be reached: ${I(t)}`}}}async removeRun(e,t,r,n,o,i){let{includeChanged:a,again:d}=n,{forgeId:c,targetOrgId:u}=t,l=$l(r),p=l>0||n.setsAgain===!0,f=(E,$)=>this.refuseUndo(e,E,$),g=this.deps.infraServices?.productionGuard;if(!g){Y(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:u,outcome:"stopped",code:ve.code}),f(ve.message,ve.code);return}let h=this.deps.orgManager.getOrg(u),m=Pe(h),{check:y,decision:v}=p?await et(g,{orgId:u,orgTier:m,operation:"delete",objectName:l>0?xl(r).join(", "):On,recordCount:l>0?l:"unknown",module:"forge"}):{check:void 0,decision:"allowed"};if(y&&(v==="refused"||v==="declined")){Y(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:u,outcome:"stopped",guard:v}),v==="refused"?f(`Operation blocked by Production Guard: ${y.blockedReason??y.impactSummary}`,"GUARD_BLOCKED"):T(this.deps,"forge:undo","forge:undo:error",e,new Error("Operation cancelled by user (confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}if(i?.signal.aborted){Y(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:u,outcome:"stopped",guard:v,code:ht});let E={forgeId:c,status:"cancelled",includeChanged:a,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(A(this.deps,e,"forge:undo:response",{result:E,operationId:e.id}));return}let b=e.id,k=l>0?`Removing ${l} record(s) a Forge run created`:n.setsAgain?"Removing the duplicate record sets a Forge run\u2019s records went in":"Sweeping what the target\u2019s automation created during a Forge run",S=new AbortController;Ge(this.deps,b,"forge",k);let C=this.trackRun(b,k,S);this.liveTracker?.register(b,"forge",k,l);let R,w,P,O;try{let E=await B(u,this.deps.orgRegistry,this.deps.orgManager),{inJournal:$}=t,H=t.writtenBetween??await this.datedByItsJournal({journalId:t.journalId??$?.journalId,part:t.journalPart??$?.part},E),J={...t.removalStamps,...$?await this.runJournal?.stampsOf($.journalId,$.part).catch(j=>(ie.warn(`Forge removal stamps not read: ${I(j)}`),{})):{}};l>0&&(w=await this.otherPartsOf(c,u,E));let W=Dl(t.removalSpans,w?.spans);o&&(P=await this.sweepOfRemoval({conn:E,entry:o,includeChanged:a,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,removalSpans:W,signal:S.signal,guard:g,orgTier:m,operationId:b,muted:()=>p?void 0:O}));let Z=P;await Z?.ask();let _=Z?.takes??[],Q=n.muteAutomation===!0&&(p||_.length>0)?await this.removalMute(u,xl(r),n.setsAgain?[..._,On]:_,w?.parts.flatMap(j=>j.objects)??[],t.runUserId!==void 0&&l>0):void 0,N;O=Q?.muted;let z=async()=>{let j=Q?.prepared;!j||S.signal.aborted||(N=await j.acquire(b),O=N.outcome)},re=await(p?vb(Wt(E,"forge:undo"),r,{...H?{runStartedAt:new Date(H.first),runEndedAt:new Date(H.last)}:{runDurationMs:t.duration,runRecordedAt:new Date(t.timestamp)},...Object.keys(J).length>0?{removalStamps:J}:{},...W.length>0?{removalSpans:W}:{},...w&&w.laterParts.length>0?{laterParts:w.laterParts}:{},...Z?{sweep:j=>Z.first(j),afterRemoval:j=>Z.afterRemoval(j),automationMade:Z.automationMade}:{},...t.runUserId?{runUserId:t.runUserId}:{},...w&&w.parts.length>0?{otherParts:w.parts.map(j=>j.alongside)}:{},includeChanged:a,onUndeletable:Gr(this.deps,u,"forge:undo"),beforeFirstWrite:z,signal:S.signal,onProgress:(j,se,U)=>{let te=Math.min(100,Math.round(j/Math.max(se,1)*100));_e(this.deps,b,te,j,se,U),S.signal.aborted||this.deps.infraServices?.backgroundRegistry?.updateProgress(b,te),this.liveTracker?.updateProgress(b,te,j,se,U)}}):(async()=>(await z(),await Z?.first(),await Z?.afterRemoval(),Rb))()).finally(async()=>{N&&(O=await N.release())});w&&await this.keepOtherPartStamps(w.parts,re.otherPartStamps??[]);let q=await P?.settle(),F=d?void 0:t.undo?.removedAt,ne=t.unreachable,ke=w?g0(re.objects,w.parts):[],de=(w?.parts??[]).flatMap(j=>j.undo&&j.records>0?[{forgeId:j.forgeId,records:j.records}]:[]),Ze={forgeId:c,status:Sb(re.objects,re.cancelled),includeChanged:a,objects:re.objects,finishedAt:new Date().toISOString(),...F?{leftBy:F}:{},...ne>0?{mayHaveBeenWritten:ne}:{},...t.notLookedFor?{notLookedFor:t.notLookedFor}:{},...O?{mutedAutomation:O}:{},...ke.length>0?{heldByOtherParts:ke}:{},...de.length>0?{otherPartsLeft:de}:{}};p&&Y(this.deps,{action:"cleanup_delete",module:"forge",operationId:b,orgId:u,outcome:jo(Ze),guard:v,objects:In(Ze.objects),...F?{leftBy:F}:{},...O?{muted:ft(O)}:{}});let xe={...Ze,status:No(Ze.status,q),...q?{sweep:q}:{},...n.wholeOrgNotSwept?{wholeOrgNotSwept:!0}:{}};n.wholeOrgNotSwept&&ie.info("Forge removal: a clone of the whole org removed without its sweep; what the target\u2019s automation created during the run stays");let Ue=kb(xe,l,t.undo,d)??(n.setsAgain&&t.undo&&xe.status!=="cancelled"?Ob(xe,t.undo):void 0),V=q&&Fv(q,new Date().toISOString(),o?.sweep),ae=Object.keys(re.stamps).length>0,ee=re.span,fe,D;if($)(re.objects.some(se=>se.deleted+se.alreadyGone>0)||d&&Ue!==void 0)&&(D=await this.runJournal?.keepLeftPages($.journalId,$.part,re.left()).catch(se=>{ie.warn(`Forge removal left not kept: ${I(se)}`)})),ae&&await this.runJournal?.keepStamps($.journalId,$.part,re.stamps).catch(se=>{ie.warn(`Forge removal stamps not kept: ${I(se)}`)});else if((re.gone.length>0||d&&Ue)&&!bb(r)){let j=new Set(re.gone);fe=r.flatMap(({ids:se})=>se.filter(U=>!j.has(U)))}if(Ue||ae||ee||fe||D||V){let j=se=>({...se,...Ue?{undo:Ue}:{},...V?{sweep:V}:{},...ae&&!$?{removalStamps:{...se.removalStamps,...re.stamps}}:{},...ee?{removalSpans:[...se.removalSpans??[],ee]}:{},...fe?{removalLeft:fe}:{}});this.saveHistory(this.loadHistory().map(se=>se.forgeId===c?{...j(se),...D?{removalLeftByObject:D}:{}}:se)),await this.removalPlans?.update(c,se=>{let U={...j(se),...se.inJournal&&D?{inJournal:{...se.inJournal,left:D}}:{}};return Wr(U).length>0?U:void 0}).catch(se=>{ie.warn(`Forge removal plan not updated: ${I(se)}`)})}let G=A(this.deps,e,"forge:undo:response",{result:xe,operationId:b});this.deps.broker.postToWebview(G);let ue=xe.status==="failure"?"No record this run created could be removed.":!p&&q&&q.status!=="success"?q.refusal??"The sweep left records in the org.":void 0;xe.status==="cancelled"||q?.status==="cancelled"?(me(this.deps,b,{aborted:!0}),this.liveTracker?.cancel(b)):(me(this.deps,b,{status:ue&&!p?"failure":xe.status}),ue?(R=new Error(ue),this.liveTracker?.fail(b,ue)):xe.status==="partial"?this.liveTracker?.partial(b):this.liveTracker?.complete(b))}catch(E){R=E,await P?.settle().catch(H=>{ie.warn(`Forge sweep not recorded: ${I(H)}`)});let $=jt(E)?E:void 0;Y(this.deps,{action:"cleanup_delete",module:"forge",operationId:b,orgId:u,outcome:$?"stopped":"failure",guard:v,...$?{code:$.code}:{}}),T(this.deps,"forge:undo","forge:undo:error",e,E,{code:$?.code??"UNDO_ERROR",retryable:!0}),me(this.deps,b,{status:"failure"}),this.liveTracker?.fail(b,I(E))}finally{w?.close(),C(R)}}async otherPartsOf(e,t,r){let n=[],o=[],i=this.loadHistory(),a=new Set(i.map(l=>l.forgeId)),d=(await this.keptRemovalPlans()).filter(l=>!a.has(l.forgeId)),c=l=>f0(l,i,d,t),u=[];for(let l of await this.runLineOf(e,i,d)){let p=i.find(h=>h.forgeId===l),f=p?void 0:d.find(h=>h.forgeId===l);(p??f)?.targetOrgId===t&&u.push((p??f)?.removalSpans??[]);let g=p?await this.otherPartFromEntry(p,t,r,c(l)):await this.otherPartFromPlan(f,t,r,c(l));g&&(g.close&&n.push(g.close),o.push(g.part))}return{parts:o,spans:Dl(...u),laterParts:c(e),close:()=>n.forEach(l=>l())}}async otherPartObjectsOf(e,t){let r=this.loadHistory(),n=new Set(r.map(a=>a.forgeId)),o=(await this.keptRemovalPlans()).filter(a=>!n.has(a.forgeId)),i=new Set;for(let a of await this.runLineOf(e,r,o)){let d=r.find(l=>l.forgeId===a),c=d?void 0:o.find(l=>l.forgeId===a);if((d??c)?.targetOrgId!==t)continue;let u=d?yn(d):c?Wr(c):[];for(let{objectApiName:l}of u)i.add(l)}return[...i]}async runLineOf(e,t,r){let n=[...t.map(a=>({forgeId:a.forgeId,...a.retryOf!==void 0?{retryOf:a.retryOf}:{},...a.journalId!==void 0?{journalId:a.journalId}:{}})),...r.map(a=>({forgeId:a.forgeId,...a.retryOf!==void 0?{retryOf:a.retryOf}:{},...a.inJournal?{journalId:a.inJournal.journalId}:{}}))],o=this.runJournal,i=new Map;for(;;){let{inLine:a,journals:d}=p0(e,n,i),c=o?[...d].filter(u=>!i.has(u)):[];if(!o||c.length===0)return[...a].filter(u=>u!==e);for(let u of c)i.set(u,await o.partsOf(u).catch(l=>(ie.warn(`Forge run journal parts not read: ${I(l)}`),[])))}}async keptRemovalPlans(){try{return await this.removalPlans?.list()??[]}catch(e){return ie.warn(`Forge removal plans could not be read: ${I(e)}`),[]}}async otherPartFromEntry(e,t,r,n){if(e.targetOrgId!==t||!e.idRemapCreated||this.removing.has(e.forgeId)||yn(e).length===0)return;let o=e.remapInJournal&&e.journalId&&e.journalPart!==void 0?{journalId:e.journalId,part:e.journalPart}:void 0,i,a;if(o){let c=await this.journalRecordsOf(o,e.undo);if("gone"in c)return;i=c.records,a=c.close}else i=Ts(e);let d=e.writtenBetween??await this.datedByItsJournal({journalId:e.journalId,part:e.journalPart},r);return{part:{forgeId:e.forgeId,...o?{inJournal:o}:{},alongside:await this.alongside(i,d,e,e.removalStamps,o,n),...e.undo?{undo:e.undo}:{},objects:yn(e).map(c=>c.objectApiName),records:yn(e).reduce((c,u)=>c+u.count,0)},...a?{close:a}:{}}}async otherPartFromPlan(e,t,r,n){if(!e||e.targetOrgId!==t||this.removing.has(e.forgeId)||Wr(e).length===0)return;let o=e.inJournal?{journalId:e.inJournal.journalId,part:e.inJournal.part}:void 0,i,a;if(o){let c=await this.journalRecordsOf(o,e.undo);if("gone"in c)return;i=c.records,a=c.close}else i=sl(e);let d=e.writtenBetween??await this.datedByItsJournal({journalId:o?.journalId,part:o?.part},r);return{part:{forgeId:e.forgeId,...o?{inJournal:o}:{},alongside:await this.alongside(i,d,e,e.removalStamps,o,n),...e.undo?{undo:e.undo}:{},objects:Wr(e).map(c=>c.objectApiName),records:Wr(e).reduce((c,u)=>c+u.count,0)},...a?{close:a}:{}}}async alongside(e,t,r,n,o,i){let a={...n,...o?await this.runJournal?.stampsOf(o.journalId,o.part).catch(()=>({})):{}};return{plan:e,span:BT(t,r),...Object.keys(a).length>0?{removalStamps:a}:{},...i.length>0?{laterParts:i}:{}}}async keepOtherPartStamps(e,t){for(let[r,n]of e.entries()){let o=t[r]??{};if(Object.keys(o).length===0)continue;if(n.inJournal){await this.runJournal?.keepStamps(n.inJournal.journalId,n.inJournal.part,o).catch(a=>{ie.warn(`Forge removal stamps of another part not kept: ${I(a)}`)});continue}let i=a=>({...a,removalStamps:{...a.removalStamps,...o}});this.saveHistory(this.loadHistory().map(a=>a.forgeId===n.forgeId?i(a):a)),await this.removalPlans?.update(n.forgeId,a=>i(a)).catch(a=>{ie.warn(`Forge removal plan not updated: ${I(a)}`)})}}sweepOfRemoval(e){let{conn:t,entry:r}=e,n=r.targetOrgId??"";return Yo({input:async()=>{let o=await this.sweepInputOf(r,t,e.signal);return"gone"in o?{refused:o.gone}:o},org:tn(t,"forge:undo sweep",e.signal),options:{includeChanged:e.includeChanged,removalSpans:e.removalSpans,sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},guard:e.guard,guardOf:{orgId:n,orgTier:e.orgTier,operation:"delete",module:"forge"},onGuardDecision:(o,i)=>{let a=e.muted();Y(this.deps,{action:"cleanup_delete",module:"forge",operationId:`${e.operationId}-sweep`,orgId:n,outcome:o.status==="refused"?"stopped":o.status,...i?{guard:i}:{},...o.status==="refused"?{code:Qo(i)}:{},objects:Go(o),details:Jo(o,r.forgeId),...a?{muted:ft(a)}:{}})},keepMade:async(o,i,a)=>{await this.removalPlans?.keepMade(r.forgeId,o,i,a).catch(d=>{ie.warn(`Forge sweep finds not kept: ${I(d)}`)})}})}async sweepInputOf(e,t,r){let n=await this.withIdsOf(e);if("gone"in n)return n;let o=n.entry,i=qr(o),a=await this.sweepPartsBeside(e),d=new Set(Object.values(o.idRemapTable??{}).map(p=>p.slice(0,15))),c=this.targetAutomation,u=e.targetOrgId??"",l;if(!c)l={error:"Target automation reader not configured"};else try{l=await new pe(Ci).withTimeout("forge:undo-sweep automation",()=>c.read(u,i.map(p=>p.objectApiName)))}catch(p){l={error:I(p)}}return Ko({writtenBetween:e.writtenBetween,created:i,remap:d,automation:Lv(l),...e.runUserId?{runUserId:e.runUserId}:{},ties:await this.tiesOf(e),...a.length>0?{otherParts:a}:{},...r?{signal:r}:{}},Wt(t,"forge:undo-sweep copies"))}async sweepPartsBeside(e){let t=this.loadHistory(),r=new Set(t.map(a=>a.forgeId)),n=(await this.keptRemovalPlans()).filter(a=>!r.has(a.forgeId)),o=[],i=0;for(let a of await this.runLineOf(e.forgeId,t,n)){i++;let d=t.find(l=>l.forgeId===a),c=d?void 0:n.find(l=>l.forgeId===a);if((d??c)?.targetOrgId!==e.targetOrgId)continue;let u;if(d){let l=await this.withIdsOf(d);"gone"in l||(u=qr(l.entry))}else if(c?.inJournal){let l=await this.planRecordsOf({...c,inJournal:c.inJournal},!0);"gone"in l||(u=l.records)}else c&&(u=c.objects);u&&o.push({part:d?.journalPart??c?.inJournal?.part??i,created:u})}return o}async tiesOf(e){let t=e.writtenBetween,r=await this.localRunsOn(e.targetOrgId,t,e.forgeId);e.targetOrgId!==void 0&&r.push(...await this.otherModuleRuns(e.targetOrgId,t).catch(()=>[]));let n=e.mutedAutomation,o=iS(e.removalSpans),i=await this.removalPlans?.madeOf(e.forgeId).catch(()=>[]),a=await this.removalPlans?.lateOf(e.forgeId).catch(()=>[]);return{otherRuns:nS(t,r),...n?.state==="muted"?{muted:{silenced:n.silenced,stillRan:n.stillRan}}:{},...o?{removalBegan:o}:{},...i&&i.length>0?{madeEarlier:i}:{},...a&&a.length>0?{lateEarlier:a}:{}}}async localRunsOn(e,t,r){let n=await this.removalPlans?.list().catch(()=>[]),o=new Set,i=[],a=async(d,c)=>{if(!oS(t,d))return{ids:[],...d};let u=await c();return u?{ids:u.flatMap(({ids:l})=>l),...d}:{ids:[],idsUntold:!0,...d}};for(let d of this.loadHistory()){if(o.add(d.forgeId),d.forgeId===r||d.targetOrgId!==e)continue;let c=$T(d);i.push(d.remapInJournal?await a(c,async()=>{let u=await this.withIdsOf(d);return"gone"in u?void 0:qr(u.entry)}):{ids:qr(d).flatMap(({ids:u})=>u),...c})}for(let d of n??[]){if(o.has(d.forgeId)||d.forgeId===r||d.targetOrgId!==e)continue;let c=$T(d),u=d.inJournal;i.push(u?await a(c,async()=>{let l=await this.planRecordsOf({...d,inJournal:u},!0);return"gone"in l?void 0:l.records}):{ids:d.objects.flatMap(({ids:l})=>l),...c})}return i}setOtherModuleRuns(e){this.otherModuleRuns=e}setJournalLocks(e){this.journalLocks=e}journalBusy(e,t){let r=t==="remove"?"Removing its records now would delete under it what it goes on writing; remove them once it has ended.":"Taken up now, two runs would write the same journal; resume it once it has ended.";if(this.journalsRunning.has(e))return`A run of this window still writes this run's journal \u2014 a part that resumes it. ${r} Stop it on the Forge page, or let it end. Nothing was read or written.`;let n=this.runJournal;if(!n)return;let o;try{o=this.journalLocks.holder(n.pathOf(e))}catch(i){return`The lock of this run's journal, in ${Xf(n.pathOf(e))}, could not be read (${I(i)}): whether a run still writes it is not known. Try again once the folder can be read. Nothing was read or written.`}if(o)return`${Pi(td(o))}. ${r} ${Pi(rd(o))}. Nothing was read or written.`}lockToRemove(e,t){let r=this.runJournal;if(!r)return;let n;try{n=this.journalLocks.take(r.pathOf(e),{journalId:e,...t!==void 0?{target:we(this.deps.orgManager.getOrg(t),t)}:{},removes:!0})}catch(o){ie.warn(`Forge removal: the lock of the run's journal could not be taken (${I(o)})`);return}return"busy"in n?{busy:`${Pi(td(n.busy))}. Removing its records now would delete under it what it goes on writing; remove them once it has ended. ${Pi(rd(n.busy))}. Nothing was read or written.`}:n}async handleUndoSweep(e){let t=st(AM,e,"forge:undo-sweep:error",this.deps);if(!t)return;let r=(a,d)=>T(this.deps,"forge:undo-sweep","forge:undo-sweep:error",e,new Error(a),{code:d}),n=this.loadHistory().find(a=>a.forgeId===t.forgeId);if(!n){r(xT,ys);return}let o=n.journalId?this.journalBusy(n.journalId,"remove"):void 0;if(o){r(o,Ei);return}let i=n.targetOrgId;if(!n.idRemapCreated||!i){r("This run was recorded before Forge kept what a run created: nothing of it can be swept. "+Qc,"NOT_RECORDED");return}try{let a=await new pe(i0).withTimeout("forge:undo-sweep",async()=>{let d=await B(i,this.deps.orgRegistry,this.deps.orgManager),c=await this.sweepInputOf(n,d);return"gone"in c?c:zo(tn(d,"forge:undo-sweep"),c,n.removalSpans??[])});if("gone"in a){r(a.gone,ms);return}this.deps.broker.postToWebview(A(this.deps,e,"forge:undo-sweep:response",{forgeId:t.forgeId,listing:a}))}catch(a){let d=a instanceof zt;T(this.deps,"forge:undo-sweep","forge:undo-sweep:error",e,a,{code:d?"TIMEOUT":"SWEEP_ERROR",retryable:!0})}}async handlePlanRequest(e){if(!this.planGenerator){T(this.deps,"forge:plan","forge:plan:error",e,new Error("Plan generator not configured"),{code:"NOT_INITIALIZED"});return}let t=st(xM,e,"forge:plan:error",this.deps);if(!t)return;let{graph:r,config:n}=t,o=`forge-plan-${this.deps.nextId()}`;Ge(this.deps,o,"forge","Generating execution plan");try{ie.info("Forge plan generation started");let i=await this.readPersonalFields(r,n),a=await new pe(CT).withTimeout("forge:plan",()=>Promise.resolve(this.planGenerator.generate(i))),d=A(this.deps,e,"forge:plan:response",i===r?{plan:a}:{plan:a,graph:i});this.deps.broker.postToWebview(d),me(this.deps,o,{waveCount:a.waves?.length??0})}catch(i){let a=i instanceof zt;T(this.deps,"forge:plan","forge:plan:error",e,i,{code:a?"TIMEOUT":"PLAN_ERROR",retryable:a}),me(this.deps,o,{status:"failure"})}}async readPersonalFields(e,t){let r=this.orchestrator;if(!r)return e;try{return await new pe(CT).withTimeout("forge:plan:personal-fields",n=>r.readPersonalFields(e,t,n))}catch(n){return ie.warn(`Forge personal fields not read: ${I(n)}`),e}}async handleClassificationRequest(e){let t=st(DM,e,"forge:classification:error",this.deps);if(!t)return;let r=this.orchestrator;try{let n=r?await new pe(n0).withTimeout("forge:classification",o=>r.readClassification(t.sourceOrgId,t.objects,o)):void 0;if(!n)throw new Error("This session cannot read how the org classifies its fields.");this.deps.broker.postToWebview(A(this.deps,e,"forge:classification:response",{...n})),ie.info("Forge classification read",{objects:t.objects.length,classified:n.objects.length,refused:n.refused.length,requests:n.requests})}catch(n){let o=n instanceof zt;T(this.deps,"forge:classification","forge:classification:error",e,n,{code:o?"TIMEOUT":"CLASSIFICATION_ERROR",retryable:!0})}}async handleComplianceRequest(e){if(!this.complianceService){T(this.deps,"forge:compliance","forge:compliance:error",e,new Error("Compliance service not configured"),{code:"NOT_INITIALIZED"});return}let t=st(NM,e,"forge:compliance:error",this.deps);if(!t)return;let{framework:r,graph:n,config:o,anonymizationRules:i}=t,a=`forge-compliance-${this.deps.nextId()}`;Ge(this.deps,a,"forge","Generating compliance report");try{ie.info("Forge compliance report generation started");let d=await new pe(o0).withTimeout("forge:compliance",()=>Promise.resolve(this.complianceService.generate(r,n,o,i))),c=A(this.deps,e,"forge:compliance:response",{report:d});this.deps.broker.postToWebview(c),me(this.deps,a,{framework:r})}catch(d){let c=d instanceof zt;T(this.deps,"forge:compliance","forge:compliance:error",e,d,{code:c?"TIMEOUT":"COMPLIANCE_ERROR",retryable:c}),me(this.deps,a,{status:"failure"})}}async handleMetadataDiffRequest(e){if(!this.metadataDiff){T(this.deps,"forge:metadata-diff","forge:metadata-diff:error",e,new Error("Metadata diff service not configured"),{code:"NOT_INITIALIZED"});return}let t=st(jM,e,"forge:metadata-diff:error",this.deps);if(!t)return;let{sourceOrgId:r,targetOrgId:n,objectApiNames:o}=t,i=`forge-metadata-diff-${this.deps.nextId()}`;Ge(this.deps,i,"forge","Comparing metadata schemas");try{ie.info("Forge metadata diff started");let a=await new pe(s0).withTimeout("forge:metadata-diff",()=>this.metadataDiff.compare(r,n,o)),d=A(this.deps,e,"forge:metadata-diff:response",{diffs:a});this.deps.broker.postToWebview(d),ie.info("Forge metadata diff finished",{objects:o.length,differences:a.length,objectsMissing:a.filter(c=>c.issue==="object_missing").length}),me(this.deps,i,{objectCount:o.length})}catch(a){let d=a instanceof zt;T(this.deps,"forge:metadata-diff","forge:metadata-diff:error",e,a,{code:d?"TIMEOUT":"METADATA_DIFF_ERROR",retryable:d}),me(this.deps,i,{status:"failure"})}}async handleRehearseRequest(e){let t=this.rehearser,r=(R,w,P=!1)=>T(this.deps,"forge:rehearse","forge:rehearse:error",e,R,{code:w,retryable:P});if(!t){r(new Error("Forge rehearsal is not initialized"),"NOT_INITIALIZED");return}let n=st(MM,e,"forge:rehearse:error",this.deps);if(!n)return;let{graph:o,config:i,anonymizationRules:a}=n;if(i.inputMode==="org"){r(new Error(fM),pM);return}let d=(R,w,P={})=>Y(this.deps,{action:"forge_rehearse",module:"forge",operationId:R,orgId:i.targetOrgId,outcome:w,...P}),c=(R,w,P=!1)=>{d(e.id,"stopped",{code:w}),r(R,w,P)},u=this.deps.infraServices?.productionGuard;if(!u){c(new Error(ve.message),ve.code);return}let l=this.deps.orgManager.getOrg(i.targetOrgId),p=Pe(l),f=we(l,i.targetOrgId);if(p==="production"){c(new Error(`${f} is a production org, or an org SandForge cannot tell is a sandbox, a scratch org or a Developer Edition org: a rehearsal creates records in those only. Nothing was read or sent.`),"PRODUCTION_TARGET");return}if(this.rehearseOperationId!==null){c(new Error("A rehearsal is already under way in this window: rehearse once it has ended."),"REHEARSAL_RUNNING",!0);return}if(this.executeOperationId!==null){c(new Error("A Forge run is under way in this window: rehearse once it has ended."),Zf,!0);return}let g=`forge-rehearse-${this.deps.nextId()}`,h="Rehearsing a forge run";this.rehearseOperationId=g,Ge(this.deps,g,"forge",h);let m=new AbortController,y=this.trackRun(g,h,m);this.liveTracker?.register(g,"forge",h);let v,b=!1,k=R=>this.deps.broker.postToWebview(A(this.deps,e,"forge:rehearse:progress",{...R})),S=R=>{if(R.phase!=="rehearsing"||!R.call||!R.calls)return;let w=Math.min(100,Math.round((R.call-1)/R.calls*100));m.signal.aborted||this.deps.infraServices?.backgroundRegistry?.updateProgress(g,w),this.liveTracker?.updateProgress(g,w,R.call-1,R.calls,`call ${R.call} of ${R.calls}`)},C=Yc(k,100);try{let R=await this.automationBeforeTheRun(i.targetOrgId,o),w="automation"in R?R.automation:void 0,P=await this.loadRecordTypeMappings(i,new AbortController().signal,{requests:0}),O=await t.rehearse(o,i,{recordTypeMappings:P,anonymizationRules:a,signal:m.signal,onProgress:E=>{if(E.phase==="reading"){C(E);return}C.flush(),k(E),S(E)},confirm:async E=>{let $=await u.confirmRun({stage:"rehearsal",org:f,orgTier:p,rows:E.rows,sampled:E.sampled,updates:E.updates.reduce((H,J)=>H+J.updates,0),calls:E.calls,maxCalls:E.maxCalls,fired:w?ql(w):[],firedOnUpdate:w?Wl(w,E.updates.map(H=>H.objectApiName)):[],unread:w?Gl(w):[{part:"automation",reason:"unread"in R?R.unread:""}]});if($==="confirmed"){b=!0;return}throw new Zc($==="declined"?"REHEARSAL_DECLINED":"CONFIRMATION_UNAVAILABLE",$==="declined"?"The rehearsal was cancelled at its confirmation. Nothing was sent to the target.":"The rehearsal needed a confirmation, and there was no one to ask. Nothing was sent to the target.")}});this.deps.broker.postToWebview(A(this.deps,e,"forge:rehearse:response",{rehearsal:O})),this.trials.note("rehearsal",rp(o,i)),ie.info("Forge rehearsal",{rows:O.rows,sampled:O.sampled,judged:O.judged,passed:O.passed,notJudged:O.notJudged,calls:O.calls,plannedCalls:O.plannedCalls,codes:[...new Set(O.gaps.flatMap(E=>typeof E.detail?.statusCode=="string"?[E.detail.statusCode]:[]))]}),d(g,"success",{guard:b?"confirmed":"allowed",details:T0(O)}),me(this.deps,g,{status:"success"}),this.liveTracker?.complete(g)}catch(R){let w=R instanceof Zc?R:void 0,P=R instanceof Vv?R:void 0,O=R instanceof Jv?R:void 0,E=I(R);if(r(R instanceof Error?R:new Error(E),w?.code??(P?"REHEARSAL_CANCELLED":"REHEARSAL_ERROR"),!0),w||P){let $=w?.code==="REHEARSAL_DECLINED"?"declined":b?"confirmed":void 0;d(g,"stopped",{code:w?.code??"REHEARSAL_CANCELLED",...$?{guard:$}:{},...P?{details:{calls:P.calls}}:{}}),me(this.deps,g,{aborted:!0}),this.liveTracker?.cancel(g)}else v=R,d(g,"failure",{...b?{guard:"confirmed"}:{},...O?{code:"REHEARSAL_NOT_ROLLED_BACK",details:{recordsLeft:O.ids.length},objects:O.objects.map(({objectApiName:$,created:H})=>({objectApiName:$,created:H,updated:0,deleted:0,failed:0}))}:{}}),Le(this.deps,g,E,!0),this.liveTracker?.fail(g,E)}finally{C.flush(),y(v),this.rehearseOperationId===g&&(this.rehearseOperationId=null)}}async handleAutomationRequest(e){if(!this.targetAutomation){T(this.deps,"forge:automation","forge:automation:error",e,new Error("Target automation reader not configured"),{code:"NOT_INITIALIZED"});return}let t=st(LM,e,"forge:automation:error",this.deps);if(!t)return;let{targetOrgId:r,graph:n}=t,o=`forge-automation-${this.deps.nextId()}`;Ge(this.deps,o,"forge","Reading the target org's automation");try{let i=new pe(Ci).withTimeout("forge:automation",()=>this.targetAutomation.readForGraph(r,n));this.keepAutomationRead(r,n,i);let a=await this.withDeliverability(r,n,await i);this.deps.broker.postToWebview(A(this.deps,e,"forge:automation:response",{automation:a})),ie.info("Forge target automation read",{objects:a.objectsRead.length,objectsWithAutomation:a.objects.length,flows:a.objects.reduce((d,c)=>d+c.flows.length,0),triggers:a.objects.reduce((d,c)=>d+c.triggers.length,0),conditionsNotRead:a.conditionsNotRead,unread:a.unread.map(d=>d.part),requests:a.requests}),me(this.deps,o,{objectCount:a.objectsRead.length})}catch(i){let a=i instanceof zt;T(this.deps,"forge:automation","forge:automation:error",e,i,{code:a?"TIMEOUT":"AUTOMATION_ERROR",retryable:a}),me(this.deps,o,{status:"failure"})}}async readDeliverability(e,t){let r=()=>{},n=new Promise((o,i)=>{r=()=>i(new Error(Un)),t?.addEventListener("abort",r,{once:!0})});try{return await Promise.race([new pe(Wb).withTimeout("forge:deliverability",async()=>Jt(await B(e,this.deps.orgRegistry,this.deps.orgManager))),n])}finally{t?.removeEventListener("abort",r)}}async withDeliverability(e,t,r){let n=this.deps.orgManager.getOrg(e),o=zl(t,{leftOut:new Set(t.nodes.filter(qi).map(d=>d.objectApiName))}),i=new Set(o.map(d=>d.objectApiName)),{ofRun:a}=await ir({read:r,writes:(d,c)=>c==="insert"||c==="update"&&i.has(d),readDeliverability:()=>Pe(n)==="production"?Promise.resolve(Gt):this.readDeliverability(e),accepted:!1,target:we(n,e),run:"clone"});return a.read?{...r,deliverability:a.read.reading,requests:r.requests+a.read.requests}:r}async handleUndoAutomation(e){let t=st(IM,e,"forge:undo-automation:error",this.deps);if(!t)return;let r=(c,u)=>T(this.deps,"forge:undo-automation","forge:undo-automation:error",e,c,{code:u}),n=this.targetAutomation;if(!n){r(new Error("Target automation reader not configured"),"NOT_INITIALIZED");return}let o=this.loadHistory().find(c=>c.forgeId===t.forgeId);if(!o?.targetOrgId){r(new Error("This run is no longer in the Forge history."),ys);return}let i=o.journalId?this.journalBusy(o.journalId,"remove"):void 0;if(i){r(new Error(i),Ei);return}let a=(t.again===!0?nh(o):yn(o)).map(c=>c.objectApiName),d=o.targetOrgId;try{let c=await this.otherPartObjectsOf(t.forgeId,d),u=[...new Set([...$a(a,c,{userKept:o.runUserId!==void 0}),...a.length===0&&jT(o)?[On]:[],...t.sweptObjects??[]])],l=await new pe(Ci).withTimeout("forge:undo-automation",()=>n.read(d,u));this.deps.broker.postToWebview(A(this.deps,e,"forge:undo-automation:response",{forgeId:t.forgeId,automation:l,drafted:or(a)}))}catch(c){let u=c instanceof zt;T(this.deps,"forge:undo-automation","forge:undo-automation:error",e,c,{code:u?"TIMEOUT":"AUTOMATION_ERROR",retryable:u})}}async handleGapsRequest(e){if(!this.targetGaps){T(this.deps,"forge:gaps","forge:gaps:error",e,new Error("Target gap reader not configured"),{code:"NOT_INITIALIZED"});return}let t=st(FM,e,"forge:gaps:error",this.deps);if(!t)return;let{graph:r,config:n}=t,o=this.targetGaps,i=`forge-gaps-${this.deps.nextId()}`;Ge(this.deps,i,"forge","Reading what the target org holds against the rows");try{let a=await new pe(a0).withTimeout("forge:gaps",()=>o.read(n.sourceOrgId,n.targetOrgId,r,n));this.deps.broker.postToWebview(A(this.deps,e,"forge:gaps:response",{gaps:a})),ie.info("Forge target gaps read",{gaps:a.gaps.length,blocking:a.gaps.filter(d=>d.severity==="blocking").length,kinds:[...new Set(a.gaps.map(d=>d.kind))],unread:a.unread.map(d=>d.part),requests:a.requests}),me(this.deps,i,{objectCount:r.nodes.length})}catch(a){let d=a instanceof zt;T(this.deps,"forge:gaps","forge:gaps:error",e,a,{code:d?"TIMEOUT":"GAPS_ERROR",retryable:d}),me(this.deps,i,{status:"failure"})}}async handleUsersRequest(e){let t=st(_M,e,"forge:users:error",this.deps);if(t)try{let r=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager),n=await r.query(wT);$e(r.limitInfo,"forge:users query");let{users:o,truncated:i}=bT(n.records,n.done===!1);this.deps.broker.postToWebview(A(this.deps,e,"forge:users:response",{orgId:t.orgId,users:o,truncated:i}))}catch(r){T(this.deps,"forge:users","forge:users:error",e,r,{code:"USERS_ERROR"})}}async handleTargetRecordsRequest(e){let t=st(UM,e,"forge:target-records:error",this.deps);if(t)try{let r=await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await new pe(ws).withTimeout("forge:target-records",()=>r.request(`/services/data/v${r.version}/limits/recordCount`)),o=gR(n);if(!o)throw new Error("The target org answered its record counts in no form known.");let i=[...new Set(t.objectApiNames)].map(a=>({objectApiName:a,records:o.get(a)??0})).filter(({records:a})=>a>0).sort((a,d)=>d.records-a.records||a.objectApiName.localeCompare(d.objectApiName));this.deps.broker.postToWebview(A(this.deps,e,"forge:target-records:response",{targetOrgId:t.targetOrgId,objects:i}))}catch(r){T(this.deps,"forge:target-records","forge:target-records:error",e,r,{code:"TARGET_RECORDS_ERROR"})}}async handleSampleBudgetRequest(e){let t=st(HM,e,"forge:sample-budget:error",this.deps);if(!t)return;let{graph:r,config:n}=t;try{let[o,i]=await Promise.all([this.readTargetDataStorage(n.targetOrgId),this.readSourceApiBudget(n,{requests:0})]),a=Sv({graph:r,options:n.sample,...n.excludedObjects?{excludedObjects:n.excludedObjects}:{},storage:o,source:i,maxRecordsPerObject:this.maxRecordsPerObject()});this.deps.broker.postToWebview(A(this.deps,e,"forge:sample-budget:response",{targetOrgId:n.targetOrgId,budget:a}))}catch(o){T(this.deps,"forge:sample-budget","forge:sample-budget:error",e,o,{code:"SAMPLE_BUDGET_ERROR"})}}async handlePreviewRoots(e){let t=st(BM,e,"forge:previewRoots:error",this.deps);if(!t)return;let{sourceOrgId:r,soqlQuery:n}=t,o=t.maxRoots??this.maxRoots(),i=iR(n);if("issue"in i){let c=uR(i.issue,void 0);this.deps.broker.postToWebview(A(this.deps,e,"forge:previewRoots:error",{code:c.code,message:c.message,retryable:!1,soqlQuery:n}));return}let{objectApiName:a,query:d}=i;try{let c=await B(r,this.deps.orgRegistry,this.deps.orgManager),u=d.limit!==void 0&&d.limit<=o?d.limit:o+1,{records:l,pages:p}=await new pe(r0).withTimeout("forge:previewRoots",()=>nr({query:async f=>c.query(f),queryMore:async f=>c.queryMore(f)},aR(a,d,void 0,o),u));$e(c.limitInfo,`forge:previewRoots ${a}`),this.deps.broker.postToWebview(A(this.deps,e,"forge:previewRoots:response",{sourceOrgId:r,soqlQuery:n,objectApiName:a,cap:o,chosen:Math.min(l.length,o),more:l.length>o,...d.limit!==void 0?{limit:d.limit}:{},...d.orderBy!==void 0?{orderBy:d.orderBy}:{},requests:p}))}catch(c){T(this.deps,"forge:previewRoots","forge:previewRoots:error",e,c,{code:"ROOTS_PREVIEW_ERROR",retryable:!0,extraPayload:{soqlQuery:n}})}}maxRoots(){let e=this.deps.services?.getSandforgeSetting?.("forge.maxRoots",Gu);return sR(typeof e=="number"?e:void 0,Gu)}withMaxRoots(e){return e.inputMode!=="soql"||e.queryScope!=="records"||e.maxRoots!==void 0?e:{...e,maxRoots:this.maxRoots()}}async rootsOfTheRun(e){let{config:t}=e;if(!Ju(t)||t.inputMode!=="soql")return;let r=await this.readSourceApiBudget(t,e.lookup),n="unread"in r?void 0:r.remaining,o=n!==void 0?{sourceRequestsLeft:n}:{};if(e.retried&&!e.resumes){let{objectApiName:p,ids:f,sha256:g,readAt:h,query:m}=e.retried;return{...o,plan:{version:1,sourceOrgId:t.sourceOrgId,fingerprint:"",objectApiName:p,...m?{query:m}:{},from:"query",readAt:h,ids:f,sha256:g},planOfTheRunRetried:!0}}let i=this.runJournal?.storagePath;if(i===void 0||e.resumes)return o;let a=new Date;await this.sweepRootPlansOf(i,a);let d=this.setupFingerprintOf(e.graph,t,e.anonymizationRules,e.readCeiling),c;try{c=Iv(i,d)}catch(p){if(p instanceof ep)return o;throw p}if(e.dryRun)return{...o,keepAt:c,fingerprint:d};let u;try{u=await Av(c)}catch(p){if(!(p instanceof ep))throw p;p.fault==="changed"&&ie.warn(`Forge roots: the simulation's roots no longer read whole (${p.message})`)}let l=u?void 0:this.rootPlansSwept.get(d);return{...o,fingerprint:d,...u?{plan:u}:l?{planPastItsDay:l}:{}}}};import{randomUUID as E0}from"node:crypto";import*as zT from"node:os";import*as jr from"node:path";var qT=50*1024*1024,P0=new Set(["migration:pick-file","migration:import-sfdmu","migration:save-sync-config"]),C0="Saved from the SandForge SFDMU Import page",$0=new Set([".json"]);function x0(s,e,t){if(typeof s!="string"||s.trim().length===0)throw new Error("Invalid import path: path is empty.");if(!jr.isAbsolute(s))throw new Error(`Invalid import path: "${s}" is not absolute. Pick a file inside the workspace or your home directory.`);let r=jr.resolve(s),n=jr.extname(r).toLowerCase();if(!e.has(n))throw new Error(`Invalid import path: "${n||"(none)"}" is not a supported extension (expected ${[...e].join(", ")}).`);if(!t.some(i=>{let a=jr.resolve(i);if(process.platform==="win32"){let d=r.toLowerCase(),c=a.toLowerCase();return d===c||d.startsWith(c+jr.sep)}return r===a||r.startsWith(a+jr.sep)}))throw new Error("Invalid import path: the file must be inside an open workspace folder or your home directory.");return r}async function WT(s,e){let t=await s.statSize(e);if(t>qT){let r=(t/1048576).toFixed(1),n=qT/(1024*1024);throw new Error(`Import file is too large: ${r} MB exceeds the ${n} MB limit. Split the file into smaller chunks and retry.`)}}var tu=class{constructor(e){this.deps=e}deps;fileReader;setFileReader(e){this.fileReader=e}async handle(e){if(!P0.has(e.type))return!1;switch(e.type){case"migration:pick-file":return await this.handlePickFile(e),!0;case"migration:import-sfdmu":return await this.handleImportSfdmu(e),!0;case"migration:save-sync-config":return this.handleSaveSyncConfig(e),!0;default:return!1}}handleSaveSyncConfig(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(yw,e,"migration:error",this.deps);if(!t)return;let r=n=>{this.deps.broker.postToWebview(A(this.deps,e,"migration:save-sync-config:response",n))};try{let n=t.name.trim();if(n===""){r({success:!1,code:"NAME_REQUIRED"});return}let o=new Pt(this.deps.configStore);if(Rh(o.list(),n)){r({success:!1,code:"DUPLICATE_NAME"});return}let a=(Array.isArray(t.config.objects)?t.config.objects:[]).map(l=>typeof l=="object"&&l!==null?l.objectApiName:void 0).filter(l=>typeof l=="string").filter(l=>Ra(l));if(a.length>0){r({success:!1,code:"SYNC_CANNOT_COPY",objects:a});return}let d=new Date().toISOString(),c=Lm.safeParse({...t.config,id:E0(),name:n,description:C0,createdAt:d,updatedAt:d});if(!c.success){let[l]=c.error.issues;r({success:!1,code:"INVALID_CONFIG",reason:l?`${l.path.join(".")}: ${l.message}`:c.error.message});return}let u=c.data;o.save(u),this.deps.log(`[TX] migration:save-sync-config:response saved ${u.id}`),r({success:!0,id:u.id,name:u.name})}catch(n){T(this.deps,"migration:save-sync-config","migration:error",e,n)}}getAllowedBaseDirs(){return[...this.deps.services?.getWorkspaceFolders?.()??[],zT.homedir()]}async handlePickFile(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.fileReader;if(!t?.pickExportFile)throw new Error("Migration services not available.");let r=await t.pickExportFile();this.deps.broker.postToWebview(A(this.deps,e,"migration:pick-file:response",r===void 0?{}:{filePath:r}))}catch(t){T(this.deps,"migration:pick-file","migration:error",e,t)}}async handleImportSfdmu(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(mw,e,"migration:error",this.deps);if(!t)return;let{filePath:r}=t;try{let n=this.fileReader;if(!n)throw new Error("Migration services not available.");let o=x0(r,$0,this.getAllowedBaseDirs());await WT(n,o);let{SfdmuImporter:i,SfdmuRefusal:a}=await import("./chunk-LNXBCE7E.mjs"),d=new i({readFile:async c=>(c!==o&&await WT(n,c),n.readFile(c))});try{let{config:c,notes:u}=await d.import(o),l=A(this.deps,e,"migration:import-sfdmu:response",{success:!0,config:c,notes:u});this.deps.broker.postToWebview(l)}catch(c){if(!(c instanceof a))throw c;this.deps.log(`[ERR] migration:import-sfdmu: ${c.message}`),this.deps.broker.postToWebview(A(this.deps,e,"migration:import-sfdmu:response",{success:!1,error:c.message,code:c.code,objects:[...c.objects]}))}}catch(n){this.deps.log(`[ERR] migration:import-sfdmu: ${I(n)}`);let o=A(this.deps,e,"migration:import-sfdmu:response",{success:!1,error:I(n)});this.deps.broker.postToWebview(o)}}};import*as bs from"node:fs/promises";var XT="settings",GT=K({version:L(),exportedAt:L(),exportedBy:L().optional(),categories:Re(Be(["syncMappings","forgePlans","pipelines","anonymizationTemplates",XT])),data:Bi(L(),hn())});function JT(s){return s!==XT}var tg={syncMappings:"sync:config:",forgePlans:"forge:templates",pipelines:"pipeline:saved:",anonymizationTemplates:"anonymization:"},VT={syncMappings:"syncConfigs",forgePlans:"forge",pipelines:"pipelines",anonymizationTemplates:"anonymizationTemplates"},$i="forge:templates";function D0(s){return typeof s.name=="string"&&s.name.length>0?s.name:s.id}var ru=class{constructor(e,t){this.configStore=e;this.workspace=t}configStore;workspace;async exportProfile(e,t){try{let r={},n=0;for(let i of e){if(i==="forgePlans"){let u=await this.heldTemplates();r[i]=u.length>0?{[$i]:u}:{},n+=u.length;continue}let a=tg[i],d=this.configStore.getKeysByPrefix(a),c={};for(let u of d){let l=this.configStore.get(u);l!==void 0&&(c[u]=l,n++)}r[i]=c}let o={version:"1.0.0",exportedAt:new Date().toISOString(),exportedBy:t,categories:e,data:r};return{success:!0,json:JSON.stringify(o,null,2),categoriesExported:e.length,entriesExported:n}}catch(r){return{success:!1,categoriesExported:0,entriesExported:0,error:r instanceof Error?r.message:String(r)}}}async importProfile(e,t=!0){let r=[];try{let n=JSON.parse(e),o=GT.safeParse(n);if(!o.success)return{success:!1,categoriesImported:0,entriesImported:0,warnings:[],error:`Invalid profile format: ${o.error.issues.map(c=>c.message).join(", ")}`};let i=o.data,a=i.categories.filter(JT),d=0;for(let c of a){let u=i.data[c];if(!u||typeof u!="object"){r.push(`Category "${c}" has no data, skipped.`);continue}if(c==="forgePlans"){d+=await this.importTemplates(u,t,r);continue}let l=tg[c];for(let[p,f]of Object.entries(u)){if(!p.startsWith(l)){r.push(`Key "${p}" does not match expected prefix "${l}" for category "${c}", skipped.`);continue}if(!t&&this.configStore.has(p)){r.push(`Key "${p}" already exists, skipped.`);continue}if(this.configStore.set(p,f,VT[c]),d++,c==="pipelines"){let g=nk(this.configStore,p.slice(l.length));g.length>0&&r.push(`Pipeline "${p}" was written over: confirm its Rewind ${g.length===1?"step":"steps"} again.`)}}}return{success:!0,categoriesImported:a.length,entriesImported:d,warnings:r}}catch(n){return{success:!1,categoriesImported:0,entriesImported:0,warnings:r,error:n instanceof Error?n.message:String(n)}}}validateProfile(e){try{let t=JSON.parse(e),r=GT.safeParse(t);return r.success?{valid:!0,categories:r.data.categories.filter(JT)}:{valid:!1,error:r.error.issues.map(n=>n.message).join(", ")}}catch(t){return{valid:!1,error:t instanceof Error?t.message:String(t)}}}async listCategories(){let e=[];for(let[t,r]of Object.entries(tg)){let n=t==="forgePlans"?(await this.heldTemplates()).length:this.configStore.getKeysByPrefix(r).length;e.push({category:t,entryCount:n})}return e}async heldTemplates(){if(!this.workspace){let r=this.configStore.get($i);return Array.isArray(r)?r.filter(ln):[]}let e=await this.workspace.readTemplates(),t=Kc(this.configStore,this.workspace.folder);return t?Ti(e,t.templates,new Set(t.replacing)):[...e]}async importTemplates(e,t,r){let n=await this.heldTemplates(),o=new Set(n.map(c=>c.id)),i=new Set,a=[],d=[];for(let[c,u]of Object.entries(e)){if(c!==$i){r.push(`Key "${c}" does not match expected prefix "${$i}" for category "forgePlans", skipped.`);continue}if(!Array.isArray(u)){r.push(`Key "${c}" holds no list of templates, skipped.`);continue}for(let l of u){if(!ln(l)){r.push(`An entry of "${c}" has no id, skipped.`);continue}if(!i.has(l.id)){if(i.add(l.id),o.has(l.id)){if(!t){r.push(`Forge template "${D0(l)}" already exists, skipped.`);continue}d.push(l.id)}a.push(l)}}}return this.workspace?hT(this.configStore,this.workspace.folder,a,d):a.length>0&&this.configStore.set($i,Ti(n,a,new Set(d)),VT.forgePlans),a.length}};import*as rg from"node:path";var nu=class{deps;filePath;constructor(e){this.deps=e,this.filePath=rg.join(e.workspacePath,".sandforge","forge-templates.json")}async list(){let e;try{e=JSON.parse(await this.deps.readFile(this.filePath))}catch{return[]}return Array.isArray(e)?e.filter(ln):[]}async save(e){let t=await this.list(),r=t.findIndex(n=>n.id===e.id);r>=0?t[r]=e:t.push(e),await this.write(t)}get workspacePath(){return this.deps.workspacePath}async merge(e,t=new Set){let r=await this.list(),n=Ti(r,e.filter(ln),t);return JSON.stringify(n)===JSON.stringify(r)?r:(await this.write(n),n)}async delete(e){let r=(await this.list()).filter(n=>n.id!==e);await this.write(r)}async write(e){let t=rg.join(this.deps.workspacePath,".sandforge");await this.deps.mkdir(t).catch(()=>{}),await this.deps.writeFile(this.filePath,JSON.stringify(e,null,2))}};var N0=new Set(["config:export","config:import","config:categories","config:validate"]);function j0(s){let e=s.services?.getWorkspaceFolders?.()[0];if(!e)return;let t=new nu({workspacePath:e,readFile:r=>bs.readFile(r,"utf-8"),writeFile:(r,n)=>bs.writeFile(r,n,"utf-8"),mkdir:r=>bs.mkdir(r,{recursive:!0}).then(()=>{})});return{folder:e,readTemplates:()=>t.list()}}var ou=class{constructor(e){this.deps=e;this.profileManager=new ru(e.configStore,j0(e))}deps;profileManager;async handle(e){if(!N0.has(e.type))return!1;switch(e.type){case"config:export":return await this.handleExport(e),!0;case"config:import":return await this.handleImport(e),!0;case"config:categories":return await this.handleCategories(e),!0;case"config:validate":return this.handleValidate(e),!0;default:return!1}}async handleExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Ow,e,"config:error",this.deps);if(!t)return;let r=t;try{let n=await this.profileManager.exportProfile(r.categories),o=A(this.deps,e,"config:export:response",{success:n.success,json:n.json,categoriesExported:n.categoriesExported,entriesExported:n.entriesExported,error:n.error});this.deps.broker.postToWebview(o),this.deps.log(`[TX] config:export:response (${n.entriesExported} entries)`)}catch(n){T(this.deps,"config:export","config:error",e,n)}}async handleImport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Iw,e,"config:error",this.deps);if(!t)return;let r=t;try{let n=await this.profileManager.importProfile(r.json,r.overwrite),o=A(this.deps,e,"config:import:response",{success:n.success,categoriesImported:n.categoriesImported,entriesImported:n.entriesImported,warnings:n.warnings,error:n.error});this.deps.broker.postToWebview(o),this.deps.log(`[TX] config:import:response (${n.entriesImported} entries)`)}catch(n){T(this.deps,"config:import","config:error",e,n)}}async handleCategories(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=await this.profileManager.listCategories(),r=A(this.deps,e,"config:categories:response",{categories:t});this.deps.broker.postToWebview(r),this.deps.log("[TX] config:categories:response")}catch(t){T(this.deps,"config:categories","config:error",e,t)}}handleValidate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Aw,e,"config:error",this.deps);if(!t)return;let r=t;try{let n=this.profileManager.validateProfile(r.json),o=A(this.deps,e,"config:validate:response",{valid:n.valid,categories:n.categories,error:n.error});this.deps.broker.postToWebview(o),this.deps.log("[TX] config:validate:response")}catch(n){T(this.deps,"config:validate","config:error",e,n)}}};var M0=K({metric:L(),operator:Be(["gt","gte","lt","lte","eq","neq"]),threshold:Te(),warningThreshold:Te().optional()}),L0=K({id:L(),name:L(),description:L(),category:Be(["security","performance","compliance","custom"]),condition:M0,remediation:L(),enabled:Ve()}),xi=K({id:L(),name:L(),description:L(),rules:Re(L0),createdAt:L(),updatedAt:L()});function KT(s,e,t){switch(e){case"gt":return s>t;case"gte":return s>=t;case"lt":return s<t;case"lte":return s<=t;case"eq":return s===t;case"neq":return s!==t}}var su=class s{evaluateRule(e,t){let{metric:r,operator:n,threshold:o,warningThreshold:i}=e.condition;if(!Object.prototype.hasOwnProperty.call(t,r))return{ruleId:e.id,ruleName:e.name,category:e.category,status:"unknown",actualValue:null,threshold:o,message:`${e.name}: not measured \u2014 SandForge reads no ${r} value for this org`,remediation:""};let a=t[r],d="pass";KT(a,n,o)?d="fail":i!==void 0&&KT(a,n,i)&&(d="warning");let c=d==="pass"?`${e.name}: compliant (${a})`:`${e.name}: ${d} \u2014 actual ${a} ${n} ${d==="fail"?o:i??o}`;return{ruleId:e.id,ruleName:e.name,category:e.category,status:d,actualValue:a,threshold:o,message:c,remediation:d==="pass"?"":e.remediation}}evaluatePolicy(e,t){let n=e.rules.filter(a=>a.enabled).map(a=>this.evaluateRule(a,t)),o=s.computeComplianceScore(n),i=n.filter(a=>(a.status==="fail"||a.status==="warning")&&a.remediation).map(a=>a.remediation);return{policyId:e.id,policyName:e.name,evaluatedAt:new Date().toISOString(),complianceScore:o,ruleResults:n,remediations:i}}static computeComplianceScore(e){let t=e.filter(o=>o.status!=="unknown");if(t.length===0)return null;let r={pass:100,warning:50,fail:0},n=t.reduce((o,i)=>o+r[i.status],0);return Math.round(n/t.length)}};var iu="governance:policy:",F0="governance",Di=class{constructor(e){this.configStore=e}configStore;getAll(){let e=this.configStore.getKeysByPrefix(iu),t=[];for(let r of e){let n=this.configStore.get(r);if(n){let o=xi.safeParse(n);o.success&&t.push(o.data)}}return t}getById(e){let t=this.configStore.get(`${iu}${e}`);if(!t)return;let r=xi.safeParse(t);return r.success?r.data:void 0}save(e){this.configStore.set(`${iu}${e.id}`,e,F0)}delete(e){return this.configStore.delete(`${iu}${e}`)}static getDefaultTemplates(){let e=new Date().toISOString();return[{id:"template-security",name:"Security Policy",description:"Default security governance rules",rules:[{id:"sec-mfa",name:"MFA Enabled",description:"Multi-factor authentication should be enabled for all users",category:"security",condition:{metric:"mfaEnabledPercent",operator:"lt",threshold:100,warningThreshold:90},remediation:"Enable MFA for all user profiles in Setup > Identity Verification",enabled:!0},{id:"sec-password",name:"Password Policy Strength",description:"Password policy should enforce minimum complexity",category:"security",condition:{metric:"passwordPolicyScore",operator:"lt",threshold:60,warningThreshold:80},remediation:"Strengthen password policy in Setup > Password Policies",enabled:!0}],createdAt:e,updatedAt:e},{id:"template-performance",name:"Performance Policy",description:"Default performance governance rules",rules:[{id:"perf-api",name:"API Usage Limit",description:"API usage should stay below critical thresholds",category:"performance",condition:{metric:"apiUsagePercent",operator:"gt",threshold:90,warningThreshold:75},remediation:"Optimize API-heavy integrations or request a limit increase",enabled:!0},{id:"perf-storage",name:"Storage Usage",description:"Data storage should not exceed safe limits",category:"performance",condition:{metric:"storageUsagePercent",operator:"gt",threshold:90,warningThreshold:75},remediation:"Archive old records or increase storage allocation",enabled:!0}],createdAt:e,updatedAt:e},{id:"template-compliance",name:"Compliance Policy",description:"Default compliance governance rules",rules:[{id:"comp-coverage",name:"Code Coverage",description:"Apex code coverage must meet minimum threshold",category:"compliance",condition:{metric:"codeCoveragePercent",operator:"lt",threshold:75,warningThreshold:85},remediation:"Write additional unit tests to increase code coverage",enabled:!0}],createdAt:e,updatedAt:e}]}};var _0={apiUsagePercent:"DailyApiRequests",storageUsagePercent:"DataStorageMB"},U0=new Set(["governance:policies:list","governance:policy:save","governance:policy:delete","governance:evaluate","governance:templates"]),au=class{constructor(e,t){this.deps=e;this.store=new Di(e.configStore),this.engine=new su,this.alertEngine=t}deps;store;engine;alertEngine;async handle(e){if(!U0.has(e.type))return!1;switch(e.type){case"governance:policies:list":return this.handlePoliciesList(e),!0;case"governance:policy:save":return this.handlePolicySave(e),!0;case"governance:policy:delete":return this.handlePolicyDelete(e),!0;case"governance:evaluate":return await this.handleEvaluate(e),!0;case"governance:templates":return this.handleTemplates(e),!0;default:return!1}}handlePoliciesList(e){try{let r=this.store.getAll().map(o=>({id:o.id,name:o.name,description:o.description,ruleCount:o.rules.length,createdAt:o.createdAt,updatedAt:o.updatedAt})),n=A(this.deps,e,"governance:policies:result",{policies:r});this.deps.broker.postToWebview(n),this.deps.log("[TX] governance:policies:result")}catch(t){T(this.deps,"governance:policies:list","governance:error",e,t)}}handlePolicySave(e){let t=x(Rw,e,"governance:error",this.deps);if(t)try{let r=xi.safeParse(t.policy);if(!r.success){T(this.deps,"governance:policy:save","governance:error",e,new Error(`Validation failed: ${r.error.message}`),{code:"VALIDATION_ERROR"});return}this.store.save(r.data);let n=A(this.deps,e,"governance:policy:save:response",{success:!0});this.deps.broker.postToWebview(n),this.deps.log("[TX] governance:policy:save:response")}catch(r){T(this.deps,"governance:policy:save","governance:error",e,r)}}handlePolicyDelete(e){let t=x(bw,e,"governance:error",this.deps);if(t)try{let r=this.store.delete(t.policyId),n=A(this.deps,e,"governance:policy:delete:response",{success:r});this.deps.broker.postToWebview(n),this.deps.log("[TX] governance:policy:delete:response")}catch(r){T(this.deps,"governance:policy:delete","governance:error",e,r)}}async handleEvaluate(e){let t=x(vw,e,"governance:error",this.deps);if(!t)return;let r=t;try{let n=this.store.getById(r.policyId);if(!n){T(this.deps,"governance:evaluate","governance:error",e,new Error(`Policy not found: ${r.policyId}`),{code:"NOT_FOUND"});return}let i=await(await B(r.orgId,this.deps.orgRegistry,this.deps.orgManager)).request(`/services/data/${Oo}/limits`),a={};for(let[u,{Max:l,Remaining:p}]of Object.entries(i))a[u]=l>0?Math.round((l-p)/l*100):0;for(let[u,l]of Object.entries(_0))l in a&&(a[u]=a[l]);let d=this.engine.evaluatePolicy(n,a);if(this.alertEngine)for(let u of d.ruleResults)u.status==="fail"&&u.actualValue!==null&&this.alertEngine.evaluate(`governance:${u.ruleId}`,u.actualValue,r.orgId);let c=A(this.deps,e,"governance:evaluate:response",{success:!0,result:d});this.deps.broker.postToWebview(c),this.deps.log("[TX] governance:evaluate:response")}catch(n){T(this.deps,"governance:evaluate","governance:error",e,n)}}handleTemplates(e){try{let t=Di.getDefaultTemplates(),r=A(this.deps,e,"governance:templates:response",{templates:t});this.deps.broker.postToWebview(r),this.deps.log("[TX] governance:templates:response")}catch(t){T(this.deps,"governance:templates","governance:error",e,t)}}};var du=class s{static COMMON_OBJECTS=[{apiName:"Account",label:"Account"},{apiName:"Contact",label:"Contact"},{apiName:"Opportunity",label:"Opportunity"},{apiName:"Case",label:"Case"},{apiName:"Lead",label:"Lead"}];suggest(e,t){let r=new Set(e),n=new Set(t);return s.COMMON_OBJECTS.map(o=>({objectApiName:o.apiName,label:o.label,isAvailable:r.has(o.apiName),isAlreadySelected:n.has(o.apiName)}))}};var H0=new Set(["OpportunityId","CaseId","ContractId","OrderId"]),cu=class{detect(e,t,r,n){let o=new Set(r),i=new Set(n),a=[];for(let d of t)if(d.type==="reference"&&d.referenceTo.length!==0)for(let c of d.referenceTo){if(c===e||o.has(c)||!i.has(c)||zh(c))continue;let u=this.inferRelationshipType(d.name);a.push({childObject:e,parentObject:c,lookupField:d.name,relationshipType:u,suggestedInsertOrder:0})}return a}inferRelationshipType(e){return H0.has(e)?"masterDetail":"lookup"}};var uu=class{estimate(e,t=new Set,r=200){let n=r>0?r:200,o=e.map(c=>({objectApiName:c.objectApiName,recordCount:c.count,...c.heldInSource!==void 0?{heldInSource:c.heldInSource}:{},estimatedApiCalls:c.count>0?Math.ceil(c.count/n):0,isParentDependency:t.has(c.objectApiName)})),i=o.reduce((c,u)=>c+u.recordCount,0),a=o.reduce((c,u)=>c+u.estimatedApiCalls,0),d=a*2;return{objects:o,totalRecords:i,totalApiCalls:a,estimatedDurationSec:d}}};var lu=class{minConfidence;constructor(e=.4){this.minConfidence=e}suggest(e,t){let r=[],n=new Set,o=[...e];for(let i of o){let a;for(let d of t){if(n.has(d.apiName))continue;let c=this.computeScore(i,d);c.confidence>(a?.confidence??0)&&(a=c)}a&&a.confidence>=this.minConfidence&&(r.push(a),n.add(a.targetField))}return r.sort((i,a)=>a.confidence-i.confidence)}toMappings(e){return e.map(t=>({sourceField:t.sourceField,targetField:t.targetField,type:t.type}))}computeScore(e,t){if(e.apiName===t.apiName)return{sourceField:e.apiName,targetField:t.apiName,type:this.inferType(e,t),confidence:1,reason:"exact_name"};let r=this.normalize(e.apiName),n=this.normalize(t.apiName);if(r===n&&r.length>0)return{sourceField:e.apiName,targetField:t.apiName,type:this.inferType(e,t),confidence:.9,reason:"normalized_name"};let o=this.stringSimilarity(e.label.toLowerCase(),t.label.toLowerCase());if(o>=.8&&this.isTypeCompatible(e.type,t.type))return{sourceField:e.apiName,targetField:t.apiName,type:this.inferType(e,t),confidence:Math.min(.85,o),reason:"label_match"};let i=this.stringSimilarity(r,n),a=this.isTypeCompatible(e.type,t.type);return i>=.6&&a?{sourceField:e.apiName,targetField:t.apiName,type:this.inferType(e,t),confidence:i*.7,reason:"partial_match"}:{sourceField:e.apiName,targetField:t.apiName,type:"direct",confidence:0,reason:"no_match"}}normalize(e){return e.replace(/__c$/i,"").replace(/__r$/i,"").replace(/_/g,"").toLowerCase()}stringSimilarity(e,t){if(e===t)return 1;if(e.length<2||t.length<2)return 0;let r=this.bigrams(e),n=this.bigrams(t),o=0,i=[...n];for(let a of r){let d=i.indexOf(a);d>=0&&(o++,i.splice(d,1))}return 2*o/(r.length+n.length)}bigrams(e){let t=[];for(let r=0;r<e.length-1;r++)t.push(e.slice(r,r+2));return t}isTypeCompatible(e,t){return uf(e,t)}inferType(e,t){return e.apiName===t.apiName&&e.type===t.type?"direct":e.apiName!==t.apiName?"rename":"direct"}};var B0=new Set(["quicksync:suggest-objects","quicksync:detect-relationships","quicksync:preview","quicksync:execute"]),Ni={direction:"source_to_target",mode:"full",conflictStrategy:"source_wins",operation:"insert",batchSize:200},pu=class{constructor(e){this.deps=e}deps;suggester=new du;relationshipDetector=new cu;previewEstimator=new uu;autoFieldMapper=new lu;async handle(e){if(!B0.has(e.type))return!1;switch(e.type){case"quicksync:suggest-objects":return await this.handleSuggestObjects(e),!0;case"quicksync:detect-relationships":return await this.handleDetectRelationships(e),!0;case"quicksync:preview":return await this.handlePreview(e),!0;case"quicksync:execute":return await this.handleExecute(e),!0;default:return!1}}async handleSuggestObjects(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(nw,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let i=(await(await B(r.orgId??"",this.deps.orgRegistry,this.deps.orgManager)).describeGlobal()).sobjects.filter(c=>c.createable&&c.queryable).map(c=>c.name),a=this.suggester.suggest(i,r.alreadySelected??[]),d=A(this.deps,e,"quicksync:suggest-objects:response",{suggestions:a,availableObjects:[...i].sort((c,u)=>c.localeCompare(u))});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(n){T(this.deps,"quicksync:suggest-objects","quicksync:error",e,n)}}async handleDetectRelationships(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ow,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let n=await B(r.orgId??"",this.deps.orgRegistry,this.deps.orgManager),i=(await n.describe(r.objectApiName??"")).fields.map(u=>({name:u.name,type:u.type,referenceTo:u.referenceTo??[],relationshipName:u.relationshipName??null})),a=r.availableObjects??(await n.describeGlobal()).sobjects.filter(u=>u.createable&&u.queryable).map(u=>u.name),d=this.relationshipDetector.detect(r.objectApiName??"",i,r.alreadySelected??[],a),c=A(this.deps,e,"quicksync:detect-relationships:response",{suggestions:d});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(n){T(this.deps,"quicksync:detect-relationships","quicksync:error",e,n)}}async handlePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(sw,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let n=await B(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=[...new Set([...r.selectedObjects,...r.parentObjects??[]])],i=[],a=fd(this.deps.services?.getSandforgeSetting?.("sync.maxRecordsPerObject",void 0));for(let l of o){let f=(await n.query(`SELECT COUNT() FROM ${l}`)).totalSize??0;i.push({objectApiName:l,count:Math.min(f,a),...f>a?{heldInSource:f}:{}})}let d=new Set(r.parentObjects??[]),c={...this.previewEstimator.estimate(i,d),readCap:a},u=A(this.deps,e,"quicksync:preview:response",{preview:c});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`)}catch(n){T(this.deps,"quicksync:preview","quicksync:error",e,n)}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(iw,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let n=Mg.parse(r.config),o=await B(n.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),i=await B(n.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=[...new Set([...n.selectedObjects,...n.parentObjects])],d=[];for(let l=0;l<a.length;l++){let p=a[l],f=n.parentObjects.includes(p),[g,h]=await Promise.all([er(n.sourceOrgId,p,()=>o.describe(p)),er(n.targetOrgId,p,()=>i.describe(p))]),m=g.fields.filter(k=>k.createable).map(k=>({apiName:k.name,label:k.label,type:k.type})),y=h.fields.filter(k=>k.createable).map(k=>({apiName:k.name,label:k.label,type:k.type})),v=this.autoFieldMapper.suggest(m,y),b=this.autoFieldMapper.toMappings(v);d.push({objectApiName:p,operation:Ni.operation,fieldMappings:b,transformRules:[],excludedFields:[],batchSize:Ni.batchSize,insertOrder:f?0:l+1})}let c={id:e.id,name:`Quick Sync ${new Date().toISOString()}`,description:"Auto-generated by Quick Sync",sourceOrgId:n.sourceOrgId,targetOrgId:n.targetOrgId,direction:Ni.direction,mode:Ni.mode,objects:d,conflictStrategy:Ni.conflictStrategy,enableRollback:!1};Ae(this.deps,"info","Quick Sync",`Starting sync of ${a.length} object(s)`);let u=A(this.deps,e,"quicksync:execute:response",{syncConfig:c,objectCount:a.length});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`)}catch(n){T(this.deps,"quicksync:execute","quicksync:error",e,n)}}};var YT=6e4,q0=2880*6e4,W0=60*6e4,fu=class{deps;schedules=new Map;checkInterval;lastTickTime=0;claims;lastPrune=0;running=new Set;constructor(e){this.deps=e,this.claims=e.claims??fs()}start(){if(this.checkInterval)return;let e=this.deps.scheduleStore.loadAll(),t=this.now();for(let r of e)this.schedules.set(r.id,this.withPlausibleNextRun(r,t));this.lastTickTime=this.now(),this.checkInterval=setInterval(()=>{this.tick()},YT),this.deps.log("[SyncScheduleExecutor] started")}withPlausibleNextRun(e,t){if(!e.nextRunAt)return e;let r=new Date(e.nextRunAt).getTime(),n=Number.isNaN(r);if(!n&&r<=t+XS)return e;let o={...e,nextRunAt:this.computeNextRunAt(e.cron,e.timezone)};return this.deps.scheduleStore.save(o),this.deps.log(`[SyncScheduleExecutor] ${e.id}: next run ${n?`"${e.nextRunAt}" cannot be read,`:e.nextRunAt} replaced by ${o.nextRunAt||"none"}`),o}stop(){this.checkInterval&&(clearInterval(this.checkInterval),this.checkInterval=void 0,this.deps.log("[SyncScheduleExecutor] stopped"))}async tick(){let e=this.now(),t=e-this.lastTickTime;t>2*YT&&this.deps.log(`[SyncScheduleExecutor] sleep-wake detected (elapsed ${Math.round(t/1e3)}s)`),this.lastTickTime=e,e-this.lastPrune>=W0&&(this.lastPrune=e,this.claims.prune(q0));for(let r of this.schedules.values()){if(!r.enabled||!r.nextRunAt)continue;let n=new Date(r.nextRunAt).getTime();if(Number.isNaN(n)){let i=r.nextRunAt;r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),this.deps.scheduleStore.save(r),this.deps.log(`[SyncScheduleExecutor] ${r.id}: next run "${i}" cannot be read, replaced by ${r.nextRunAt||"none"}`);continue}if(n>e||this.running.has(r.id))continue;if(!this.claims.claim(`sync-schedule:${r.id}:${n}`)){this.deps.log(`[SyncScheduleExecutor] ${r.id} due at ${r.nextRunAt} is run by another window`),r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone);continue}let o=this.deps.configStore.load(r.configId);if(!o){this.deps.log(`[SyncScheduleExecutor] config not found for schedule ${r.id} (configId=${r.configId})`),r.lastRunAt=new Date(e).toISOString(),r.lastResult="failure",r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),r.updatedAt=new Date(e).toISOString(),this.deps.scheduleStore.save(r),r.notifyOnFailure&&this.deps.notificationCenter.notify("error","Sync schedule failed",`${r.name}: sync configuration "${r.configId}" no longer exists. Save the configuration again, or delete the schedule.`);continue}r.notifyOnComplete&&this.deps.notificationCenter.notify("info","Sync schedule started",r.name),this.running.add(r.id);try{let i=await this.deps.onExecute(o);if(r.lastRunAt=new Date(e).toISOString(),r.lastResult=i.cancelled?"cancelled":i.status,r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),r.updatedAt=new Date(e).toISOString(),this.deps.scheduleStore.save(r),i.cancelled)r.notifyOnComplete&&this.deps.notificationCenter.notify("info","Sync schedule cancelled",`${r.name}: ${i.error??"the run was cancelled."} Its entry in the sync history has what it wrote.`);else if(i.status==="failure"){if(r.notifyOnFailure){let a=i.objectResults.flatMap(d=>d.errors)[0];this.deps.notificationCenter.notify("error","Sync schedule failed",`${r.name}: ${a??"the run failed; its entry in the sync history has the details."}`)}}else if(i.status==="partial"&&r.notifyOnComplete){let a=i.objectResults.flatMap(u=>u.errors)[0],d=gd(i),c=[a,d].filter(u=>u!==void 0);this.deps.notificationCenter.notify("warning",a===void 0&&d!==void 0?"Sync schedule copied part of the source":"Sync schedule completed with errors",`${r.name}: ${c.length>0?c.join("; "):"some records failed; its entry in the sync history has the details."}`)}else r.notifyOnComplete&&this.deps.notificationCenter.notify("success","Sync schedule completed",r.name)}catch(i){if(r.lastRunAt=new Date(e).toISOString(),r.lastResult="failure",r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),r.updatedAt=new Date(e).toISOString(),this.deps.scheduleStore.save(r),r.notifyOnFailure){let a=i instanceof Error?i.message:String(i);this.deps.notificationCenter.notify("error","Sync schedule failed",`${r.name}: ${a}`)}}finally{this.running.delete(r.id)}}}upsert(e){let t=this.schedules.get(e.id),r={...e,nextRunAt:this.computeNextRunAt(e.cron,e.timezone),lastRunAt:t?.lastRunAt,lastResult:t?.lastResult};return this.schedules.set(r.id,r),this.deps.scheduleStore.save(r),this.deps.log(`[SyncScheduleExecutor] upserted schedule ${r.id}`),r}delete(e){let t=this.schedules.delete(e);return t&&(this.deps.scheduleStore.delete(e),this.deps.log(`[SyncScheduleExecutor] deleted schedule ${e}`)),t}toggle(e,t){let r=this.schedules.get(e);if(r)return r.enabled=t,t&&(r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone)),r.updatedAt=new Date(this.now()).toISOString(),this.deps.scheduleStore.save(r),this.deps.log(`[SyncScheduleExecutor] toggled ${e} -> ${t?"enabled":"disabled"}`),r}getSchedules(){return Array.from(this.schedules.values())}getSchedule(e){return this.schedules.get(e)}computeNextRunAt(e,t){let r=Rd(e,t,this.now());return typeof r=="number"?new Date(r).toISOString():(this.deps.log(`[SyncScheduleExecutor] no next run for cron "${e}": ${r.reason}`),"")}now(){return this.deps.now?this.deps.now():Date.now()}};var ng="schedule:sync:",QT="syncSchedules",gu=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${ng}${e.id}`,e,QT)}load(e){return this.configStore.get(`${ng}${e}`)}list(){let e=this.configStore.getByCategory(QT);return Object.values(e).sort((r,n)=>n.createdAt.localeCompare(r.createdAt))}delete(e){return this.configStore.delete(`${ng}${e}`)}loadAll(){return this.list()}};var z0=new Set(["sync:schedule:list","sync:schedule:upsert","sync:schedule:toggle","sync:schedule:delete"]),hu=class{constructor(e){this.deps=e}deps;executor;executeBridge;inFlight=0;claims=fs();async handle(e){if(!z0.has(e.type))return!1;switch(e.type){case"sync:schedule:list":return this.handleList(e),!0;case"sync:schedule:upsert":return this.handleUpsert(e),!0;case"sync:schedule:toggle":return this.handleToggle(e),!0;case"sync:schedule:delete":return this.handleDelete(e),!0;default:return!1}}getExecutor(){if(!this.executor){let e=new fu({scheduleStore:new gu(this.deps.configStore),configStore:new Pt(this.deps.configStore),onExecute:t=>this.executeDue(t),notificationCenter:{notify:(t,r,n)=>{this.deps.log(`[SyncSchedule] ${t}: ${r} \u2014 ${n}`),Ae(this.deps,t,r,n)}},log:this.deps.log,claims:{claim:t=>this.claims.claim(t),prune:t=>this.claims.prune(t)}});e.start(),e.stop(),this.executor=e}return this.executor}async executeDue(e){if(!this.executeBridge)throw new Error("Scheduled sync execution is not wired to the sync engine yet");let t=this.deps.services?.getSandforgeSetting?.("sync.maxConcurrentOps",3)??3;if(this.inFlight>=t)throw new Error(`Scheduled sync skipped: ${this.inFlight} execution(s) already in flight (max ${t})`);this.inFlight++;try{return await this.executeBridge(e)}finally{this.inFlight--}}startScheduler(e,t){this.executeBridge=e,t&&(this.claims=t),this.getExecutor().start(),this.deps.log("[SyncScheduleHandler] scheduler started (tick loop running)")}stopScheduler(){this.executor?.stop()}handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.getExecutor().getSchedules(),r=A(this.deps,e,"sync:schedule:list:response",{schedules:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id}`)}catch(t){T(this.deps,"sync:schedule:list","sync:schedule:error",e,t)}}handleUpsert(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(oy,e,"sync:schedule:error",this.deps);if(!t)return;let r=t.schedule.configId;if(!new Pt(this.deps.configStore).load(r)){T(this.deps,"sync:schedule:upsert","sync:schedule:error",e,new Error(`Sync configuration not found: ${r}. Save it from the Sync tab first.`),{code:"NOT_FOUND"});return}let{cron:n,timezone:o}=t.schedule,i=Rd(n,o,Date.now());if(typeof i!="number"){T(this.deps,"sync:schedule:upsert","sync:schedule:error",e,new Error(i.refused==="unreadable"?`The schedule was not saved: SandForge cannot read the cron expression "${n}" (${i.reason}).`:`The schedule was not saved. ${i.reason}`),{code:"INVALID_SCHEDULE"});return}try{let a=this.getExecutor().upsert(t.schedule),d=A(this.deps,e,"sync:schedule:upsert:response",{success:!0,schedule:a});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(a){T(this.deps,"sync:schedule:upsert","sync:schedule:error",e,a)}}handleToggle(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(sy,e,"sync:schedule:error",this.deps);if(t)try{let r=this.getExecutor().toggle(t.scheduleId,t.enabled);if(!r){T(this.deps,"sync:schedule:toggle","sync:schedule:error",e,new Error(`Schedule not found: ${t.scheduleId}`),{code:"NOT_FOUND"});return}let n=A(this.deps,e,"sync:schedule:toggle:response",{success:!0,schedule:r,scheduleId:t.scheduleId,enabled:t.enabled});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){T(this.deps,"sync:schedule:toggle","sync:schedule:error",e,r)}}handleDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(iy,e,"sync:schedule:error",this.deps);if(t)try{let r=this.getExecutor().delete(t.scheduleId),n=A(this.deps,e,"sync:schedule:delete:response",{success:r,scheduleId:t.scheduleId});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){T(this.deps,"sync:schedule:delete","sync:schedule:error",e,r)}}};var G0=new Set(["direct","rename"]);function ZT(s,e,t,r={}){let n={objectApiName:s.objectApiName,fieldMappings:[],addOnFields:[],transformRules:[],applyDeletes:s.applyDeletes},o=r.keepContactPoints===!0?{keepContactPoints:!0}:{};switch(s.match.kind){case"id":return{...n,keyField:"Id",keySource:"Id",...o};case"externalId":return{...n,keyField:s.match.field,keySource:s.match.field,...o};case"syncConfig":{let i=e(s.match.configId);if(!i)throw new Error(`${s.objectApiName}: the saved Sync configuration picked no longer exists.`);if(i.sourceOrgId!==t.sourceOrgId||i.targetOrgId!==t.targetOrgId)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" runs between two other orgs.`);let a=i.objects.find(p=>p.objectApiName===s.objectApiName);if(!a)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" does not carry it.`);let d=Ao([a]);if(d.length>0)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" cannot be applied. ${To(d)}`);let c=eh([a]);if(c.length>0)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" cannot be applied. ${th(c)}`);let u=a.externalIdField?.trim()||"Id",l=a.fieldMappings.find(p=>p.targetField===u&&G0.has(p.type));return{...n,keyField:u,keySource:u==="Id"?"Id":l?.sourceField??u,fieldMappings:a.fieldMappings,...a.excludedFields?.length?{excludedFields:a.excludedFields}:{},addOnFields:a.addOnFields,transformRules:a.transformRules,...i.keepContactPoints===!0?{keepContactPoints:!0}:{}}}}}var J0=K({entityName:L().min(1),changeType:L().min(1),recordIds:Re(L()),commitTimestamp:Te(),commitUser:L().optional(),transactionKey:L().optional(),changeOrigin:L().optional(),changedFields:Re(L()).optional(),nulledFields:Re(L()).optional()}).loose(),V0=K({event:K({replayId:Te()}).loose(),payload:K({ChangeEventHeader:J0}).loose()}).loose(),mu="ChangeEvent";function tE(s){return`/data/${s.endsWith("__c")?s.slice(0,-1):s}${mu}`}function rE(s){if(!s.endsWith(mu)||s===mu)return null;let e=s.slice(0,-mu.length);return e.endsWith("__")?`${e}c`:e}function nE(s,e){return s.endsWith("__c")?`${s.slice(0,-3)}__${e}__s`:s.endsWith("Address")?`${s.slice(0,-7)}${e}`:e}function eE(s){let e=s.indexOf(".");return e<0?s:nE(s.slice(0,e),s.slice(e+1))}function X0(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function oE(s,e){let t=V0.safeParse(e);if(!t.success){let i=t.error.issues[0];throw new Error(`A message on ${s} is not a change event (${i.path.join(".")||"message"}: ${i.message}).`)}let{ChangeEventHeader:r,...n}=t.data.payload,o={};for(let[i,a]of Object.entries(n))if(X0(a))for(let[d,c]of Object.entries(a))o[nE(i,d)]=c;else o[i]=a;for(let i of r.nulledFields??[])o[eE(i)]=null;return{channel:s,replayId:t.data.event.replayId,objectApiName:r.entityName,changeType:r.changeType,recordIds:r.recordIds,commitTimestamp:r.commitTimestamp,commitUser:r.commitUser??"",transactionKey:r.transactionKey??"",changeOrigin:r.changeOrigin??"",changedFieldNames:(r.changedFields??[]).map(eE),values:o}}var og="SandForgeRealtime";function sE(s){return s.changeOrigin.split(";").some(e=>e.trim()===`client=${og}`)}var Rs=class extends Error{constructor(t,r){super(`${t}: ${r}`);this.channel=t;this.answer=r;this.name="SubscriptionRefused"}channel;answer;get replayIdRefused(){return/replay ?id/i.test(this.answer)}};function K0(s){return s instanceof Error?s.message:typeof s=="object"&&s!==null&&"message"in s?String(s.message):String(s)}function iE(s){let e=new Map,t=new Map,r=[],n=!1,o={added(a){a.disable("websocket")},outgoing(a,d){if(a.channel==="/meta/subscribe"&&a.subscription){let c=e.get(a.subscription);c!==void 0&&(a.ext={...a.ext??{},replay:{[a.subscription]:c}})}d(a)},incoming(a,d){if(a.channel==="/meta/subscribe"&&a.successful===!1)t.set(a.subscription??"",a.error??"refused without a reason");else if((a.channel==="/meta/handshake"||a.channel==="/meta/connect")&&a.successful===!1&&a.advice?.reconnect==="none"){if(!n){n=!0;let c=a.error??`${a.channel} refused`;for(let u of r)u(c)}}else if(!a.channel.startsWith("/meta/")){let c=a.data?.event?.replayId;typeof c=="number"&&e.has(a.channel)&&e.set(a.channel,c)}d(a)}},i=s.createClient([o]);return{subscribe(a,d,c){return e.set(a,d),t.delete(a),new Promise((u,l)=>{i.subscribe(a,c).then(()=>u(),p=>{e.delete(a),l(new Rs(a,t.get(a)??K0(p)))})})},onDown(a){r.push(a)},disconnect(){n=!0,i.disconnect()}}}var aE="SELECT EventChannel, SelectedEntity FROM PlatformEventChannelMember";function dE(s){let e=new Map;for(let t of s){let r=typeof t.SelectedEntity=="string"?t.SelectedEntity:"",n=rE(r);if(!n||e.has(n))continue;let o=typeof t.EventChannel=="string"?t.EventChannel:"";e.set(n,{objectApiName:n,channel:o})}return[...e.values()].sort((t,r)=>t.objectApiName.localeCompare(r.objectApiName))}async function cE(s,e,t,r,n=()=>{}){let o=t.filter(i=>i.sourceOrgId===r.sourceOrgId&&i.targetOrgId===r.targetOrgId);return Promise.all(s.map(async({objectApiName:i,channel:a})=>{let d=!0,c=[];try{c=(await e(i)).fields.filter(l=>l.externalId===!0).map(l=>l.name).sort()}catch(u){d=!1,n(`[realtime] ${i} could not be described in the target: ${I(u)}`)}return{objectApiName:i,channel:a,inTarget:d,externalIdFields:c,syncConfigs:o.filter(u=>u.objects.some(l=>l.objectApiName===i)).map(u=>({id:u.id,name:u.name}))}}))}var wu=class{constructor(e=1e4){this.capacity=e}capacity;stamps=new Map;record(e,t){if(this.stamps.delete(e),this.stamps.set(e,t),this.stamps.size>this.capacity){let r=this.stamps.keys().next().value;r!==void 0&&this.stamps.delete(r)}}wrote(e,t){return this.stamps.get(e)===t}},Wn=200,uE=new Set(["int","double","currency","percent","long"]),Y0="The org sent an overflow notice instead of this change: one transaction changed more records than change events carry. A Sync run brings the target up to date.";function Q0(s){return s==="DELETE"||s==="GAP_DELETE"}function lE(s){return s==="CREATE"||s==="UNDELETE"}function yu(s){if(typeof s!="string"||s==="")return null;let e=s.replace(/([+-]\d{2})(\d{2})$/,"$1:$2"),t=Date.parse(e);return Number.isNaN(t)?null:t}function pE(s){return Object.fromEntries(Object.entries(s).filter(([e])=>e!=="attributes"))}function fE(s){return s==null||s===""}function sg(s){return String(s).toLowerCase()}var bu=class{constructor(e,t){this.plan=e;this.deps=t;this.objectConfig={objectApiName:e.objectApiName,operation:e.keyField==="Id"?"update":"upsert",externalIdField:e.keyField,fieldMappings:[],transformRules:e.transformRules,excludedFields:[],addOnFields:[],batchSize:Wn,insertOrder:0}}plan;deps;mapping=new Cm;transforms=new Pm;objectConfig;masked=new Set;get contactPoints(){return this.plan.keepContactPoints===!0?void 0:this.deps.contactPoints}async apply(e){let t=e.map(()=>[]),r=[],n=this.deps.maskedSourceFields;n&&(this.masked=new Set(await n(this.plan.objectApiName).catch(()=>[])));let o=[];e.forEach((i,a)=>{if(i.changeType==="GAP_OVERFLOW"){t[a].push({outcome:"failed",error:Y0});return}if(i.recordIds.length===0){t[a].push({outcome:"failed",error:"The change named no record."});return}let d=Q0(i.changeType)?"delete":"upsert";if(d==="delete"&&!this.plan.applyDeletes){t[a].push({outcome:"deletes-off"});return}let c=o[o.length-1];(!c||c.kind!==d)&&(c={kind:d,changes:new Map},o.push(c));for(let u of i.recordIds){let l=c.changes.get(u);l?(l.eventIndexes.push(a),l.values={...l.values,...i.values},l.full=l.full||lE(i.changeType),l.needsRead=l.needsRead||i.changeType.startsWith("GAP_"),l.commitTimestamp=Math.min(l.commitTimestamp,i.commitTimestamp),l.replayId=Math.max(l.replayId,i.replayId)):c.changes.set(u,{recordId:u,eventIndexes:[a],changeType:i.changeType,full:lE(i.changeType),needsRead:i.changeType.startsWith("GAP_")&&d==="upsert",values:{...i.values},commitTimestamp:i.commitTimestamp,replayId:i.replayId})}});for(let i of o){let a=[...i.changes.values()],d=(c,u)=>{for(let l of c.eventIndexes)t[l].push(u)};try{i.kind==="upsert"?await this.applyUpserts(a,d,r):await this.applyDeletes(a,d,r)}catch(c){let u=I(c);for(let l of a)d(l,{outcome:"failed",error:u})}}return{results:t.map(Z0),held:r}}async resolve(e,t,r){let n=e.record[this.plan.keyField],o;if(e.kind==="delete"?o=t==="source_wins"?{}:null:o=this.resolvedValues(e,t,r),o===null)return{success:!0,resolvedValues:{}};try{if(e.kind==="delete"){let d=await this.writeOne("delete",{Id:e.targetId});return d.success?{success:!0,resolvedValues:{Id:e.targetId}}:{success:!1,resolvedValues:{},error:d.errors[0]??"Delete refused."}}let i=await this.coerced({...o,[this.plan.keyField]:n}),a=await this.writeOne(this.objectConfig.operation,i);return a.success?(await this.rememberWrites([a.id??e.targetId]),{success:!0,resolvedValues:i}):{success:!1,resolvedValues:{},error:a.errors[0]??"Write refused."}}catch(i){return{success:!1,resolvedValues:{},error:I(i)}}}resolvedValues(e,t,r){let n=Object.fromEntries(Object.entries(e.record).filter(([o])=>o!==this.plan.keyField));switch(t){case"source_wins":return n;case"merge":{let o=Object.fromEntries(Object.entries(n).filter(([,i])=>i!==null));return Object.keys(o).length>0?o:null}case"manual":{let o=Object.fromEntries(Object.entries(r??{}).filter(([i])=>i in n).map(([i,a])=>[i,a.value]));return Object.keys(o).length>0?o:null}case"target_wins":case"newest_wins":return null}}async coerced(e){let t=await this.deps.target.describe(this.plan.objectApiName),r=new Map(t.fields.map(o=>[o.name,o.type??""])),n={};for(let[o,i]of Object.entries(e)){let a=r.get(o)??"";if(typeof i=="string"&&a==="boolean")n[o]=i.trim().toLowerCase()==="true";else if(typeof i=="string"&&uE.has(a)&&i.trim()!==""){let d=Number(i);n[o]=Number.isNaN(d)?i:d}else n[o]=i}return n}async writeOne(e,t){let{outcomes:r}=await this.deps.write({...this.objectConfig,operation:e,batchSize:1},[t],this.contactPoints);return r[0]??{success:!1,errors:["The target answered nothing."]}}async applyUpserts(e,t,r){let n=this.plan.objectApiName,o=new Map((await this.deps.target.describe(n)).fields.map(f=>[f.name,f]));if(this.plan.keyField!=="Id"&&!o.has(this.plan.keyField))throw new Error(`${n} has no field ${this.plan.keyField} in the target org.`);await this.readWhole(e.filter(f=>f.needsRead),t);let i=e.filter(f=>!f.needsRead||f.full),a=await this.keysOf(i,t,!1);i=i.filter(f=>a.has(f.recordId));let d=await this.readTarget([...new Set([...a.values()])],o,this.writtenFieldsOf(i,a)),c=[],u=[];for(let f of i){let g=a.get(f.recordId),h=d.get(sg(g))??[];if(h.length>1){t(f,{outcome:"failed",error:`${h.length} records of ${n} in the target have ${this.plan.keyField} = ${String(g)}.`});continue}let m=h[0];if(!m){this.plan.keyField==="Id"?t(f,{outcome:"failed",error:"No record in the target has this Id: it was made after the two orgs were copied. Match on an external id to copy records made since."}):f.full?c.push({change:f,record:this.recordFor(f,g,o,!1)}):u.push(f);continue}let y=String(m.Id),v=this.recordFor(f,g,o,!0),b=yu(m.LastModifiedDate);if(!(b!==null&&b>f.commitTimestamp&&!this.deps.ownWrites.wrote(y,b))){c.push({change:f,record:v,targetId:y});continue}switch(this.deps.conflictStrategy){case"source_wins":c.push({change:f,record:v,targetId:y});break;case"merge":{let S=Object.fromEntries(Object.entries(v).filter(([C,R])=>R!==null||C===this.plan.keyField));Object.keys(S).length>1?c.push({change:f,record:S,targetId:y}):t(f,{outcome:"kept-target"});break}case"manual":r.push(this.held(f,"upsert",v,m)),t(f,{outcome:"held"});break;case"target_wins":case"newest_wins":t(f,{outcome:"kept-target"});break}}if(u.length>0){for(let f of u)f.needsRead=!0;await this.readWhole(u,t);for(let f of u.filter(g=>g.full))c.push({change:f,record:this.recordFor(f,a.get(f.recordId),o,!1)})}if(c.length===0)return;let{outcomes:l}=await this.deps.write(this.objectConfig,c.map(f=>f.record),this.contactPoints),p=[];c.forEach((f,g)=>{let h=l[g];if(h?.success){t(f.change,{outcome:"applied"});let m=h.id??f.targetId;m&&p.push(m)}else t(f.change,{outcome:"failed",error:h?.errors[0]??"The target answered nothing for this record."})}),await this.rememberWrites(p)}async applyDeletes(e,t,r){let n=this.plan.objectApiName,o=new Map((await this.deps.target.describe(n)).fields.map(l=>[l.name,l])),i=await this.keysOf(e,t,!0),a=e.filter(l=>i.has(l.recordId)),d=await this.readTarget([...new Set([...i.values()])],o,[]),c=[];for(let l of a){let p=i.get(l.recordId),f=d.get(sg(p))??[];if(f.length>1){t(l,{outcome:"failed",error:`${f.length} records of ${n} in the target have ${this.plan.keyField} = ${String(p)}.`});continue}let g=f[0];if(!g){t(l,{outcome:"applied"});continue}let h=String(g.Id),m=yu(g.LastModifiedDate);!(m!==null&&m>l.commitTimestamp&&!this.deps.ownWrites.wrote(h,m))||this.deps.conflictStrategy==="source_wins"?c.push({change:l,targetId:h}):this.deps.conflictStrategy==="manual"?(r.push(this.held(l,"delete",{[this.plan.keyField]:p},g)),t(l,{outcome:"held"})):t(l,{outcome:"kept-target"})}if(c.length===0)return;let{outcomes:u}=await this.deps.write({...this.objectConfig,operation:"delete"},c.map(l=>({Id:l.targetId})));c.forEach((l,p)=>{let f=u[p];t(l.change,f?.success?{outcome:"applied"}:{outcome:"failed",error:f?.errors[0]??"The target answered nothing for this record."})})}held(e,t,r,n){let o=Object.keys(r).filter(i=>i!==this.plan.keyField);return{conflictId:`${this.plan.objectApiName}:${e.recordId}:${e.replayId}`,objectApiName:this.plan.objectApiName,recordId:e.recordId,replayId:e.replayId,changeType:e.changeType,kind:t,record:r,targetId:String(n.Id),targetValues:Object.fromEntries(o.map(i=>[i,n[i]??null])),targetLastModified:new Date(yu(n.LastModifiedDate)??0).toISOString()}}async keysOf(e,t,r){let{keySource:n}=this.plan,o=e.filter(a=>n!=="Id"&&fE(a.values[n])&&!(n in a.values&&a.full));if(o.length>0){let a=await this.readSource(o.map(d=>d.recordId),`Id, ${Xe(n)}`,r);for(let d of o){let c=a.get(d.recordId);c&&(d.values={...d.values,[n]:c[n]??null})}}let i=new Map;for(let a of e){if(n!=="Id"&&!(n in a.values)){t(a,{outcome:"failed",error:r?"The deleted record can no longer be read in the source (it left the recycle bin), so the record to delete in the target cannot be found.":"The source record could not be read back, so its record in the target cannot be found."});continue}let d=this.plan.keyField==="Id"?a.recordId:this.mapped(a)[this.plan.keyField];if(fE(d)){t(a,{outcome:"failed",error:`The source record has no ${n}, so its record in the target cannot be found.`});continue}i.set(a.recordId,d)}return i}mapped(e){let r={...this.masked.size>0?Object.fromEntries(Object.entries(e.values).filter(([o])=>!this.masked.has(o))):e.values,Id:e.recordId},n=this.mapping.apply(r,this.plan.fieldMappings,this.plan.excludedFields);return this.plan.keySource!=="Id"&&n[this.plan.keyField]===void 0&&(n[this.plan.keyField]=r[this.plan.keySource]),n=this.transforms.transformRecord(n,this.objectConfig),this.mapping.applyAddOns(n,this.plan.addOnFields)}recordFor(e,t,r,n){let o=this.mapped(e),i=n?[]:da(this.plan.objectApiName,o),a={};for(let[d,c]of Object.entries(o)){if(c===void 0||d==="Id"||d===this.plan.keyField||i.includes(d))continue;let u=r.get(d);u&&((n?u.updateable!==!0:u.createable!==!0)||(a[d]=c))}return a[this.plan.keyField]=t,a}writtenFieldsOf(e,t){let r=new Set;for(let n of e)if(t.has(n.recordId))for(let[o,i]of Object.entries(this.mapped(n)))i!==void 0&&r.add(o);return[...r]}async readWhole(e,t){if(e.length===0)return;let r=await this.readSource(e.map(n=>n.recordId),"FIELDS(ALL)",!1);for(let n of e){let o=r.get(n.recordId);if(!o){t(n,{outcome:"failed",error:"The source record could not be read back: it was deleted since."});continue}n.values={...pE(o),...n.values},n.full=!0}}async readSource(e,t,r){let n=St(this.plan.objectApiName),o=new Map;for(let i=0;i<e.length;i+=Wn){let d=e.slice(i,i+Wn).map(l=>`'${tr(l)}'`).join(", "),c=t==="FIELDS(ALL)"?` LIMIT ${Wn}`:"",u=await this.deps.source.query(`SELECT ${t} FROM ${n} WHERE Id IN (${d})${c}`,{includeDeleted:r});for(let l of u)o.set(String(l.Id),l)}return o}async readTarget(e,t,r){let n=St(this.plan.objectApiName),o=Xe(this.plan.keyField),i=uE.has(t.get(this.plan.keyField)?.type??""),a=r.filter(u=>u!=="Id"&&u!==this.plan.keyField&&u!=="LastModifiedDate"&&t.has(u)),d=["Id",...o==="Id"?[]:[o],"LastModifiedDate",...a],c=new Map;for(let u=0;u<e.length;u+=Wn){let p=e.slice(u,u+Wn).map(h=>i?String(Number(h)):`'${tr(String(h))}'`).join(", "),f=`WHERE ${o} IN (${p})`,g;try{g=await this.deps.target.query(`SELECT ${d.map(Xe).join(", ")} FROM ${n} ${f}`)}catch{g=await this.deps.target.query(`SELECT Id${o==="Id"?"":`, ${o}`}, LastModifiedDate FROM ${n} ${f}`)}for(let h of g){let m=sg(h[this.plan.keyField]);c.set(m,[...c.get(m)??[],pE(h)])}}return c}async rememberWrites(e){if(e.length===0)return;let t=St(this.plan.objectApiName);try{for(let r=0;r<e.length;r+=Wn){let n=e.slice(r,r+Wn).map(i=>`'${tr(i)}'`).join(", "),o=await this.deps.target.query(`SELECT Id, LastModifiedDate FROM ${t} WHERE Id IN (${n})`);for(let i of o){let a=yu(i.LastModifiedDate);a!==null&&this.deps.ownWrites.record(String(i.Id),a)}}}catch{}}};function Z0(s){let e=s.find(t=>t.outcome==="failed");return e||(s.some(t=>t.outcome==="held")?{outcome:"held"}:s.length>0&&s.every(t=>t.outcome==="kept-target")?{outcome:"kept-target"}:s.length>0&&s.every(t=>t.outcome==="deletes-off")?{outcome:"deletes-off"}:{outcome:"applied"})}var Ru=class{constructor(e){this.deps=e}deps;async open(e){let t={subscribed:[],refused:[],notes:[]};for(let r of e){let n=tE(r),o=a=>{let d;try{d=oE(n,a)}catch(c){this.deps.onUnreadable(n,I(c));return}this.deps.onEvent(d)},i=this.deps.replayStore.get(n);try{await this.deps.transport.subscribe(n,i??-1,o),t.subscribed.push(r)}catch(a){if(i!==void 0&&a instanceof Rs&&a.replayIdRefused)try{await this.deps.transport.subscribe(n,-2,o),t.subscribed.push(r),t.notes.push(`${r}: the org no longer holds the point the last session stopped at (replay id ${i}), so every change it still holds \u2014 up to three days \u2014 is replayed instead. Changes older than that were not received; a Sync run brings the target up to date.`)}catch(d){t.refused.push({objectApiName:r,reason:gE(d)})}else t.refused.push({objectApiName:r,reason:gE(a)})}}return t}close(){this.deps.transport.disconnect()}};function gE(s){return s instanceof Rs?s.answer:I(s)}var rL=[2e3,1e4,3e4],nL=6e4,vu=class{constructor(e,t){this.config=e;this.deps=t}config;deps;state="disconnected";subscription;watched=[];refused=[];notes=[];error;stopped=!1;buffer=[];flushTimer;flushing=Promise.resolve();held=new Map;startedAt=0;lastEventAt;received=0;applied=0;failed=0;lagTotal=0;lagCount=0;currentLag=0;recentReceipts=[];now(){return(this.deps.now??Date.now)()}get sessionId(){return this.config.sessionId}get running(){return this.state==="syncing"||this.state==="connecting"}async start(){this.state="connecting",this.startedAt=this.now();let e;try{e=await this.open(this.config.watchedObjects)}catch(t){throw this.state="error",this.error=I(t),t}return this.watched=e.subscribed,this.refused=e.refused,this.notes=e.notes,e.subscribed.length===0?(this.state="error",this.error="The source org refused a subscription to every watched object.",this.closeSubscription()):this.state="syncing",e}async stop(){this.stopped=!0,this.state="disconnected",this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0,this.closeSubscription(),this.buffer=[],await this.flushing;let e=this.held.size;return this.held.clear(),e}snapshot(){return{status:this.state,sessionId:this.config.sessionId,watchedObjects:this.watched,refused:this.refused,notes:this.notes,...this.error?{error:this.error}:{}}}metrics(){let e=this.now();this.recentReceipts=this.recentReceipts.filter(r=>e-r<nL);let t=this.applied+this.failed;return{eventsReceived:this.received,eventsApplied:this.applied,eventsFailed:this.failed,eventsPerMinute:this.recentReceipts.length,averageLagMs:this.lagCount>0?this.lagTotal/this.lagCount:0,currentLagMs:this.currentLag,errorRate:t>0?this.failed/t*100:0,startedAt:new Date(this.startedAt).toISOString(),...this.lastEventAt!==void 0?{lastEventAt:new Date(this.lastEventAt).toISOString()}:{}}}async resolveConflict(e,t,r){let n=this.held.get(e);if(!n)return{success:!1,resolvedValues:{},error:"This change is no longer held: the session that held it has stopped, or it was already decided."};let o=await n.applier.resolve(n.change,t,r);return o.success&&this.held.delete(e),o}closeSubscription(){this.subscription?.close(),this.subscription=void 0}async open(e){let t=await this.deps.openTransport();return t.onDown(r=>{this.reconnect(r)}),this.subscription=new Ru({transport:t,replayStore:this.deps.replayStore,onEvent:r=>this.receive(r),onUnreadable:(r,n)=>this.deps.log(`[WARN] realtime ${r}: ${n}`)}),this.subscription.open(e)}async reconnect(e){if(!(this.stopped||this.state!=="syncing")){this.state="connecting",this.error=`The connection to the source org was closed (${e}); reconnecting.`,this.deps.sink.status(this.snapshot()),this.closeSubscription(),this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0,await this.flushing,this.buffer=[];for(let t of rL){if(await new Promise(r=>setTimeout(r,t)),this.stopped)return;try{let r=await this.open(this.watched);if(r.subscribed.length>0){this.watched=r.subscribed,this.notes=[...this.notes,...r.notes],this.state="syncing",this.error=void 0,this.deps.sink.status(this.snapshot());return}this.closeSubscription()}catch(r){this.deps.log(`[WARN] realtime reconnect failed: ${I(r)}`)}}this.stopped||(this.state="error",this.error=`The connection to the source org was closed (${e}) and could not be reopened.`,this.deps.sink.status(this.snapshot()))}}receive(e){if(this.stopped)return;let t=this.now();this.received++,this.lastEventAt=t,this.recentReceipts.push(t),this.buffer.push(e),this.scheduleFlush(this.buffer.length>=this.config.maxBatchSize?0:this.config.flushIntervalMs)}scheduleFlush(e){if(this.flushTimer!==void 0){if(e>0)return;clearTimeout(this.flushTimer)}this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushing=this.flushing.then(()=>this.flush())},e)}async flush(){for(;this.buffer.length>0&&!this.stopped;){let e=this.buffer.splice(0,this.config.maxBatchSize);try{await this.process(e)}catch(t){this.deps.log(`[ERR] realtime batch: ${I(t)}`)}}}async process(e){let t=e.map(()=>({outcome:"watched"})),r=new Map;e.forEach((i,a)=>{sE(i)?t[a]={outcome:"own-write"}:this.config.appliers.has(i.objectApiName)&&r.set(i.objectApiName,[...r.get(i.objectApiName)??[],a])});for(let[i,a]of r){let d=this.config.appliers.get(i);if(d)try{let{results:c,held:u}=await d.apply(a.map(l=>e[l]));c.forEach((l,p)=>{t[a[p]]=l});for(let l of u)this.held.set(l.conflictId,{change:l,applier:d}),this.deps.sink.conflict(l)}catch(c){let u=I(c);for(let l of a)t[l]={outcome:"failed",error:u}}}let n=this.now(),o=new Map;e.forEach((i,a)=>{let d=t[a];d.outcome==="applied"&&this.applied++,d.outcome==="failed"&&this.failed++;let c=Math.max(0,n-i.commitTimestamp);this.lagTotal+=c,this.lagCount++,this.currentLag=c,o.set(i.channel,Math.max(o.get(i.channel)??0,i.replayId))}),this.deps.sink.events(e.map((i,a)=>oL(i,t[a]))),this.deps.replayStore.save(o)}};function oL(s,e){let t={};for(let r of s.changedFieldNames)r in s.values&&(t[r]=s.values[r]);return{replayId:s.replayId,objectApiName:s.objectApiName,changeType:s.changeType,recordIds:s.recordIds,commitTimestamp:new Date(s.commitTimestamp).toISOString(),changedFields:s.changedFieldNames.length>0?t:{...s.values},commitUser:s.commitUser,transactionKey:s.transactionKey,applied:e.outcome==="applied",outcome:e.outcome,...e.error?{error:e.error}:{}}}var sL="realtime:replay:",iL="realtime",ji=class{constructor(e,t){this.configStore=e;this.sourceOrgId=t}configStore;sourceOrgId;get key(){return`${sL}${this.sourceOrgId}`}read(){let e=this.configStore.get(this.key),t={};if(!e||typeof e!="object")return t;for(let[r,n]of Object.entries(e))typeof n=="number"&&Number.isFinite(n)&&(t[r]=n);return t}get(e){return this.read()[e]}save(e){e.size!==0&&this.configStore.set(this.key,{...this.read(),...Object.fromEntries(e)},iL)}forget(){this.configStore.delete(this.key)}};function ig(s){return s.eventsFailed===0?"success":s.eventsApplied>0?"partial":"failure"}function hE(s){return s.slice(0,15)}function mE(s){let e=s.store.recorder({runId:s.sessionId,configId:`realtime:${s.sessionId}`,configName:"",sourceOrgId:s.sourceOrgId,targetOrgId:s.targetOrgId,realtime:!0});s.identity&&Ir(e,s.identity,`realtime ${s.sessionId}`);let t=s.backups?ld({runId:s.sessionId,orgId:s.targetOrgId,files:s.backups,meta:s.meta}):void 0,r=d=>s.target.query(d),n=t?pd({query:r,backup:t,recorder:e,describe:async d=>Ar(await s.target.describe(d)),viewsEncrypted:wr(r)}):void 0,o=new Set,i=(d,c,u,l)=>{if(c==="insert"||c==="upsert"){for(let f of hd(c,l))o.add(hE(f));return}if(c!=="delete")return;let p=u.flatMap((f,g)=>{let h=f.Id;return l[g]?.success===!0&&typeof h=="string"&&!o.has(hE(h))?[h]:[]});p.length>0&&e.deleted?.(d,p)},a;return{runId:s.sessionId,calls:md(e,n),write:d=>{let c=Promise.resolve();return(u,l,p)=>{let f=c.then(async()=>{let g=await d(u,l,p);return i(u.objectApiName,u.operation,l,g.outcomes),g});return c=f.catch(()=>{}),f}},get ended(){return a!==void 0},end:d=>(a??=(async()=>{await e.end({status:d.status,...d.cancelled?{cancelled:!0}:{}});try{t?.close()}catch(c){s.log(`[WARN] realtime ${s.sessionId}: the backup of what it wrote over could not be listed whole: ${c instanceof Error?c.message:String(c)}`)}return e.flush()})(),a)}}var aL=new Set(["realtime:start","realtime:stop","realtime:status","realtime:metrics","realtime:objects","realtime:resolve-conflict"]);function dL(s){let e=r=>B(r,s.orgRegistry,s.orgManager),t=ut(s);return{async openTransport(r){let{streaming:n}=await e(r);return iE({createClient(o){let i=n.createClient(o);return{subscribe:(a,d)=>i.subscribe(a,d),disconnect:()=>i.disconnect?.()}}})},async identity(r){return(await e(r)).identity()},reader(r){return{async query(n,o){let i=await e(r),a=o?.includeDeleted===!0,{records:d}=await nr({query:async c=>i.query(c,{scanAll:a}),queryMore:async c=>i.queryMore(c)},n);return d},async describe(n){let o=await e(r);return{fields:(await er(r,n,()=>o.describe(n))).fields}}}},writer(r,n){return async(o,i,a)=>{let d=await e(r),c=await $h(d,og),u=new Nn({connection:c,bulkExecutor:new kn(t.bulk.threshold),bulkManager:yr(s),retryConfig:t.retry,onProgress:()=>{},log:p=>s.log(p),...n?{calls:n}:{}});return new uS({upsert:(p,f,g,h)=>u.upsert(p,f,g,h),insert:(p,f,g)=>u.insert(p,f,g),update:(p,f,g)=>u.update(p,f,g),delete:(p,f,g)=>u.delete(p,f,g),describeTargetFields:async p=>Ar(await er(r,p,()=>d.describe(p))),...a?{contactPoints:a}:{}}).write(o,i)}},async tooling(r,n){let o=await e(r),{records:i}=await nr({query:async a=>o.tooling.query(a),queryMore:async a=>o.tooling.queryMore(a)},n);return i}}}var Su=class{constructor(e,t){this.deps=e;this.syncConfigs=new Pt(e.configStore),this.access=t??dL(e)}deps;current;lastMetrics=null;registry;liveTracker;syncConfigs;access;runCreations;backupRecords;openRuns=new Set;isWritingTo(e){let t=this.current;return t!==void 0&&t.guard!==void 0&&t.session.running&&t.targetOrgId===e}isRunning(e){return this.openRuns.has(e)}setRunCreations(e){this.runCreations=e}setBackupRecordStore(e){this.backupRecords=e}async handle(e){if(!aL.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"realtime:objects":return await this.handleObjects(e),!0;case"realtime:start":return await this.handleStart(e),!0;case"realtime:stop":return await this.handleStop(e),!0;case"realtime:status":return this.post(A(this.deps,e,"realtime:status:response",this.statusPayload())),!0;case"realtime:metrics":return this.post(A(this.deps,e,"realtime:metrics:response",{metrics:this.current?.session.metrics()??this.lastMetrics})),!0;case"realtime:resolve-conflict":return await this.handleResolve(e),!0;default:return!1}}setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}async dispose(){await this.stopCurrent()}forgetOrg(e){new ji(this.deps.configStore,e).forget()}post(e){this.deps.broker.postToWebview(e),this.deps.log(`[TX] ${e.type} id=${e.id}`)}pushEvents(e){let t={id:this.deps.nextId(),type:"realtime:events-batch",timestamp:Date.now(),payload:{events:e}};this.deps.broker.postToWebview(t)}pushConflict(e){let t={id:this.deps.nextId(),type:"realtime:conflict",timestamp:Date.now(),payload:{replayId:e.replayId,objectApiName:e.objectApiName,recordIds:[e.recordId],changeType:e.changeType,sourceValues:Object.fromEntries(Object.entries(e.record).filter(([r])=>r in e.targetValues)),targetValues:e.targetValues,targetLastModified:e.targetLastModified}};this.deps.broker.postToWebview(t)}pushStatus(e){let t={id:this.deps.nextId(),type:"realtime:status:response",timestamp:Date.now(),payload:e};this.deps.broker.postToWebview(t)}pushStopped(e,t){let r={id:this.deps.nextId(),type:"realtime:stopped",timestamp:Date.now(),payload:{sessionId:e,reason:t,success:!0}};this.deps.broker.postToWebview(r)}statusPayload(){if(!this.current)return{status:"disconnected",watchedObjects:[]};let e=this.current.encryptedLeftOut??[];return{...this.current.session.snapshot(),...e.length>0?{encryptedLeftOut:e}:{}}}async stopCurrent(){let e=this.current;if(!e)return;this.current=void 0,e.detach();let t=await e.session.stop();return this.lastMetrics=e.session.metrics(),e.finish(),await e.endRun(),e.guard&&Y(this.deps,{action:"realtime_sync",module:"sync",operationId:e.operationId,orgId:e.targetOrgId,outcome:ig(this.lastMetrics),guard:e.guard,source:{origin:"org",orgId:e.sourceOrgId}}),t>0&&Ae(this.deps,"warning","Real-time sync",`${t} change(s) held for a decision were not applied: the session that held them has stopped.`),e.session.sessionId}async handleObjects(e){let t=x(zm,e,"realtime:error",this.deps);if(t)try{let r=await this.access.tooling(t.sourceOrgId,aE),n=this.access.reader(t.targetOrgId),o=await cE(dE(r),i=>n.describe(i),this.syncConfigs.list(),t,i=>this.deps.log(i));this.post(A(this.deps,e,"realtime:objects:response",{objects:o}))}catch(r){let n=kh(I(r));T(this.deps,"realtime:objects","realtime:error",e,r,n?{code:n}:void 0)}}async handleStart(e){let t=x(qm,e,"realtime:error",this.deps);if(!t)return;let r=n=>{this.post(A(this.deps,e,"realtime:started",{success:!1,watchedObjects:[],refused:[],notes:[],error:n}))};if(this.current?.session.running){r(`A real-time session is already running (${this.current.session.sessionId}). Stop it before starting another.`);return}try{let n=t.apply.map(O=>ZT(O,E=>this.syncConfigs.load(E),t,{keepContactPoints:t.keepContactPoints===!0})),o=n.length>0?await this.passesProductionGuard(e,t.targetOrgId,n):void 0;if(n.length>0&&!o){r("The target org is protected by the Production Guard, which did not allow the writes.");return}let i=new AbortController,a=new wu,d=this.access.reader(t.sourceOrgId),c=this.access.reader(t.targetOrgId),u=crypto.randomUUID(),l=o&&this.runCreations?mE({sessionId:u,sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,store:this.runCreations,...this.backupRecords?{backups:this.backupRecords}:{},meta:this.deps.configStore,target:c,identity:async()=>await this.access.identity?.(t.targetOrgId)??{},log:O=>this.deps.log(O)}):void 0,p=l?l.write(this.access.writer(t.targetOrgId,l.calls)):this.access.writer(t.targetOrgId),f=new KR,g=no(wr(O=>d.query(O)),O=>d.describe(O)),h=new Map(n.map(O=>[O.objectApiName,new bu(O,{source:d,target:c,write:p,conflictStrategy:t.conflictStrategy,ownWrites:a,contactPoints:f,maskedSourceFields:g})])),m,y=()=>{},v=new Promise((O,E)=>{y=$=>{$?m?.fail($):i.signal.aborted?m?.cancel():m?.complete(),$?E(new Error($)):O()}});v.catch(()=>{});let b=async()=>{if(!l)return;let O=await l.end({status:ig(k.metrics()),cancelled:i.signal.aborted}).catch(E=>I(E));this.openRuns.delete(l.runId),O!==void 0&&Ae(this.deps,"warning","Real-time sync",`What the session wrote could not all be kept (${O}): removing it may leave some of it in the target.`)},k=new vu({sessionId:u,watchedObjects:t.watchedObjects,appliers:h,flushIntervalMs:t.flushIntervalMs,maxBatchSize:t.maxBatchSize},{openTransport:()=>this.access.openTransport(t.sourceOrgId),replayStore:new ji(this.deps.configStore,t.sourceOrgId),sink:{events:O=>this.pushEvents(O),conflict:O=>this.pushConflict(O),status:O=>{if(O.status!=="error"){this.pushStatus(O);return}y(O.error),b().then(()=>this.pushStatus(O))}},log:O=>this.deps.log(O)}),S={session:k,abort:i,operationId:e.id,sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,guard:o,finish:O=>y(O),detach:()=>{},endRun:b};this.current=S,this.lastMetrics=null,l&&this.openRuns.add(l.runId);let C;try{C=await k.start()}catch(O){throw await b(),O}let R=k.snapshot();if(C.subscribed.length>0){let O=`Real-time sync of ${C.subscribed.length} object(s)`;this.registry?.register(k.sessionId,"sync",O,v,i),m=sr(this.liveTracker,k.sessionId,"realtime",O);let E=()=>{this.current?.session===k&&this.stopCurrent().then($=>{$&&this.pushStopped($,"cancelled")})};i.signal.addEventListener("abort",E,{once:!0}),S.detach=()=>i.signal.removeEventListener("abort",E)}else y(),await b();let w=new Set(C.subscribed),P=(await Promise.all(n.filter(O=>w.has(O.objectApiName)).map(async O=>({objectApiName:O.objectApiName,fields:[...await g(O.objectApiName)].sort()})))).filter(O=>O.fields.length>0);P.length>0&&(S.encryptedLeftOut=P),this.post(A(this.deps,e,"realtime:started",{success:C.subscribed.length>0,sessionId:k.sessionId,watchedObjects:C.subscribed,refused:C.refused,notes:C.notes,...P.length>0?{encryptedLeftOut:P}:{},...R.error?{error:R.error}:{}}))}catch(n){r(I(n))}}async passesProductionGuard(e,t,r){let n=this.deps.infraServices?.productionGuard;if(!n)throw Y(this.deps,{action:"realtime_sync",module:"sync",operationId:e.id,orgId:t,outcome:"stopped",code:ve.code}),ua();let o={orgId:t,orgTier:Pe(this.deps.orgManager.getOrg(t)),operation:r.some(a=>a.applyDeletes)?"delete":"upsert",objectName:r.map(a=>a.objectApiName).join(", "),recordCount:"unknown",module:"sync"},{decision:i}=await et(n,o);if(i==="refused"||i==="declined"){Y(this.deps,{action:"realtime_sync",module:"sync",operationId:e.id,orgId:t,outcome:"stopped",guard:i});return}return i}async handleStop(e){let t=x(Wm,e,"realtime:error",this.deps);if(!t)return;let r=this.current;if(!r||t.sessionId!==""&&t.sessionId!==r.session.sessionId){this.post(A(this.deps,e,"realtime:status:response",this.statusPayload()));return}let n=await this.stopCurrent();this.post(A(this.deps,e,"realtime:stopped",{sessionId:n??r.session.sessionId,reason:"stopped",success:!0}))}async handleResolve(e){let t=x(Gm,e,"realtime:error",this.deps);if(!t)return;let r=this.current?await this.current.session.resolveConflict(t.conflictId,t.resolution,t.fieldResolutions&&Object.fromEntries(Object.entries(t.fieldResolutions).map(([n,o])=>[n,{value:o.value,source:o.source}]))):{success:!1,resolvedValues:{},error:"No real-time session is running: the change it held was dropped when it stopped."};r.success||Ae(this.deps,"warning","Real-time sync",`The decision on ${t.conflictId} was not applied: ${r.error??"refused"}`),this.post(A(this.deps,e,"realtime:conflict-resolved",{conflictId:t.conflictId,resolution:t.resolution,success:r.success,resolvedValues:r.resolvedValues,...r.error?{error:r.error}:{}}))}};var cL=new Set(["file:save"]),ku=class{constructor(e,t){this.deps=e;this.saveDialog=t??new An}deps;saveDialog;async handle(e){return cL.has(e.type)?(await this.handleSave(e),!0):!1}async handleSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Fm.safeParse(e.payload);if(!t.success){let i={status:"error",message:`Invalid payload \u2014 ${t.error.issues.slice(0,3).map(a=>`${a.path.join(".")||"(root)"}: ${a.message}`).join("; ")}`};this.deps.log(`[FileHandler] save ${i.status}: ${i.message}`),this.deps.broker.postToWebview(A(this.deps,e,"file:save:response",i));return}let r=t.data,n=await this.saveDialog.save(r.suggestedName,r.content,r.extensions);this.deps.log(`[FileHandler] save ${n.status}`),this.deps.broker.postToWebview(A(this.deps,e,"file:save:response",n))}};var uL=new Set(["reports:list","reports:audit","reports:lineage"]),lL="forge:history",pL="sync:history:all",yE=50;function fL(s){return s.readByObject?s.readByObject.reduce((t,r)=>t+r.read,0):(s.graph?.nodes??[]).reduce((t,r)=>t+(r.recordCount??0),0)}function gL(s){let e=s.graph?.nodes??[];return e.filter(t=>!Pg(t)).length+Cg(s,e).length}var Ou=class{constructor(e){this.deps=e}deps;async handle(e){if(!uL.has(e.type))return!1;switch(e.type){case"reports:list":return this.handleList(e),!0;case"reports:audit":return this.handleAudit(e),!0;case"reports:lineage":return this.handleLineage(e),!0;default:return!1}}handleAudit(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Sw,e,"reports:error",this.deps);if(t===null)return;let r=new $o(this.deps.configStore).list(t??{});this.deps.log(`[ReportsHandler] audit trail: ${r.entries.length} of ${r.total} entries`),this.deps.broker.postToWebview(A(this.deps,e,"reports:audit:response",{...r}))}handleLineage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(kw,e,"reports:error",this.deps);if(t===null)return;let r=new Qh(this.deps.configStore);this.deps.broker.postToWebview(A(this.deps,e,"reports:lineage:response",{lineage:r.get(t?.operationId),runs:r.runs()}))}handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.readLimit(e),r=this.build(t);this.deps.log(`[ReportsHandler] ${r.reports.length} report(s) from stored history (${r.summary.successRate}% success)`),this.deps.broker.postToWebview(A(this.deps,e,"reports:list:response",{...r}))}readLimit(e){let t=e.payload?.limit;return typeof t!="number"||!Number.isFinite(t)||t<=0?yE:Math.min(Math.floor(t),500)}build(e=yE){let t=this.deps.configStore.get(lL)??[],r=this.deps.configStore.get(pL)??[],n=[...t.map(o=>this.forgeReport(o)),...r.map(o=>this.syncReport(o))].sort((o,i)=>i.generatedAt.localeCompare(o.generatedAt)).slice(0,e);return{reports:n,summary:mL(n)}}forgeReport(e){let t=gL(e),r=fL(e);return{id:`forge-${e.forgeId}`,definitionId:`forge-${e.forgeId}`,type:"forge_execution",title:`Forge clone \u2014 ${t} object(s)`,summary:`${e.status} \xB7 ${r} record(s) across ${t} object(s) \xB7 ${e.idRemapCount} id(s) remapped`,sections:[{title:"Outcome",type:"summary",order:0,content:{status:e.status,objects:t,records:r,idRemapCount:e.idRemapCount,durationMs:e.duration}}],metadata:{module:"forge",operationId:e.forgeId,duration:e.duration,recordCount:r},generatedAt:e.timestamp}}syncReport(e){let t=e.result,r=t?.totalProcessed??0,n=t?.totalFailed??0;return{id:`sync-${e.id}`,definitionId:`sync-${e.id}`,type:"sync_execution",title:`Sync \u2014 ${e.configSnapshot?.name??"unnamed configuration"}`,summary:`${t?.status??"unknown"} \xB7 ${r} processed, ${t?.totalSuccess??0} succeeded, ${n} failed \xB7 triggered ${e.triggeredBy}`,sections:[{title:"Outcome",type:"summary",order:0,content:{status:t?.status??"unknown",processed:r,succeeded:t?.totalSuccess??0,failed:n,skipped:t?.totalSkipped??0,triggeredBy:e.triggeredBy}}],metadata:{module:"sync",operationId:e.id,duration:t?.duration,recordCount:r},generatedAt:e.endTime??e.startTime}}};function hL(s){let e=s.sections[0]?.content?.status;return e==="failure"||e==="failed"||e==="partial"}function mL(s){let e=s.length;if(e===0)return{totalOperations:0,successRate:0,avgDuration:0,errorRate:0};let t=s.filter(hL).length,r=s.map(o=>o.metadata.duration??0),n=o=>Math.round(o*10)/10;return{totalOperations:e,successRate:n((e-t)/e*100),avgDuration:Math.round(r.reduce((o,i)=>o+i,0)/e),errorRate:n(t/e*100)}}function wE(s){return Object.values(s).every(e=>e<50)}var Iu=class{deps;constructor(e){this.deps=e}async analyzeOrg(e,t){let r=await this.deps.getConnection(e),n=await this.queryRecordCounts(r),o;if(t){let i=await this.deps.getConnection(t);o=await this.queryRecordCounts(i)}return this.decide(e,n,t,o)}async queryRecordCounts(e){let t=await Promise.all(yg.map(async n=>{try{let o=await e.query(`SELECT COUNT() FROM ${n}`);return{objectName:n,count:o.totalSize}}catch{return{objectName:n,count:0}}})),r={};for(let{objectName:n,count:o}of t)r[n]=o;return r}decide(e,t,r,n){let o=Object.values(t).reduce((u,l)=>u+l,0),i=wE(t),a=n!==void 0&&!wE(n),d="none",c="";return i&&a&&r?(d="clone",c="home.smartAction.reasonClone"):i&&o===0?(d="quick-seed",c="home.smartAction.reasonEmpty"):i?(d="quick-seed",c="home.smartAction.reasonSampleOnly"):a&&r&&(d="sync",c="home.smartAction.reasonSync"),{action:d,reasonKey:c,details:{targetOrgId:e,sourceOrgId:r,recordCounts:t,...n?{sourceRecordCounts:n}:{}}}}};function wL(s,e){return`smart-action:${s}:${e??""}`}var bL=300*1e3,RL=new Set(["smart-action:analyze"]),Au=class{constructor(e){this.deps=e;this.analyzer=new Iu({getConnection:t=>B(t,e.orgRegistry,e.orgManager)})}deps;analyzer;cache=new Map;async handle(e){return RL.has(e.type)&&e.type==="smart-action:analyze"?(await this.handleAnalyze(e),!0):!1}forgetOrg(e){for(let[t,r]of this.cache)r.orgIds.includes(e)&&this.cache.delete(t)}async handleAnalyze(e){let t=x(_w,e,"smart-action:error",this.deps);if(t)try{let r=t.targetOrgId,n=t.sourceOrgId,o=wL(r,n),i=this.cache.get(o);if(i&&Date.now()-i.fetchedAt<bL){this.deps.log(`[SmartAction] Cache hit for ${r}`);let c=A(this.deps,e,"smart-action:analyze:response",{recommendation:i.recommendation});this.deps.broker.postToWebview(c),this.deps.log("[TX] smart-action:analyze:response (cached)");return}this.deps.log(`[SmartAction] Analyzing org ${r}`);let a=await this.analyzer.analyzeOrg(r,n);this.cache.set(o,{recommendation:a,fetchedAt:Date.now(),orgIds:n?[r,n]:[r]});let d=A(this.deps,e,"smart-action:analyze:response",{recommendation:a});this.deps.broker.postToWebview(d),this.deps.log("[TX] smart-action:analyze:response")}catch(r){T(this.deps,"smart-action:analyze","smart-action:error",e,r)}}};var vL=new Set(["execution:abort"]),Tu=class{constructor(e,t){this.deps=e;this.registry=t}deps;registry;async handle(e){return vL.has(e.type)&&e.type==="execution:abort"?(await this.handleAbort(e),!0):!1}async handleAbort(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=x(ww,e,"execution:error",this.deps);if(!t)return;let r=t.operationId??t.executionId??"",n=this.registry.get(r);if(!n&&this.registry.cancelBeforeStart(r)){let i=A(this.deps,e,"execution:abort:response",{success:!0,operationId:r});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} (before it started)`);return}if(!n){let i=A(this.deps,e,"execution:abort:response",{success:!1,error:`Operation not found: ${r}`});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} (not found)`);return}if(n.status!=="running"){let i=A(this.deps,e,"execution:abort:response",{success:!1,error:"Operation already finished",status:n.status});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} (already ${n.status})`);return}this.registry.abort(r);let o=A(this.deps,e,"execution:abort:response",{success:!0,operationId:r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(t){T(this.deps,"execution:abort","execution:error",e,t)}}};import{readFile as SL}from"node:fs/promises";import{join as kL}from"node:path";var ag=new Map;function bE(s,e){let t=kL(s,`${e}.json`),r=ag.get(t);if(r)return r;let n=SL(t,"utf-8").then(o=>JSON.parse(o));return ag.set(t,n),n.catch(()=>ag.delete(t)),n}var OL=new Set(["i18n:locale"]),Eu=class{constructor(e,t){this.deps=e;this.localesDir=t}deps;localesDir;async handle(e){return OL.has(e.type)?(await this.handleLocaleRequest(e),!0):!1}async handleLocaleRequest(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Fw,e,"i18n:locale:response",this.deps);if(!t)return;let{lng:r}=t;if(!this.localesDir){let n=A(this.deps,e,"i18n:locale:response",{lng:r,error:"Locale files are not available in this extension host."});this.deps.broker.replyToRequester(n);return}try{let n=await bE(this.localesDir,r),o=A(this.deps,e,"i18n:locale:response",{lng:r,bundle:n});this.deps.broker.replyToRequester(o),this.deps.log(`[TX] i18n:locale:response (${r})`)}catch(n){this.deps.log(`[ERR] i18n:locale (${r}): ${I(n)}`);let o=A(this.deps,e,"i18n:locale:response",{lng:r,error:I(n)});this.deps.broker.replyToRequester(o)}}};import{AsyncLocalStorage as IL}from"node:async_hooks";function vE(s,e){if(!s)return{decision:"refused",reason:"no Production Guard runs in this window"};let t=s.check(e);return t.allowed?t.requiresConfirmation?{decision:"asks"}:{decision:"allowed"}:{decision:"refused",reason:t.blockedReason??t.impactSummary}}var RE=new IL;async function SE(s,e,t,r){let n=Symbol("pipeline sync"),o,i=s.registry?.onEvent((d,c,u)=>{c!=="started"||u.module!=="sync"||RE.getStore()!==n||(o=d,r?.aborted&&s.registry?.abort(d))}),a=()=>{o!==void 0&&s.registry?.abort(o)};r?.addEventListener("abort",a,{once:!0});try{let d=await RE.run(n,()=>ja(t,()=>s.execute(e)));return o!==void 0?{...d,operationId:o}:d}finally{i?.(),r?.removeEventListener("abort",a)}}var AL=K({setting:L().regex(/^sandforge(?:\.[A-Za-z][A-Za-z0-9]*)+$/)}),Pu=class{handlerDeps;executeCommand;showLog;panelRouteListener;panelReloadListener;idCounter=0;orgHandler;settingsHandler;monitorHandler;seedHandler;seedCloneHandler;seedCsvHandler;syncHandler;syncHistoryHandler;syncRemovalHandler;seedRemovalHandler;compareHandler;dataOpsHandler;complianceHandler;templateHandler;cleanupHandler;emptyHandler;verifyHandler;automationHandler;aiHandler;autopilotHandler;forgeHandler;frozenHandler;checkpointHandler;migrationHandler;configHandler;governanceHandler;quickSyncHandler;syncScheduleHandler;realtimeHandler;fileHandler;reportsHandler;smartActionHandler;i18nHandler;syncHistoryStore;executionHandler;backgroundRegistry;refreshDetector;recoveryProgressSource;recoveryHandler;checkpointStore;beforeRunCheckpoints;constructor(e){this.executeCommand=e.executeCommand??(()=>Promise.resolve()),this.showLog=e.showLog??(()=>{}),this.refreshDetector=new Dd({configStore:e.configStore,orgManager:e.orgManager,log:e.log}),this.recoveryProgressSource=WS({refreshesOf:r=>this.refreshDetector.refreshesOf(r),organizationIdOf:r=>this.refreshDetector.organizationIdOf(r),orgOf:r=>e.orgManager.getOrg(r),configStore:e.configStore,statusOf:r=>this.recoveryHandler.progressCountOf(r),log:e.log}),this.handlerDeps={log:e.log,broker:e.broker,stateSync:e.stateSync,orgManager:e.orgManager,orgRegistry:e.orgRegistry,configStore:e.configStore,secretVault:e.secretVault,authProvider:e.authProvider,sfdxBridge:e.sfdxBridge,services:e.services,robustness:Ku,bulkManager:new Yh(Ku.bulk.maxConcurrentJobs),nextId:()=>this.nextId(),sandboxRefreshes:this.refreshDetector,recoveryProgress:this.recoveryProgressSource},this.orgHandler=new Ld(this.handlerDeps),this.recoveryHandler=new Nd(this.handlerDeps),this.settingsHandler=new Fd(this.handlerDeps),this.monitorHandler=new Yd(this.handlerDeps),this.seedHandler=new tc(this.handlerDeps),this.seedCloneHandler=new sc(this.handlerDeps),this.seedCsvHandler=new dc(this.handlerDeps),this.seedRemovalHandler=new gc(this.handlerDeps,void 0,r=>this.seedHandler.isRunning(r)||this.seedCsvHandler.isRunning(r)||this.seedCloneHandler.isRunning(r)),this.syncHandler=new lc(this.handlerDeps),this.syncHistoryStore=new mc(e.configStore),this.syncHandler.setHistoryLogger(new yc(this.syncHistoryStore)),this.syncHistoryHandler=new pc(this.handlerDeps,this.syncHistoryStore,this.syncHandler),this.syncRemovalHandler=new fc(this.handlerDeps,this.syncHistoryStore,r=>this.syncHandler.isRunning(r)||this.realtimeHandler.isRunning(r)),this.compareHandler=new wc(this.handlerDeps),this.dataOpsHandler=new hR(this.handlerDeps),this.complianceHandler=new Sc(this.handlerDeps),this.templateHandler=new JS(this.handlerDeps),this.cleanupHandler=new kc(this.handlerDeps),this.emptyHandler=new Fc(this.handlerDeps),this.verifyHandler=new VS(this.handlerDeps),this.automationHandler=new Hc(this.handlerDeps),this.aiHandler=new Gc(this.handlerDeps),this.autopilotHandler=new Vc(this.handlerDeps),this.forgeHandler=new eu(this.handlerDeps),this.frozenHandler=new ZS(this.handlerDeps),this.frozenHandler.setSaltKeeper(QS(e.secretVault));let t=()=>[this.forgeHandler,this.frozenHandler,this.dataOpsHandler,this.complianceHandler,this.emptyHandler,this.autopilotHandler,this.realtimeHandler];this.checkpointHandler=new Pd(this.handlerDeps,{isRunning:r=>this.syncHandler.isRunning(r)||this.seedHandler.isRunning(r)||this.seedCsvHandler.isRunning(r)||this.seedCloneHandler.isRunning(r),writingTo:(r,n)=>t().some(o=>o.isWritingTo(r,n))}),this.beforeRunCheckpoints={scope:(r,n)=>this.checkpointHandler.scopeBeforeRun(r,n),take:(r,n,o)=>this.checkpointHandler.takeBeforeRun(r,n,o),settle:(r,n)=>this.checkpointHandler.settleBeforeRun(r,n)},this.forgeHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.autopilotHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.frozenHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.syncHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.seedHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.seedCsvHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.seedCloneHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.emptyHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.emptyHandler.setRunWriting((r,n,o)=>this.checkpointHandler.writingTo(r,n,"empty it","Nothing was deleted.",{operationId:o})),this.forgeHandler.setOtherModuleRuns(this.otherModuleRuns("forge",t)),this.syncRemovalHandler.setOtherModuleRuns(this.otherModuleRuns("sync",t)),this.seedRemovalHandler.setOtherModuleRuns(this.otherModuleRuns("seed",t)),this.frozenHandler.setOtherModuleRuns(this.otherModuleRuns("frozen",t)),this.migrationHandler=new tu(this.handlerDeps),this.configHandler=new ou(this.handlerDeps),this.governanceHandler=new au(this.handlerDeps,this.monitorHandler.getAlertEngine()),this.quickSyncHandler=new pu(this.handlerDeps),this.syncScheduleHandler=new hu(this.handlerDeps),this.realtimeHandler=new Su(this.handlerDeps),this.fileHandler=new ku(this.handlerDeps),this.reportsHandler=new Ou(this.handlerDeps),this.smartActionHandler=new Au(this.handlerDeps),this.i18nHandler=new Eu(this.handlerDeps,e.localesDir),this.automationHandler.setStepRunners({orgName:r=>{let n=e.orgManager.getOrg(r);return n?we(n,n.id):void 0},newId:()=>crypto.randomUUID(),backup:(r,n)=>this.dataOpsHandler.backupForPipeline(r,n),compare:(r,n)=>this.compareHandler.compareOrgs(r,n),readOrgHealth:(r,n)=>this.monitorHandler.readOrgHealth(r,n),notify:e.services?.showNotification,savedSyncConfig:r=>new Pt(e.configStore).load(r),listSyncConfigs:()=>new Pt(e.configStore).list(),syncGuard:r=>vE(this.handlerDeps.infraServices?.productionGuard,gf(r,e.orgManager.getOrg(r.targetOrgId))),runSync:(r,n,o)=>SE({execute:i=>this.syncHandler.executeScheduled(i,"pipeline"),registry:this.backgroundRegistry},r,n,o),orgTier:r=>{let n=e.orgManager.getOrg(r);return n?Pe(n):void 0},organizationIdsOf:r=>[e.orgManager.getOrg(r)?.orgId,this.refreshDetector.organizationIdOf(r)].filter(n=>typeof n=="string"&&n!==""),savedSeedTemplate:r=>new dn(e.configStore).load(r),listSeedTemplates:()=>new dn(e.configStore).list(),seed:(r,n)=>this.seedHandler.seedForPipeline(r,n),maskingTemplates:()=>[...em.map(r=>({...r,builtIn:!0})),...new Na(e.configStore).list().map(r=>({...r,builtIn:!1}))],anonymize:(r,n)=>this.dataOpsHandler.anonymizeForPipeline(r,n),verifyMasking:(r,n)=>this.verifyHandler.verify(r,n),takeCheckpoint:(r,n)=>this.checkpointHandler.takeForPipeline(r,n),rewind:(r,n)=>this.checkpointHandler.rewindForPipeline(r,n),readCheckpoint:r=>this.readCheckpointForRewind(r),...e.services?.runsFrom?{ranFrom:e.services.runsFrom}:{},simulateSync:(r,n)=>this.syncHandler.simulateForPipeline(r,n),previewSeed:(r,n)=>this.seedHandler.previewForPipeline(r,n),previewMasking:(r,n)=>this.dataOpsHandler.previewMaskingForPipeline(r,n),estimateTake:(r,n)=>this.checkpointHandler.estimateTakeForPipeline(r,n),previewRewind:(r,n)=>this.checkpointHandler.previewRewindForPipeline(r,n)}),this.automationHandler.setDryRunApplier(dO),this.checkpointHandler.onCheckpointsChanged(()=>{this.automationHandler.revokeVoidGrants()}),this.recoveryHandler.onStatusChanged(r=>this.recoveryProgressSource.invalidate(r)),this.checkpointHandler.onCheckpointsChanged(()=>this.recoveryProgressSource.invalidate()),this.refreshDetector.onRefreshDetected(r=>this.forgetOrg(r.orgId)),this.refreshDetector.onRefreshDetected(r=>{let n=r.previousOrganizationId??this.refreshDetector.organizationIdOf(r.orgId)??r.detectedAt;Promise.resolve().then(()=>this.automationHandler.noticeSandboxRefresh({orgId:r.orgId,key:n}))}),this.refreshDetector.onRefreshDetected(r=>this.recoveryProgressSource.invalidate(r.orgId))}get sandboxRefreshes(){return this.refreshDetector}get recoveryProgress(){return this.recoveryProgressSource}postSettings(){this.settingsHandler.postSettings()}forgetOrg(e){Po().remove(e),uO(e),this.monitorHandler.forgetOrg(e),this.forgeHandler.forgetOrg(e),this.frozenHandler.forgetOrg(e),this.aiHandler.forgetOrg(e),this.smartActionHandler.forgetOrg(e),this.realtimeHandler.forgetOrg(e),this.handlerDeps.log(`[sandbox-refresh] dropped what was cached about ${e}`)}setLiveOperationTracker(e){this.monitorHandler.setLiveOperationTracker(e),this.seedHandler.setLiveOperationTracker(e),this.syncHandler.setLiveOperationTracker(e),this.syncRemovalHandler.setLiveOperationTracker(e),this.seedRemovalHandler.setLiveOperationTracker(e),this.forgeHandler.setLiveOperationTracker(e),this.seedCloneHandler.setLiveOperationTracker(e),this.seedCsvHandler.setLiveOperationTracker(e),this.frozenHandler.setLiveOperationTracker(e),this.autopilotHandler.setLiveOperationTracker(e),this.checkpointHandler.setLiveOperationTracker(e),this.dataOpsHandler.setLiveOperationTracker(e),this.cleanupHandler.setLiveOperationTracker(e),this.emptyHandler.setLiveOperationTracker(e),this.complianceHandler.setLiveOperationTracker(e),this.automationHandler.setLiveOperationTracker(e),this.realtimeHandler.setLiveOperationTracker(e)}setBackupRecordStore(e){this.dataOpsHandler.setBackupRecordStore(e),this.dataOpsHandler.setRunKeyStore(oR(this.handlerDeps.secretVault)),this.syncHandler.setBackupRecordStore(e),this.syncRemovalHandler.setBackupRecordStore(e),this.realtimeHandler.setBackupRecordStore(e),this.verifyHandler.setBackupRecordStore(e)}otherModuleRuns(e,t){return async(r,n)=>{let o=e==="forge"?this.forgeHandler:e==="frozen"?this.frozenHandler:void 0,i=new $o(this.handlerDeps.configStore).list({orgId:r,limit:Ag}).entries,a=[...e==="forge"?[]:await this.forgeHandler.localRunsOn(r,n),...e==="sync"?[]:await this.syncRemovalHandler.localRunsOn(r),...e==="seed"?[]:await this.seedRemovalHandler.localRunsOn(r),...sS(i,e==="frozen"?"frozen_load":void 0)];if(t().some(d=>d!==o&&d.isWritingTo(r))){let d=Date.now();a.push({ids:[],idsUntold:!0,from:d,to:d})}return a}}setSyncRunCreations(e){this.syncHandler.setRunCreations(e),this.syncRemovalHandler.setRunCreations(e),this.realtimeHandler.setRunCreations(e),this.dataOpsHandler.setSyncRuns(e),this.checkpointHandler.setRunFiles("sync",e)}setSeedRunCreations(e){this.seedHandler.setRunCreations(e),this.seedCsvHandler.setRunCreations(e),this.seedCloneHandler.setRunCreations(e),this.seedRemovalHandler.setRunCreations(e),this.checkpointHandler.setRunFiles("seed",e)}sweepCheckpoints(){return this.checkpointHandler.sweep()}setCheckpointStore(e){this.checkpointStore=e,this.checkpointHandler.setStore(e),this.recoveryHandler.setCheckpointStore(e)}async readCheckpointForRewind(e){let{openCheckpointStore:t,defaultCheckpointStoreRoot:r}=await import("./chunk-YGTOX7IL.mjs"),n=this.checkpointStore;if(!n){let d=t({root:r()});if(!("store"in d))throw new Error(`The checkpoints of this machine cannot be read: ${d.refusal.reason}`);n=d.store}let o=await n.read(e);if(o===void 0)return{kept:!1};if(o.checkpoint===void 0)return{kept:!0,valid:!1,why:"damaged"};let{organizationId:i}=o.checkpoint.org,a=(await n.list({organizationId:i,refreshedAt:d=>this.refreshedAtOf(d)})).find(d=>d.checkpointId===e);return{kept:!0,organizationId:i,name:o.checkpoint.name,valid:a?.valid??!1,...a?.why!==void 0?{why:a.why}:{}}}refreshedAtOf(e){let t=r=>r!==void 0&&r.length>=15&&r.slice(0,15)===e.slice(0,15);for(let r of this.handlerDeps.orgManager.getAllOrgs())for(let n of this.refreshDetector.refreshesOf(r.id)){let o=n.previousOrganizationId??(n.organizationId===void 0?this.refreshDetector.organizationIdOf(r.id):void 0);if(t(o))return n.detectedAt}}setEmptyStores(e){this.emptyHandler.setStores(e)}rewindCheckpointsFromPreviewsAnswered(){this.checkpointHandler.rewindFromPreviewsAnswered()}exportCheckpoint(e){return this.checkpointHandler.exportCheckpoint(e)}readCheckpointImport(e){return this.checkpointHandler.readImport(e)}importCheckpoint(e){return this.checkpointHandler.importCheckpoint(e)}checkpointsKeptBefore(e){return this.checkpointHandler.keptBefore(e)}latestCheckpointOf(e){return this.checkpointHandler.latestUsableOf(e)}onCheckpointsChanged(e){return this.checkpointHandler.onCheckpointsChanged(e)}setPanelRouteListener(e){this.panelRouteListener=e}setPanelReloadListener(e){this.panelReloadListener=e}setAIAssistant(e){this.aiHandler.setAIAssistant(e)}setInfraServices(e){this.handlerDeps.infraServices=e}setOrgSelectionCallback(e){this.handlerDeps.onOrgSelected=e}setBackgroundRegistry(e){this.backgroundRegistry=e,this.syncHandler.setRegistry(e),this.syncRemovalHandler.setRegistry(e),this.seedRemovalHandler.setRegistry(e),this.seedHandler.setRegistry(e),this.seedCloneHandler.setRegistry(e),this.seedCsvHandler.setRegistry(e),this.frozenHandler.setRegistry(e),this.realtimeHandler.setRegistry(e),this.autopilotHandler.setRegistry(e),this.executionHandler=new Tu(this.handlerDeps,e)}async replayQueuedOperation(e){let t=Rn("offline-replay",e.id,`${e.type}:execute`);switch(e.type){case"sync":await this.syncHandler.rerunFromSnapshot(t,e.payload.config);return;case"seed":{let r={...t,payload:e.payload};await this.seedHandler.handle(r);return}default:throw new Error(`Unsupported queued operation type: ${e.type}`)}}startSyncScheduler(e){this.syncScheduleHandler.startScheduler(t=>this.syncHandler.executeScheduled(t),e)}stopSyncScheduler(){this.syncScheduleHandler.stopScheduler()}stopLiveOperationsPush(){this.monitorHandler.dispose()}async stopRealtime(){await this.realtimeHandler.dispose()}startPipelineTriggers(e){this.automationHandler.startTriggers(e)}stopPipelineTriggers(){this.automationHandler.stopTriggers()}setAIModules(e){this.aiHandler.setAIModules(e),this.handlerDeps.errorResolver=e?.errorResolver}setRuleModules(e){this.aiHandler.setRuleModules(e)}setMigrationServices(e){this.migrationHandler.setFileReader(e)}setPipelineMarketplace(e){this.automationHandler.setPipelineMarketplace(e)}setAutopilotOrchestrator(e){this.autopilotHandler.setOrchestrator(e)}sweepForgePlans(){return this.forgeHandler.sweepSimulationPlans()}setForgeOrchestrator(e,t){this.forgeHandler.setForgeOrchestrator(e,t)}registerAll(e){let t=(r,n)=>{for(let o of r)e.route(o,async i=>{await n.handle(i)})};t(["org:list","org:connect","org:connect:cancel","org:disconnect","org:select","org:update","org:open-in-browser","org:cli-status","org:assign-right"],this.orgHandler),t(["settings:get","settings:update","telemetry:status","telemetry:toggle","anonymization:mode:ask"],this.settingsHandler),t(["i18n:locale"],this.i18nHandler),t(["seed:execute","seed:automation","seed:describe-global","seed:describe-object","seed:template:save","seed:template:load","seed:template:list","seed:template:delete","seed:list-personas","seed:create-persona","seed:scenario:packs","seed:scenario:prepare","seed:scenario:execute","seed:scenario:agents","seed:scenario:save","seed:scenario:test-file"],this.seedHandler),t(["seed:clone:describe-source","seed:clone:preview","seed:clone:execute"],this.seedCloneHandler),t(["seed:csv:validate","seed:csv:execute"],this.seedCsvHandler),t(["sync:execute","sync:simulate","sync:write-order","sync:pause","sync:resume","sync:describe-global","sync:describe-fields","sync:config:save","sync:config:load","sync:config:list","sync:config:delete","sync:config:reset-delta"],this.syncHandler),t(["sync:history:list","sync:history:detail","sync:history:rerun","sync:history:export"],this.syncHistoryHandler),t(["sync:removal:info","sync:removal:list","sync:remove","sync:remove:sweep","sync:remove:automation","sync:earlier-copies"],this.syncRemovalHandler),t(["seed:removal:info","seed:removal:list","seed:remove","seed:remove:sweep","seed:remove:automation","seed:open-record"],this.seedRemovalHandler),t(["sync:schedule:list","sync:schedule:upsert","sync:schedule:toggle","sync:schedule:delete"],this.syncScheduleHandler),t(["quicksync:suggest-objects","quicksync:detect-relationships","quicksync:preview","quicksync:execute"],this.quickSyncHandler),t(["monitor:refresh","monitor:open-apex-jobs","monitor:live-operations","monitor:storage","monitor:deployments","monitor:api-usage","monitor:error-logs","monitor:sessions","monitor:apex-insights","monitor:sandbox-refresh","monitor:alerts","monitor:alert:acknowledge","monitor:alert:dismiss"],this.monitorHandler),t(["governance:policies:list","governance:policy:save","governance:policy:delete","governance:evaluate","governance:templates"],this.governanceHandler),t(["compare:execute","compare:permissions","compare:snapshots","compare:drift","compare:validate-deployment","compare:deploy"],this.compareHandler),t(["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"],this.dataOpsHandler),t(["dataops:anonymize:gaps","dataops:anonymization-template:import"],this.templateHandler),t(["dataops:pii-inventory","dataops:dsr:search","dataops:dsr:export","dataops:dsr:erase","dataops:dsr:log"],this.complianceHandler),t(["dataops:cleanup:scan","dataops:cleanup:export","dataops:cleanup:delete"],this.cleanupHandler),t(["dataops:empty:scope","dataops:empty:preview","dataops:empty:run","dataops:empty:cancel","dataops:empty:undo"],this.emptyHandler),t(["dataops:anonymize:verify","dataops:anonymize:verify:export","dataops:anonymize:verify:open"],this.verifyHandler),t(["pipeline:execute","pipeline:templates","pipeline:list","pipeline:history","pipeline:save","pipeline:delete","pipeline:approval","pipeline:sync-configs","pipeline:seed-templates","pipeline:masking-templates","pipeline:rewind-steps","pipeline:rewind-grant","pipeline:rewind-revoke","pipeline:export","marketplace:list","marketplace:install"],this.automationHandler),t(["ai:chat","ai:chat:cancel","ai:conversation:create","ai:conversation:load","ai:conversation:list","ai:conversation:delete","ai:conversation:delete-all","ai:status","ai:save-key","ai:settings","ai:remove-key","ai:tool:cancel","ai:forge-plan","ai:anomaly-scan","ai:generate-pipeline","ai:scenario-draft"],this.aiHandler),t(["autopilot:list-objects","autopilot:count-objects","autopilot:scan-schema","autopilot:generate-plan","autopilot:fit-plan","autopilot:fit-undo","autopilot:execute","autopilot:pause","autopilot:resume","autopilot:skip-node","autopilot:compliance-report"],this.autopilotHandler),t(["forge:preview","forge:discover","forge:execute","forge:pause","forge:resume","forge:abort","forge:templates:list","forge:templates:save","forge:templates:delete","forge:history:list","forge:undo","forge:resume-run","forge:open-record","forge:verify:request","forge:export-ids:request","forge:plan:request","forge:classification:request","forge:compliance:request","forge:metadata-diff:request","forge:rehearse:request","forge:automation:request","forge:undo-automation:request","forge:undo-sweep:request","forge:gaps:request","forge:users:request","forge:target-records:request","forge:sample-budget:request","forge:previewRoots"],this.forgeHandler),t(["frozen:config:get","frozen:config:save","frozen:select","frozen:extract","frozen:load","frozen:load:preview","frozen:verify","frozen:remove","frozen:remove:sweep","frozen:remove:automation","frozen:remove:preview","frozen:status","frozen:rules:clear","frozen:rules:create"],this.frozenHandler),t(["checkpoint:list","checkpoint:scope","checkpoint:take","checkpoint:preview","checkpoint:plan-selection","checkpoint:rewind","checkpoint:undo","checkpoint:delete","checkpoint:keep","checkpoint:rename","checkpoint:ignore-fields","checkpoint:rewinds","checkpoint:export","checkpoint:import-read","checkpoint:import"],this.checkpointHandler),t(["recovery:status","recovery:users:list","recovery:users:plan","recovery:users:apply","recovery:users:cancel","recovery:users:config:save","recovery:users:config:export","recovery:users:config:import","recovery:audit","recovery:handoff","recovery:handoff:open","recovery:ack"],this.recoveryHandler),t(["migration:pick-file","migration:import-sfdmu","migration:save-sync-config"],this.migrationHandler),t(["config:export","config:import","config:categories","config:validate"],this.configHandler),t(["smart-action:analyze"],this.smartActionHandler),t(["file:save"],this.fileHandler),t(["reports:list","reports:audit","reports:lineage"],this.reportsHandler),this.executionHandler&&t(["execution:abort"],this.executionHandler),t(["realtime:objects","realtime:start","realtime:stop","realtime:status","realtime:metrics","realtime:resolve-conflict"],this.realtimeHandler),e.route("panel:route",r=>{this.panelRouteListener?.(r)}),e.route("panel:reload",r=>{this.panelReloadListener?.(r)}),e.route("workbench:reload",()=>{this.executeCommand("workbench.action.reloadWindow")}),e.route("workbench:open-setting",r=>{let n=AL.safeParse(r.payload);if(!n.success){this.handlerDeps.log("[WARN] workbench:open-setting: not a SandForge setting id");return}this.executeCommand("workbench.action.openSettings",n.data.setting)}),e.route("workbench:open-log",()=>{this.showLog()}),e.route("error:boundary",r=>{let{payload:n}=r;this.handlerDeps.log(`[ERR] Webview crash (error:boundary): ${n?.message??"unknown error"}`+(n?.stack?`
20
+ ${n.stack}`:""))})}nextId(){return`ext-${++this.idCounter}`}};var Cu=class{maxActions;windowMs;nowFn;timestamps=[];constructor(e,t,r=Date.now){this.maxActions=Math.max(1,e),this.windowMs=Math.max(100,t),this.nowFn=r}tryAcquire(){let e=this.nowFn();return this.pruneExpired(e),this.timestamps.length>=this.maxActions?!1:(this.timestamps.push(e),!0)}get remaining(){return this.pruneExpired(this.nowFn()),Math.max(0,this.maxActions-this.timestamps.length)}reset(){this.timestamps=[]}pruneExpired(e){let t=e-this.windowMs,r=0;for(;r<this.timestamps.length&&this.timestamps[r]<=t;)r++;r>0&&(this.timestamps=this.timestamps.slice(r))}};var TL=100,EL=1e3,PL=3,CL=1e3;function $L(s){return typeof s=="object"&&s!==null&&"protocolVersion"in s&&"payload"in s&&typeof s.payload=="object"}var kE=500;function xL(s){let e=s.map(t=>`${t.path.map(String).join(".")}: ${t.message}`).join("; ");return e.length<=kE?e:`${e.slice(0,kE)}\u2026(+${s.length} issues)`}var xu=class{handlers=new Map;panels=new Set;rateLimiter;telemetry;fixSuggestionNotifier;mismatchCount=0;webviewSeen=!1;firstWebviewCallbacks=[];senders=new Map;constructor(e){this.rateLimiter=new Cu(e?.rateLimitMax??TL,e?.rateLimitWindowMs??EL),this.telemetry=e?.telemetry,this.fixSuggestionNotifier=e?.showFixSuggestion}registerPanel(e,{inbound:t=!0}={}){this.panels.add(e);let r=t?e.webview.onDidReceiveMessage(n=>{this.dispatch(n,e)}):void 0;if(!this.webviewSeen){this.webviewSeen=!0;for(let n of this.firstWebviewCallbacks.splice(0))this.runFirstWebview(n)}return{dispose:()=>{this.panels.delete(e),r?.dispose();for(let[n,o]of this.senders)o===e&&this.senders.delete(n)}}}onFirstWebview(e){if(this.webviewSeen){this.runFirstWebview(e);return}this.firstWebviewCallbacks.push(e)}runFirstWebview(e){try{e()}catch(t){this.logError("first webview",t)}}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>{this.handlers.get(e)?.delete(t)}}postToWebview(e){for(let t of this.panels)t.webview.postMessage(e)}replyToRequester(e){let t=typeof e.correlationId=="string"?this.senders.get(e.correlationId):void 0;if(t&&this.panels.has(t)){t.webview.postMessage(e);return}this.postToWebview(e)}get panelCount(){return this.panels.size}showFixSuggestion(e){this.fixSuggestionNotifier?.(e)}dispose(){this.handlers.clear(),this.panels.clear(),this.firstWebviewCallbacks=[],this.senders.clear()}logFn;setLogFunction(e){this.logFn=e}logError(e,t){let r=I(t);this.logFn?.(`[MessageBroker] Handler error for "${e}": ${r}`)}warn(e,t){try{this.telemetry?.addBreadcrumb(e,"bridge","warning"),this.telemetry?.getLogger?.()?.warn?.(t??{},e)}catch{}}dispatch(e,t){if(!$L(e)){this.logFn?.("[MessageBroker] Received malformed message: not an envelope");return}let r=kg.safeParse(e);if(!r.success){let o=xL(r.error.issues);this.logFn?.(`[MessageBroker] Invalid enveloped payload: ${o}`),this.warn("bridge invalid payload",{issues:o});let i=e.payload,a=typeof i?.id=="string"?i.id:void 0;this.postBridgeError("invalid-payload",o,a);return}let n=r.data;wg(n.protocolVersion)?this.mismatchCount=0:(this.mismatchCount++,this.warn("bridge protocol mismatch",{serverVersion:1,clientVersion:n.protocolVersion,count:this.mismatchCount}),this.postBridgeMismatch(n.protocolVersion),this.mismatchCount>=PL&&this.postBridgeReloadBanner()),t&&this.rememberSender(n.payload.id,t),this.continueDispatch(n.payload)}rememberSender(e,t){if(this.senders.delete(e),this.senders.set(e,t),this.senders.size>CL){let r=this.senders.keys().next().value;r!==void 0&&this.senders.delete(r)}}continueDispatch(e){if(!this.rateLimiter.tryAcquire()){this.logFn?.(`[MessageBroker] Rate limited: dropping message of type "${e.type}"`),this.postBridgeError("rate-limited",`"${e.type}" was dropped`,e.id);return}let t=this.handlers.get(e.type);if(!t){this.logFn?.(`[MessageBroker] Unhandled message type: "${e.type}"`),this.postBridgeError("unhandled-type",`no handler for "${e.type}"`,e.id);return}for(let r of t)try{let n=r(e);n&&typeof n.catch=="function"&&n.catch(o=>{this.logError(e.type,o)})}catch(n){this.logError(e.type,n)}}nextControlId(){return`bridge-${globalThis.crypto.randomUUID()}`}postBridgeError(e,t,r){this.postToWebview({id:this.nextControlId(),type:"bridge:error",timestamp:Date.now(),...r?{correlationId:r}:{},payload:{reason:e,details:t}})}postBridgeMismatch(e){this.postToWebview({id:this.nextControlId(),type:"bridge:protocol-mismatch",timestamp:Date.now(),payload:{serverVersion:1,clientVersion:e}})}postBridgeReloadBanner(){this.postToWebview({id:this.nextControlId(),type:"bridge:reload-banner",timestamp:Date.now(),payload:{reason:"protocol-mismatch"}})}};var Du=class{constructor(e){this.broker=e}broker;disposers=[];route(e,t){let r=this.broker.on(e,n=>t(Object.freeze(n)));this.disposers.push(r)}routePrefix(e,t,r){for(let n of t)n.startsWith(e)&&this.route(n,r)}routeAll(e){for(let[t,r]of Object.entries(e))this.route(t,r)}get routeCount(){return this.disposers.length}dispose(){for(let e of this.disposers)e();this.disposers=[]}};var Nu=class{constructor(e){this.broker=e}broker;state={orgs:[],settings:{},activeOperations:[],extensionReady:!1,selectedOrgId:null};idCounter=0;pushTimer;disposed=!1;updateState(e){this.state={...this.state,...e},!this.pushTimer&&!this.disposed&&(this.pushTimer=setTimeout(()=>{this.pushTimer=void 0,this.pushState()},16))}setActiveOperations(e){this.updateState({activeOperations:e})}getState(){return this.state}pushState(){let e={id:`state-sync-${++this.idCounter}`,type:"state:sync",timestamp:Date.now(),payload:{...this.state}};this.broker.postToWebview(e)}dispose(){this.disposed=!0,this.pushTimer&&(clearTimeout(this.pushTimer),this.pushTimer=void 0)}reset(){this.pushTimer&&(clearTimeout(this.pushTimer),this.pushTimer=void 0),this.state={orgs:[],settings:{},activeOperations:[],extensionReady:!1,selectedOrgId:null}}};var ju=class{storage;prefix;logWarning;constructor(e,t="sandforge",r){this.storage=e,this.prefix=t,this.logWarning=r}async storeSecret(e,t){await this.storage.store(this.prefixKey(e),t)}async getSecret(e){return this.storage.get(this.prefixKey(e))}async deleteSecret(e){await this.storage.delete(this.prefixKey(e))}async storeObject(e,t){await this.storeSecret(e,JSON.stringify(t))}async getObject(e){let t=await this.getSecret(e);if(t)try{return JSON.parse(t)}catch(r){let n=I(r);this.logWarning?.(`[SecretVault] Failed to parse JSON for key "${e}": ${n}`);return}}async hasSecret(e){return await this.storage.get(this.prefixKey(e))!==void 0}prefixKey(e){return`${this.prefix}.${e}`}};var Mu=class{orgs=new Map;listeners=new Set;onOrgChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}offOrgChange(e){this.listeners.delete(e)}emit(e){for(let t of this.listeners)try{t(e)}catch(r){ie.warn("OrgManager listener threw",{error:I(r)})}}addOrg(e){let t=this.orgs.has(e.id);this.orgs.set(e.id,e),this.emit({type:t?"updated":"added",orgId:e.id,org:e})}removeOrg(e){let t=this.orgs.delete(e);return t&&this.emit({type:"removed",orgId:e}),t}getOrg(e){return this.orgs.get(e)}getAllOrgs(){return Array.from(this.orgs.values())}updateStatus(e,t){let r=this.orgs.get(e);if(!r)return!1;let n={...r,status:t};return this.orgs.set(e,n),this.emit({type:"statusChanged",orgId:e,org:n}),!0}findByTag(e){return this.getAllOrgs().filter(t=>t.tags.includes(e))}get connectedCount(){return this.getAllOrgs().filter(e=>e.status==="connected").length}clear(){let e=Array.from(this.orgs.keys());this.orgs.clear();for(let t of e)this.emit({type:"removed",orgId:t})}dispose(){this.listeners.clear(),this.orgs.clear()}};var vs="org.",Lu="org-cred.",dg="orgs",OE=1e4;function DL(s){let e={...s,tags:Array.isArray(s.tags)?s.tags:[],appearance:{color:s.appearance?.color??"#4a9eff",icon:s.appearance?.icon??"cloud",position:s.appearance?.position??0}};return NL(e)}function NL(s){if(s.orgType===Ki(s.orgType,s.metadata?.edition))return s;let{safetyTier:e,color:t}=Br("Developer");return{...s,orgType:"Developer",safetyTier:e,appearance:{...s.appearance,color:s.appearance.color===rl?t:s.appearance.color}}}var Fu=class{constructor(e,t,r){this.configStore=e;this.secretVault=t;this.orgManager=r}configStore;secretVault;orgManager;loadAll(){let e=this.configStore.getByCategory(dg),t=new Map,r=[];for(let[n,o]of Object.entries(e)){if(!n.startsWith(vs))continue;let i=DL(o),a=i.orgId??i.id,d=n.slice(vs.length),c=t.get(a);if(!c){t.set(a,{key:n,org:i});continue}d===a?(r.push(c.key),t.set(a,{key:n,org:i})):r.push(n)}for(let n of r){this.configStore.delete(n);let o=n.slice(vs.length);this.secretVault.deleteSecret(`${Lu}${o}`).catch(()=>{}),this.orgManager.removeOrg(o),ie.warn("Pruned duplicate org entry (same orgId as a canonical entry)",{key:n})}for(let{org:n}of t.values())this.orgManager.addOrg(n)}async saveOrg(e,t){let r=`${vs}${e.id}`,n=this.configStore.get(r),i=n!==void 0&&Pe(n)==="production"&&Io(e)&&n.appearance?.color===rl?void 0:n?.appearance?.color,a=n?{...e,alias:n.alias??e.alias,appearance:{...e.appearance,color:i??e.appearance.color,icon:n.appearance?.icon??e.appearance.icon},tags:n.tags??e.tags,...n.staging!==void 0?{staging:n.staging}:{},...e.organizationName===void 0&&n.organizationName!==void 0?{organizationName:n.organizationName}:{}}:e;this.configStore.set(r,a,dg),this.orgManager.addOrg(a),t&&await this.secretVault.storeObject(`${Lu}${e.id}`,t)}async removeOrg(e){this.configStore.delete(`${vs}${e}`),await this.secretVault.deleteSecret(`${Lu}${e}`),this.orgManager.removeOrg(e)}async getCredentials(e){let t=this.secretVault.getObject(`${Lu}${e}`);t.catch(()=>{});let r;try{return await Promise.race([t,new Promise((n,o)=>{r=setTimeout(()=>{o(new Error(`Secret storage did not answer within ${OE} ms for org "${e}" \u2014 the OS keyring may be locked or unavailable.`))},OE)})])}finally{r!==void 0&&clearTimeout(r)}}updateOrgMetadata(e){this.configStore.set(`${vs}${e.id}`,e,dg),this.orgManager.addOrg(e)}};import{mkdtemp as jL,readFile as ML,rm as LL}from"node:fs/promises";import{tmpdir as FL}from"node:os";import{join as cg}from"node:path";async function IE(s){let e=await jL(cg(FL(),"sandforge-sf-"));try{let t={stdout:cg(e,"stdout.json"),stderr:cg(e,"stderr.txt")},r;try{await s(t)}catch(o){r=o}let n=o=>ML(o,"utf8").catch(()=>"");return{stdout:await n(t.stdout),stderr:await n(t.stderr),...r!==void 0?{failure:r}:{}}}finally{await LL(e,{recursive:!0,force:!0}).catch(()=>{})}}var PE=10*1024*1024,_L=3e4,_u=3e4,fg=6e4,AE=12e4,TE=3e4,UL=4,HL=2e3,BL=/["%!\u0000-\u001f\u007f]/,EE=/^[A-Za-z0-9._-]+={0,2}$/;async function gg(s,e){let{exec:t}=await import("child_process"),{promisify:r}=await import("util"),n=await r(t)(s,{maxBuffer:PE,windowsHide:!0,env:pl(),...e});return{stdout:String(n.stdout),stderr:String(n.stderr)}}function CE(s,e){if(BL.test(s))throw new Error(`The ${e} cannot contain ", %, ! or control characters on Windows: the command prompt that runs sf would act on them.`);return`"${s}"`}async function Uu(s,e){let{exec:t,execFile:r}=await import("child_process");return new Promise(n=>{let o={encoding:"utf8",maxBuffer:PE,windowsHide:!0,timeout:e.timeoutMs,env:pl()},i={},a=!1,d=l=>{a||(a=!0,clearTimeout(i.timer),n(l))},c=(l,p,f)=>{d({stdout:String(p),stderr:String(f),...l?{failure:{message:l.message,killed:l.killed}}:{}})},u=process.platform==="win32"?t(["sf",...s.map(l=>CE(l.value,l.role))].join(" "),o,c):r("sf",s.map(l=>l.value),o,c);i.timer=setTimeout(()=>{d({stdout:"",stderr:"",failure:{message:`sf did not finish within ${Math.round(e.timeoutMs/1e3)} s`,killed:!0}}),process.platform==="win32"&&u.pid!==void 0&&r("taskkill",["/pid",String(u.pid),"/T","/F"],{windowsHide:!0},()=>{})},e.timeoutMs+HL),u.stdin?.once("error",()=>{}),u.stdin?.end(e.input??"")})}var qL=K({status:Te().optional(),result:hn().optional(),message:L().optional(),name:L().optional()}).loose();function $E(s){try{let e=qL.safeParse(JSON.parse(DE(s.stdout)));return e.success?e.data:void 0}catch{return}}function xE(s,e,t,r){let n=e?.message?.trim();if(n)return new Error(n);if(s.failure?.killed)return new Error(`${t} did not finish within ${r/1e3} s.`);let o=s.stderr.split(/\r?\n/).map(i=>i.trim()).find(i=>i.length>0);return new Error(o??s.failure?.message??`${t} failed without saying why.`)}var WL=K({id:L().min(1),username:L().min(1),instanceUrl:L().min(1),accessToken:L().nullish(),alias:L().nullish(),connectedStatus:L().nullish(),apiVersion:L().nullish(),devHubId:L().nullish(),status:L().nullish(),expirationDate:L().nullish(),edition:L().nullish()}).loose(),zL=K({username:L().min(1),orgId:L().min(1),instanceUrl:L().min(1)}).loose();function ug(s,e,t=fg){let r=$E(s);if(s.failure||r?.status!==0)throw xE(s,r,e,t);let n=zL.safeParse(r.result);if(!n.success)throw new Error(`${e} succeeded but did not say which org it signed in to.`);return{username:n.data.username,orgId:n.data.orgId,instanceUrl:n.data.instanceUrl}}function lg(s){let e=ra(s);if(!e.ok)throw new Error(`Invalid instanceUrl: "${s}" \u2014 expected an https:// Salesforce login host with no path (${e.reason})`);return e.origin}function DE(s){let e=s.replace(/\u001b\[[0-9;]*m/g,""),t=e.search(/[{[]/);if(t===-1)throw new Error(`No JSON found in output (${s.length} chars): ${s.slice(0,200)}`);return e.slice(t)}function GL(s){if(/['\u0000-\u001f\u007f]/.test(s))throw new Error("The temporary folder path cannot contain a quote or control characters: the shell that runs sf would act on them.");return`'${s}'`}function JL(s,e){let t=s;return t.killed===!0?`its ${e/1e3} s limit`:typeof t.code=="number"?`exit code ${t.code}`:fl(I(s))??"an error that says nothing"}async function VL(s,e){let t=Date.now(),r=o=>process.platform==="win32"?CE(o,"temporary folder path"):GL(o),n=!1;try{let o=await IE(async a=>{let d=`${s} > ${r(a.stdout)} 2> ${r(a.stderr)}`;n=!0,await gg(d,{timeout:e})}),i=o.failure===void 0?void 0:n?JL(o.failure,e):I(o.failure);return{ran:n,stdout:o.stdout,stderr:o.stderr,ms:Date.now()-t,...i?{failure:Ds(i)}:{}}}catch(o){return{ran:n,stdout:"",stderr:"",ms:Date.now()-t,failure:Ds(I(o))}}}function NE(s){if(!s.ran)return`could not be made (${(s.failure??"").slice(0,200)})`;let e=Bu(s.stderr);return`ended with ${s.failure??"exit code 0"} after ${hg(s.ms)} s, with ${s.stdout.length} chars in its stdout file and ${s.stderr.length} in its stderr file${e?` ("${e}")`:""}`}function Bu(s){let e=fl(s);return e===void 0?void 0:Ds(e).slice(0,200)}function hg(s){return(s/1e3).toFixed(1)}function jE(s,e){return s.ms>=e-500}function XL(s,e,t,r,n){let o=Bu(s.stderr),i=a=>a.length>0?a.join(" | "):"none";return[`first run: ${hg(s.ms)} s of the ${n/1e3} s allowed`+(jE(s,n)?" (it reached the limit)":"")+`, exit code 0, stdout ${s.stdout.length} chars, stderr ${s.stderr.length} chars`+(o?` ("${o}")`:""),`run with its output sent to files: ${NE(e)}`,t.failure?`the search for sf could not run: ${t.failure}`:`sf found: ${i(t.sf)}; node found: ${i(t.node)}`,`sf --version: ${r===void 0?"not run":r===""?"printed nothing":`"${r}"`}`,`sf runs from: ${Ds(process.cwd())}`,`variables ${Ih()}`].join("; ")}function KL(s,e,t,r,n){let o=Bu(s.stderr),i=process.platform==="win32"?"where.exe sf":"which -a sf",a=new Set(t.sf.map(u=>u.replace(/[\\/][^\\/]*$/,""))).size,d=t.runs?`This window runs ${t.runs}${a>1?` (sf is found in ${a} folders of its PATH)`:""}`:t.failure?`${i} could not run in this window (${t.failure.slice(0,200)})`:`${i} finds no sf this window can run`,c=r===void 0?"":r===""?", and its sf --version printed nothing either":`, and its sf --version says ${r}`;return`sf org list --json ended without an error and printed nothing${o?` (it said: ${o})`:""}, so there are no orgs to read. It ran ${hg(s.ms)} s${jE(s,n)?`, its ${n/1e3} s limit,`:""} and exited with code 0. Run again with its output sent to a file, it ${NE(e)}. ${d}${c}. In a terminal of this window, run sf org list --json and ${i}: another first line there means VS Code runs another sf than the terminal. Details in View > Output > SandForge.`}function pg(s){return s.connectedStatus!==void 0?s.connectedStatus==="Connected":s.isScratch===!0&&s.status==="Active"&&s.isExpired!==!0}function YL(s){return s.connectedStatus!==void 0?`the CLI reports ${s.connectedStatus}`:s.isScratch===!0&&(s.isExpired===!0||s.status==="Expired")?s.expirationDate?`a scratch org that expired on ${s.expirationDate}`:"a scratch org that expired":s.isScratch===!0?`a scratch org its Dev Hub reports ${s.status??"without a status"}`:"the CLI did not say it is connected"}async function QL(s){let e=await Th({instanceUrl:s.instanceUrl,accessToken:s.accessToken,...s.apiVersion?{version:s.apiVersion}:{}});return na(e)}async function ZL(s,e){let t=new Array(s.length),r=0,n=async()=>{for(;r<s.length;){let o=r++;t[o]=await s[o]()}};return await Promise.all(Array.from({length:Math.min(e,s.length)},n)),t}var Hu=class{constructor(e=Ch,t=QL){this.readToken=e;this.readKind=t}readToken;readKind;versionAnswer;async isCliAvailable(){try{let{stdout:e}=await gg("sf --version",{timeout:_L});return this.versionAnswer=Bu(e)??"",!0}catch{return!1}}async listOrgs(e){let t=await this.readOrgEntries(),r=this.dedupeByOrgId(t.filter(a=>pg(a))),n=new Set(r.map(a=>a.orgId));for(let a of this.dedupeByOrgId(t.filter(d=>!pg(d))))n.has(a.orgId)||e?.({username:a.username,...a.alias?{alias:a.alias}:{},orgId:a.orgId,reason:YL(a),why:"notConnected"});let o=await ZL(r.map(a=>async()=>{try{return{entry:await this.withUsableToken(a)}}catch(d){return{entry:a,reason:I(d)}}}),UL),i=[];for(let{entry:a,reason:d}of o)d===void 0?i.push(this.mapToSalesforceOrg(a)):e?.({username:a.username,alias:a.alias,orgId:a.orgId,reason:d});return i}async findOrg(e){let t=await this.displayOrg(e);if(!t||!pg(t))return;let r;try{r=await this.withUsableToken(t)}catch(n){throw new Error(`The Salesforce CLI gave no access token for ${t.username}: ${I(n)}`)}return this.mapToSalesforceOrg(await this.typedByTheOrg(r))}async displayOrg(e){if(!/^[\w.@+-]+$/.test(e)||e.startsWith("-"))throw new Error(`Invalid username format: "${e}"`);let t=await Uu([{value:"org",role:"command"},{value:"display",role:"command"},{value:"--target-org",role:"flag"},{value:e,role:"username"},{value:"--json",role:"flag"}],{timeoutMs:TE}),r=$E(t);if(r?.name==="NamedOrgNotFoundError")return;if(t.failure||r?.status!==0)throw xE(t,r,"sf org display",TE);let n=WL.safeParse(r.result);if(!n.success)throw new Error("sf org display succeeded but did not say which org it shows.");let o=n.data,i=typeof o.devHubId=="string"&&o.devHubId!=="";return{orgId:o.id,username:o.username,instanceUrl:o.instanceUrl,...o.alias?{alias:o.alias}:{},...o.accessToken?{accessToken:o.accessToken}:{},...o.connectedStatus?{connectedStatus:o.connectedStatus}:{},...o.apiVersion?{instanceApiVersion:o.apiVersion}:{},...i?{isScratch:!0}:{},...i&&o.status?{status:o.status}:{},...i&&o.expirationDate?{expirationDate:o.expirationDate}:{},...i&&o.edition?{orgEdition:o.edition}:{}}}async typedByTheOrg(e){if(e.isScratch===!0||e.accessToken===void 0)return e;try{let t=await this.readKind({instanceUrl:e.instanceUrl,accessToken:e.accessToken,...e.instanceApiVersion?{apiVersion:e.instanceApiVersion}:{}});return{...e,isSandbox:t.sandbox,...t.edition?{orgEdition:t.edition}:{}}}catch{return e}}async loginJwt(e){let t=[{value:"org",role:"command"},{value:"login",role:"command"},{value:"jwt",role:"command"},{value:"--username",role:"flag"},{value:e.username,role:"username"},{value:"--jwt-key-file",role:"flag"},{value:e.keyFile,role:"private key file path"},{value:"--client-id",role:"flag"},{value:e.clientId,role:"consumer key"},{value:"--instance-url",role:"flag"},{value:lg(e.loginUrl),role:"login URL"}];return e.alias&&t.push({value:"--alias",role:"flag"},{value:e.alias,role:"alias"}),t.push({value:"--json",role:"flag"}),ug(await Uu(t,{timeoutMs:fg}),"sf org login jwt")}async loginWithRefreshToken(e){if(!EE.test(e.clientId))throw new Error("The consumer key holds characters the Salesforce CLI does not accept.");if(!EE.test(e.refreshToken))throw new Error("Salesforce issued a refresh token the Salesforce CLI cannot store (unexpected characters).");let t=new URL(lg(e.instanceUrl)).host,r=[{value:"org",role:"command"},{value:"login",role:"command"},{value:"sfdx-url",role:"command"}];e.alias&&r.push({value:"--alias",role:"flag"},{value:e.alias,role:"alias"}),r.push({value:"--json",role:"flag"},{value:"--sfdx-url-stdin",role:"flag"});let n=`force://${e.clientId}::${e.refreshToken}@${t}
21
+ `;return ug(await Uu(r,{timeoutMs:fg,input:n}),"sf org login sfdx-url")}async readOrgEntries(){let e="sf org list --json",t=Date.now(),r,n="";try{let a=await gg(e,{timeout:_u});r=a.stdout,n=a.stderr}catch(a){let d=a;if(r=String(d.stdout??""),!r)throw new Error(`SF CLI failed with no output: ${d.message}`)}r.trim()===""&&(r=await this.rereadBlankOrgList(e,{ms:Date.now()-t,stdout:r,stderr:n}));let o=DE(r),i;try{i=JSON.parse(o)}catch(a){throw new Error(`Failed to parse SF CLI JSON: ${a instanceof Error?a.message:a}. Output starts with: ${r.slice(0,300)}`)}return[...i.result?.nonScratchOrgs??[],...i.result?.scratchOrgs??[],...i.result?.sandboxes??[],...i.result?.other??[],...i.result?.devHubs??[]]}async rereadBlankOrgList(e,t){let r=await VL(e,_u),n=await Ah(),o=XL(t,r,n,this.versionAnswer,_u);if(r.stdout.trim()!=="")return ie.warn(`${e} printed nothing on its pipe; what it wrote to a file was read instead. ${o}`),r.stdout;throw ie.warn(`${e} printed nothing, on its pipe or to a file. ${o}`),new Error(KL(t,r,n,this.versionAnswer,_u))}async loginWeb(e,t){if(e&&!/^[\w.-]+$/.test(e))throw new Error(`Invalid alias format: "${e}"`);let r=[{value:"org",role:"command"},{value:"login",role:"command"},{value:"web",role:"command"},{value:"--instance-url",role:"flag"},{value:lg(t),role:"login URL"}];return e&&r.push({value:"--alias",role:"flag"},{value:e,role:"alias"}),r.push({value:"--json",role:"flag"}),ug(await Uu(r,{timeoutMs:AE}),"sf org login web",AE)}dedupeByOrgId(e){let t=new Map;for(let r of e)r.orgId&&!t.has(r.orgId)&&t.set(r.orgId,r);return Array.from(t.values())}async withUsableToken(e){if(gl(e.accessToken))return e;let t=await this.readToken(e.username);if(!gl(t.accessToken))throw new Error("the Salesforce CLI showed no usable access token");return{...e,accessToken:t.accessToken,instanceUrl:t.instanceUrl??e.instanceUrl}}mapToSalesforceOrg(e){let t=eo({isScratch:e.isScratch,isSandbox:e.isSandbox,edition:e.orgEdition}),{safetyTier:r,color:n}=Br(t),o={id:e.orgId,alias:e.alias||e.username,username:e.username,...typeof e.name=="string"&&e.name.trim()!==""?{organizationName:e.name.trim()}:{},instanceUrl:e.instanceUrl,orgId:e.orgId,orgType:t,authMethod:"sfdx_import",safetyTier:r,appearance:{color:n,icon:"cloud",position:0},metadata:{apiVersion:e.instanceApiVersion??ko.DEFAULT_API_VERSION,edition:e.orgEdition??"",features:[],...t==="Scratch"&&e.expirationDate?{expirationDate:e.expirationDate}:{}},status:"connected",lastConnected:new Date().toISOString(),tags:[]},i={loginUrl:e.instanceUrl,accessToken:e.accessToken,instanceUrl:e.instanceUrl,username:e.username};return{org:o,credentials:i}}};function eF(s,e){return e?new Promise((t,r)=>{let n=()=>r(e.reason);e.aborted?n():e.addEventListener("abort",n,{once:!0}),s.then(o=>{e.removeEventListener("abort",n),t(o)},o=>{e.removeEventListener("abort",n),r(o)})}):s}var qu=class{deps;results=new Map;constructor(e){this.deps=e}async execute(e,t){let r=Date.now(),{items:n,managedLeftOut:o}=await eF(this.deps.metadataCompare.compare(e.sourceOrgId,e.targetOrgId,e.componentTypes,{includeManaged:e.includeManaged},t),t),i=this.deps.diffEngine.computeSummary(n),a=this.deps.diffEngine.computeCoverage(n,this.deps.metadataCompare.budget,o),d=Date.now()-r,c={configId:e.id,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,mode:e.mode,summary:i,content:a,diffs:n,timestamp:new Date().toISOString(),duration:d};return this.results.set(e.id,c),c}getLastResult(e){return this.results.get(e)}};function tF(){return globalThis.crypto.randomUUID()}function ME(s){return{stepId:s.id,stepName:s.name,stepType:s.type,status:"skipped"}}function rF(s,e){let t={};for(let r of s.variables)r.defaultValue!==void 0&&(t[r.name]=r.defaultValue);return{...t,...e}}function nF(s){if(s.status!=="completed")return{};let e=s.output?.variables;return typeof e!="object"||e===null||Array.isArray(e)?{}:Object.fromEntries(Object.entries(e).filter(t=>typeof t[1]=="string"))}function LE(s){return`Validation failed: ${s.join(", ")}`}function oF(s,e,t){let r=[["success",s.onSuccess],["failure",s.onFailure]];for(let[n,o]of r){if(!o)continue;let i=t.findIndex(d=>d.id===o);if(i>e)continue;let a=i===-1?`"${o}", which is not a step of this pipeline`:`"${t[i].name}", which does not come after it`;return`Step "${s.name}" routes on ${n} to ${a}: a route can only skip ahead.`}}var Wu=class{deps;activeRuns=new Map;handlers=new Map;cancelledRuns=new Set;aborters=new Map;constructor(e){this.deps=e}async execute(e,t,r,n){let o=this.deps.builder.validate(e);if(o.length>0){let h=this.createRun(e,t,r);return h.status="failed",h.error=LE(o),h.endTime=new Date().toISOString(),this.emit("failed",{runId:h.id,error:h.error}),h}let i=this.refuseUnrunnable(e,t,r);if(i)return i;let a=this.createRun(e,t,r);a.status="running",this.activeRuns.set(a.id,a);let d=new AbortController,c=()=>d.abort();n?.aborted&&d.abort(),n?.addEventListener("abort",c,{once:!0}),this.aborters.set(a.id,d),this.emit("started",{runId:a.id,pipelineId:e.id});let u=rF(e,t),{steps:l}=e,p=this.deps.conditionalRouter,f=!1,g=0;for(;g<l.length;){if(this.cancelledRuns.has(a.id)||d.signal.aborted){a.status="cancelled";break}let h=l[g],m=await this.runStep(h,a,u,d.signal);if(a.stepResults.push(m),m.status==="skipped"){this.emit("stepSkipped",{runId:a.id,stepResult:m}),g+=1;continue}if(this.emit("stepCompleted",{runId:a.id,stepResult:m}),Object.assign(u,nF(m)),u[uh]=m.status==="completed"?"succeeded":"failed",d.signal.aborted||m.status==="stopped"){a.status="cancelled";break}if(m.status==="failed"&&(f=!0,!h.continueOnError)){a.status="failed",a.error=m.error;break}let y=g+1;if(p.endsRun(h,m))y=l.length;else{let v=p.getNextStep(h,m),b=v?l.findIndex((k,S)=>S>g&&k.id===v):-1;b!==-1&&(y=b)}for(let v of l.slice(g+1,y)){let b=ME(v);a.stepResults.push(b),this.emit("stepSkipped",{runId:a.id,stepResult:b})}g=y}return a.status==="running"&&(a.status=f?"completed_with_warnings":"completed"),a.endTime=new Date().toISOString(),a.duration=new Date(a.endTime).getTime()-new Date(a.startTime).getTime(),n?.removeEventListener("abort",c),this.aborters.delete(a.id),this.activeRuns.delete(a.id),this.cancelledRuns.delete(a.id),this.deps.history.record(a),a.status==="failed"?this.emit("failed",{runId:a.id,error:a.error}):this.emit("completed",{runId:a.id,status:a.status}),a}cancel(e){if(this.activeRuns.has(e)){this.cancelledRuns.add(e),this.aborters.get(e)?.abort();let t=this.activeRuns.get(e);t&&(t.status="cancelled")}}getRun(e){return this.activeRuns.get(e)??this.deps.history.getRun(e)}getActiveRuns(){return[...this.activeRuns.values()]}on(e,t){let r=this.handlers.get(e);r||(r=new Set,this.handlers.set(e,r)),r.add(t)}off(e,t){let r=this.handlers.get(e);r&&r.delete(t)}async runStep(e,t,r,n){if(e.condition&&e.type!=="condition"){let o;try{o=this.deps.conditionalRouter.evaluate(e.condition,r)}catch(i){return{stepId:e.id,stepName:e.name,stepType:e.type,status:"failed",error:`Step "${e.name}" did not run: its condition could not be evaluated, as ${I(i)}.`}}if(!o)return ME(e)}return this.emit("stepStarted",{runId:t.id,stepId:e.id}),this.deps.stepExecutor.execute(e,{variables:r,previousResults:t.stepResults,pipelineId:t.pipelineId,pipelineName:t.pipelineName,runId:t.id,signal:n})}refuseUnrunnable(e,t,r){let n=this.refusals(e);if(n.length===0)return;let o=this.createRun(e,t,r);return o.status="failed",o.stepResults=n.map(({step:i,reason:a})=>({stepId:i.id,stepName:i.name,stepType:i.type,status:"failed",error:a})),o.error=`Pipeline did not start: ${n.map(({reason:i})=>i).join(" ")}`,o.endTime=new Date().toISOString(),o.duration=new Date(o.endTime).getTime()-new Date(o.startTime).getTime(),this.deps.history.record(o),this.emit("failed",{runId:o.id,error:o.error}),o}check(e){let t=this.deps.builder.validate(e);return t.length>0?[LE(t)]:this.refusals(e).map(({reason:r})=>r)}refusals(e){let t=new Set(e.variables.map(r=>r.name));return e.steps.flatMap((r,n)=>{let o=this.deps.stepExecutor.check(r,{steps:e.steps,index:n,declared:t})??this.conditionProblem(r)??oF(r,n,e.steps);return o===void 0?[]:[{step:r,reason:o}]})}conditionProblem(e){if(!e.condition||e.type==="condition")return;let t=this.deps.conditionalRouter.check(e.condition);return t===void 0?void 0:`Step "${e.name}" runs only when its condition holds, and the condition ${t}.`}emit(e,t){let r=this.handlers.get(e);if(r)for(let n of r)n(e,t)}createRun(e,t,r){return{id:tF(),pipelineId:e.id,pipelineName:e.name,status:"queued",triggeredBy:r,stepResults:[],variables:t,startTime:new Date().toISOString()}}};var zu=class{operations=new Map;changeHandlers=new Set;cleanupTimers=new Map;register(e,t,r,n=0,o={}){let i={operationId:e,module:t,description:r,status:"running",percentage:0,processedRecords:0,totalRecords:n,currentStep:r,startedAt:new Date().toISOString(),elapsedMs:0,recordsPerSecond:0,...o.pausable?{pausable:!0}:{}};this.operations.set(e,i),this.notifyChange()}updateProgress(e,t,r,n,o){let i=this.operations.get(e);if(!i)return;let a=Date.now()-new Date(i.startedAt).getTime(),d=a/1e3,c=d>0?Math.round(r/d):0;i.percentage=Math.min(100,Math.max(0,t)),i.processedRecords=r,i.totalRecords=n,i.currentStep=o,i.elapsedMs=a,i.recordsPerSecond=c,this.notifyChange()}complete(e){let t=this.operations.get(e);t&&(t.status="completed",t.percentage=100,t.elapsedMs=Date.now()-new Date(t.startedAt).getTime(),this.notifyChange(),this.scheduleRemoval(e,3e4))}partial(e){let t=this.operations.get(e);t&&(t.status="partial",t.elapsedMs=Date.now()-new Date(t.startedAt).getTime(),this.notifyChange(),this.scheduleRemoval(e,6e4))}fail(e,t){let r=this.operations.get(e);r&&(r.status="failed",r.error=t,r.elapsedMs=Date.now()-new Date(r.startedAt).getTime(),this.notifyChange(),this.scheduleRemoval(e,6e4))}pause(e){let t=this.operations.get(e);t?.status==="running"&&(t.status="paused",this.notifyChange())}resume(e){let t=this.operations.get(e);t?.status==="paused"&&(t.status="running",this.notifyChange())}cancel(e){let t=this.operations.get(e);t&&(t.status="cancelled",t.elapsedMs=Date.now()-new Date(t.startedAt).getTime(),this.notifyChange(),this.scheduleRemoval(e,3e4))}offerResume(e,t){let r=this.operations.get(e);!r||r.status!=="cancelled"&&r.status!=="failed"||(r.resumeRun=t,this.notifyChange())}getAll(){return Array.from(this.operations.values())}getActive(){return this.getAll().filter(e=>e.status==="running"||e.status==="paused")}get(e){return this.operations.get(e)}onChange(e){this.changeHandlers.add(e)}offChange(e){this.changeHandlers.delete(e)}get activeCount(){return this.getActive().length}dispose(){for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear(),this.operations.clear(),this.changeHandlers.clear()}scheduleRemoval(e,t){let r=this.cleanupTimers.get(e);r&&clearTimeout(r);let n=setTimeout(()=>{this.operations.delete(e),this.cleanupTimers.delete(e),this.notifyChange()},t);this.cleanupTimers.set(e,n)}notifyChange(){let e=this.getAll();for(let t of this.changeHandlers)t(e)}};var aF=3e4;function dF(s,e,t={}){let r=eo({isSandbox:e.isSandbox,edition:e.orgType,...t.typeScratch===!0&&s.scratch===!0?{isScratch:!0}:{}}),{safetyTier:n,color:o}=Br(r);return{id:e.orgId,alias:s.alias,username:e.username||s.username,instanceUrl:s.instanceUrl,orgId:e.orgId,orgType:r,authMethod:"sfdx_import",safetyTier:n,appearance:{color:o,icon:"cloud",position:0},metadata:{apiVersion:ko.DEFAULT_API_VERSION,edition:e.orgType,features:[]},status:"connected",lastConnected:new Date().toISOString(),tags:[]}}function cF(s,e,t){if(s.correlationId===e){if(s.type===t)return"answered";if(s.type==="bridge:error")return"refused";if(s.type.endsWith(":error"))return"failed"}}function uF(s){let e=s.payload??{};if(s.type.endsWith(":error")||s.type==="operation:failed"){let t=e.message??e.error??e.details??JSON.stringify(e);return`! ${s.type}: ${String(t)}`}if(s.type==="notification")return`! notification (${String(e.level)}): ${String(e.title)} \u2014 ${String(e.message)}`}function lF(s,e,t={}){return{compareOrchestrator:n=>new qu(n),automationOrchestrator:n=>new Wu(n),seedOrchestrator:n=>new wS(n),syncOrchestrator:n=>new yS(n),getSandforgeSetting:(n,o)=>o,isAIEnabled:()=>!1,configStore:s,showNotification:n=>e(` notification: ${n}`),runsFrom:"commandLine",...t}}function b6(s){let{log:e}=s,t=s.waitMs??5*6e4,r=ll();Ph("command line");let n=uv(iF(s.storeDir,"configStore.json")),o=new Map,i=new ju({get:b=>Promise.resolve(o.get(b)),store:(b,k)=>(o.set(b,k),Promise.resolve()),delete:b=>(o.delete(b),Promise.resolve())}),a=new Mu,d=new Fu(n,i,a),c=new Hu,u=new BS;u.setSfdxBridge(c);let l=new xu;l.setLogFunction(e);let p=new Du(l),f=lF(n,e,s.services),g=new Pu({log:e,broker:l,stateSync:new Nu(l),orgManager:a,orgRegistry:d,configStore:n,secretVault:i,authProvider:u,sfdxBridge:c,services:f});g.setLiveOperationTracker(new zu),s.compose?.({handlers:g,configStore:n,orgRegistry:d,orgManager:a,services:f,log:e}),g.registerAll(p);let h=[],m=new Set,y,v={webview:{postMessage:b=>{h.push(b);let k=uF(b);k&&e(` ${k}`),s.onPost?.(b);for(let S of[...m])S(b);return Promise.resolve(!0)},onDidReceiveMessage:b=>(y=b,{dispose:()=>{y=void 0}})}};return l.registerPanel(v),{posted:h,async connect(b){let k=await Dh(b),S=await u.validateConnection(k.accessToken,k.instanceUrl),C=dF(k,S,{typeScratch:s.typeScratchOrgs===!0});return await d.saveOrg(C,{loginUrl:k.instanceUrl,instanceUrl:k.instanceUrl,accessToken:k.accessToken,username:k.username}),C},connectingRequests:()=>ll()-r,request(b){let k=y;if(!k)return Promise.reject(new Error("No panel is registered with the broker."));let S=b.responseType??`${b.type}:response`,C=b.timeoutMs??aF,R={id:b.id??`wv-${sF()}`,type:b.type,timestamp:Date.now(),...b.payload!==void 0?{payload:b.payload}:{}},w=Date.now();return new Promise(P=>{let O=H=>{m.delete(E),clearTimeout($),P(H)},E=H=>{let J=cF(H,R.id,S);if(!J)return;let W=Date.now()-w;O({outcome:J,message:H,elapsedMs:W,late:W>C})},$=setTimeout(()=>O({outcome:"unanswered",elapsedMs:Date.now()-w,late:!0}),Math.max(t,C));m.add(E),k({protocolVersion:1,payload:R})})}}}export{Mn as a,FE as b,dn as c,hp as d,yp as e,kd as f,hk as g,Id as h,yk as i,CF as j,Rp as k,bk as l,MF as m,Ok as n,LF as o,PP as p,b6 as q};