sandforge 1.83.0 → 1.84.1

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 (254) hide show
  1. package/README.md +1 -1
  2. package/lib/chunk-23SEDORH.mjs +11 -0
  3. package/lib/{chunk-I5C4O3VA.mjs → chunk-24RFOFYT.mjs} +1 -1
  4. package/lib/chunk-26POJDIT.mjs +7 -0
  5. package/lib/{chunk-WJAZ5LHL.mjs → chunk-2AZQHBEF.mjs} +1 -1
  6. package/lib/{chunk-IHGYJZZ2.mjs → chunk-2HVOZUM4.mjs} +1 -1
  7. package/lib/{chunk-3V4YH5KO.mjs → chunk-2JDAOWUW.mjs} +1 -1
  8. package/lib/{chunk-BNKT3R3F.mjs → chunk-2METQHGG.mjs} +1 -1
  9. package/lib/chunk-2WFIVO4F.mjs +13 -0
  10. package/lib/chunk-2YHZBUZE.mjs +7 -0
  11. package/lib/{chunk-7DPHZWA4.mjs → chunk-326AJTIU.mjs} +14 -14
  12. package/lib/{chunk-UIR77ZJD.mjs → chunk-36JOHEJL.mjs} +1 -1
  13. package/lib/chunk-3PVRGTVK.mjs +7 -0
  14. package/lib/{chunk-2WMKJVD2.mjs → chunk-3Q353S2R.mjs} +1 -1
  15. package/lib/chunk-3TZSBHEY.mjs +7 -0
  16. package/lib/{chunk-T36DZJPH.mjs → chunk-43TOMFV4.mjs} +1 -1
  17. package/lib/{chunk-XAMMIPZ4.mjs → chunk-4CVUUVGJ.mjs} +1 -1
  18. package/lib/{chunk-6YC2ELCU.mjs → chunk-4EOHEDFP.mjs} +1 -1
  19. package/lib/{chunk-ZB5E7NHU.mjs → chunk-4JE4BYXK.mjs} +1 -1
  20. package/lib/{chunk-JREKJO3D.mjs → chunk-54WZUS7J.mjs} +1 -1
  21. package/lib/{chunk-CGZGL6VT.mjs → chunk-5CRLRHOJ.mjs} +1 -1
  22. package/lib/{chunk-UOHZW2L4.mjs → chunk-5IZTFMJM.mjs} +1 -1
  23. package/lib/{chunk-6VOQFISN.mjs → chunk-5M5FQ7RP.mjs} +1 -1
  24. package/lib/{chunk-U4YFYSF3.mjs → chunk-5SMWFNE7.mjs} +1 -1
  25. package/lib/{chunk-HQZUQXDC.mjs → chunk-5XTUSN72.mjs} +1 -1
  26. package/lib/chunk-6I6TWNV5.mjs +7 -0
  27. package/lib/{chunk-QLRWU3MB.mjs → chunk-6JWWSDM6.mjs} +1 -1
  28. package/lib/chunk-6O222PW6.mjs +7 -0
  29. package/lib/{chunk-J3TIHLWG.mjs → chunk-6PD6K7LP.mjs} +1 -1
  30. package/lib/{chunk-ISAUCWYK.mjs → chunk-6QE6R6RL.mjs} +1 -1
  31. package/lib/{chunk-2KTGDYUH.mjs → chunk-6WX5ZU7Q.mjs} +1 -1
  32. package/lib/{chunk-XAUQXYPW.mjs → chunk-6YL7BNYD.mjs} +1 -1
  33. package/lib/chunk-6ZLKIT3H.mjs +7 -0
  34. package/lib/{chunk-XKFHTBAB.mjs → chunk-7QYHEHMA.mjs} +1 -1
  35. package/lib/chunk-7SQSWVAU.mjs +9 -0
  36. package/lib/{chunk-NNV7IGM7.mjs → chunk-7UVKIWKV.mjs} +1 -1
  37. package/lib/{chunk-RZKJQOOC.mjs → chunk-7WATA4SB.mjs} +1 -1
  38. package/lib/{chunk-DMT5SCO3.mjs → chunk-7YNM6KFZ.mjs} +1 -1
  39. package/lib/{chunk-TMIESDE5.mjs → chunk-A3MYSOOC.mjs} +1 -1
  40. package/lib/chunk-AL4C3GFT.mjs +7 -0
  41. package/lib/chunk-B3FBHVNN.mjs +21 -0
  42. package/lib/{chunk-CDWZGQAJ.mjs → chunk-B63POIPQ.mjs} +1 -1
  43. package/lib/{chunk-YEVB7LVK.mjs → chunk-BAWCOKRW.mjs} +1 -1
  44. package/lib/{chunk-FVLFO2S6.mjs → chunk-BBRWFKS5.mjs} +1 -1
  45. package/lib/chunk-BEA27DLS.mjs +7 -0
  46. package/lib/chunk-BRY3PLIZ.mjs +7 -0
  47. package/lib/chunk-CBH3TOWK.mjs +341 -0
  48. package/lib/{chunk-7V2UYZ6S.mjs → chunk-CPQIZGG5.mjs} +1 -1
  49. package/lib/chunk-CVHNXJH3.mjs +7 -0
  50. package/lib/{chunk-ZOSESZ22.mjs → chunk-D4GF4FAB.mjs} +1 -1
  51. package/lib/chunk-DGDRQRCW.mjs +7 -0
  52. package/lib/{chunk-2N73W63D.mjs → chunk-DPMRIMUC.mjs} +1 -1
  53. package/lib/chunk-DUN2EPRC.mjs +7 -0
  54. package/lib/chunk-E3A3LOCY.mjs +7 -0
  55. package/lib/{chunk-KWAVSZ2B.mjs → chunk-EAC5QCE3.mjs} +1 -1
  56. package/lib/{chunk-JUOQUG7U.mjs → chunk-EC72TIEG.mjs} +1 -1
  57. package/lib/chunk-EPFCERGL.mjs +7 -0
  58. package/lib/{chunk-6KOUYHEY.mjs → chunk-ETDCBLGU.mjs} +1 -1
  59. package/lib/{chunk-2R6GFNKF.mjs → chunk-F3AQW6IU.mjs} +1 -1
  60. package/lib/{chunk-AHUGG3WU.mjs → chunk-FITPY3L4.mjs} +1 -1
  61. package/lib/chunk-FNJ4SGWO.mjs +7 -0
  62. package/lib/{chunk-EOQON3E5.mjs → chunk-FP7CYB2F.mjs} +1 -1
  63. package/lib/{chunk-262TP6UU.mjs → chunk-GKY2JMHY.mjs} +1 -1
  64. package/lib/{chunk-JBWJ6UEZ.mjs → chunk-GMIGWR6U.mjs} +1 -1
  65. package/lib/{chunk-OS5GE52G.mjs → chunk-GNRSF65U.mjs} +1 -1
  66. package/lib/chunk-GOOVPVWX.mjs +7 -0
  67. package/lib/{chunk-DB5RVDC5.mjs → chunk-GWZRR3MM.mjs} +1 -1
  68. package/lib/{chunk-SX6QWYCQ.mjs → chunk-H2BHESDA.mjs} +2 -2
  69. package/lib/chunk-H4CGM6YO.mjs +7 -0
  70. package/lib/{chunk-NFEBX75O.mjs → chunk-HCGXK7G7.mjs} +1 -1
  71. package/lib/{chunk-4X5D3MSV.mjs → chunk-HIDW7FNV.mjs} +1 -1
  72. package/lib/chunk-HSBXRQTI.mjs +7 -0
  73. package/lib/chunk-HUZPBE47.mjs +7 -0
  74. package/lib/{chunk-F5SBGJWW.mjs → chunk-HV7VPEXP.mjs} +1 -1
  75. package/lib/chunk-I6E6T6YY.mjs +7 -0
  76. package/lib/chunk-IUM4NFKI.mjs +10 -0
  77. package/lib/chunk-IVFVNNGB.mjs +37 -0
  78. package/lib/{chunk-L4MSL4U7.mjs → chunk-IZGCEOYO.mjs} +1 -1
  79. package/lib/{chunk-E3RQ575Y.mjs → chunk-J3DND3BC.mjs} +1 -1
  80. package/lib/{chunk-MJD6CPZZ.mjs → chunk-JAEDM4SI.mjs} +1 -1
  81. package/lib/chunk-JCFBFF4Y.mjs +7 -0
  82. package/lib/{chunk-U2CTKIPE.mjs → chunk-JE6SCT6R.mjs} +1 -1
  83. package/lib/{chunk-XJICAOAQ.mjs → chunk-JGZPD4IM.mjs} +1 -1
  84. package/lib/{chunk-XCJUNX63.mjs → chunk-JKJ74BX5.mjs} +1 -1
  85. package/lib/{chunk-WAYQLQAD.mjs → chunk-JLSIWO4Z.mjs} +1 -1
  86. package/lib/{chunk-D7XUNWWU.mjs → chunk-JSAJS3MY.mjs} +1 -1
  87. package/lib/chunk-JTJK2D36.mjs +7 -0
  88. package/lib/{chunk-OTJH6AEA.mjs → chunk-KAZS5Z6W.mjs} +1 -1
  89. package/lib/chunk-KB4ZHM4Q.mjs +10 -0
  90. package/lib/{chunk-N2HYG3BL.mjs → chunk-KGU4SVIT.mjs} +1 -1
  91. package/lib/{chunk-FKCIGJOI.mjs → chunk-KJWFYBMU.mjs} +2 -2
  92. package/lib/{chunk-KXUOHACP.mjs → chunk-KZTZDC7H.mjs} +1 -1
  93. package/lib/{chunk-S4PRKKGC.mjs → chunk-L2E5WBGD.mjs} +1 -1
  94. package/lib/{chunk-X2XZQ434.mjs → chunk-L53JWJ3S.mjs} +1 -1
  95. package/lib/{chunk-CQAFVEKP.mjs → chunk-LA4KIATH.mjs} +6 -6
  96. package/lib/chunk-LC3NDW4N.mjs +7 -0
  97. package/lib/{chunk-4V3QO7HF.mjs → chunk-LKTNQEBS.mjs} +1 -1
  98. package/lib/chunk-M2ABR4JM.mjs +7 -0
  99. package/lib/{chunk-3CM7LAPE.mjs → chunk-M4BLK6HJ.mjs} +1 -1
  100. package/lib/{chunk-Z3MGN42K.mjs → chunk-M6K34KGF.mjs} +1 -1
  101. package/lib/{chunk-TUPZY2QJ.mjs → chunk-MDMPJEV3.mjs} +1 -1
  102. package/lib/{chunk-BVZ5H3N4.mjs → chunk-MJZU3U5O.mjs} +68 -63
  103. package/lib/{chunk-OUU47Y7A.mjs → chunk-MSIEU5MR.mjs} +1 -1
  104. package/lib/{chunk-QQDZQCO2.mjs → chunk-N4WPCWJO.mjs} +1 -1
  105. package/lib/{chunk-MTM4KG3T.mjs → chunk-NCZKWSC7.mjs} +1 -1
  106. package/lib/{chunk-Y7YUNRKK.mjs → chunk-NED4MBIM.mjs} +1 -1
  107. package/lib/{chunk-QKJXIY6L.mjs → chunk-NOBQTEQD.mjs} +1 -1
  108. package/lib/{chunk-WBELLGNE.mjs → chunk-NSQWI7ZY.mjs} +1 -1
  109. package/lib/{chunk-BPHTA6KP.mjs → chunk-O677VOGO.mjs} +1 -1
  110. package/lib/chunk-OFTT7J2M.mjs +7 -0
  111. package/lib/{chunk-JH4ZTVQN.mjs → chunk-OLCVHL7I.mjs} +1 -1
  112. package/lib/chunk-OM5NORJG.mjs +7 -0
  113. package/lib/{chunk-QP3JLFIO.mjs → chunk-OMNMLKDT.mjs} +1 -1
  114. package/lib/{chunk-WABXKL4N.mjs → chunk-OPMO6I45.mjs} +1 -1
  115. package/lib/{chunk-7ZBDACVG.mjs → chunk-OUZQPYT3.mjs} +1 -1
  116. package/lib/chunk-OVNMB6Q2.mjs +7 -0
  117. package/lib/{chunk-DKDKCGXV.mjs → chunk-PAXNWTYK.mjs} +1 -1
  118. package/lib/{chunk-GLN4PI5P.mjs → chunk-PBY2O6OF.mjs} +1 -1
  119. package/lib/chunk-PEDQPM2P.mjs +926 -0
  120. package/lib/chunk-PH7SP4YK.mjs +21 -0
  121. package/lib/{chunk-BT43WSOS.mjs → chunk-PMN4PAC3.mjs} +1 -1
  122. package/lib/chunk-PMWAFDUB.mjs +48 -0
  123. package/lib/chunk-PPLVFX6N.mjs +7 -0
  124. package/lib/{chunk-L3I6DAHX.mjs → chunk-PR3XCSPO.mjs} +1 -1
  125. package/lib/{chunk-WZN36ACK.mjs → chunk-PR42EZSR.mjs} +1 -1
  126. package/lib/{chunk-NDFFIJL5.mjs → chunk-PWRJRL5U.mjs} +1 -1
  127. package/lib/{chunk-NS6ONPWL.mjs → chunk-Q7GIJBCD.mjs} +1 -1
  128. package/lib/chunk-Q7TLC3I2.mjs +7 -0
  129. package/lib/{chunk-ALBY5SOH.mjs → chunk-QAFPQ3YB.mjs} +1 -1
  130. package/lib/{chunk-KKS2KFBT.mjs → chunk-QKEKG2LD.mjs} +1 -1
  131. package/lib/{chunk-OOIDCHBQ.mjs → chunk-QO53K5W2.mjs} +2 -2
  132. package/lib/{chunk-HVX2AFYW.mjs → chunk-QTG6LUZT.mjs} +1 -1
  133. package/lib/{chunk-K7G3W7XH.mjs → chunk-RE7RYF3B.mjs} +1 -1
  134. package/lib/{chunk-JIPT5FUD.mjs → chunk-RGBGUCJA.mjs} +1 -1
  135. package/lib/{chunk-GT5ZKU6V.mjs → chunk-RGUQOSBU.mjs} +1 -1
  136. package/lib/{chunk-VXZ5PTOM.mjs → chunk-RHNTHGNU.mjs} +1 -1
  137. package/lib/chunk-RKTFFCNS.mjs +7 -0
  138. package/lib/chunk-RMFU4BAL.mjs +28 -0
  139. package/lib/{chunk-DNQKVCUV.mjs → chunk-ROV3QXEF.mjs} +11 -11
  140. package/lib/chunk-RT47RKLY.mjs +7 -0
  141. package/lib/{chunk-ISOSTAJR.mjs → chunk-S42RBRH2.mjs} +1 -1
  142. package/lib/{chunk-27BBEGUD.mjs → chunk-SI267LYR.mjs} +1 -1
  143. package/lib/chunk-T3G6VZNS.mjs +7 -0
  144. package/lib/chunk-TNT27RBG.mjs +7 -0
  145. package/lib/chunk-UBIKR5VO.mjs +7 -0
  146. package/lib/chunk-UI3JQVRU.mjs +8 -0
  147. package/lib/{chunk-RVCPQVKM.mjs → chunk-UIOMAX56.mjs} +1 -1
  148. package/lib/chunk-UX3BVH2Y.mjs +7 -0
  149. package/lib/{chunk-L4RJX7DG.mjs → chunk-VCUXCK36.mjs} +1 -1
  150. package/lib/chunk-VINGECAJ.mjs +10 -0
  151. package/lib/chunk-VOXJHJIE.mjs +7 -0
  152. package/lib/chunk-W6PN6TJG.mjs +7 -0
  153. package/lib/{chunk-D6JT4PAB.mjs → chunk-WAPSSYMT.mjs} +1 -1
  154. package/lib/{chunk-7BQMBXKX.mjs → chunk-WUUKFE2U.mjs} +1 -1
  155. package/lib/chunk-WWTCWWZI.mjs +7 -0
  156. package/lib/chunk-WXDLQT2O.mjs +10 -0
  157. package/lib/{chunk-TCEXCHXR.mjs → chunk-WY5V5PR3.mjs} +1 -1
  158. package/lib/chunk-X4BXESMQ.mjs +7 -0
  159. package/lib/chunk-XBQGZGWR.mjs +7 -0
  160. package/lib/{chunk-AXFD2OH6.mjs → chunk-XGGOUNPP.mjs} +1 -1
  161. package/lib/chunk-XKWW3GKF.mjs +7 -0
  162. package/lib/{chunk-PDRXM5WN.mjs → chunk-Y2DRK37K.mjs} +1 -1
  163. package/lib/{chunk-ZXOUWHYE.mjs → chunk-YA6ATMTB.mjs} +1 -1
  164. package/lib/{chunk-54HYHHVL.mjs → chunk-YDXMTWAT.mjs} +1 -1
  165. package/lib/chunk-YHR4WQPR.mjs +7 -0
  166. package/lib/{chunk-LWES2KZE.mjs → chunk-YTLUYSMF.mjs} +1 -1
  167. package/lib/{chunk-2K5BYZQM.mjs → chunk-YWEQQL3C.mjs} +1 -1
  168. package/lib/{chunk-C6RKM4BB.mjs → chunk-Z4LKKOFY.mjs} +1 -1
  169. package/lib/chunk-ZBAWJUG2.mjs +7 -0
  170. package/lib/{chunk-446GBKAC.mjs → chunk-ZJW6YOMV.mjs} +1 -1
  171. package/lib/chunk-ZQQXSCVI.mjs +7 -0
  172. package/lib/{chunk-L6CLN664.mjs → chunk-ZQWIVYVM.mjs} +1 -1
  173. package/lib/{chunk-CXKZ6TYV.mjs → chunk-ZV7ZFQQC.mjs} +1 -1
  174. package/lib/sandforge-autopilot.mjs +25 -25
  175. package/lib/sandforge-backup.mjs +1 -1
  176. package/lib/sandforge-checkpoint.mjs +1 -1
  177. package/lib/sandforge-cleanup.mjs +1 -1
  178. package/lib/sandforge-clone.mjs +1 -1
  179. package/lib/sandforge-compare.mjs +52 -21
  180. package/lib/sandforge-dataops.mjs +1 -1
  181. package/lib/sandforge-empty.mjs +1 -1
  182. package/lib/sandforge-env.mjs +95 -95
  183. package/lib/sandforge-frozen.mjs +1 -1
  184. package/lib/sandforge-mcp.mjs +12 -12
  185. package/lib/sandforge-monitor.mjs +1 -1
  186. package/lib/sandforge-pipeline.mjs +1 -1
  187. package/lib/sandforge-seed.mjs +1 -1
  188. package/lib/sandforge-sync.mjs +1 -1
  189. package/lib/sandforge-users.mjs +1 -1
  190. package/lib/sandforge.mjs +1 -1
  191. package/lib/sf/sandforge/compare.mjs +2 -2
  192. package/lib/sfPlugin.mjs +1 -1
  193. package/oclif.manifest.json +1 -1
  194. package/package.json +1 -1
  195. package/lib/chunk-2ADSD5WK.mjs +0 -7
  196. package/lib/chunk-2GSMHGIV.mjs +0 -7
  197. package/lib/chunk-36Y225OM.mjs +0 -7
  198. package/lib/chunk-3OVTKRS4.mjs +0 -7
  199. package/lib/chunk-4GCYGQXD.mjs +0 -7
  200. package/lib/chunk-4JKR4PTZ.mjs +0 -8
  201. package/lib/chunk-5OGNK3JP.mjs +0 -37
  202. package/lib/chunk-6QSHWIZI.mjs +0 -48
  203. package/lib/chunk-77IVKH7R.mjs +0 -7
  204. package/lib/chunk-77MZRBWX.mjs +0 -7
  205. package/lib/chunk-7WSQ65WG.mjs +0 -9
  206. package/lib/chunk-A32ISQ6M.mjs +0 -28
  207. package/lib/chunk-AG24QMSY.mjs +0 -7
  208. package/lib/chunk-BH76USTQ.mjs +0 -11
  209. package/lib/chunk-BZ24IAP5.mjs +0 -7
  210. package/lib/chunk-CN5HGFG4.mjs +0 -7
  211. package/lib/chunk-CTPLYUXA.mjs +0 -7
  212. package/lib/chunk-DIGUC7S4.mjs +0 -341
  213. package/lib/chunk-DSR2MSBH.mjs +0 -7
  214. package/lib/chunk-ETNQHIDI.mjs +0 -9
  215. package/lib/chunk-FBXH4VRQ.mjs +0 -7
  216. package/lib/chunk-FYWNSMOZ.mjs +0 -10
  217. package/lib/chunk-GEEWPTV5.mjs +0 -7
  218. package/lib/chunk-GTRU5AV5.mjs +0 -7
  219. package/lib/chunk-I3ZO76LL.mjs +0 -21
  220. package/lib/chunk-ISA2NYJV.mjs +0 -7
  221. package/lib/chunk-IXIY6Q4M.mjs +0 -7
  222. package/lib/chunk-JAV6F6OA.mjs +0 -7
  223. package/lib/chunk-JYUMD357.mjs +0 -7
  224. package/lib/chunk-L47JCNP3.mjs +0 -7
  225. package/lib/chunk-LI2XNV7F.mjs +0 -7
  226. package/lib/chunk-LP2D3JJP.mjs +0 -7
  227. package/lib/chunk-LYOGCIYD.mjs +0 -925
  228. package/lib/chunk-N5UIE4IR.mjs +0 -7
  229. package/lib/chunk-O7GCCRPW.mjs +0 -7
  230. package/lib/chunk-OO24ZYYJ.mjs +0 -7
  231. package/lib/chunk-OS6HFJ7L.mjs +0 -7
  232. package/lib/chunk-P6WRYJN3.mjs +0 -7
  233. package/lib/chunk-PGRY365W.mjs +0 -7
  234. package/lib/chunk-PPGDAUEQ.mjs +0 -7
  235. package/lib/chunk-Q4PPI3KG.mjs +0 -7
  236. package/lib/chunk-QFTF2PGS.mjs +0 -21
  237. package/lib/chunk-QO4MPHZD.mjs +0 -7
  238. package/lib/chunk-QXB6U3ZP.mjs +0 -7
  239. package/lib/chunk-R3OM3X4L.mjs +0 -8
  240. package/lib/chunk-R7GKMAT4.mjs +0 -7
  241. package/lib/chunk-SCKUIE3R.mjs +0 -7
  242. package/lib/chunk-SU65Z2BA.mjs +0 -7
  243. package/lib/chunk-T7DDS4UQ.mjs +0 -7
  244. package/lib/chunk-TQJ5NPRC.mjs +0 -7
  245. package/lib/chunk-VZLJZEV2.mjs +0 -7
  246. package/lib/chunk-W3BQGMTR.mjs +0 -7
  247. package/lib/chunk-WXU6ZJIV.mjs +0 -7
  248. package/lib/chunk-X4HZD5U2.mjs +0 -7
  249. package/lib/chunk-X6XNTOGO.mjs +0 -7
  250. package/lib/chunk-XMQ5R6TC.mjs +0 -10
  251. package/lib/chunk-XPXEQKLR.mjs +0 -7
  252. package/lib/chunk-YBZIDW6W.mjs +0 -7
  253. package/lib/chunk-ZCOSME6P.mjs +0 -7
  254. package/lib/chunk-ZTHC42X6.mjs +0 -7
@@ -1,21 +0,0 @@
1
- import { createRequire as __sandforgeRequire } from 'node:module';
2
- import { fileURLToPath as __sandforgePath } from 'node:url';
3
- import { dirname as __sandforgeDirname } from 'node:path';
4
- const require = __sandforgeRequire(import.meta.url);
5
- const __filename = __sandforgePath(import.meta.url);
6
- const __dirname = __sandforgeDirname(__filename);
7
- import{a as Yv,b as sd,c as Qv,d as Zv}from"./chunk-BXZ73A5M.mjs";import{b as Vv}from"./chunk-7V2UYZ6S.mjs";import{a as Db}from"./chunk-BPHTA6KP.mjs";import{c as $b,d as xb}from"./chunk-U2CTKIPE.mjs";import{b as Tb}from"./chunk-ZRUDYB7O.mjs";import{d as eS,m as tS}from"./chunk-I3ZO76LL.mjs";import{a as Xv,b as to,c as Gs,d as Ju,e as Vu,f as Xu,g as Kv,h as Ku}from"./chunk-JBWJ6UEZ.mjs";import{a as Iu,b as Pb,c as Cb,d as xa,f as Bs}from"./chunk-RVCPQVKM.mjs";import{a as aR,d as gR,e as hR,f as Ws,g as Lo,h as Nu,i as La,j as mR,k as yR,l as wR,m as bR}from"./chunk-CTPLYUXA.mjs";import{a as ov,b as Wu,c as Fv,d as _v,e as Uv,h as Hv,i as Bv,j as qv,k as Wv,n as zv,o as Gv,p as nd,q as zu,r as od,s as Gu}from"./chunk-D7XUNWWU.mjs";import{b as Mv,e as Lv}from"./chunk-FVLFO2S6.mjs";import{A as Za,B as Rv,C as vv,D as ed,E as td,F as rd,G as Cn,H as Sv,I as kv,L as Ov,M as Iv,N as Av,O as Tv,P as Ev,R as Pv,S as qu,T as Cv,U as $v,V as xv,_ as Dv,a as qa,aa as Nv,ba as jv,c as Wa,d as za,e as sv,f as iv,g as av,h as It,j as Ga,k as Ja,l as Zr,m as Bo,n as qo,o as Wo,p as dv,q as cv,r as lv,s as Va,t as Xa,u as Ka,v as uv,w as mv,x as yv,y as wv,z as bv}from"./chunk-OO24ZYYJ.mjs";import{b as Ya,g as Qa}from"./chunk-ALBY5SOH.mjs";import{e as Or,g as pv,i as fv,k as gv,l as zo,m as hv}from"./chunk-GEEWPTV5.mjs";import{a as Jv}from"./chunk-WAYQLQAD.mjs";import{a as Ch,b as ra,e as ba,g as kn,h as ir,i as pb,l as mb,p as Eb}from"./chunk-FKCIGJOI.mjs";import{a as vt,b as _w}from"./chunk-C6RKM4BB.mjs";import{a as Qw,b as Zw}from"./chunk-XCA5AONB.mjs";import{a as Ra,b as Uw,c as Hw,d as Bw,e as _s,f as qw,g as Ww,h as zw,j as Gw}from"./chunk-WB2RIVO3.mjs";import{$ as wm,$b as Uy,A as Kh,Ab as gy,B as wn,Bb as hy,C as au,Ca as $m,Cb as my,D as Yh,Da as xm,Db as yy,Dc as Ze,E as Qh,Ea as Dm,Eb as wy,Ec as Kn,F as oa,Fa as Nm,Fb as by,Fc as eb,G as Zh,Ga as jm,Gb as ia,Gc as tb,H as em,Ha as Mm,Hb as Ry,I as tm,Ia as Lm,Ib as vy,J as rm,Ja as Fm,Jb as Sy,K as nm,Ka as _m,Kb as ky,L as om,La as Um,Lb as Oy,M as du,Ma as Hm,Mb as Iy,N as sm,Na as Bm,Nb as Ay,O as im,Oa as qm,Ob as Ty,P as am,Pa as Jr,Pb as Ey,Q as dm,Qa as Wm,Qb as Py,R as cm,Ra as pu,Rb as Cy,S as lm,Sa as sa,Sb as $y,T as um,Ta as xs,Tb as xy,U as pm,Ua as zm,Ub as Dy,V as fm,Va as Gm,Vb as Ny,W as gm,Wb as jy,X as hm,Xb as My,Y as mm,Yb as Ly,Z as ym,Zb as Fy,_ as To,_b as _y,a as zr,aa as bm,ac as Hy,b as be,ba as Rm,bc as By,c as ea,ca as vm,cc as qy,d as $t,da as cu,dc as Wy,e as mn,ea as Sm,ec as zy,f as Ao,fa as km,fb as Jm,fc as Gy,g as lt,ga as Om,gb as Vm,gc as Jy,h as mr,ha as Im,hb as Xm,hc as Vy,i as yn,ia as Am,ib as Km,ic as Xy,j as A,ja as Tm,jb as Ym,jc as Ky,k as Ie,ka as Em,kb as Qm,kc as Yy,l as ze,la as Pm,lb as Zm,lc as aa,m as Le,ma as Cm,mb as ey,mc as Qy,n as pe,na as lu,nb as ty,nc as Zy,o as E,oa as uu,ob as ry,oc as ew,p as ta,pa as $s,pb as ny,pc as tw,q as As,qb as oy,qc as rw,r as Gr,rb as sy,rc as nw,s as De,sb as iy,sc as ow,t as zh,tb as ay,tc as sw,u as Gh,ub as dy,uc as iw,v as Jh,vb as cy,vc as fu,w as Vh,wb as ly,wc as $,x as na,xb as uy,yb as py,yc as wa,z as Xh,zb as fy}from"./chunk-AXFD2OH6.mjs";import{g as ya}from"./chunk-X2XZQ434.mjs";import{a as jt,b as Ps,c as Nh,d as jh}from"./chunk-CE6ZDGBB.mjs";import{a as rb,b as nb,c as ob,e as sb,f as ib,g as ka,h as xo,i as Qn,j as Kr,k as On,l as Oa}from"./chunk-O7GCCRPW.mjs";import{b as Yn,c as ub}from"./chunk-BOGNK4LV.mjs";import{Aa as _R,Ba as UR,D as SR,Da as HR,Ea as BR,Fa as Uu,Ha as Fo,Ja as qR,Ka as Ua,La as WR,S as kR,Ua as zR,Wa as _o,Ya as GR,Za as Uo,_a as Ho,a as Xi,b as lh,ca as Mu,cb as JR,da as Lu,db as kr,eb as Hu,fa as Fu,fb as VR,g as iR,gb as XR,h as Du,hb as KR,ib as YR,ja as _a,jb as Ha,kb as Ba,la as $R,m as RR,na as _u,nb as QR,ob as ZR,pa as xR,qb as Bu,ra as DR,rb as ev,sb as tv,ta as NR,tb as rv,ua as zs,ub as nv,va as jR,xa as MR,ya as LR,z as vR,za as FR}from"./chunk-5OGNK3JP.mjs";import{a as Dw,b as Eo,c as Po,d as Sn,e as Nw,f as bu,i as Jw,j as Vw,k as Sa,l as Xw,m as Kw,p as ku,q as Hs,r as Zn,s as Ca}from"./chunk-XMQ5R6TC.mjs";import{A as Pw,B as or,C as ga,D as ha,E as ma,J as Cw,K as yu,L as wu,M as sr,N as $w,O as xw,P as vn,a as Th,b as dw,c as cw,d as lw,e as nr,f as hu,g as mu,h as uw,i as pw,j as fw,k as gw,l as Jn,n as js,o as vw,p as Sw,r as kw,s as Ow,t as Ms,v as Iw,w as Aw,x as Tw,y as Ew}from"./chunk-IXIY6Q4M.mjs";import{h as dR}from"./chunk-TEIBWMJM.mjs";import{a as cR,b as lR,f as uR,g as pR,h as fR}from"./chunk-BWWQXU2B.mjs";import{d as va}from"./chunk-T63U4OZJ.mjs";import{a as kb,b as $a,c as Ob,k as Ib,p as Ab}from"./chunk-HQZUQXDC.mjs";import{a as Yw}from"./chunk-YYZL7UGV.mjs";import{a as pa,c as fa}from"./chunk-54HYHHVL.mjs";import{b as jw,f as Mw,p as Mt,q as Ls,r as Ru,s as $o,t as vu,u as Fs,x as Lw,y as Fw}from"./chunk-BT43WSOS.mjs";import{b as OR,c as IR,d as Fa,e as ju,g as AR,h as TR,i as ER,j as PR,m as CR}from"./chunk-SX6QWYCQ.mjs";import{c as yr,d as Xn}from"./chunk-EOQON3E5.mjs";import{b as Ea,f as Pa}from"./chunk-Y7YUNRKK.mjs";import{L as hb,d as Ia,h as Aa,i as fb,k as gb,z as Ta}from"./chunk-N2HYG3BL.mjs";import{a as Lt,b as xt,d as Su,e as Xr,f as lb,h as Ot,i as Us,j as Xt}from"./chunk-7WSQ65WG.mjs";import{a as da,b as Bt,c as Vr,d as Ds,e as ca,f as Ns,g as la,h as bn,i as aw,j as ua,k as gu}from"./chunk-MJD6CPZZ.mjs";import{a as $e}from"./chunk-5LFSFYFJ.mjs";import{b as ch}from"./chunk-7ZBDACVG.mjs";import{a as Zl,c as So,d as eu,e as th,f as Os,g as tu,h as rh,j as nh,k as oh,l as ko,m as sh,n as ru,o as ih,p as ah,q as dh,r as B}from"./chunk-OUU47Y7A.mjs";import{a as Ji,f as Vi}from"./chunk-4GCYGQXD.mjs";import{a as ab,b as qt,c as Wt,g as ar}from"./chunk-WXU6ZJIV.mjs";import{$a as Da,$b as En,Ab as Wb,C as Rb,D as vb,E as Ou,Fa as Qr,Gb as zb,H as Sb,Ha as Au,Hb as Gb,Ia as Nb,Ib as Jb,Jb as Sr,La as eo,Ma as Tu,Na as jb,Oa as Mb,Pb as Vb,Qa as Lb,Ra as Fb,Rb as Xb,Sa as _b,Sb as Kb,Tb as Yb,Ua as Rr,Ub as Qb,Va as dr,Vb as Zb,Yb as eR,Za as In,_a as No,_b as Tn,ab as jo,b as $h,bb as An,c as nt,cb as Mo,d as xh,db as Na,e as su,f as Dh,fb as ja,fc as Pn,g as Ts,gc as qs,h as iu,ic as Pu,jc as Cu,kc as $u,lc as tR,mc as rR,nc as nR,oc as xu,qb as Ub,rb as Hb,rc as ut,sb as Bb,sc as Ma,tb as vr,tc as oR,ub as qb,uc as sR,v as yb,wb as Eu,x as wb,z as bb}from"./chunk-R3OM3X4L.mjs";import{a as Eh,b as Io,c as Rt,d as Ph,e as Z,f as ht}from"./chunk-77IVKH7R.mjs";import{q as br,r as Yr,s as Do}from"./chunk-2WMKJVD2.mjs";import{a as eh}from"./chunk-PPGDAUEQ.mjs";import{a as wr,b as fe}from"./chunk-VV3B6IC3.mjs";import{a as oe}from"./chunk-4TLYUZD5.mjs";import{i as Es}from"./chunk-INIT2UKJ.mjs";import{a as ks,b as Ql}from"./chunk-SU65Z2BA.mjs";import{e as yw,h as Rn,k as ww,l as bw,m as Rw}from"./chunk-ZOSESZ22.mjs";import{D as Cs,F as Wh,p as Uh}from"./chunk-ZXOUWHYE.mjs";import{b as Mh,e as Lh,k as Fh,m as _h}from"./chunk-HFSBDM7B.mjs";import{a as db,b as cb}from"./chunk-PC247GKX.mjs";import{a as rr}from"./chunk-EADHKH3A.mjs";import{c as vh,f as Zi,g as Sh,j as kh,l as Oh,r as Ih,s as Ah}from"./chunk-Z3MGN42K.mjs";import{$ as Rh,F as hr,G as Is,N as mh,P as yh,Y as wh,Z as bh,a as Ki,b as tr,c as Yi,f as ph,j as fh,m as Qi,n as ou,o as gh,p as hh,q as Oo,r as gr}from"./chunk-2GSMHGIV.mjs";import{a as er,d as nu,f as uh,h as qe}from"./chunk-TZE3Y7IQ.mjs";import{a as Zg,b as O}from"./chunk-CA5NAXSU.mjs";import{f as hw,j as mw}from"./chunk-ISOSTAJR.mjs";import{a as Bh,d as qh}from"./chunk-7BQMBXKX.mjs";import{a as Hh}from"./chunk-KWAVSZ2B.mjs";import{a as Co,d as Vn}from"./chunk-TUACWKIH.mjs";import{$b as Ig,$c as Wl,A as ms,Aa as _r,Ad as gn,Ae as Ct,Ba as Ni,Bd as Dg,Be as qi,Ca as fg,Cd as Br,Ce as vs,Da as Ll,Dd as Ng,De as Ss,Ea as Fl,Ed as Vl,Ee as Wi,Fa as gg,Fd as jg,Fe as Xl,Ga as _l,Gd as Mg,Ge as Jg,Hd as Bi,He as Kl,I as dg,Id as Lg,Je as Vg,Lb as wg,Le as Xg,Ma as hg,Mb as zn,Me as Yl,Na as mg,Nb as Hl,Ne as zi,Ob as Bl,Oe as Kg,Pb as bg,Pd as Fg,Pe as Yg,Qb as Rg,Qe as Qg,Re as Gi,Ub as vg,Uc as bt,Wc as Gn,Wd as bs,Xb as Sg,Xc as _i,Y as Di,Yb as kg,Yd as qr,Z as Nl,Zb as Og,Zc as Ee,_ as cg,_b as ji,_c as bo,ac as Ag,ad as Ur,ae as _g,b as Yf,bc as Mi,c as Qf,cd as zl,d as ng,dc as Tg,dd as he,ec as Eg,ee as Wr,fc as Pg,fe as ct,ja as jl,k as yo,kd as Ui,l as wo,la as lg,lc as Cg,ld as Ro,mc as ql,md as vo,me as Ug,nb as yg,ne as Hg,o as fn,ob as Ul,od as $g,oe as Rs,p as hs,pd as xg,q as og,r as sg,s as ig,se as Bg,td as Gl,te as qg,ud as Hr,ue as Wg,va as ug,vc as Li,ve as zg,wa as Ml,we as Gg,xa as pg,xc as Fi,xd as ws,yd as Hi,z as ag,zc as ys,zd as Jl,ze as hn}from"./chunk-6QSHWIZI.mjs";import{a as Zf,b as j,e as Te,f as Ge,i as pn,k as ve,l as G,o as eg,p as $i,s as xi,u as _e,v as wt,x as tg,y as rg,z as Wn}from"./chunk-WZQEK4WT.mjs";var rS="pipeline-rewind-grants",oS="pipeline:rewind-grant:",nS="pipeline:saved:",Yu=G({pipelineId:j().min(1).max(200),stepId:j().min(1).max(200),organizationId:j().min(1).max(18),checkpointId:j().min(1).max(200),digest:j().regex(/^sha256:[0-9a-f]{64}$/),grantedAt:Wn.datetime(),grantedBy:j().max(80).optional(),takenBackAt:Wn.datetime().optional()}).strict();function $n(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 Qu(s,e){return`${oS}${s}:${e}`}var Js=class{constructor(e){this.store=e}store;all(){return Object.values(this.store.getByCategory(rS)).flatMap(e=>{let t=Yu.safeParse(e);return t.success?[t.data]:[]})}get(e,t){let r=Yu.safeParse(this.store.get(Qu(e,t)));return r.success?r.data:void 0}write(e){this.store.set(Qu(e.pipelineId,e.stepId),Yu.parse(e),rS)}revoke(e,t){return this.store.delete(Qu(e,t))}revokePipeline(e){let t=`${oS}${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&&Vs(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(`${nS}${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(`${nS}${e}`)?{refusal:"never"}:r.takenBackAt!==void 0||Vs(t.config)!==r.digest?{refusal:"changed"}:{grant:{organizationId:r.organizationId,checkpointId:r.checkpointId,digest:r.digest,grantedAt:r.grantedAt}}}};function Vs(s){let e=Ct.safeParse(s??{});return e.success?Ss(e.data):void 0}function sS(s,e){return new Js(s).revokePipeline(e)}function xn(s){let e;try{e=new URL(s)}catch{return{ok:!1,reason:"invalid"}}return e.protocol!=="https:"?{ok:!1,reason:"not-https",protocol:e.protocol}:{ok:!0,url:e}}var UT="/lightning/setup/AsyncApexJobs/home";function iS(s){let e=xn(s);return e.ok?{ok:!0,url:new URL(UT,e.url.origin).toString()}:e}import{randomBytes as HT}from"node:crypto";import{createReadStream as BT}from"node:fs";import{open as qT,readdir as WT,rm as zT,stat as GT}from"node:fs/promises";import{homedir as JT}from"node:os";import{join as cr,resolve as VT}from"node:path";import{createInterface as XT}from"node:readline";var Zu="journal.ndjson",id=2e3,uS=/^em-\d{8}-\d{6}-[a-z0-9]{4}$/,aS="abcdefghijklmnopqrstuvwxyz0123456789";function tp(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(HT(4),o=>aS[o%aS.length]).join("");return`em-${t}-${r}-${n}`}function ep(s){return uS.test(s)}function rp(s=process.env){let e=s.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?VT(e):cr(JT(),".sandforge");return cr(t,"empty")}var KT=j().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),en=j().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Not an API name").max(80),Xs=Wn.datetime({offset:!0}),dS=ve(KT).max(id),pS=_e(["success","partial","failure","cancelled"]),fS=G({v:wt(1),kind:wt("head"),runId:j().regex(uS),organizationId:j().min(15).max(18),orgName:j(),startedAt:Xs,readAt:Xs,previewId:j(),mode:_e(["objects","org"]),deleteMode:_e(["recycle","hard"]),request:G({mode:_e(["objects","org"]),objects:ve(j()).optional(),excluded:ve(j()).optional(),customSettings:Ge().optional(),files:Ge().optional(),managedPackages:Ge().optional(),unrestorable:Ge().optional()}).strict(),passes:ve(G({objectApiName:en,records:Te().int().nonnegative().optional(),sent:Te().int().nonnegative().optional(),rows:j().max(200).optional()})),toDraftAlong:ve(G({objectApiName:en,condition:j().optional()})),beforeParent:ve(G({objectApiName:en,field:j(),parent:en,reason:_e(["restricted","customPrices"])})),undoLost:ve(G({objectApiName:en,field:j().optional(),parent:en.optional(),reason:_e(["restricted","unordered","notRestorable"]),records:Te().int().nonnegative().optional(),atLeast:wt(!0).optional()})).optional()}),YT=G({kind:wt("attempt"),at:Xs,resumed:Ge()}),gS=G({kind:wt("spooled"),objectApiName:en,place:Te().int().nonnegative(),count:Te().int().nonnegative(),sinceRead:Ge()}),QT=G({kind:wt("settled"),objectApiName:en,deleted:dS,gone:dS}),ZT=G({objectApiName:en,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:ve(j())}),hS=G({kind:wt("end"),at:Xs,status:pS,hardRefused:j().optional(),passes:ve(ZT)}),eE=G({kind:wt("undo"),at:Xs,status:pS}),cS=$i("kind",[fS,YT,gS,QT,hS,eE]),Ir=class extends Error{constructor(e){super(e),this.name="EmptyJournalDamaged"}};function tE(s){return s==="success"||s==="partial"}var ad=class s{constructor(e,t){this.dir=e;this.head=t}dir;head;static async begin(e,t){let r=fS.parse({v:1,kind:"head",...t});await Ta(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 lS(cr(e,Zu))){r.kind==="head"&&(t=r);break}if(t===void 0)throw new Ir("The journal of this emptying names nothing it was to do.");return new s(e,t)}idsDirOf(e,t){return cr(this.dir,"ids",`${e}-${bt(t)}`)}async write(e,t="a"){let r=cr(this.dir,Zu),n=await qT(r,t,Ia);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(gS.parse({kind:"spooled",...e}))}async settled(e,t,r){for(let n=0;n<Math.max(t.length,r.length);n+=id)await this.write({kind:"settled",objectApiName:e,deleted:t.slice(n,n+id),gone:r.slice(n,n+id)})}ended(e,t,r,n){return this.write(hS.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 lS(cr(this.dir,Zu))}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":tE(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*lS(s){let e=BT(s,{encoding:"utf8"}),t=XT({input:e,crlfDelay:1/0}),r,n=0,o=(i,a)=>{try{return cS.parse(JSON.parse(i))}catch{throw new Ir(`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 Ir("The journal of this emptying is not on this machine."):i}finally{t.close(),e.destroy()}if(r)try{yield cS.parse(JSON.parse(r.raw))}catch{return}}var dd=class{constructor(e){this.root=e}root;orgDir(e){return cr(this.root,gb(e))}begin(e,t){return ad.begin(cr(this.orgDir(e),t.runId),{...t,organizationId:e})}async runsOf(e){let t=this.orgDir(e),r;try{r=await WT(t)}catch(n){if(n.code==="ENOENT")return[];throw n}return r.filter(ep).sort().map(n=>({runId:n,dir:cr(t,n)}))}async lastOf(e){return(await this.runsOf(e)).at(-1)}async open(e,t){if(!ep(t))throw new Ir(`Not an emptying's id: ${t}`);let r=cr(this.orgDir(e),t);try{await GT(r)}catch{throw new Ir(`No journal of the emptying ${t} is on this machine.`)}return ad.open(r)}async remove(e,t){ep(t)&&await zT(cr(this.orgDir(e),t),{recursive:!0,force:!0})}};import{createHash as rE}from"node:crypto";import{readFileSync as nE}from"node:fs";import{homedir as oE}from"node:os";import{join as cd,resolve as sE}from"node:path";var mS=G({...db,pipelineId:j().min(1).max(200),pipelineName:j().max(200).optional(),ranFrom:_e(["editor","commandLine"]),triggeredBy:_e(["manual","schedule","event","webhook","sandbox_refresh","deployment_complete"]),dryRun:Ge().optional()}),np=cb(s=>{let e=mS.safeParse(s);return e.success?e.data:void 0}),iE="run.lock",aE=/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;function yS(s=process.env){let e=s.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?sE(e):cd(oE(),".sandforge");return cd(t,"pipelines")}function Ks(s){return aE.test(s)&&!s.includes("..")?s:`p-${rE("sha256").update(s).digest("hex").slice(0,32)}`}function ld(s,e){return cd(s,Ks(e))}function wS(s,e){return cd(ld(s,e),iE)}function dE(s){try{let e=mS.safeParse(JSON.parse(nE(s,"utf8")));return e.success?e.data:void 0}catch{return}}function op({version:s,token:e,...t}){return t}function bS(s,e,t,r={}){let n=wS(s,e),o=dE(n),i=o!==void 0&&np.holder(n,r)===void 0,a=np.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:op(a.busy)}:{lock:{pipelineId:e,release:a.lock.release},...i&&o!==void 0?{tookOver:op(o)}:{}}}function $L(s,e,t={}){let r=np.holder(wS(s,e),t);return r!==void 0?op(r):void 0}function RS(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 sp(s,e){return`Pipeline "${e}" is already running on this machine: ${RS(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 vS(s){return`The run lock of pipeline "${s.pipelineName??s.pipelineId}" was left by ${RS(s)} started at ${s.acquiredAt} (process ${s.pid} on ${s.host}), whose process has ended: taken over.`}import{randomBytes as cE}from"node:crypto";import{mkdirSync as lE,readFileSync as OS,readdirSync as uE,renameSync as SS,statSync as pE,unlinkSync as fE,writeFileSync as gE}from"node:fs";import{join as ap}from"node:path";var dp=50,cp="history.json",lp=1,kS=4*1024*1024,hE=448,mE=384,yE=G({decision:_e(["approved","rejected","timedOut","cancelled"]),via:_e(["notification","page","terminal","commandLine"]).optional(),at:j().max(64),by:j().max(64).optional()}),wE=G({stepName:j().max(200),stepType:j().max(80),status:_e(["pending","running","completed","failed","skipped","stopped"]),duration:Te().nonnegative().optional(),summary:j().max(8e3).optional(),error:j().max(8e3).optional(),approval:yE.optional()}),ip=G({runId:j().min(1).max(200),pipelineId:j().min(1).max(200),pipelineName:j().max(200),status:_e(["idle","queued","running","completed","completed_with_warnings","failed","cancelled"]),triggeredBy:_e(["manual","schedule","event","webhook","sandbox_refresh","deployment_complete"]),startTime:Wn.datetime({offset:!0}),duration:Te().nonnegative(),stepCount:Te().int().nonnegative(),errorCount:Te().int().nonnegative(),steps:ve(wE).max(200).optional()}),bE=G({sandforgePipelineHistory:wt(lp),entries:ve(pn()).max(dp*4)});function LL(s,e){return ap(ld(s,e),cp)}function RE(s){let e=Date.parse(s.startTime);return{...s,ranFrom:"commandLine",timestamp:Number.isNaN(e)?0:e}}function IS(s){let e;try{e=JSON.parse(s)}catch{return{why:"it is not JSON"}}let t=bE.safeParse(e);if(!t.success){let o=e?.sandforgePipelineHistory;return{why:typeof o=="number"&&o>lp?`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=ip.safeParse(o);i.success?r.push(RE(i.data)):n+=1}return{entries:r,skipped:n}}function AS(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=uE(s,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name)}catch{return[]}let o=[];for(let i of n.sort()){let a=ap(s,i,cp),d,c;try{let u=pE(a);if(d=`${u.size}:${u.mtimeMs}`,u.size>kS){r(a,d,`[WARN] pipeline history ${a} is not listed: at ${u.size} bytes it is past the ${kS} a history of ${dp} runs takes.`);continue}c=OS(a,"utf8")}catch{continue}let l=IS(c);if("why"in l){r(a,d,`[WARN] pipeline history ${a} is not listed: ${l.why}. The runs it held are not shown in History; the next run from the command line starts it again.`);continue}l.skipped>0&&r(a,d,`[WARN] pipeline history ${a}: ${l.skipped} of its runs do not read and are not listed.`),o.push(...l.entries)}return o.sort((i,a)=>a.timestamp-i.timestamp)}}}function FL(s,e,t){let r=ip.safeParse(t);if(!r.success)throw new Error(`The run was not recorded: ${r.error.issues.slice(0,3).map(u=>`${u.path.join(".")||"(entry)"}: ${u.message}`).join("; ")}`);let n=ld(s,e);lE(n,{recursive:!0,mode:hE});let o=ap(n,cp),i=[],a,d;try{d=OS(o,"utf8")}catch{d=void 0}if(d!==void 0){let u=IS(d);"why"in u?(a=`${o}.unreadable-${Date.now()}`,SS(o,a)):i=u.entries.map(({ranFrom:f,timestamp:p,...g})=>ip.parse(g))}let c=[r.data,...i.filter(u=>u.runId!==r.data.runId)].sort((u,f)=>Date.parse(f.startTime)-Date.parse(u.startTime)).slice(0,dp),l=`${o}.${process.pid}-${cE(4).toString("hex")}.tmp`;gE(l,`${JSON.stringify({sandforgePipelineHistory:lp,entries:c},null,2)}
9
- `,{encoding:"utf8",mode:mE,flag:"wx"});try{SS(l,o)}catch(u){try{fE(l)}catch{}throw u}return{kept:c.length,...a!==void 0?{setAside:a}:{}}}var _t={major:20,minor:19},TS=5,vE=12,SE=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function pt(s){return s.replace(/\s*[\r\n\u2028\u2029]+\s*/g," ").trim()}function Ft(s){return`'${s.replace(/'/g,"'\\''")}'`}function Kt(s){return`'${s.replace(/['\u2018\u2019\u201a\u201b]/g,e=>e+e)}'`}function Go(s){return JSON.stringify(s)}function up(s){return s.endsWith(Xl)?s.slice(0,-Xl.length):s.replace(/\.json$/,"")}function kE(s){return`SFDX_AUTH_URL_${s.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")}`}function pp(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 ES(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 OE(s){return`npx -y sandforge@${s.sandforgeVersion} pipeline run --file ${s.fileName}`}function fp(s,e){return[`SandForge pipeline "${pt(s.pipelineName)}", run from its file with VS Code closed.`,`Exported by SandForge ${s.sandforgeVersion} on ${s.exportedAt}.`,"",...e,"",`It runs: ${OE(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 gp(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} "${pt(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} "${pt(n.name)}" rewinds an org with no alias: confirm it with pipeline confirm.`)}return r}function Jo(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 IE({alias:s,...e}){return e}function hp(s){if(!Jo(s.fileName))throw new Error("A pipeline file name is one line of text.");let e=[],t=s.orgs.flatMap(i=>Jo(i.key)?i.alias===void 0||Jo(i.alias)?[i]:(e.push(`The alias of org "${pt(i.label)}" holds a line break: it is asked below as an alias of this machine.`),[IE(i)]):(e.push(`Org "${pt(i.label)}" is named by a key no line can hold: run it from a terminal.`),[])),r=s.variables.filter(i=>Jo(i.name)?!0:(e.push(`Variable "${pt(i.name)}" holds a line break in its name, which no line gives: rename it.`),!1)),n=s.approvals.filter(i=>Jo(i.name)?!0:(e.push(`Approval step "${pt(i.name)}" holds a line break in its name: only a terminal answers it.`),!1)),o=s.rewinds.map(i=>i.alias===void 0||Jo(i.alias)?i:{name:i.name});return{input:{...s,orgs:t,variables:r,approvals:n,rewinds:o},leftOut:e}}function PS(s){return s.orgs.filter(e=>e.alias===void 0).map((e,t)=>({...e,slot:`org_alias_${t+1}`}))}function AE(s){let{input:e,leftOut:t}=hp(s),n=`${up(e.fileName)}.sh`,o=Ks(e.pipelineId),i=e.schedule===null?void 0:pp(zi(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.`]:[],...ES(i)]:["Its schedule cannot be written as a line of this machine's crontab:",pt(i.reason)],d=[`Keep it beside ${e.fileName}. It needs Node.js ${_t.major}.${_t.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=PS(e),l=["#!/usr/bin/env bash",...fp(e,d).map(u=>u===""?"#":`# ${u}`),"set -u","",'here="$(cd "$(dirname "$0")" && pwd)"',`file="$here/"${Ft(e.fileName)}`,`store="\${SANDFORGE_JOURNAL_DIR:-$HOME/.sandforge}/pipelines/"${Ft(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 > ${_t.major} || (a === ${_t.major} && b >= ${_t.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 ${_t.major}.${_t.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){l.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 u of c)l.push(`# The alias, on this machine, of org "${pt(u.label)}", which has none of its own`,"# (sf alias set <alias>=<its username>).",`${u.slot}="\${${u.slot.toUpperCase()}:-}"`);l.push("missing=()");for(let u of c)l.push(`[ -n "$${u.slot}" ] || missing+=(${Ft(`${u.slot} (the alias of org "${pt(u.label)}")`)})`);for(let u of e.variables)l.push(`[ -n "\${${u.env}:-}" ] || missing+=(${Ft(`${u.env} (variable "${pt(u.name)}"${u.secret?", a secret":""})`)})`);l.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 l.push('args=(pipeline run --file "$file" --triggered-by schedule --fail-on-partial)',...c.map(u=>`args+=(--org ${Ft(`${u.key}=`)}"$${u.slot}")`),...e.variables.map(u=>`args+=(--var-env ${Ft(`${u.name}=${u.env}`)})`),...gp(e,"#",(u,f)=>`args+=(${u} ${Ft(f)})`),"",'say "start"',`npx -y ${Ft(`sandforge@${e.sandforgeVersion}`)} "\${args[@]}" >>"$log" 2>&1`,"code=$?",'say "exit $code"','exit "$code"',""),{runner:"cron",fileName:n,text:l.join(`
10
- `),...i!==void 0?{schedule:i.kind==="line"?{...i,text:`${i.text} /bin/bash /path/to/${n}`}:i}:{}}}function TE(s){let e=Yl(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>vE)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=>SE[n]).join(",");return t.map(n=>r===void 0?`New-ScheduledTaskTrigger -Daily -At ${Kt(n)}`:`New-ScheduledTaskTrigger -Weekly -DaysOfWeek ${r} -At ${Kt(n)}`)}function EE(s){let{input:e,leftOut:t}=hp(s),r=up(e.fileName),n=`${r}.ps1`,o=Ks(e.pipelineId),i;if(e.schedule!==null){let u=pp(zi(e.schedule.cron,e.schedule.timezone,e.machineTimezone,e.now));if(u.kind!=="line")i=u;else{let f=TE(u.text);i=typeof f=="string"?{kind:"manual",reason:f}:{...u,text:[`# In PowerShell, from the folder that holds ${n}, once:`,`$action = New-ScheduledTaskAction -Execute 'pwsh' -Argument ('-NoProfile -File "{0}"' -f (Join-Path $PWD ${Kt(n)}))`,"$triggers = @(",...f.map(p=>` ${p}`),")",`Register-ScheduledTask -TaskName ${Kt(`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(u=>` ${u}`),...ES(i)]:i.kind==="manual"?[`Its schedule, ${e.schedule?.cron} in ${e.schedule?.timezone}, as Task Scheduler reads it:`,pt(i.reason)]:["Its schedule cannot be written for this machine's clock:",pt(i.reason)],d=[`Keep it beside ${e.fileName}. It needs PowerShell 7 (pwsh), Node.js`,`${_t.major}.${_t.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=PS(e),l=[...fp(e,d).map(u=>u===""?"#":`# ${u}`),"$ErrorActionPreference = 'Continue'","","$here = Split-Path -Parent $MyInvocation.MyCommand.Path",`$file = Join-Path $here ${Kt(e.fileName)}`,"$journal = if ($env:SANDFORGE_JOURNAL_DIR) { $env:SANDFORGE_JOURNAL_DIR } else { Join-Path $HOME '.sandforge' }",`$store = Join-Path (Join-Path $journal 'pipelines') ${Kt(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)","}","","$node = Get-Command node -ErrorAction SilentlyContinue","$nodeOk = $false","if ($node) {",` & node -e 'const [a, b] = process.versions.node.split(".").map(Number); process.exit(a > ${_t.major} || (a === ${_t.major} && b >= ${_t.minor}) ? 0 : 1)'`," $nodeOk = ($LASTEXITCODE -eq 0)","}","if (-not $nodeOk) {",` Say "Node.js ${_t.major}.${_t.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){l.push("# What the pipeline file does not hold, set here or in the environment.");for(let u of c)l.push(`# The alias, on this machine, of org "${pt(u.label)}", which has none of its own.`,`$${u.slot} = $env:${u.slot.toUpperCase()}`);l.push("$missing = @()");for(let u of c)l.push(`if (-not $${u.slot}) { $missing += ${Kt(`${u.slot} (the alias of org "${pt(u.label)}")`)} }`);for(let u of e.variables)l.push(`if (-not $env:${u.env}) { $missing += ${Kt(`${u.env} (variable "${pt(u.name)}"${u.secret?", a secret":""})`)} }`);l.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 l.push("$runArgs = @('pipeline', 'run', '--file', $file, '--triggered-by', 'schedule', '--fail-on-partial')",...c.map(u=>`$runArgs += @('--org', (${Kt(`${u.key}={0}`)} -f $${u.slot}))`),...e.variables.map(u=>`$runArgs += @('--var-env', ${Kt(`${u.name}=${u.env}`)})`),...gp(e,"#",(u,f)=>`$runArgs += @('${u}', ${Kt(f)})`),"","Say 'start'",`& npx -y ${Kt(`sandforge@${e.sandforgeVersion}`)} @runArgs *>> $log`,"$code = $LASTEXITCODE",'Say "exit $code"',"exit $code",""),{runner:"taskScheduler",fileName:n,text:l.join(`
13
- `),...i!==void 0?{schedule:i}:{}}}function PE(s){let e=Yl(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]<TS)return!0;return!1}function CE(s){let{input:e,leftOut:t}=hp(s),n=`${up(e.fileName)}.yml`,o=Ks(e.pipelineId),i=e.schedule===null?void 0:pp(zi(e.schedule.cron,e.schedule.timezone,e.schedule.timezone,e.now)),a=e.orgs.map((u,f)=>{let p=u.alias??`pipeline-org-${f+1}`;return{...u,ciAlias:p,secret:kE(p)}}),d=u=>u===""?"#":`# ${u}`,c=[...fp(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(u=>` ${u.secret}: the sfdx auth URL of "${pt(u.label)}" (sf org auth show-sfdx-auth-url --target-org ${u.alias??"<its username>"} --json, its result.sfdxAuthUrl)`),...e.variables.map(u=>` ${u.env}: variable "${pt(u.name)}"${u.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:",pt(i.reason)]:[],...i?.kind==="line"&&PE(i.text)?["",`GitHub starts a schedule every ${TS} minutes at most, whatever its line says.`]:[],...t.length>0?["",...t]:[]]).map(d),`name: ${Go(`SandForge pipeline: ${pt(e.pipelineName)}`)}`,"","on:"];i?.kind==="line"&&c.push(" schedule:",` - cron: ${Go(i.text)}`,` timezone: ${Go(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: ${Go(`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(u=>` ${u.secret}: \${{ secrets.${u.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((u,f)=>[` printf '%s' "$${u.secret}" > "$auth_dir/org-${f+1}.txt"`,` sf org login sfdx-url --sfdx-url-file "$auth_dir/org-${f+1}.txt" --alias ${Ft(u.ciAlias)}`])),c.push(" # The Sync watermarks, the confirmations and the history of earlier runs."," - uses: actions/cache@v4"," with:"," path: .sandforge",` key: ${Go(`sandforge-pipeline-${o}-\${{ github.run_id }}`)}`,` restore-keys: ${Go(`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 l=[`args=(pipeline run --file ${Ft(e.fileName)} --triggered-by "$TRIGGERED_BY" --fail-on-partial)`,...a.filter(u=>u.alias===void 0).map(u=>`args+=(--org ${Ft(`${u.key}=${u.ciAlias}`)})`),...e.variables.map(u=>`args+=(--var-env ${Ft(`${u.name}=${u.env}`)})`),...gp(e,"#",(u,f)=>`args+=(${u} ${Ft(f)})`),`npx -y ${Ft(`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(u=>` ${u.env}: \${{ secrets.${u.env} }}`)," run: |",...l.map(u=>` ${u}`),""),{runner:"githubActions",fileName:n,text:c.join(`
14
- `),...i!==void 0?{schedule:i}:{}}}function CS(s){return{cron:AE(s),taskScheduler:EE(s),githubActions:CE(s)}}var $E={"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},xE=new Set(["seed","anonymize","rewind","restore","delete"]),DE={sandbox_refresh:"sandbox refresh",event:"event",webhook:"webhook",deployment_complete:"deployment"},NE="prebuilt-",jE="tpl-";function Qs(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)?s:void 0}function Ar(s){return typeof s=="string"&&s.trim()!==""?s:void 0}function pd(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Zs(s,e){return pd(s,e)?s[e]:void 0}function Ys(s){return JSON.parse(JSON.stringify(s))}function ME(s){switch(_i(s.orgType??"",s.metadata?.edition)){case"Sandbox":return"sandbox";case"Scratch":return"scratch";case"Developer":return"developer";default:return"production"}}function LE(s){let e=ME(s),t=zl(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&&zl(r,s.username)?{name:r}:{}}}function mp(s,e){return e.alias??e.name??s}function ud(s,e,t,r){return{exported:!1,pipelineId:s,code:e,message:t,...r?{issues:r}:{}}}function FE(s,e){let t=[];return s.forEach((r,n)=>{let o=Qs(r.config)??{};if(r.type==="sync"){let a=e.get(Ar(o.configId)??""),d=Ar(a?.sourceOrgId),c=Ar(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=pd(Kl,r.type)?Kl[r.type]??[]:[];for(let a of i){let d=Ar(o[a]);d!==void 0&&t.push({orgId:d,stepIndex:n,stepName:r.name,writes:xE.has(r.type)})}}),t}function _E({defaultValue:s,...e}){return e}function UE(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 HE(s,e){let t=(s.triggers??[]).filter(n=>n.type==="schedule"&&(n.enabled||s.runsOutside!==void 0)&&Ar(n.config?.cron)!==void 0);if(t.length>1)return{many:t.length};let[r]=t;return r?{cron:(r.config.cron??"").trim(),timezone:Ar(r.config.timezone)?.trim()??e}:null}function BE(s){let e={};for(let t of Object.keys(Jg)){let r=$E[t],n=s.setting(t,r);n===r||n===void 0||n===null||(e[t]=n)}return e}function ei(s,e,t={}){return{code:s,text:e,...t}}function $S(s){let{pipeline:e}=s,t=e.id,r=Ys(e.steps??[]).map(p=>({...p,config:Qs(p.config)??{}})),n=HE(e,s.machineTimezone);if(n!==null&&"many"in n)return ud(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 p of r){let g=p.config;if(p.type==="sync"){let m=Ar(g.configId);if(m===void 0||pd(o,m))continue;let y=Qs(s.syncConfig(m));if(!y)return ud(t,"SYNC_CONFIG_UNKNOWN",`Sync step "${p.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]={...Ys(y),id:m}}let h=Ar(g.templateId);if(p.type==="seed"&&h&&!h.startsWith(NE)){let m=Qs(s.seedTemplate(h));m&&(i[h]={...Ys(m),id:h})}if(p.type==="anonymize"&&h&&!h.startsWith(jE)){let m=Qs(s.maskingTemplate(h));m&&(a[h]={...Ys(m),id:h})}}let d=FE(r,new Map(Object.entries(o))),c={},l=new Map;for(let p of d){if(pd(c,p.orgId))continue;let g=s.org(p.orgId);if(!g)return ud(t,"ORG_UNKNOWN",`Step "${p.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[p.orgId]=LE(g),l.set(p.orgId,g.authMethod!=="usernamePassword")}let u=UE(e.variables??[]),f=Ys(e.variables??[]).map(p=>p.type==="secret"?_E(p):p);return{pipelineId:t,fileName:Xg(e.name),schedule:n,orgs:c,cliHolds:l,uses:d,syncConfigs:o,seedTemplates:i,maskingTemplates:a,settings:BE(s),steps:r,variables:f,envs:u}}function xS(s,e,t){return s.checkedWhereItRuns!==!0&&e.type==="rewind"&&t!==void 0&&(t===$n(e.name,"never")||t===$n(e.name,"changed"))}function qE(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(ei(g,h,{step:o.name}))},c=s.stepRefusal?.(o,i),l=xS(s,o,c)?void 0:c,u=n(i).find(g=>Zs(e.orgs,g)?.kind==="production"),f="runs",p;if(l!==void 0)f="refused",p=l,d("STEP_REFUSED",l);else if(u!==void 0){f="refused";let g=Zs(e.orgs,u);p=`Step "${o.name}" writes to "${g?mp(u,g):u}", a production org: the command line never writes to a production org, whatever an Approval answers.`,d("STEP_REFUSED",p)}else if(o.type==="approval")f="asks",e.uses.some(h=>h.stepIndex>i&&h.writes&&Zs(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"){f="asks";let g=Ar(o.config.orgId),h=g!==void 0?Zs(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:f,notes:a,...p!==void 0?{refusal:p}:{}})}),{steps:r,notes:t}}function WE(s,e){let t=[];for(let[r,n]of Object.entries(e.orgs))if(n.alias===void 0&&t.push(ei("ORG_NO_ALIAS",`Org "${mp(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(ei("ORG_NOT_SIGNED_IN",`The Salesforce CLI of this machine does not hold org "${mp(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(ei("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=DE[r.type];!r.enabled||n===void 0||t.push(ei("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 zE(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 GE(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 DS(s,e,t){let{pipeline:r}=s;return Vg({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 NS(s){let e=s.pipeline.id,t=$S(s);if("exported"in t)return t;let{steps:r,notes:n}=qE(s,t),o=[...n,...WE(s,t)],i=DS(s,t,o);if(!i.ok)return ud(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=zE(t),d=GE(t),c=a.map(f=>({key:f.key,...f.alias!==void 0?{alias:f.alias}:{},label:f.alias??f.name??f.key})),l=d.flatMap(f=>f.env!==void 0?[{name:f.name,env:f.env,secret:f.type==="secret"}]:[]),u={fileName:t.fileName,text:i.text,digest:i.file.digest,schedule:t.schedule,steps:r,orgs:a,variables:d,launchers:CS({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:l,approvals:r.filter(f=>f.type==="approval"&&f.fate==="asks").map(f=>({name:f.name,staging:f.notes.includes("STAGING_NEEDS_PERSON")})),rewinds:t.steps.filter(f=>f.type==="rewind").map(f=>{let p=Ar(f.config.orgId),g=p!==void 0?Zs(t.orgs,p)?.alias:void 0;return{name:f.name,...g!==void 0?{alias:g}:{}}})}),notes:o,problems:(s.problems??[]).filter(f=>!t.steps.some(p=>xS(s,p,f)))};return{exported:!0,pipelineId:e,...u}}function jS(s){let e=$S(s);if("exported"in e)return;let t=DS(s,e,[]);return t.ok?t.file.digest:void 0}import{randomUUID as sL}from"node:crypto";import{join as iL}from"node:path";import{randomBytes as JE,randomUUID as Vo}from"node:crypto";import{lstat as VE,rename as XE,rm as KE,stat as YE}from"node:fs/promises";import{hostname as QE}from"node:os";import{basename as ri,dirname as _S,join as ZE,sep as eP}from"node:path";var tP=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"]),Tr="checkpoint",rP=8,nP=6e4,lr="CANCELLED",oP={success:"success",partial:"partial",unstable:"partial",failure:"failure",cancelled:"cancelled"},sP={preview:"previewed",rewind:"rewound to",undo:"used",export:"exported"};function yp(s){let{result:e,notes:t,deliverability:r}=s;return{done:!0,result:e,notes:t,...r!==void 0?{deliverability:r}:{}}}var iP=/\s*\b(?:No record was (?:read or )?written|Nothing was written)\./g;function wp(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:US([n,...o])},alsoRefused:o}:{done:!1,refusal:n,alsoRefused:o}}function US(s){let e=!1;return s.map(({message:t})=>{let r=t.replace(iP,"").trim();return e?r:(e=r!==t.trim(),t)}).join(" ")}var aP=new Set(["RUN_WRITING","API_BUDGET","EMAILS"]),Er=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 MS(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 dP(){let[s,e,t,r,n,o,i,a,d,c,l,u,f]=await Promise.all([import("./chunk-XAMMIPZ4.mjs"),import("./chunk-GTRU5AV5.mjs"),import("./chunk-LI2XNV7F.mjs"),import("./chunk-ZCOSME6P.mjs"),import("./chunk-OS6HFJ7L.mjs"),import("./chunk-36Y225OM.mjs"),import("./chunk-L6CLN664.mjs"),import("./chunk-LP2D3JJP.mjs"),import("./chunk-R7GKMAT4.mjs"),import("./chunk-QQDZQCO2.mjs"),import("./chunk-ZTHC42X6.mjs"),import("./chunk-WABXKL4N.mjs"),import("./chunk-3CM7LAPE.mjs")]);return{pageEmailsRefusal:l.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,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:u.ReplayStore,defaultReplayStoreRoot:u.defaultReplayStoreRoot,loadToRemove:f.loadToRemove,loadRecordsInfo:f.loadRecordsInfo}}var ke=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 fd(s){return s instanceof vt?s:s instanceof ke?s.code===lr?new vt(s.message):new Er(s.code,s.alsoRefused.length>0?US([s,...s.alsoRefused]):s.message,s.result,s.alsoRefused):s}async function LS(s){try{return(await YE(s)).isDirectory()}catch{return!1}}function Dt(s,e){return s!==void 0&&e!==void 0&&s.length>=15&&s.slice(0,15)===e.slice(0,15)}var FS=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function ti(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 ke("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 ft(s){return he(s)}function cP(s,e){let t=[...e].sort((n,o)=>o.length-n.length),r=s;for(let n of t)r=r.replaceAll(n,ri(n));for(let n of t){let o=_S(n);o===n||o.length<=1||(r=r.replaceAll(`${o}${eP}`,"").replaceAll(o,ri(o)))}return r}function lP(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 uP(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 bp(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 gd=class{constructor(e,t={},r=Co){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(!tP.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: ${O(e)}`)}}async keptBefore(e){let t=e.previousOrganizationId??this.deps.sandboxRefreshes?.organizationIdOf(e.orgId);return t===void 0||!FS.test(t)?0:(await(await this.openedStore()).list({organizationId:t})).length}async latestUsableOf(e){let t=this.deps.orgManager.getOrg(e);if(!t||!bo(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:${Vo()}`,o=this.registeredOrg(e.orgId),i=await this.modules(),a=await this.openedStore(),d=this.beforeRunRequestOf(i,e),c=i.beforeRunScopeOf(d),l=(g,h={})=>{let{taken:m}=h;Z(this.deps,{action:"checkpoint_take",module:Tr,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 l("stopped",{code:g.code}),{taken:!1,refusal:g}}let u=await this.connect(o);if(r.signal?.aborted)return l("cancelled"),{taken:!1,stopped:!0};let f;try{f=await this.take(n,i,a,u,o,i.beforeRunAskedOf(c,d),{description:`Checkpoint first: taking a checkpoint of ${ft(o)} before the run`,runWriting:this.beforeRunWriting(o,t),...r.signal?{signal:r.signal}:{},...r.onProgress?{onProgress:r.onProgress}:{}})}catch(g){if(g instanceof ke&&g.code===lr)return l("cancelled"),{taken:!1,stopped:!0};if(g instanceof ke&&g.refusal!==void 0)return l("stopped",{code:g.refusal.code}),{taken:!1,refusal:g.refusal};throw l("failure"),g}let p=await i.beforeRunOutcomeOf(a,c,f);return p.taken?l("success",{taken:p.checkpoint}):(this.checkpointsChanged(),l("stopped",{..."refusal"in p?{code:p.refusal.code}:{}})),p}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",ag.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,ft(e),"start this run","No record was read.",t)}async takeForPipeline(e,t){let r=`checkpoint:pipeline:${Vo()}`;try{let n=hn.safeParse(e.config);if(!n.success)throw new ke("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 ke(lr,new a.CheckpointTakeStopped().message);let{checkpoint:l}=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 ${ft(i)}`,...t?{signal:t}:{}});return{operationId:r,checkpointId:l.checkpointId,name:l.name,records:l.objects.reduce((u,f)=>u+f.records,0),objects:l.objects.length,bytes:l.bytes,movedWhileTaken:l.movedWhileTaken}}catch(n){throw fd(n)}}async rewindForPipeline(e,t){let r=`checkpoint:pipeline:${Vo()}`,{grant:n,origin:o}=e;try{let i=await this.modules(),a=Ct.safeParse(e.config);if(!a.success)throw new ke("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!==Ss(d)||n.checkpointId!==d.checkpointId)throw this.refusalOf(i.notConfirmedRefusal(o.step,!0));let c=await this.openedStore(),{folder:l,checkpoint:u}=await this.checkpointOf(c,d.checkpointId);if(!Dt(n.organizationId,u.org.organizationId))throw this.refusalOf(i.notConfirmedRefusal(o.step,!0));this.usable(i,u,"rewind");let f=this.registeredOrg(d.orgId);if(!Dt(f.orgId,u.org.organizationId)&&!Dt(this.deps.sandboxRefreshes?.organizationIdOf(f.id),u.org.organizationId))throw new ke("OTHER_ORG",`The checkpoint '${u.name}' is not of ${ft(f)}, the org the Rewind step "${o.step}" names. No record was read or written.`);let p=ti(u,d.objects),g=await this.connect(f),h=ft(f),m={operationId:r,pipeline:{origin:o,grantedAt:n.grantedAt}},y=()=>(this.audit(m,"rewind",f,u,"stopped",{code:Rt}),new vt(new i.RewindStopped().message)),R=(D,z=[])=>(this.audit(m,"rewind",f,u,"stopped",{code:D.code}),this.refusalOf(D,z));if(t?.aborted)throw y();let k;try{k=await i.previewCheckpoint({org:i.takeOrgOf(g),store:c,readAutomation:D=>this.readAutomation(f.id,D),runWriting:this.runWriting(f.id,h,"rewind","No record would be read or written."),...t?{signal:t}:{}},{checkpoint:u,folder:l,orgName:h,registered:f,username:f.username,...p!==void 0?{objects:p}:{},reusesPreview:!0,...d.muteAutomation?{muteAutomation:!0}:{},acceptOutside:d.acceptOutside})}catch(D){throw t?.aborted?y():D}if(!k.previewed)throw R(k.refusal);let w=p!==void 0?i.selectionDiff(k.diff,await i.planSelection({checkpoint:u,previewDir:i.previewDirOf(l,k.diff.previewId),readAt:k.diff.readAt,objects:new Set(p),acceptOutside:d.acceptOutside,heldRows:i.snapshotRowsOf(u,l),...t?{signal:t}:{}})):k.diff,I=d.muteAutomation&&k.automation?Su(k.automation,qr(i.rewindStepsOf(w))).automation:k.automation,P=await i.boundsRefusals({orgName:h,preview:{diff:w,...I?{automation:I}:{},...k.emails?{emails:k.emails}:{},...k.emailsUncounted!==void 0?{emailsUncounted:k.emailsUncounted}:{},...k.deliverability?{deliverability:k.deliverability}:{}},bounds:{maxRecords:d.maxRecords,refuseWhenActive:d.refuseWhenActive},accepted:d,writers:async()=>i.rewindWriters(u.takenBy,await i.takeOrgOf(g).userId()),words:d.muteAutomation?i.REWIND_MUTING_STEP_WORDS:i.REWIND_STEP_WORDS,user:f.username}),[b,...S]=[...k.refusal!==void 0?[k.refusal]:[],...P.filter(D=>D.code!==k.refusal?.code)];if(b!==void 0)throw R(b,S);if(t?.aborted)throw y();let C=[],v=[],T=await this.writeAct(m,"rewind",f,u,`Pipeline '${o.pipeline}': rewinding ${h} to '${u.name}'`,async(D,z)=>{let H=await i.rewindOrg({org:i.rewindOrgOf(g),undelete:Y=>g.soap.undelete(Y),store:c,readAutomation:Y=>this.readAutomation(f.id,Y),runWriting:this.runWriting(f.id,h,"rewind","No record was read or written."),onUndeletable:Y=>(C.push(...Y),this.deps.log(`[WARN] checkpoint:rewind ${r}: the user may not delete ${Y.map(U=>`${U.objectApiName} (${U.records})`).join(", ")} in the target, and nobody runs the pipeline to be asked: the deletion is left untouched`),Promise.resolve(!1)),onProgress:({percentage:Y,step:U})=>z(Y,U),signal:D,...d.muteAutomation?{mute:this.muteOf(g)}:{}},{checkpoint:u,folder:l,orgName:h,registered:f,username:f.username,previewId:k.diff.previewId,reusesPreview:k.diff,...p!==void 0?{objects:p}:{},acceptAutomation:d.acceptAutomation,acceptEmails:d.acceptEmails,acceptNoUndo:d.acceptNoUndo,acceptRecreate:d.acceptRecreate,acceptOutside:d.acceptOutside,acceptUnseen:d.acceptUnseen});return H.rewound?(v=H.notes,yp(H)):wp(H.refusal,H.alsoRefused,Y=>Y,!1)},D=>D instanceof i.RewindStopped,{...t?{signal:t}:{},acceptEmails:d.acceptEmails,refusalOf:D=>C.length>0?i.undeletableUnattendedRefusal(h,C,MS(D)):void 0});return{operationId:r,checkpointId:u.checkpointId,result:T,notes:v,estimate:k.estimate}}catch(i){throw fd(i)}}async estimateTakeForPipeline(e,t){try{let r=hn.safeParse(e.config);if(!r.success)throw new ke("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 ke(lr,new i.CheckpointTakeStopped().message);let c=await i.scopeCheckpoint({org:i.takeOrgOf(d),store:a,handler:this.deps,runWriting:this.runWriting(o.id,ft(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((l,u)=>l+u.records,0),leftOut:c.leftOut.length,estimate:c.estimate}}catch(r){throw fd(r)}}async previewRewindForPipeline(e,t){let{grant:r,origin:n}=e;try{let o=await this.modules(),i=Ct.safeParse(e.config);if(!i.success)throw new ke("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!==Ss(a)||r.checkpointId!==a.checkpointId)throw this.refusalOf(o.notConfirmedRefusal(n.step,!0));let d=await this.openedStore(),{folder:c,checkpoint:l}=await this.checkpointOf(d,a.checkpointId);if(!Dt(r.organizationId,l.org.organizationId))throw this.refusalOf(o.notConfirmedRefusal(n.step,!0));this.usable(o,l,"rewind");let u=this.registeredOrg(a.orgId);if(!Dt(u.orgId,l.org.organizationId)&&!Dt(this.deps.sandboxRefreshes?.organizationIdOf(u.id),l.org.organizationId))throw new ke("OTHER_ORG",`The checkpoint '${l.name}' is not of ${ft(u)}, the org the Rewind step "${n.step}" names. No record was read or written.`);let f=ti(l,a.objects),p=await this.connect(u),g=ft(u);if(t?.aborted)throw new ke(lr,new o.RewindStopped().message);let h=await o.previewCheckpoint({org:o.takeOrgOf(p),store:d,readAutomation:P=>this.readAutomation(u.id,P),runWriting:this.runWriting(u.id,g,"rewind","No record would be read or written."),...t?{signal:t}:{}},{checkpoint:l,folder:c,orgName:g,registered:u,username:u.username,...f!==void 0?{objects:f}:{},reusesPreview:!0,...a.muteAutomation?{muteAutomation:!0}:{},acceptOutside:a.acceptOutside});if(!h.previewed)throw this.refusalOf(h.refusal);let m=f!==void 0?o.selectionDiff(h.diff,await o.planSelection({checkpoint:l,previewDir:o.previewDirOf(c,h.diff.previewId),readAt:h.diff.readAt,objects:new Set(f),acceptOutside:a.acceptOutside,heldRows:o.snapshotRowsOf(l,c),...t?{signal:t}:{}})):h.diff,y=a.muteAutomation&&h.automation?Su(h.automation,qr(o.rewindStepsOf(m))).automation:h.automation,R=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(l.takenBy,await o.takeOrgOf(p).userId()),words:a.muteAutomation?o.REWIND_MUTING_STEP_WORDS:o.REWIND_STEP_WORDS,user:u.username}),[k,...w]=[...h.refusal!==void 0?[h.refusal]:[],...R.filter(P=>P.code!==h.refusal?.code)];if(k!==void 0)throw this.refusalOf(k,w);let I=P=>m.objects.reduce((b,S)=>b+P(S),0);return{checkpointId:l.checkpointId,toDelete:I(({toDelete:P})=>P.createdSince+P.broughtBackSince+P.comesBackWithParent),toGiveBack:I(({toGiveBack:P})=>P.records),toBringBack:I(({toBringBack:P})=>P.inBin+P.withParent+P.deletedWhileTaken),toRecreate:I(({toRecreate:P})=>P??0),estimate:h.estimate}}catch(o){throw fd(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 Z(this.deps,{action:"checkpoint_export",module:Tr,operationId:Vo(),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,l,u={})=>{Z(this.deps,{action:"checkpoint_import",module:Tr,operationId:Vo(),orgId:d,outcome:c,...u.code!==void 0?{code:u.code}:{},details:{...l?{checkpointId:l.checkpointId,records:l.records,objects:l.objects}:{},...u.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:QE(),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=ft(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:ft(i),registered:i,username:i.username,organizationId:t.organizationId});if(!c.allowed){let l=c.refusal.code==="OTHER_ORG"?this.refreshedAt(t.organizationId):void 0;return{refusal:l!==void 0?{code:"OTHER_ORG",message:`The sandbox this file's checkpoint was taken of was refreshed on ${l.slice(0,10)}: ${ft(i)} is another org now, and the checkpoint can no longer be rewound to. ${ms} 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 ke)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:O(e)}}async handleExport(e){let t=$(Zm,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 l=await VE(c).then(()=>!0,()=>!1),u=l?ZE(_S(c),`.${ri(c)}.${JE(4).toString("hex")}.export`):c;r.push(u);let f=await this.exportCheckpoint({checkpointId:d,out:u,sandforgeVersion:n.sandforgeVersion});if(!f.exported)throw new ke(f.refusal.code,f.refusal.message);if(l)try{await XE(u,c)}catch(p){throw await KE(u,{force:!0}),p}this.respond(e,"checkpoint:export:response",{status:"saved",checkpointId:d,fileName:ri(c),key:f.key,records:f.header.records,objects:f.header.objects,bytes:f.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=[],l;for(let f of this.deps.orgManager.getAllOrgs()){if(!this.organizationIdsOf(f.id).some(h=>Dt(h,d.organizationId)))continue;let g=await this.readImport({orgId:f.id,file:i});g.allowed?c.push(f.id):l??=g.refusal}if(c.length===0&&l!==void 0)throw new ke(l.code,l.message);let u=await o.read(d.checkpointId)!==void 0;this.respond(e,"checkpoint:import-read:response",{status:"read",token:this.keepImportFile(i),fileName:ri(i),summary:lP(d),orgIds:c,...u?{keptHere:!0}:{}})}catch(r){this.fail(e,this.pathless(r,t,"IMPORT_ERROR"),"IMPORT_ERROR")}}async handleImport(e){let t=$(ey,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 ke("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 ke("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 ke(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 ke(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 ke("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=Vo();this.importFiles.set(t,e);for(let r of this.importFiles.keys()){if(this.importFiles.size<=rP)break;this.importFiles.delete(r)}return t}pathless(e,t,r){let n=e instanceof ke?e:new ke(r,O(e));return new ke(n.code,cP(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: ${O(t)}`)}}modules(){return this.loaded??=dP(),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 ke("STORE_REFUSED",uP(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 ke){let o=t.refusal?.holdingLimit,i={...t.alsoRefused.length>0?{alsoRefused:[...t.alsoRefused]}:{},...o!==void 0?{holdingLimit:o}:{}};E(this.deps,e.type,"checkpoint:error",e,t,{code:t.code,retryable:t.retryable,...Object.keys(i).length>0?{extraPayload:i}:{}});return}E(this.deps,e.type,"checkpoint:error",e,t,{code:r,retryable:n})}refusalOf(e,t=[]){return new ke(e.code,e.message,aP.has(e.code),void 0,e,t)}registeredOrg(e){let t=this.deps.orgManager.getOrg(e);if(!t)throw new ke("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 So&&t.code==="SCRATCH_ORG_EXPIRED"?new ke("SCRATCH_EXPIRED",`${ft(e)} is a scratch org that has expired: its checkpoints no longer rewind it. `+ms):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:ft(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||Vn(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||Dt(e.targetOrganizationId,r)||Dt(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(Dt(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||!FS.test(o)||n.some(i=>Dt(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(l=>l.checkpointId===a.checkpointId),c=[];for(let l of d){let u=n.find(g=>Dt(g.orgId,l.target.organizationId)),f=await r.mappingStoreOf(r.folderOf(l.sourceOrganizationId,l.checkpointId),l.target.organizationId).recordedLoads(),p=t.loadToRemove(f);c.push({target:{organizationId:l.target.organizationId,...l.target.name!==void 0?{name:l.target.name}:{},...u?{orgId:u.id}:{}},...l.replayedAt!==void 0?{replayedAt:l.replayedAt}:{},inPlace:l.inPlace,...l.removed?{removed:!0}:{},...l.choices?{choices:l.choices}:{},...u&&p?{records:{...t.loadRecordsInfo(p),orgId:u.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: ${O(t)}`),e}}orgOfCheckpoint(e){let t=e.org.organizationId,r=this.deps.orgManager.getAllOrgs(),n=r.filter(a=>Dt(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=>Dt(i?.organizationIdOf(a.id),t))}async checkpointOf(e,t){let r=await e.read(t);if(r===void 0)throw new ke("NOT_FOUND",`No checkpoint ${t} is kept on this machine.`,!1);if(r.checkpoint===void 0)throw new ke("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=he(t.org);if(t.status!=="ready")throw new ke(t.status==="taking"?"TAKING":"FAILED",t.status==="taking"?`The checkpoint '${t.name}' is being taken, or its take never ended: it can be ${sP[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 ke("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. `+ms);if(e.scratchOrgExpired(t.org,Date.now()))throw new ke("SCRATCH_EXPIRED",`${n} is a scratch org that has expired: its checkpoints no longer rewind it. `+ms)}connectedOrgOf(e,t){let r=this.orgOfCheckpoint(e);if(!r){let n=he(e.org);throw new ke("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 ke("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,l=a?.mutedAutomation??i.muted,u=a?.rewindId??i.rewindId,f=e.pipeline;Z(this.deps,{action:t==="rewind"?"checkpoint_rewind":"checkpoint_undo",module:Tr,operationId:e.operationId,orgId:r.id,outcome:o,...a?{objects:ya(Sn(a.deleted),a.restored,a.undeleted)}:{},...d!==void 0?{code:d}:{},...l?{muted:ct(l)}:{},details:{checkpointId:n.checkpointId,...u!==void 0?{rewindId:u}:{},...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"}:{},...f?{pipeline:f.origin.pipeline,step:f.origin.step,trigger:f.origin.trigger,grantedAt:f.grantedAt}:{}}})}async handleList(e){let t=$(Jm,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=$(Vm,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,ft(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=$(Xm,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 ke(lr,new a.CheckpointTakeStopped().message,!0);await this.take(e.id,a,d,c,i,t,{kept:({checkpoint:l,requests:u,estimate:f})=>this.respond(e,"checkpoint:take:response",{checkpoint:l,operationId:e.id,...u?{requests:u}:{},estimate:f})})}catch(i){this.fail(e,i,"TAKE_ERROR")}finally{o?.release()}}async take(e,t,r,n,o,i,a={}){let d=ft(o),c=a.description??`Taking a checkpoint of ${d}`,l=this.deps.infraServices?.backgroundRegistry,u=new AbortController,f=()=>{},p=new Promise((y,R)=>{f=k=>k===void 0?y():R(k)});p.catch(()=>{}),ze(this.deps,e,Tr,c),l?.register(e,Tr,c,p,u);let g=ir(this.liveTracker,e,Tr,c),h=y=>{let{percentage:R,processedObjects:k,totalObjects:w,step:I}=y;Le(this.deps,e,R,k,w,I),u.signal.aborted||l?.updateProgress(e,R),g.progress(R,k,w,I),a.onProgress?.(y)},m=()=>{l?l.abort(e):u.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:u.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 pe(this.deps,e,{status:"refused",code:y.refusal.code}),g.fail(y.refusal.message),f(new Error(y.refusal.message)),this.refusalOf(y.refusal);for(let{objectApiName:w,reason:I}of y.notChecked)this.deps.log(`[WARN] checkpoint:take ${e}: what moved in ${w} while it was read was not checked: ${I}`);let{checkpoint:R}=y,k={checkpoint:R,...y.requests?{requests:y.requests}:{},estimate:y.estimate};return a.kept?.(k),this.checkpointsChanged(),pe(this.deps,e,{status:"success",objects:R.objects.length,records:R.objects.reduce((w,I)=>w+I.records,0)}),g.complete(),f(),k}catch(y){throw y instanceof ke?y:y instanceof t.CheckpointTakeStopped?(l?.abort(e),pe(this.deps,e,{aborted:!0}),g.cancel(),f(),new ke(lr,y.message,!0)):(pe(this.deps,e,{status:"failure"}),g.fail(O(y)),f(y),y)}finally{a.signal?.removeEventListener("abort",m)}}async handlePreview(e){let t=$(Km,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=ti(i,t.objects),d=this.connectedOrgOf(i,`preview the checkpoint '${i.name}'`),c=await this.connect(d),l=await r.previewCheckpoint({org:r.takeOrgOf(c),store:n,readAutomation:u=>this.readAutomation(d.id,u),runWriting:this.runWriting(d.id,ft(d),"rewind","No record would be read or written."),...t.muteAutomation===!0?{mute:this.muteOf(c)}:{}},{checkpoint:i,folder:o,orgName:ft(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(!l.previewed)throw this.refusalOf(l.refusal);this.previewsAnswered?.set(l.diff.previewId,l.diff),this.previewReads.set(l.diff.previewId,{checkpointId:i.checkpointId,readAt:l.diff.readAt}),this.respond(e,"checkpoint:preview:response",{diff:l.diff,...l.automation?{automation:l.automation}:{},...l.emails?{emails:l.emails}:{},...l.emailsKeepingOutside?{emailsKeepingOutside:l.emailsKeepingOutside}:{},...l.emailsUncounted!==void 0?{emailsUncounted:l.emailsUncounted}:{},...l.deliverability?{deliverability:l.deliverability}:{},estimate:l.estimate,...l.refusal?{refusal:l.refusal}:{}})}catch(r){this.fail(e,r,"PREVIEW_ERROR")}}async handlePlanSelection(e){let t=$(Qm,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=ti(i,t.objects)??[],d=r.previewDirOf(o,t.previewId),c=this.previewReads.get(t.previewId);if(c?.checkpointId!==i.checkpointId||!await LS(d))throw new ke("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 l=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:l})}catch(r){this.fail(e,r,"PLAN_SELECTION_ERROR")}}async handleRewind(e){let t=$(Ym,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=ti(d,t.objects);if(!await LS(o.previewDirOf(a,t.previewId)))throw new ke("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 l=this.connectedOrgOf(d,`rewind it to the checkpoint '${d.name}'`),u=await this.connect(l),f=this.pageAt(e);if(n?.signal.aborted)throw this.audit(f,"rewind",l,d,"stopped",{code:Rt}),new ke(lr,new o.RewindStopped().message,!0);let p=this.previewsAnswered?.get(t.previewId);this.previewsAnswered?.delete(t.previewId);let g=p?.checkpointId===d.checkpointId?p:void 0,h=ft(l);await this.writeAct(f,"rewind",l,d,`Rewinding ${h} to '${d.name}'`,async(m,y)=>{let R=await o.rewindOrg({org:o.rewindOrgOf(u),undelete:w=>u.soap.undelete(w),store:i,readAutomation:w=>this.readAutomation(l.id,w),runWriting:this.runWriting(l.id,h,"rewind","No record was read or written."),onUndeletable:zr(this.deps,l.id,"checkpoint:rewind"),onProgress:({percentage:w,step:I})=>y(w,I),signal:m,...t.muteAutomation===!0?{mute:this.muteOf(u)}:{}},{checkpoint:d,folder:a,orgName:h,registered:l,username:l.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(R.rewound)return yp(R);let k=t.fromPage===!0;return wp(R.refusal,R.alsoRefused,w=>k?o.pageEmailsRefusal(w,"rewind",h):w,k)},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=$(ty,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}'`),l=await this.connect(c),u=this.pageAt(e);if(n?.signal.aborted)throw this.audit(u,"undo",c,d,"stopped",{code:Rt,rewindId:t.rewindId}),new ke(lr,new o.UndoStopped().message,!0);let f=ft(c);await this.writeAct(u,"undo",c,d,`Undoing the rewind of ${f} to '${d.name}'`,async(p,g)=>{let h=await o.undoCheckpoint({org:o.rewindOrgOf(l),undelete:y=>l.soap.undelete(y),store:i,readAutomation:y=>this.readAutomation(c.id,y),runWriting:this.runWriting(c.id,f,"undo the rewind","No record was read or written."),onUndeletable:zr(this.deps,c.id,"checkpoint:undo"),onProgress:({percentage:y,step:R})=>g(y,R),signal:p,...t.muteAutomation===!0?{mute:this.muteOf(l)}:{}},{checkpoint:d,folder:a,orgName:f,registered:c,username:c.username,rewindId:t.rewindId,acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails===!0,canMute:!0});if(h.undone)return yp(h);let m=t.fromPage===!0;return wp(h.refusal,h.alsoRefused,y=>m?o.pageEmailsRefusal(y,"undo",f):y,m)},p=>p 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)=>Ot(async()=>Lt(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:l}=d,u=this.deps.infraServices?.backgroundRegistry,f=new AbortController,p=()=>{},g=new Promise((k,w)=>{p=I=>I===void 0?k():w(I)});g.catch(()=>{}),ze(this.deps,c,Tr,o),u?.register(c,Tr,o,g,f);let h=ir(this.liveTracker,c,Tr,o),m=l!==void 0?{rewindId:l}:{},y=(k,w)=>{Le(this.deps,c,k,0,0,w),f.signal.aborted||u?.updateProgress(c,k),h.progress(k,0,0,w)},R=()=>{u?u.abort(c):f.abort()};d.signal?.addEventListener("abort",R,{once:!0}),d.signal?.aborted&&R();try{let k=await i(f.signal,y);if(!k.done)throw this.audit(e,t,r,n,"stopped",{code:k.refusal.code,...m}),pe(this.deps,c,{status:"refused",code:k.refusal.code}),h.fail(k.refusal.message),p(new Error(k.refusal.message)),this.refusalOf(k.refusal,k.alsoRefused);let{result:w,notes:I,deliverability:P}=k,b={...P!==void 0?{deliverability:P}:{},...d.acceptEmails===!0?{acceptEmails:!0}:{}};for(let C of I)this.deps.log(`[WARN] checkpoint:${t} ${c}: ${C}`);for(let C of w.removedJournals??[])this.deps.log(`[INFO] Removed the journal of rewind ${C.rewindId} of checkpoint '${C.name}': Undo reaches the last rewind of the org alone`);let S=d.refusalOf?.(w);if(S!==void 0)throw this.audit(e,t,r,n,MS(w)?"partial":"stopped",{result:w,code:S.code,...b}),pe(this.deps,c,{status:"refused",code:S.code}),h.fail(S.message),p(new Error(S.message)),new ke(S.code,S.message,!1,w);if(this.audit(e,t,r,n,oP[w.status],{result:w,...b}),e.respond?.(`checkpoint:${t}:response`,{result:w,operationId:c}),w.status==="cancelled")u?.abort(c),pe(this.deps,c,{aborted:!0}),h.cancel(),p();else if(w.status==="failure"){let C=`Nothing the ${t} set out to write went through: its result says why.`;pe(this.deps,c,{status:w.status}),h.fail(C),p(new Error(C))}else pe(this.deps,c,{status:w.status}),w.status==="success"?h.complete():h.partial(),p();return w}catch(k){if(k instanceof ke)throw k;if(a(k))throw u?.abort(c),pe(this.deps,c,{aborted:!0}),h.cancel(),p(),this.audit(e,t,r,n,"stopped",{code:lr,...m}),new ke(lr,O(k),!0);let w=Us(k);throw this.audit(e,t,r,n,"failure",{...m,...w?{muted:w}:{}}),this.unreleased(e,t,r,w),pe(this.deps,c,{status:"failure"}),h.fail(O(k)),p(k),k}finally{d.signal?.removeEventListener("abort",R)}}unreleased(e,t,r,n){n?.released===!1&&this.deps.log(`[WARN] checkpoint:${t} ${e.operationId}: `+Xt(n,ft(r)).map(o=>o.trim()).join("; "))}readAutomation(e,t){let r=this.targetAutomation;return new fe(nP).withTimeout("checkpoint:preview automation",()=>r.read(e,t,{undeletes:!0}))}ownReader(){return this.reader??=import("./chunk-QO4MPHZD.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=$(ry,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 ${bp(i)}`);if(n.length===0&&o.length>0)throw new ke("RUN_WRITING",`The checkpoint was not deleted: ${bp(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=$(ny,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=$(oy,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=$(sy,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=$(iy,e,"checkpoint:error",this.deps);if(t!==null)try{let r=await this.openedStore(),{readRewindLedgers:n}=await import("./chunk-GT5ZKU6V.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,l]of a){for(let u of l.unreadable)this.deps.log(`[WARN] Line ${u} of the rewind ledger of ${c} does not parse: left out`);for(let u of l.records){let f=i.filter(({ids:p})=>p.some(g=>Dt(g,u.organizationId)));d.push({...u,orgIds:f.map(({orgId:p})=>p)})}}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 ke("RUN_WRITING",`The checkpoint was not changed: ${bp(d)}. Change it once that has ended.`,!0);let c;try{c=await n(i)}catch(l){throw l instanceof o.CheckpointStoreError?new ke(l.code==="notFound"?"NOT_FOUND":l.code==="damaged"?"DAMAGED":"INVALID",l.message):l}this.respond(e,`checkpoint:${r}:response`,{checkpoint:c}),this.checkpointsChanged()}catch(o){this.fail(e,o,"CHANGE_ERROR")}}};var St={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 HS(s,e,t){let r=Wi(s);if(r==="refused")return ur(St.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(St.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 Rp(s){return s.objects.flatMap(e=>e.fieldRules.filter(t=>t.ruleType==="ai_generate").map(t=>`${e.objectApiName}.${t.fieldApiName}`))}function Xo(s,e,t){let r=t(e)??Mi.find(d=>d.id===e);if(r==null)return{refusal:ur(St.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=To.safeParse(r);if(!i.success){let d=i.error.issues[0];return{refusal:ur(St.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=Rp(i.data);return a.length>0?{refusal:ur(St.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 JS={apiLimits:"apiLimits",storage:"storage",recentErrors:"recentErrors",failedJobs:"activeJobs"},vp=Object.keys(JS),BS={apiLimits:{variable:Rs.apiLimits,read:s=>s.percent},storage:{variable:Rs.storage,read:s=>s.percent},recentErrors:{variable:Rs.recentErrors,read:s=>s.count},failedJobs:{variable:Rs.failedJobs,read:s=>s.count}},VS=500,XS=G({orgId:zh,checks:ve(_e(["apiLimits","storage","recentErrors","failedJobs"])).min(1).refine(s=>new Set(s).size===s.length)}),KS=G({message:j().trim().min(1).max(VS)});function At(s,e){return`${s} ${e}${s===1?"":"s"}`}function Cr(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 Tt(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 Pr(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 Ip(s){return Array.isArray(s)&&s.length>0?s:void 0}function pP(s){return e=>{let t=`Backup step "${e.name}"`,r=e.config??{},n=Pr(s,t,r.orgId,"the org it backs up");if(n)return n;let o=Ip(r.objects);if(!o)return`${t} names no object: list the API names of the objects it backs up.`;let i=o.filter(a=>!Gh.safeParse(a).success);if(i.length>0)return`${t} names what is not an object API name: ${i.map(String).join(", ")}.`;if(!$s.safeParse({orgId:r.orgId,objects:o}).success)return`${t} backs up more objects than one backup takes: at most 100.`}}function fP(s){return e=>{let t=`Compare step "${e.name}"`,r=e.config??{},n=Pr(s,t,r.sourceOrgId,"the org it compares from")??Pr(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=Ip(r.types);if(!o)return`${t} names no component type: choose what it compares.`;if(!xs.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 gP(s){return e=>{let t=`Pre-check step "${e.name}"`,r=e.config??{},n=Pr(s,t,r.orgId,"the org it checks");if(n)return n;let o=Ip(r.checks);if(!o)return`${t} names no check: choose what it checks (${vp.join(", ")}).`;let i=o.filter(a=>typeof a!="string"||!vp.includes(a));if(i.length>0)return`${t} names checks SandForge does not have: ${i.map(String).join(", ")}. It can check ${vp.join(", ")}.`;if(!XS.safeParse({orgId:r.orgId,checks:o}).success)return`${t} names the same check twice.`}}function hP(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(!KS.safeParse({message:r}).success)return`${t} has a message longer than ${VS} characters.`}}function mP(s){return async(e,t)=>{let r=new Date().toISOString(),{orgId:n,objects:o}=$s.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(l=>l.truncated).map(l=>l.objectApiName),c=`Backed up ${At(i.totalRecords,"record")} of ${At(i.objects.length,"object")} from ${a}`+(d.length>0?`; only part of ${d.join(", ")}: the org holds more rows than one backup reads.`:".");return Cr(e,r,{operationId:i.operationId,orgId:n,objects:i.objects,totalRecords:i.totalRecords,partial:i.partial},c)}}function yP(s){return async(e,t)=>{let r=new Date().toISOString(),{sourceOrgId:n,targetOrgId:o,types:i}=xs.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:l,unchanged:u,notCompared:f}=a.summary,p=s.orgName(n)??n,g=s.orgName(o)??o;return Cr(e,r,{sourceOrgId:n,targetOrgId:o,types:i,summary:a.summary,content:a.content,variables:{[Hg]:String(d+c+l)}},`Compared ${At(i.length,"component type")} of ${p} with ${g}: ${c} only in ${p}, ${d} only in ${g}, ${l} modified, ${u} unchanged, ${f} not compared.`)}}function qS(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 wP(s){return async e=>{let t=new Date().toISOString(),{orgId:r,checks:n}=XS.parse({orgId:e.config.orgId,checks:e.config.checks}),o=s.orgName(r)??r,i=await s.readOrgHealth(r,n.map(u=>JS[u])),a=n.map((u,f)=>({check:u,signal:i[f]})),d={};for(let{check:u,signal:f}of a){let p=f?BS[u].read(f):void 0;p!==void 0&&f.status!=="unknown"&&(d[BS[u].variable]=String(p))}let c={orgId:r,checks:a.map(({check:u,signal:f})=>({check:u,status:f?.status??"unknown",message:f?.message??"Not read"})),variables:d},l=a.filter(({signal:u})=>!u||u.status==="critical"||u.status==="unknown");return l.length>0?Tt(e,t,c,`Pre-check "${e.name}" failed on ${o}: ${l.map(({check:u,signal:f})=>f?qS(f):`${u} was not read`).join("; ")}.`):Cr(e,t,c,`${a.length===1?"The check":`${a.length} checks`} passed on ${o}: ${a.map(({signal:u})=>qS(u)).join("; ")}.`)}}function bP(s){return async(e,t)=>{let r=new Date().toISOString(),{message:n}=KS.parse({message:e.config.message});return s.notify?(s.notify(t.pipelineName?`${t.pipelineName}: ${n}`:n),Cr(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.")):Tt(e,r,{},`Notification step "${e.name}" cannot show a notification: there is no VS Code window to show it in.`)}}function YS(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=RP(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 RP(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=ni(s,t);r="problem"in n?void 0:n.config.targetOrgId}else(t.type==="seed"||t.type==="anonymize")&&(r=tn((t.config??{}).orgId));if(r!==void 0&&s.orgTier?.(r)==="staging")return s.orgName(r)??r}}function vP(s){return(e,t)=>{let r=`Approval step "${e.name}"`;if(!s.askApproval)return YS(s,e,t);switch(Gg(e.config)){case"timeout":return`${r} waits for a time it cannot keep: set a whole number of minutes from 1 to ${qg} (a day).`;case"message":return`${r} has a message that is not text, or is longer than ${Wg} characters.`;default:return}}}function WS(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 SP(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Approval step "${e.name}"`;if(!s.askApproval)return Tt(e,r,{},YS(s,e,void 0));let o=zg(e.config)??Bg,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{...Cr(e,r,c,`Approved${WS(d)} at ${d.at}.`),approval:d};case"rejected":return{...Tt(e,r,c,`${n} was rejected${WS(d)} at ${d.at}.`),approval:d};case"timedOut":return{...Tt(e,r,c,`${n} was not approved in time: nobody answered within ${At(o,"minute")}.`),approval:d};case"cancelled":return{...Tt(e,r,c,`${n} was stopped before anyone answered.`),approval:d}}}}function ni(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=wn.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 QS(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(!wn.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 ZS(s){return s===void 0||s.steps.slice(0,s.index).some(e=>e.type==="approval")}function kP(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=ni(s,e);if("problem"in n)return n.problem;let{config:o}=n,i=Pr(s,r,o.sourceOrgId,"the source org of its configuration")??Pr(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"&&!ZS(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 Ap(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 Tp(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 zS=3;function OP(s){let e=s.filter(r=>r.failed>0).flatMap(r=>Gl(r.errors).map(n=>`${r.objectApiName}, ${n.count} \xD7 ${n.example}`));if(e.length===0)return"";let t=e.length-zS;return`; refused: ${e.slice(0,zS).join("; ")}`+(t>0?`; and ${At(t,"other reason")}`:"")}function IP(s){return async(e,t)=>{let r=new Date().toISOString(),n=ni(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,Ap(t),t.signal);if(a.cancelled)throw new vt(`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,l={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(p=>{let g=p.failed>0?Gl(p.errors):[];return{objectApiName:p.objectApiName,operation:p.operation,processed:p.processed,success:p.success,failed:p.failed,skipped:p.skipped,...g.length>0?{refusals:g}:{},...p.delta?{delta:p.delta}:{}}}),...typeof c=="object"&&c!==null?{summary:c}:{}},u=Tp(a.objectResults,!0).map(p=>`; ${p}`).join(""),f=`${At(a.totalSuccess,"record")} written, ${a.totalFailed} failed and ${a.totalSkipped} skipped of ${a.totalProcessed} read${u}`;if(a.status!=="success"){let p=[a.error,ed(a)].filter(g=>g!==void 0&&g!=="");return Tt(e,r,l,`Sync step "${e.name}" ran "${i}" into ${d} and did not complete: ${f}`+OP(a.objectResults)+(p.length>0?`; ${p.join("; ")}`:"."))}return Cr(e,r,l,`Synced "${i}" into ${d}: ${f}.`)}}function tn(s){return typeof s=="string"&&s.trim()!==""?s.trim():void 0}function Ep(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 AP(s,e){return s!==void 0&&e!==void 0&&s.length>=15&&s.slice(0,15)===e.slice(0,15)}function hd(s){return s.pipelineName??s.pipelineId}function ek(s,e,t,r,n){let o=s.orgName(t)??t,i=Wi(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"&&!ZS(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 tk(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 rk(s){if(s instanceof vt)return;let e=s?.code;return typeof e=="string"?e:void 0}function TP(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=Pr(s,r,n.orgId,"the org it seeds");if(o)return o;let i=tn(n.templateId);if(i===void 0)return`${r} names no Seed template: choose the one it seeds with.`;let a=String(n.orgId),d=Xo(a,i,c=>s.savedSeedTemplate?.(c));return"refusal"in d?`${r}: ${d.refusal.message}`:tk(e,r,"a second try would write a second set of records")??ek(s,r,a,"seeds",t)}}function EP(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}=qi.parse({orgId:e.config.orgId,templateId:tn(e.config.templateId)}),a=s.orgName(o)??o,d;try{d=await s.seed({orgId:o,templateId:i,pipeline:{name:hd(t)},answer:Ap(t)},t.signal)}catch(p){let g=rk(p);if(g===void 0)throw p;return Tt(e,r,{orgId:o,templateId:i,code:g},`${n}: ${p.message}`)}let{result:c}=d,l={orgId:o,templateId:i,operationId:d.operationId,runId:d.runId,status:c.status,totalRecordsCreated:c.totalRecordsCreated,totalRecordsFailed:c.totalRecordsFailed,objects:c.objectResults.map(p=>({objectApiName:p.objectApiName,recordsCreated:p.recordsCreated,recordsFailed:p.recordsFailed})),...d.automation.length>0?{automation:d.automation}:{}},u=At(c.totalRecordsCreated,"record"),f="take them back from Seed's Recent runs";if(c.cancelled)throw new vt(`${n} was cancelled: it had created ${u} in ${a}, which stay there; ${f}.`);return c.status!=="success"?Tt(e,r,l,`${n} seeded ${a} and did not complete: ${u} created, ${c.totalRecordsFailed} refused; ${f}.`):Cr(e,r,l,`Seeded ${u} into ${a}: ${f}.`)}}function nk(s){let e=(s.listSeedTemplates?.()??[]).map(n=>({raw:n,builtIn:!1})),t=Mi.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=To.safeParse(n);return[{id:i,name:d,builtIn:o,valid:c.success,usesAi:c.success&&Rp(c.data).length>0}]})}function PP(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 ok(s){return(s.maskingTemplates?.()??[]).map(e=>({id:e.id,name:e.name,builtIn:e.builtIn,objects:PP(e)}))}function CP(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=Pr(s,r,n.orgId,"the org it masks");if(o)return o;let i=tn(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=tn(n.object),l=tn(n.where),u=pb({orgId:a,templateId:i,...c!==void 0?{object:c}:{},...l!==void 0?{where:l}:{},...e.retries!==void 0?{retries:e.retries}:{}},p=>d.some(g=>g.id===p));if("refusal"in u)return`${r}: ${u.refusal.message}`;let f=vs.safeParse({orgId:a,templateId:i,...md(n)});return f.success?ek(s,r,a,"masks",t):`${r} does not read (${Ep(f.error)}).`}}function md(s){return Object.fromEntries(["acceptAutomation","acceptEmails","muteAutomation"].flatMap(e=>s[e]===void 0?[]:[[e,s[e]]]))}var GS=3;function $P(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-GS;return`, refused by the org: ${e.slice(0,GS).join("; ")}`+(t>0?`; and ${At(t,"other reason")}`:"")}function xP(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=tn(e.config.object),i=tn(e.config.where),{orgId:a,templateId:d,acceptAutomation:c,acceptEmails:l,muteAutomation:u}=vs.parse({orgId:e.config.orgId,templateId:tn(e.config.templateId),...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...md(e.config)}),f=s.orgName(a)??a,p=I=>I?` ${Xt(I,f).map(P=>P.trim()).join("; ")}.`:"",g;try{g=await s.anonymize({orgId:a,templateId:d,...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...e.retries!==void 0?{retries:e.retries}:{},accord:{acceptAutomation:c,acceptEmails:l,muteAutomation:u},pipeline:{name:hd(t)},answer:Ap(t)},t.signal)}catch(I){let P=rk(I);if(P===void 0)throw I;let b=I.snapshot,S=Us(I);return Tt(e,r,{orgId:a,templateId:d,code:P,...b!==void 0?{snapshot:b}:{},...S?{mutedAutomation:S}:{}},`${n}: ${I.message}`+(typeof b?.operationId=="string"?` The snapshot ${b.operationId} it took keeps the values it wrote over, in clear, until it is deleted on the DataOps page.`:"")+p(S))}let{result:h}=g,m=h.snapshot?`the snapshot ${h.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",y={orgId:a,templateId:d,...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},operationId:g.operationId,status:h.status,recordsProcessed:h.recordsProcessed,recordsFailed:h.recordsFailed,recordsNotMasked:h.recordsNotMasked,objects:h.objects,message:h.message,errors:h.errors,...h.snapshot?{snapshot:h.snapshot}:{},...h.mutedAutomation?{mutedAutomation:h.mutedAutomation}:{}},R=p(h.mutedAutomation);if(h.cancelled)throw new vt(`${n} was cancelled: it masked ${At(h.recordsProcessed,"record")} in ${f} before the stop, and ${h.recordsNotMasked} still hold their values; ${m}.`+R);let k=h.objects.filter(I=>I.notMasked>0);if(h.recordsNotMasked>0){let I=`${k.map(P=>`${P.notMasked} of ${P.objectApiName}`).join(", ")} still hold their values${$P(h)}`;return Tt(e,r,y,`${n} masked ${f} and did not complete: ${I}; ${m}.${R}`)}let w=o!==void 0?i!==void 0?`the ${o} rows where ${i}`:`every ${o} row`:`every row of ${h.objects.map(I=>I.objectApiName).join(", ")}`;return Cr(e,r,y,`Masked ${At(h.recordsProcessed,"record")} in ${f}, ${w}; ${m}.${R}`)}}function DP(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=Pr(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=hn.safeParse(r);if(!i.success)return`${t} does not read (${Ep(i.error)}).`}}function NP(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 jP(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=hn.parse(e.config),i=s.orgName(o.orgId)??o.orgId,a;try{a=await s.takeCheckpoint({config:o,origin:{pipeline:hd(t),step:e.name,trigger:s.trigger??"manual"}},t.signal)}catch(l){if(!(l instanceof Er))throw l;return Tt(e,r,{orgId:o.orgId,code:l.code},l.message)}let d=a.movedWhileTaken,c=d.changed+d.deleted+d.created;return Cr(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}: ${At(a.records,"record")} of ${At(a.objects,"object")}, ${NP(a.bytes)} on this machine, `+(o.keepDays===0?"kept until it is deleted":`kept ${At(o.keepDays,"day")}`)+(c>0?`; ${At(c,"record")} changed while it was taken.`:"."))}}var MP={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 sk(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}, ${MP[a]}.`}}let i=s.organizationIdsOf?.(t)??[];if(n.organizationId!==void 0&&!i.some(a=>AP(a,n.organizationId)))return{why:"otherOrg",problem:`${e} rewinds ${s.orgName(t)??t} to the checkpoint ${o}, which was taken of another org.`}}function LP(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=Pr(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=Ct.safeParse(r);if(!i.success)return`${t} does not read (${Ep(i.error)}).`;let a=tk(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?$n(e.name,d.refusal):sk(s,t,o,i.data.checkpointId)?.problem}}function Op(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 Sp(s){let e=Op(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 kp(s){return s.undo?`Undo on the Checkpoints page takes it back until ${s.undo.until}`:"it wrote nothing Undo would take back"}function FP(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=Ct.parse(e.config),i=s.rewindGrant(t.pipelineId,e);if("refusal"in i)return Tt(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:"NOT_CONFIRMED"},$n(e.name,i.refusal));let a=s.orgName(o.orgId)??o.orgId,d=g=>g?` ${Xt(g,a).map(h=>h.trim()).join("; ")}.`:"",c;try{c=await s.rewind({config:o,grant:i.grant,origin:{pipeline:hd(t),step:e.name,trigger:s.trigger??"manual"}},t.signal)}catch(g){let h=(g instanceof Er?g.result?.mutedAutomation:void 0)??Us(g);if(!(g instanceof Er)){if(!h||g instanceof vt)throw g;return Tt(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,mutedAutomation:h},`${O(g)}${d(h)}`)}return Tt(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:g.code,...g.alsoRefused.length>0?{alsoRefused:[...g.alsoRefused]}:{},...g.result?{status:g.result.status,...Op(g.result)}:{},...h?{mutedAutomation:h}:{}},`${g.message}${d(h)}`)}let{result:l}=c,u=l.residual.reduce((g,h)=>g+h.count,0),f={orgId:o.orgId,checkpointId:c.checkpointId,operationId:c.operationId,rewindId:l.rewindId,status:l.status,...Op(l),residual:u,...l.undo?{undoUntil:l.undo.until}:{},apiRequests:l.apiRequests.used,...l.mutedAutomation?{mutedAutomation:l.mutedAutomation}:{}},p=d(l.mutedAutomation);if(l.status==="cancelled")throw new vt(`${n} was stopped part way in ${a}: ${Sp(l)}; ${kp(l)}.${p}`);return l.status!=="success"?Tt(e,r,f,`${n} rewound ${a} and did not complete (${l.status}): ${Sp(l)}; ${At(u,"record")} still ${u===1?"differs":"differ"} from the checkpoint`+(l.unread&&l.unread.length>0?`, and ${l.unread.map(g=>g.objectApiName).join(", ")} could not be read`:"")+`; ${kp(l)}.${p}`):Cr(e,r,f,`Rewound ${a} to the checkpoint ${c.checkpointId}: ${Sp(l)}, with ${At(l.apiRequests.used,"API request")}; ${kp(l)}.${p}`)}}function ik(s,e,t,r){let n=r?{granted:{at:r.grantedAt,digestMatches:r.matches}}:{},o=Ct.safeParse(e.config??{});if(!o.success)return{stepId:e.id,valid:!1,why:"config",...n};let{orgId:i,checkpointId:a}=o.data,d=sk({...s,checkpointKept:()=>t},"The step",i,a);return{stepId:e.id,checkpointId:a,valid:d===void 0,...d?{why:d.why}:{},...n}}function ak(s,e){s.registerHandler("backup",mP(e),pP(e)),s.registerHandler("compare",yP(e),fP(e)),s.registerHandler("precheck",wP(e),gP(e)),s.registerHandler("notification",bP(e),hP(e)),s.registerHandler("approval",SP(e),vP(e)),s.registerHandler("sync",IP(e),kP(e)),s.registerHandler("seed",EP(e),TP(e)),s.registerHandler("anonymize",xP(e),CP(e)),s.registerHandler("checkpoint",jP(e),DP(e)),s.registerHandler("rewind",FP(e),LP(e))}function on(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 rn(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 nn(s,e){return`${s} ${e}${s===1?"":"s"}`}function oi(s){return typeof s=="string"&&s.trim()!==""?s.trim():void 0}function yd(s){return s.pipelineName??s.pipelineId}function Pp(s){if(s instanceof vt)return;let e=s?.code;return typeof e=="string"?e:void 0}function Ko(s){return new Error(`${s} cannot be simulated here: nothing can read what it would do. Nothing was written.`)}function _P(s){return s<6e4?`${s/1e3} s`:s<36e5?`${Math.round(s/6e4)} min`:`${(s/36e5).toFixed(1)} h`}function lk(s){return`about ${nn(s.apiRequests,"API request")} of the ${s.apiRequestsLeft} the org has left today, about ${s.seconds} s`}function UP(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 dk(s){let e=Tp(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 ck=3;function HP(s){let e=s.flatMap(r=>(r.refusedFor??[]).map(({note:n})=>`${r.objectApiName}, ${n.replace(/\.$/,"")}`));if(e.length===0)return"";let t=e.length-ck;return`; refused: ${e.slice(0,ck).join("; ")}`+(t>0?`; and ${nn(t,"other reason")}`:"")}function BP(s){let e=new Date().toISOString(),t=_w(s.config)??0;return Promise.resolve(on(s,e,{wouldWait:t},`Would wait ${_P(t)}: a simulation does not wait.`))}function qP(s){let e=new Date().toISOString();return Promise.resolve(on(s,e,{asked:!1},"Not asked in a simulation: the route goes on as if it were approved."))}function WP(s){return e=>{let t=new Date().toISOString(),r=oi(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(on(e,t,{message:r},`${n}: "${r}"`))}}function zP(s){return e=>{let t=new Date().toISOString(),{orgId:r,objects:n}=$s.parse({orgId:e.config.orgId,objects:e.config.objects}),o=s.orgName(r)??r;return Promise.resolve(on(e,t,{orgId:r,objects:n},`Would take a snapshot of ${nn(n.length,"object")} of ${o} (${n.join(", ")}): a simulation takes none.`))}}function GP(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Sync step "${e.name}"`,o=ni(s,e);if("problem"in o)throw new Error(o.problem);if(!s.simulateSync)throw Ko(n);let{config:i,name:a}=o,d=s.orgName(i.targetOrgId)??i.targetOrgId,c;try{c=await s.simulateSync(i,t.signal)}catch(p){let g=Pp(p);if(g===void 0)throw p;return rn(e,r,{configId:i.id,code:g},`${n} would be refused: ${p.message}`)}if(c.cancelled)throw new vt(`${n} was stopped before its simulation read every object. Nothing was written.`);let l={configId:i.id,configName:a,operationId:c.operationId,objects:c.objects.map(p=>({objectApiName:p.objectApiName,operation:p.operation,read:p.read,insert:p.insert,update:p.update,delete:p.delete,skipped:p.skipped,refused:p.refused,...p.refusedFor?{refusedFor:p.refusedFor}:{},...p.delta?{delta:p.delta}:{}})),...c.readCap!==void 0?{readCap:c.readCap}:{},...c.cutAtReadCap?{cutAtReadCap:c.cutAtReadCap}:{}},u=UP(c.objects);return c.error?rn(e,r,l,`${n} would stop on ${c.failedObject??"an object"}: ${c.error}`):c.objects.reduce((p,g)=>p+g.refused,0)>0?rn(e,r,l,`${n} would run "${a}" into ${d} and not complete: ${u}${dk(c)}${HP(c.objects)}. Nothing was written.`):on(e,r,l,`Would sync "${a}" into ${d}: ${u}${dk(c)}. Nothing was written.`)}}function JP(s){let e=s.previousResults.filter(t=>t.stepType==="approval");return{approved:e[e.length-1]?.status==="completed"}}function VP(s,e){return Pv(s,e)}function XP(s,e){let t=`about ${nn(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 KP(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Seed step "${e.name}"`,{orgId:o,templateId:i}=qi.parse({orgId:e.config.orgId,templateId:oi(e.config.templateId)}),a=s.orgName(o)??o,d=Xo(o,i,u=>s.savedSeedTemplate?.(u));if("refusal"in d)return rn(e,r,{orgId:o,templateId:i,code:d.refusal.code},`${n} would be refused: ${d.refusal.message}`);if(!s.previewSeed)throw Ko(n);let{template:c}=d.asked,l;try{l=await s.previewSeed({orgId:o,templateId:i,pipeline:{name:yd(t)},answer:JP(t)},t.signal)}catch(u){let f=Pp(u);if(f===void 0)throw u;return rn(e,r,{orgId:o,templateId:i,code:f},`${n} would be refused: ${u.message}`)}return on(e,r,{orgId:o,templateId:i,records:l.records,objects:l.objects,storage:l.storage,apiRequests:l.apiRequests,...l.automation.length>0?{automation:l.automation}:{}},`Would seed "${c.name}" into ${a}: ${nn(l.records,"record")} of ${nn(l.objects,"object")}, as its template asks; ${VP(l.storage,a)}; ${XP(l.apiRequests,a)}. Nothing was written.`)}}function YP(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Anonymize step "${e.name}"`;if(!s.previewMasking)throw Ko(n);let o=oi(e.config.object),i=oi(e.config.where),{orgId:a,templateId:d,acceptAutomation:c,acceptEmails:l,muteAutomation:u}=vs.parse({orgId:e.config.orgId,templateId:oi(e.config.templateId),...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...md(e.config)}),f=s.orgName(a)??a;try{let p=await s.previewMasking({orgId:a,templateId:d,...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...e.retries!==void 0?{retries:e.retries}:{},accord:{acceptAutomation:c,acceptEmails:l,muteAutomation:u},pipeline:{name:yd(t)},answer:{approved:!0}},t.signal),g=p.objects.filter(h=>h.records>0).map(h=>`${h.records} of ${h.objectApiName} (${h.fields.join(", ")})`);return on(e,r,{orgId:a,templateId:d,records:p.records,objects:p.objects},p.records===0?`Would mask nothing in ${f}: no row of ${p.objects.map(h=>h.objectApiName).join(", ")} holds anything to mask. Nothing was written.`:`Would mask ${nn(p.records,"record")} in ${f}: ${g.join("; ")}, after a snapshot of them. Nothing was written.`)}catch(p){let g=Pp(p);if(g===void 0)throw p;return rn(e,r,{orgId:a,templateId:d,code:g},`${n} would be refused: ${p.message}`)}}}function QP(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Checkpoint step "${e.name}"`;if(!s.estimateTake)throw Ko(n);let o=hn.parse(e.config),i=s.orgName(o.orgId)??o.orgId;try{let a=await s.estimateTake({config:o,origin:{pipeline:yd(t),step:e.name,trigger:s.trigger??"manual"}},t.signal);return on(e,r,{orgId:o.orgId,objects:a.objects,records:a.records,leftOut:a.leftOut,estimate:a.estimate},`Would take a checkpoint of ${i}: ${nn(a.records,"record")} of ${nn(a.objects,"object")} now, ${lk(a.estimate)}. Nothing was taken.`)}catch(a){if(!(a instanceof Er))throw a;return rn(e,r,{orgId:o.orgId,code:a.code},`${n} would be refused: ${a.message}`)}}}function ZP(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Rewind step "${e.name}"`;if(!s.rewindGrant||!s.previewRewind)throw Ko(n);let o=Ct.parse(e.config),i=s.rewindGrant(t.pipelineId,e);if("refusal"in i)return rn(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:"NOT_CONFIRMED"},$n(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:yd(t),step:e.name,trigger:s.trigger??"manual"}},t.signal);return on(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`:"")+`, ${lk(d.estimate)}. Nothing was written.`)}catch(d){if(!(d instanceof Er))throw d;return rn(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 uk(s,e){s.wrapHandler("delay",()=>BP),s.wrapHandler("approval",()=>qP),s.wrapHandler("notification",()=>WP(e)),s.wrapHandler("backup",()=>zP(e)),s.wrapHandler("sync",()=>GP(e)),s.wrapHandler("seed",()=>KP(e)),s.wrapHandler("anonymize",()=>YP(e)),s.wrapHandler("checkpoint",()=>QP(e)),s.wrapHandler("rewind",()=>ZP(e))}var Yo=new Map,pk=(s,e)=>`${s}::${e}`;async function Yt(s,e,t,r=Date.now){let n=pk(s,e),o=Yo.get(n);if(o&&r()-o.at<3e5)return o.value;let i=t();Yo.set(n,{at:r(),value:i});try{return await i}catch(a){throw Yo.get(n)?.value===i&&Yo.delete(n),a}}function fk(s){let e=pk(s,"");for(let t of Yo.keys())t.startsWith(e)&&Yo.delete(t)}var eC=G({orgId:j(),detectedAt:j(),evidence:_e(["connection","monitor","production"]),previousOrganizationId:j().optional(),organizationId:j().optional(),previousInstanceName:j().optional(),instanceName:j().optional(),sandboxName:j().optional(),reportedBy:j().optional()}),tC=G({organizationId:j(),instanceName:j().optional(),formerOrganizationIds:ve(j()),refreshes:ve(eC)}),gk="sandbox-refresh:",rC="sandbox-refresh",hk=10,nC=20,oC=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function Cp(s){return s!==void 0&&oC.test(s)?s.slice(0,15):void 0}function mk(s){try{return new URL(s).hostname.toLowerCase()}catch{return}}function sC(s){let e=mk(s.instanceUrl),t=".my.salesforce.com";return e?.endsWith(t)?e.slice(0,-t.length):void 0}function iC(s,e,t){let r=t.toLowerCase(),n=sC(s);return n&&mk(e.instanceUrl)?.startsWith(`${n}--${r}.`)?!0:e.username.toLowerCase()===`${s.username.toLowerCase()}.${r}`}var wd=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=Cp(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 f=t.instanceName!==void 0&&t.instanceName!==a.instanceName;(!i||f)&&this.write(e,{...a,instanceName:t.instanceName??a.instanceName});return}if(a.formerOrganizationIds.includes(o))return;let[d,...c]=a.refreshes,l=d?.evidence==="production"&&d.organizationId===void 0?d:void 0,u={...l??{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,nC),refreshes:(l?[u,...c]:[u,...a.refreshes]).slice(0,hk)}),this.deps.log?.(`[sandbox-refresh] ${n.alias}: org ${a.organizationId} is now ${o} (${r})`),l||this.emit(u),u}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||!iC(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,hk)}),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=Cp(t);return r!==void 0&&this.refreshesOf(e).some(n=>n.organizationId===r)}baselineOf(e){let t=Cp(e.orgId);return t===void 0?void 0:{organizationId:t,formerOrganizationIds:[],refreshes:[]}}read(e){let t=this.deps.configStore.get(`${gk}${e}`);if(t===void 0)return;let r=tC.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(`${gk}${e}`,t,rC)}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 aC,writeFile as dC}from"node:fs/promises";import{homedir as cC}from"node:os";import{basename as $p}from"node:path";async function lC(){let[s,e,t,r,n,o,i,a,d,c,l]=await Promise.all([import("./chunk-Q4PPI3KG.mjs"),import("./chunk-F5SBGJWW.mjs"),import("./chunk-6VOQFISN.mjs"),import("./chunk-X6XNTOGO.mjs"),import("./chunk-JYUMD357.mjs"),import("./chunk-CGZGL6VT.mjs"),import("./chunk-QKJXIY6L.mjs"),import("./chunk-FBXH4VRQ.mjs"),import("./chunk-XPXEQKLR.mjs"),import("./chunk-XAMMIPZ4.mjs"),import("./chunk-WABXKL4N.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:l.ReplayStore,defaultReplayStoreRoot:l.defaultReplayStoreRoot}}var uC=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"]),et=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},yk="SandForge writes and reads a users.json on the disk of the machine it runs on: pick a folder there.",pC={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(cC()),s),filters:{JSON:["json"]}});if(t!==void 0){if(t.scheme!=="file")throw new et("INVALID_PAYLOAD",yk);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 et("INVALID_PAYLOAD",yk);return t.fsPath}}},fC=async s=>{let e=await import("vscode");await e.window.showTextDocument(e.Uri.file(s),{preview:!1})};function gC(s,e,t){return{org:s,users:[],emailsToPeople:0,apiRequests:t,refusals:[e]}}function hC(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 xp(s,e){return s.length>=15&&s.slice(0,15)===e.slice(0,15)}var mC=4e3,bd=class{constructor(e,t={}){this.deps=e;this.options=t;this.dialogs=t.dialogs??pC,this.openInEditor=t.openInEditor??fC,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(!uC.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=$(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=$(Rg,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,l=>o?.organizationIdOf(l)),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,wg.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=$(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=$(Hl,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=$(Hl,e,"recovery:error",this.deps);if(!t)return;let{orgId:r}=t;if(this.running.has(r)){this.fail(e,new et("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 et("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 et("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 l=d.refusals??[];if(c===void 0||l.length>0)throw new et("FAILED",`${l.map(y=>y.message).join(" ")} Nothing was written.`.trim(),!1,"users");let u=await this.consultGuard(e,a,d);if(n.signal.aborted)throw this.recordUsersRun(e,r,"stopped",u),new et("CANCELLED","Stopped before the first write: nothing was written.");let f=o.changingUsersOf(d),p=y=>{this.deps.broker.postToWebview(A(this.deps,e,"recovery:users:progress",{orgId:r,done:y,total:f}))};p(0);let g=new o.ObservedUsersRunStore({root:this.users(o).root},y=>p(o.usersDoneOf(y,d))),h;try{h=await o.applyUsers({org:a.org,organization:a.organization,users:Ul(t.config),store:g,signal:n.signal,...c.options})}catch(y){throw this.recordUsersRun(e,r,"failure",u),y}if(h.kind==="refused")throw this.recordUsersRun(e,r,"stopped",u),new et("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,u,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=$(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=l=>t.typingRequests+n.requests()+l,a;if(r.replaces!==void 0){let l=await e.replacedRunOf(this.users(e),o.organizationId,r.replaces);if("refusal"in l)return{answer:gC(o,l.refusal,i(0))};a=l.record}let d=await e.planUsersGated({conn:t.conn,org:n,orgName:t.orgName,users:Ul(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 et("FAILED",be.message,!1,"users");let o=Ee(t.registered),{updated:i,added:a,removed:d}=hC(r),c=[{operation:"delete",objectName:"PermissionSetAssignment, GroupMember",recordCount:d},{operation:"update",objectName:"User, UserLogin",recordCount:i},{operation:"insert",objectName:"PermissionSetAssignment, GroupMember",recordCount:a}].filter(u=>u.recordCount>0),l="allowed";for(let u of c){let f=await Ze(n,{orgId:t.registered.id,orgTier:o,module:"recovery",...u});if(l=Kn(l,f.decision),f.decision==="refused")throw this.recordUsersRun(e,t.registered.id,"stopped",l),new et("FAILED",`Operation blocked by Production Guard: ${f.check.blockedReason??f.check.impactSummary} Nothing was written.`,!1,"users");if(f.decision==="declined")throw this.recordUsersRun(e,t.registered.id,"stopped",l),new et("CANCELLED",`Production Guard asked before this run (${f.check.impactSummary}), and the answer was no. Nothing was written.`,!1,"users")}return l}recordUsersRun(e,t,r,n,o,i){Z(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=$(Bl,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=$(Bl,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 dC(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:$p(r)})}catch(n){this.fail(e,this.pathless(n,r),"users")}}async handleConfigImport(e){let t=$(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=$p(r),i;try{i=JSON.parse(await aC(r,"utf8"))}catch(c){throw new et("INVALID_PAYLOAD",`${o} does not read as JSON (${O(c)}). Nothing was kept.`,!1,"users")}let a=yg.safeParse(i);if(!a.success){let c=a.error.issues.map(l=>{let u=l.path.map(String).join(".");return u===""?l.message:`${u}: ${l.message}`});throw new et("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=$(bg,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:u=>o.request(u)},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 u of d.notes)this.deps.log(`[INFO] recovery:audit: ${u}`);let c=this.audited.get(t.orgId),l=c!==void 0&&xp(c.organizationId,i.organizationId)?c.audit:{};this.audited.set(t.orgId,{organizationId:i.organizationId,audit:{...l,...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=$(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 et("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&&xp(d.organizationId,i)?{audits:d.audit}:{},at:a,...this.options.sandforgeVersion!==void 0?{sandforgeVersion:this.options.sandforgeVersion}:{}}),l=n.recoveryHandoffPathOf(this.journalDir(n),{organizationId:i,at:a});await n.writeRecoveryHandoff(l,c);try{await this.openInEditor(l)}catch(u){this.deps.log(`[WARN] recovery:handoff: the note was not opened: ${O(u)}`)}this.respond(e,"recovery:handoff:response",{orgId:t.orgId,path:l}),this.changed(t.orgId)}catch(r){this.fail(e,r,"handoff")}}async handleHandoffOpen(e){let t=$(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 et("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 et("FAILED",`The handoff note could not be opened in the editor: ${O(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??=lC(),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 et("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&&xp(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 et(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 et("ORG_NOT_FOUND",`No org is registered in SandForge as ${e}: connect it on the Organizations page.`,!1,t);if(!bo(r))throw new et("NOT_A_DEVELOPMENT_ORG",`${he(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=he(n,n.username),i;try{i=await B(t,this.deps.orgRegistry,this.deps.orgManager)}catch(d){throw new et("NOT_CONNECTED",`${o} could not be reached (${O(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 et(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: ${O(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 et||t===void 0?e:new Error(O(e).replaceAll(t,$p(t)))}fail(e,t,r){let n=t instanceof et?t:new et("FAILED",O(t),!0,r),o=n.message.trim()===""?n.code:n.message,i=n.step??r;E(this.deps,e.type,"recovery:error",e,new Error(o.slice(0,mC)),{code:n.code,retryable:n.retryable,...i!==void 0?{extraPayload:{step:i}}:{}})}};var yC=5,wC=5e3,bC=3e4,RC=G({device_code:j().min(1).max(4096),user_code:j().regex(/^[A-Za-z0-9-]{4,32}$/),verification_uri:j().min(1).max(2048),interval:Te().int().positive().max(300).optional(),expires_in:Te().int().positive().optional()}),vC=G({access_token:j().min(1),refresh_token:j().min(1).optional(),instance_url:j().min(1).max(2048)}),wk=G({error:j().min(1),error_description:j().optional()}),ro=class extends Error{constructor(){super("Sign-in cancelled."),this.name="DeviceLoginCancelledError"}},Rd=class extends Error{constructor(e){super(e),this.name="RefusedByHostError"}};function SC(s,e){return new Promise((t,r)=>{if(e?.aborted){r(new ro);return}let n=()=>{clearTimeout(o),r(new ro)},o=setTimeout(()=>{e?.removeEventListener("abort",n),t()},s);e?.addEventListener("abort",n,{once:!0})})}function Rk(s){let e=xn(s);if(!(!e.ok||e.url.username!==""||e.url.password!=="")&&!(e.url.port!==""||!Qg(e.url.hostname)))return e.url}function bk(s){return`Salesforce refused the device sign-in: ${s.error_description?`${s.error_description} (${s.error})`:s.error}`}var vd=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??SC}async authorize(e,t,r){let n=await this.post(e,{response_type:"device_code",client_id:t},r),o=wk.safeParse(n);if(o.success)throw new Error(bk(o.data));let i=RC.safeParse(n);if(!i.success)throw new Error("Salesforce answered the device sign-in without a usable code.");let a=Rk(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,sg);return{deviceCode:i.data.device_code,userCode:i.data.user_code,verificationUri:a.href,intervalMs:(i.data.interval??yC)*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 ro;if(c instanceof Rd)throw c;continue}let d=wk.safeParse(a);if(d.success){if(d.data.error==="authorization_pending")continue;if(d.data.error==="slow_down"){o+=wC;continue}throw new Error(bk(d.data))}return kC(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 ro;let n=AbortSignal.timeout(bC),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 ro:a}let i=await o.text();try{return JSON.parse(i)}catch{throw new Rd(`Salesforce answered HTTP ${o.status} with a page instead of JSON. Check the login URL.`)}}};function kC(s){let e=vC.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=Rk(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}}var $r=class{host;constructor(e){this.host=e??null}async defaultHost(){let e=await import("vscode");return{openExternal:t=>e.env.openExternal(t),parseUri:t=>e.Uri.parse(t,!0)}}async open(e){let t=this.host??await this.defaultHost();try{return await t.openExternal(t.parseUri(e))?{status:"opened"}:{status:"error",message:"VS Code did not open the page."}}catch(r){return{status:"error",message:r instanceof Error?r.message:String(r)}}}};import{readFile as OC,readdir as IC}from"node:fs/promises";import{join as vk}from"node:path";var AC=/^[^.][^@/\\]*@[^/\\]+\.json$/;async function Sk(s,e=Date.now()){let t=vk(s,".sfdx"),r;try{r=await IC(t)}catch{return 0}let n=new Set;return await Promise.all(r.filter(o=>AC.test(o)&&!o.endsWith(".partial.json")).map(async o=>{let i=await TC(vk(t,o),e);i&&n.add(i)})),n.size}async function TC(s,e){try{let t=JSON.parse(await OC(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 EC}from"node:os";var PC=new Set(["org:list","org:connect","org:connect:cancel","org:disconnect","org:select","org:update","org:open-in-browser","org:cli-status"]),kk=15e3,Ok="The Salesforce CLI holds no connected org yet. Use Log in with your browser on the Organizations page: it opens the Salesforce login page.",Sd=class{constructor(e,t={}){this.deps=e;this.browser=t.browser??new $r,this.deviceLogin=t.deviceLogin??new vd,this.countCliOrgs=t.countCliOrgs??(()=>Sk(EC())),this.connectTo=t.connectTo??(r=>dh(r))}deps;browser;deviceLogin;countCliOrgs;connectTo;pendingSignIns=new Map;async handle(e){if(!PC.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;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}`)}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=$(Fy,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:Ie(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){E(this.deps,"org:connect","org:error",e,new Error(t),{code:r,retryable:!1})}notifyCliMissing(e){Ie(this.deps,"error","Salesforce CLI",`${hs} ${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,hs,"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);Ie(this.deps,"error","Import Failed",d),this.failConnect(e,d,"SFDX_IMPORT_FAILED");return}if(n.length===0){Ie(this.deps,"info","Import",Ok,{autoDismissMs:null,code:"NO_CLI_ORGS"}),this.failConnect(e,Ok,"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}`),Ie(this.deps,"success","Import",`Imported ${n.length} org(s) from SF CLI.`),r.length>0&&Ie(this.deps,"warning","Import",this.reportUnreadable(r),{autoDismissMs:null}),this.ackConnect(e,o[0])}catch(t){let r=O(t);this.deps.log(`[ERR] org:sfdx-import: ${r}`),Ie(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=>`${he(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 oh(this.connectTo({instanceUrl:o,accessToken:n,version:t.metadata.apiVersion}).then(l=>Ji(l)),kk,`the org did not answer within ${kk/1e3} s`),a=Gn({isSandbox:i.sandbox,edition:i.edition}),{safetyTier:d,color:c}=Ur(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 (${O(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){Ie(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){Ie(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=Gn({isSandbox:o.isSandbox,edition:o.orgType}),{safetyTier:a,color:d}=Ur(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:yo.DEFAULT_API_VERSION,edition:o.orgType,features:[]},status:"connected",lastConnected:new Date().toISOString(),tags:[]},l=this.deps.authProvider.buildConnectionConfig({method:"usernamePassword",loginUrl:r,username:t.username,password:t.password,securityToken:t.securityToken},n);await this.deps.orgRegistry.saveOrg(c,l);let u=A(this.deps,e,"org:statusChanged",{orgId:c.id,status:"connected"});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`),Ie(this.deps,"success","Connected",`${he(c)} connected.`)}catch(o){let i=O(o);this.deps.log(`[ERR] org:username-password: ${i}`),Ie(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=Gi(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}".`;Ie(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,hs,"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=O(n);this.deps.log(`[ERR] org:oauth-web: ${o}`),Ie(this.deps,"error","OAuth Failed",o),this.failConnect(e,o,"OAUTH_WEB_FAILED")}}async handleJwt(e){let t=$(_y,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=O(n);this.deps.log(`[ERR] org:jwt: ${o}`),Ie(this.deps,"error","JWT Sign-in Failed",o),this.failConnect(e,o,"JWT_LOGIN_FAILED")}}async handleOAuthDevice(e){let t=$(Uy,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=O(o);this.deps.log(`[ERR] org:oauth-device: ${i}`),Ie(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=$(Hy,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,hs,"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]);Ie(this.deps,"success",r,`${he(n.org)} connected.`),this.ackConnect(e,o??n.org.id)}async handleOrgDisconnect(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(By,e,"org:error",this.deps);if(!t)return;let r=t;ko().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=$(qy,e,"org:error",this.deps);if(!t)return;let{orgId:r}=t;if(!this.deps.orgManager.getOrg(r)){Ie(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=$(zy,e,"org:error",this.deps);if(!t)return;let r=this.deps.orgManager.getOrg(t.orgId);if(!r){E(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){E(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=$(Wy,e,"org:error",this.deps);if(!t)return;let r=this.deps.orgManager.getOrg(t.orgId);if(!r){E(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=xn(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";E(this.deps,"org:open-in-browser","org:error",e,new Error(`Cannot open "${he(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 CC(s){let e=lg.safeParse(s.services?.getSandforgeSetting?.("forge.graphView","auto"));return e.success?e.data:"auto"}var $C=new Set(["settings:get","settings:update","telemetry:status","telemetry:toggle"]),kd=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;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:CC(this.deps)}}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=$(Gy,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=$(Jy,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: ${O(n)}`);let o=A(this.deps,e,"telemetry:toggle:response",{success:!1,enabled:this.deps.services.getSandforgeSetting?.("telemetry",!1)??!1,error:O(n)});this.deps.broker.postToWebview(o)}}};var Dp={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"}},Np=1,Ik=.15,xC=.55;function Ak(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 DC(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 jp(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 Tk(s){switch(s){case"up":return"degrading";case"down":return"improving";case"stable":return"stable"}}function Ek(s){return s.direction!=="up"?0:Math.min(15,Math.max(0,Math.abs(s.changePercent)*.5))}function si(s){return s>=70?"healthy":s>=40?"warning":"critical"}function Pk(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 Ck(s){let e=s.max-s.remaining;return`${s.usedPercent}% used (${e.toLocaleString()} / ${s.max.toLocaleString()})`}var Od=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((p,g)=>({weightedSum:p.weightedSum+g.score*g.weight,totalWeight:p.totalWeight+g.weight}),{weightedSum:0,totalWeight:0}),d=a>0?Math.round(i/a):100,c=this.scoreToOverallStatus(d),u=[...t].sort((p,g)=>p.score-g.score).filter(p=>p.status!=="healthy").slice(0,3),f=this.buildSummary(c,u);return{overallScore:d,overallStatus:c,factors:t,summary:f,topRisks:u}}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 Np;let t=e*Ik;return Math.max(xC,Np-t)}computeOptionalDimensionWeight(e){return e===0?0:Ik}addCoreLimitFactors(e,t,r){for(let[n,o]of Object.entries(Dp)){let i=e.limits.find(f=>f.name===n);if(!i)continue;let a=Ak(i.usedPercent),d=this.fetchTrendData(e,n),c=d?Tk(d.direction):"stable",l=d?Ek(d):0,u=Math.max(0,Math.round(a-l));t.push({name:i.name,category:o.category,score:u,weight:o.weight*r,status:si(u),detail:Ck(i),recommendation:Pk(i.name,i.usedPercent),trend:c})}}addRemainingLimitFactors(e,t,r){let n=new Set(Object.keys(Dp)),o=e.limits.filter(c=>!n.has(c.name)&&c.usedPercent>0);if(o.length===0)return;let i=Object.values(Dp).reduce((c,l)=>c+l.weight,0),d=Math.max(0,(Np-i)*r)/o.length;for(let c of o){let l=Ak(c.usedPercent),u=this.fetchTrendData(e,c.name),f=u?Tk(u.direction):"stable",p=u?Ek(u):0,g=Math.max(0,Math.round(l-p));t.push({name:c.name,category:"limits",score:g,weight:d,status:si(g),detail:Ck(c),recommendation:Pk(c.name,c.usedPercent),trend:f})}}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(jp(n,50,500)*.4+jp(o,200,2e3)*.3+jp(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:si(a),detail:d,recommendation:c,trend:"stable"})}addCoverageDimension(e,t,r){if(e.codeCoverage===void 0)return;let n=DC(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:si(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:si(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 NC=ve(G({version:j()}));function $k(s){let e=NC.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 jC(s){if(!s)return;let e=new Date(s);return Number.isNaN(e.getTime())?void 0:e.toISOString()}var Id=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")]),l=o.namespacePrefix||void 0,u=jC(o.createdDate),f={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,...l!==void 0?{namespacePrefix:l}:{},...u!==void 0?{createdDate:u}:{}};return this.cache.set(e,{data:f,fetchedAt:Date.now()}),f}clearCache(e){e?this.cache.delete(e):this.cache.clear()}};function xk(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 Mp=1440*60*1e3,Dk=7*Mp,MC=500*1024,LC=900*1e3,FC=2,_C="trends",UC=new Set(ji),HC=Mp,Td=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(l=>l.timestamp>=Ad(n-Dk)),d=a.filter(l=>l.timestamp>=Ad(n-HC)),c={};for(let l of r)c[l]=this.computeTrend(l,a,d);return c}getHistory(e,t=Mp){let r=Ad(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)<LC}append(e,t,r,n){let o=Ad(n-Dk),i=[...t,r].filter(d=>d.timestamp>=o).map(d=>({...d,limits:d.limits.filter(c=>UC.has(c.name))})),a=this.trimToSizeLimit(i);return this.configStore.set(this.trendKey(e),a,_C),this.lastSaveTimestamps.set(e,n),a}computeTrend(e,t,r){let{values:n,timestamps:o}=Nk(e,t),{values:i}=Nk(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,l;Math.abs(c)<=FC?l="stable":c>0?l="up":l="down";let u;if(l==="up"&&d<100){let f=this.getTimeSpanMs(r);if(f>0){let p=c/f;if(p>0){let h=(100-d)/p;u=Math.round(h/(3600*1e3)*10)/10}}}return{limitName:e,direction:l,changePercent:Math.round(c*10)/10,predictedTimeToLimit:u,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<=MC);)t.shift();return t}};function Ad(s){return new Date(s).toISOString()}function Nk(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 Ed=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||!BC(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 BC(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 Qo="alert:state:",Lp="alerts";var Pd=class{constructor(e){this.configStore=e}configStore;saveAlerts(e){this.configStore.set(`${Qo}active`,e,Lp)}loadAlerts(){let e=this.configStore.get(`${Qo}active`);return Array.isArray(e)?e:[]}saveDefinitions(e){this.configStore.set(`${Qo}definitions`,e,Lp)}loadDefinitions(){let e=this.configStore.get(`${Qo}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(`${Qo}history`,i,Lp)}loadHistory(){let e=this.configStore.get(`${Qo}history`);return Array.isArray(e)?e:[]}};var Fp=[{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 Cd=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 $d=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 xd=class{fetchLogs;analyses=new Map;truncatedCache=new Map;constructor(e){this.fetchLogs=e}analyze(e){let t=qC(e),r=WC(e),n=zC(e),o=e.durationMs,i=GC(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 qC(s){return Math.min(Math.floor(s.logSize/500),100)}function WC(s){return Math.min(Math.floor(s.logSize/1e3),150)}function zC(s){return Math.min(s.logSize*10,6e6)}function GC(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 JC=new Set(Ig);function Mk(s){return typeof s=="string"&&JC.has(s)?s:"Unknown"}function VC(){let s=new Map;return{load:e=>s.get(e),save:(e,t)=>{s.set(e,t)}}}function jk(s){return`${s.sandboxName}:${s.refreshDate}`}var Dd=class{querySandboxes;onRefreshDetected;seen;refreshCache=new Map;supportedCache=new Map;truncatedCache=new Map;constructor(e,t,r=VC()){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(jk(c))||this.onRefreshDetected?.(c)}let a=o.map(jk);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=>Ag(r.status))}};var Nd=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 Lk=new Set(["Queued","Processing"]),jd=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=>Lk.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=>Lk.has(r.status)).length,completed:t.filter(r=>r.status==="Completed").length,failed:t.filter(r=>r.status==="Failed").length}}};var XC=3e4,KC=1440*60*1e3,Fk=100,_k=50,Uk=20,Hk="sandbox-process-seen:";function YC(s){return{load:e=>{let t=s.get(`${Hk}${e}`);return Array.isArray(t)?t.filter(r=>typeof r=="string"):void 0},save:(e,t)=>{s.set(`${Hk}${e}`,t,"sandbox-refresh")}}}function QC(s){return s instanceof So?s.code==="ORG_AUTH_EXPIRED":eh(s)||Ql(s)!==void 0}function ii(s){let e=Ql(s);return e!==void 0&&!(s instanceof So)?`the org could not be reached (${e})`:O(s)}function Bk(s){let e=new Td(s.configStore),t=async(b,S,C)=>{try{return await C(await s.getConnection(b))}catch(v){if(!QC(v))throw v;s.log(`[WARN] monitor:${S} ${b}: ${ii(v)}; read again on a new connection`);try{return await C(await s.getConnection(b,{again:!0}))}catch(T){throw T instanceof So&&T.code==="ORG_TEMPORARILY_UNREACHABLE"?v:T}}},r=new Pd(s.configStore),n=new Ed(b=>{s.log(`[ALERT] ${b.severity}: ${b.message}`);let S=b.severity==="critical"?"error":"warning";s.notify(S,b.message),r.saveAlerts(n.getActiveAlerts())}),o=r.loadDefinitions(),i=o.length>0?o:Fp;for(let b of i)n.addDefinition(b);o.length===0&&r.saveDefinitions(Fp);let a=r.loadAlerts();n.restoreAlerts(a);let d=new Cd(async(b,S)=>{let C=await s.getConnection(b),{records:v,truncated:T}=await Ps(C,`SELECT Id, Operation, Status, DurationMilliseconds, LogLength, StartTime, LogUser.Username FROM ApexLog WHERE Status != 'Success' AND StartTime > ${S} ORDER BY StartTime DESC LIMIT ${_k}`,_k);return $e(C.limitInfo,"monitor:error-logs apexLog"),{records:v.map(D=>({id:D.Id,errorType:D.Status,message:`${D.Operation} - ${D.Status}`,timestamp:D.StartTime,user:D.LogUser?.Username??void 0,context:D.Operation})),truncated:T}}),c=async(b,S)=>{let C=await b.query(`SELECT COUNT() FROM ApexLog WHERE Status != 'Success' AND StartTime > ${S}`);return $e(b.limitInfo,"monitor:refresh apexLogCount"),C.totalSize},l=new $d(async b=>{let S=await s.getConnection(b),{records:C,truncated:v}=await Ps(S,`SELECT Id, UsersId, Users.Username, LoginType, SessionType, CreatedDate, SourceIp FROM AuthSession ORDER BY CreatedDate DESC LIMIT ${Fk}`,Fk);return $e(S.limitInfo,"monitor:sessions authSession"),{records:C.map(T=>({sessionId:T.Id,userId:T.UsersId,username:T.Users?.Username??T.UsersId,sessionType:T.SessionType??T.LoginType??"Unknown",loginTime:T.CreatedDate,sourceIp:T.SourceIp??""})),truncated:v}}),u=new xd(async(b,S)=>{let C=await s.getConnection(b),{records:v,truncated:T}=await Ps(C,`SELECT Id, Operation, Status, DurationMilliseconds, LogLength, StartTime, LogUser.Username FROM ApexLog ORDER BY StartTime DESC LIMIT ${S}`,S);return $e(C.limitInfo,"monitor:apex-insights apexLog"),{records:v.map(D=>({id:D.Id,operation:D.Operation??"Unknown",status:D.Status,durationMs:D.DurationMilliseconds??0,logSize:D.LogLength??0,startTime:D.StartTime,user:D.LogUser?.Username??"Unknown"})),truncated:T}}),f=new Set,p=new Dd(async b=>{if(f.has(b))return{supported:!1,events:[],truncated:!1};let S=await s.getConnection(b),C;try{C=await Ps(S,`SELECT Id, SandboxName, Status, CreatedDate, Description FROM SandboxProcess ORDER BY CreatedDate DESC LIMIT ${Uk}`,Uk)}catch(v){let T=v instanceof Error?v.message:String(v);if(T.includes("SandboxProcess")&&T.includes("not supported"))return f.add(b),{supported:!1,events:[],truncated:!1};throw v}return $e(S.limitInfo,"monitor:sandbox-refresh sandboxProcess"),{supported:!0,events:C.records.map(v=>({orgId:b,sandboxName:v.SandboxName??"Unknown",refreshDate:v.CreatedDate,status:Mk(v.Status),sourceOrg:v.Description??void 0})),truncated:C.truncated}},b=>s.onSandboxRefreshCompleted?.(b),YC(s.configStore)),g=new Map,h=async(b,S)=>{let C=g.get(b);if(C&&Date.now()-C.fetchedAt<XC)return C.data;let v=await S.request(`/services/data/${wo}/limits`);return g.set(b,{data:v,fetchedAt:Date.now()}),v},m=async b=>{try{let C=(await t(b,"apiLimits",D=>h(b,D))).DailyApiRequests;if(!C||!C.Max)return{name:"apiLimits",status:"unknown",score:0,message:"No API limit reported"};let v=Math.round((C.Max-C.Remaining)/C.Max*100);return{name:"apiLimits",status:v>80?"critical":v>60?"warning":"ok",score:100-v,message:`API usage at ${v}%`,percent:v}}catch(S){return{name:"apiLimits",status:"unknown",score:0,message:`Unable to fetch limits: ${ii(S)}`}}},y=async b=>{try{let C=(await t(b,"storage",D=>h(b,D))).DataStorageMB;if(!C||!C.Max)return{name:"storage",status:"unknown",score:0,message:"No storage limit reported"};let v=Math.round((C.Max-C.Remaining)/C.Max*100);return{name:"storage",status:v>85?"critical":v>70?"warning":"ok",score:100-v,message:`Storage usage at ${v}%`,percent:v}}catch(S){return{name:"storage",status:"unknown",score:0,message:`Unable to fetch storage: ${ii(S)}`}}},R=async b=>{let S;try{let T=new Date(Date.now()-KC).toISOString();S=await t(b,"recentErrors",D=>c(D,T))}catch(T){return{name:"recentErrors",status:"unknown",score:0,message:`Unable to fetch error logs: ${ii(T)}`}}let C=Math.max(0,100-S*5);return{name:"recentErrors",status:S>10?"critical":S>3?"warning":"ok",score:C,count:S,message:`${S} recent errors`}},k=async b=>{let S=await jt(b,`SELECT Id, JobType, Status, NumberOfErrors, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${fn.monitorJobs}`);return $e(b.limitInfo,"monitor:refresh asyncJobs"),S.map(C=>({id:C.Id,jobType:C.JobType??"Batch",status:C.Status,createdBy:C.CreatedById,createdDate:C.CreatedDate,failedRecords:C.NumberOfErrors}))},w=new jd(b=>t(b,"activeJobs",k)),I=async b=>{try{await w.fetch(b);let S=w.getJobStats(b),C=Math.max(0,100-S.failed*10);return{name:"activeJobs",status:S.failed>5?"critical":S.failed>0?"warning":"ok",score:C,count:S.failed,outOf:S.total,message:`${S.active} active, ${S.failed} failed of ${S.total} recent jobs`}}catch(S){return{name:"activeJobs",status:"unknown",score:0,message:`Unable to fetch jobs: ${ii(S)}`}}},P=new Nd([m,y,R,I]);return{trendStorage:e,alertStateStore:r,alertEngine:n,errorLogMonitor:d,userSessionMonitor:l,apexLogAnalyzer:u,sandboxRefreshTracker:p,healthCheck:P,healthSignals:{apiLimits:m,storage:y,recentErrors:R,activeJobs:I},getOrFetchLimits:h,forgetOrg:b=>{g.delete(b)}}}var qk=25e3,Wk=20,ZC=20,e$=20,t$=500,Jk=`SELECT Id, JobType, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${fn.monitorJobs}`,r$=`SELECT Id, JobType, Status, NumberOfErrors, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${fn.monitorJobs}`,n$=new Set([Jk,r$]),o$=new Set(["Queued","Preparing","Processing"]),s$=new Set(["BatchApex","Queueable","Future"]),ai=3600*1e3,zk=ai,Gk=3;function _p(s){let e=Math.floor(s/60),t=s%60;return e>0?`${e}h${String(t).padStart(2,"0")}m`:`${t}m`}function i$(s,e){return s.status===e.status&&s.batchesProcessed===e.batchesProcessed&&s.totalBatches===e.totalBatches}function a$(s,e,t){let r=new Map;for(let n of e){let o=s?.get(n.id);if(o!==void 0&&i$(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 d$(s,e,t){let r=[],n=[],o=[];for(let a of s){if(!o$.has(a.status)||!s$.has(a.jobType))continue;let d=e.get(a.id),c=d===void 0?null:t-d.unchangedSinceMs,l=a.batchesProcessed,u=a.totalBatches;if(a.status==="Processing"&&l!==null&&u!==null&&l<u&&c!==null&&c>=ai){n.push({job:a,stillMs:c,done:l,total:u});continue}if(d?.movedWhileWatched===!0&&c!==null&&c<ai)continue;let f=t-Date.parse(a.createdDate);f>=zk&&o.push({job:a,ageMs:f,stillMs:c})}n.sort((a,d)=>d.stillMs-a.stillMs);for(let{job:a,stillMs:d,done:c,total:l}of n){let u=_p(Math.floor(d/6e4));r.push({type:"stuck",severity:"critical",title:`${a.jobType} ${a.id}: no batch completed in ${u}`,detail:`${c} of ${l} batches processed, unchanged across ${u} of observation by this dashboard while ${a.status} (stall bound ${ai/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<Gk)continue;let c=d.reduce((l,u)=>l+(u.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 ${Gk}-failure pattern threshold.`,affectedJobs:d.map(l=>l.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((f,p)=>p.ageMs-f.ageMs);let a=o[0],d=_p(Math.floor(a.ageMs/6e4)),{batchesProcessed:c,totalBatches:l}=a.job,u=c===null||l===null||l<=0?"it reports no batch counter, so its progress cannot be observed":a.stillMs===null||a.stillMs<6e4?`${c} of ${l} batches processed, first seen at these values on this refresh`:`${c} of ${l} batches processed, unchanged over the ${_p(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 ${zk/6e4}m or more after submission`,detail:`${a.job.jobType} ${a.job.id} is ${a.job.status}, submitted ${d} ago; ${u}. Time since submission includes time spent queued: it is not evidence of a stall.`,affectedJobs:o.map(({job:f})=>f.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 ${ai/6e4}m of watching; a job without batch counters never is.`})}return r}var c$=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"]),Md=class{constructor(e,t){this.deps=e;this.externalBrowser=t??new $r;let r=Bk({configStore:e.configStore,log:n=>e.log(n),notify:(n,o)=>Ie(e,n,"Alert",o),getConnection:async(n,o)=>(o?.again===!0&&ko().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 Id;healthCalculator=new Od;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)},t$),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(!c$.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&&n$.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 ${qk}ms bound; skipping ${t}`),!0):!1}async handleRefresh(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Jr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{await new fe(qk).withTimeout("monitor:refresh",n=>this.executeRefresh(e,r,n))}catch(n){E(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),jt(n,Jk)]);if(o.status==="rejected")throw o.reason;let a=xk(o.value);$e(n.limitInfo,"monitor:refresh limits");let d=[];for(let b of a){let S=this.alertEngine.evaluate(b.name,b.usedPercent,t.orgId);S&&d.push(S)}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 l=Date.now(),u=c.map(b=>({id:b.Id,jobType:b.JobType??"Unknown",status:b.Status,createdBy:b.CreatedById,createdDate:b.CreatedDate,failedRecords:b.NumberOfErrors,batchesProcessed:b.JobItemsProcessed??null,totalBatches:b.TotalJobItems??null})),f=c.length>=fn.monitorJobs,p=u.map(({id:b,jobType:S,status:C,createdBy:v,createdDate:T,failedRecords:D})=>({id:b,jobType:S,status:C,createdBy:v,createdDate:T,failedRecords:D})),g=a$(this.jobProgress.get(t.orgId),u,l);this.jobProgress.set(t.orgId,g);let h=d$(u,g,l),m={orgId:t.orgId,limits:a,timestamp:new Date().toISOString()},y=this.trendStorage.recordAndGetTrends(t.orgId,m,ji),[R,k]=await Promise.all([this.fetchOrgInfo(t.orgId,n),this.computeOrgHealth(t.orgId)]);R&&this.deps.sandboxRefreshes?.observe(t.orgId,{organizationId:R.orgId,instanceName:R.instanceName||void 0},"monitor");let w=this.healthCalculator.calculate({limits:a,orgId:t.orgId,trends:y,orgInfo:R}),I=w.overallScore;if(this.pastDeadline(r,"the monitor:data reply"))return;let P=A(this.deps,e,"monitor:data",{limits:a,jobs:p,jobsTruncated:f,healthScore:I,healthReport:w,trends:y,jobInsights:h,orgInfo:R,orgHealthStatus:k,lastUpdated:new Date().toISOString()});this.deps.broker.postToWebview(P),this.deps.log(`[TX] ${P.type} id=${P.id}`)}catch(n){if(this.pastDeadline(r,`the failure "${O(n)}"`))return;E(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()=>$k(await t.request("/services/data")),queryOrg:async()=>{let n=this.deps.orgManager.getOrg(e),o=await jt(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=$(Jr,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/${wo}/limits/recordCount`);$e(n.limitInfo,"monitor:storage recordCount");let i=(o.sObjects??[]).filter(p=>p.count>0).sort((p,g)=>g.count-p.count),a=i.slice(0,e$),d=a.map(p=>p.name).filter(p=>/^[A-Za-z][A-Za-z0-9_]*$/.test(p)),c=new Map;if(d.length>0){let p=await jt(n,`SELECT QualifiedApiName, Label FROM EntityDefinition WHERE QualifiedApiName IN (${d.map(g=>`'${g}'`).join(", ")})`);$e(n.limitInfo,"monitor:storage entityDefinition");for(let g of p)g.Label&&c.set(g.QualifiedApiName,g.Label)}let l=a.map(p=>({objectName:p.name,label:c.get(p.name)??p.name,recordCount:p.count})),u=i.reduce((p,g)=>p+g.count,0),f=A(this.deps,e,"monitor:storage:response",{success:!0,objects:l,totalRecords:u,objectCount:i.length});this.deps.broker.postToWebview(f),this.deps.log(`[TX] ${f.type} id=${f.id}`)}catch(n){E(this.deps,"monitor:storage","monitor:error",e,n)}}async handleDeployments(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Jr,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 ${Wk}`)).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>=Wk});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(n){E(this.deps,"monitor:deployments","monitor:error",e,n)}}async handleApiUsage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Jr,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 l=o[c];if(l&&typeof l.Max=="number"){let u=l.Max-l.Remaining,f=l.Max>0?Math.round(u/l.Max*100):0;a.push({category:c,used:u,max:l.Max,usedPercent:f})}}a.sort((c,l)=>l.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){E(this.deps,"monitor:api-usage","monitor:error",e,n)}}async handleOpenApexJobs(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Wm,e,"monitor:error",this.deps);if(!t)return;let r=this.deps.orgManager.getOrg(t.orgId);if(!r){E(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=iS(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";E(this.deps,"monitor:open-apex-jobs","monitor:error",e,new Error(`Cannot open Apex Jobs for "${he(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){E(this.deps,"monitor:open-apex-jobs","monitor:error",e,o)}}async handleErrorLogs(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Jr,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){E(this.deps,"monitor:error-logs","monitor:error",e,n)}}async handleSessions(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Jr,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){E(this.deps,"monitor:sessions","monitor:error",e,n)}}async handleApexInsights(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Jr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await this.apexLogAnalyzer.fetchAndAnalyze(r.orgId,ZC),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){E(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 jt(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: ${O(r)}`)}}async handleSandboxRefresh(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Jr,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){E(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=$(pu,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=$(pu,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 Up="seed:template:",Vk="seedTemplates",sn=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${Up}${e.id}`,e,Vk)}load(e){return this.configStore.get(`${Up}${e}`)}list(){let e=this.configStore.getByCategory(Vk);return Object.values(e).sort((r,n)=>n.updatedAt.localeCompare(r.updatedAt))}delete(e){return this.configStore.delete(`${Up}${e}`)}};var Ld=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 Xk=[{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"]}}}],Fd=class{customPersonas=new Map;customCounter=0;getBuiltInPersonas(){return[...Xk]}getPersona(e){let t=Xk.find(r=>r.id===e);return t||this.customPersonas.get(e)}async createCustomPersona(e,t){let r=u$(e),n=await t(r),o=f$(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())}},Kk=tg(s=>typeof s=="string"&&s.trim().length>0?Number(s):s,Te().finite()),no=Kk.optional().catch(void 0),Hp=j().min(1).optional().catch(void 0),Bp={faker:G({method:j().transform((s,e)=>{let t=Eg(s);return t||(e.addIssue({code:rg.custom,message:`unknown faker method ${s}`}),Zf)}),locale:Hp}),random_pick:G({values:ve(eg([j(),Te(),Ge()]).transform(String)).min(1)}),weighted_pick:G({values:xi(j(),Kk).refine(s=>Object.keys(s).length>0)}),range:G({min:no,max:no,currency:Hp}),sequence:G({prefix:Hp,start:no,step:no,padLength:no}),pattern:G({pattern:j().min(1)}),ai_generate:G({prompt:j().min(1)}),relative_date:G({minDaysFromNow:no,maxDaysFromNow:no})},l$={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 u$(s){let e=Object.keys(Bp);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}: ${l$[r]}`),"",`Faker methods: ${Tg.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 p$(s){let e=s.generator;if(typeof e!="string"||!Object.hasOwn(Bp,e))return null;let r=Bp[e].safeParse(s.params??{});if(!r.success)return null;let n=typeof s.fieldType=="string"?s.fieldType:"string";return e==="ai_generate"&&!vg(n)?null:{fieldType:n,generator:e,params:r.data,examples:Array.isArray(s.examples)?s.examples.filter(o=>typeof o=="string"):[]}}function f$(s){let e;try{e=hg(mg,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=p$(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 Zo="SEED_WRITE_DECLINED",Yk=6e4;function an(s){let e=s?.read.gate.audit;return e===void 0?{}:{details:{deliverability:e,...s?.accepted===!0?{confirmed:"emails"}:{}}}}var rO="the checkpoints of this window are not open to the Seed page",zt=class extends Error{constructor(t,r,n){super(r);this.code=t;this.refusal=n;this.name="SeedCheckpointStopped"}code;refusal};async function di(s,e){try{if(!s)throw new Error(rO);return{ask:e,planned:await s.scope(e,{})}}catch(t){throw new zt(An,br(t))}}async function ci(s,e,t,r,n){let o=await ja(async()=>{if(!s)throw new Error(rO);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,Do(i))})});if("stop"in o)throw new zt(o.stop.code,o.stop.message,o.stop.refusal);return o.checkpoint}async function Dn(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: `+O(o)),e}}function li(s,e){let t=new Set(s);return(r,n)=>t.has(r)&&(n==="insert"||e&&n==="update")}function Hd(s,e){return typeof s.unread=="string"?{firing:[]}:Wr(s,void 0,e)}function Qk(s,e,t){return t==="refuse"?{code:St.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:eR,message:s.gate.stop?.message??"The seed was refused for its emails. Nothing was written."}}var g$={ask:(s,e)=>s.confirmRun(e),unanswered:"goOn"};function h$(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 Zk(s,e){return`The seed needed an answer before it wrote \u2014 ${h$(s,e)} \u2014 and no Approval step before it approved the run: put one before it. Nothing was written.`}function eO(s,e,t){if(ks(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 _d=1e3;function m$(s){return Array.isArray(s.objectResults)?{...s,objectResults:s.objectResults.map(e=>{let t=e.createdIds.length>_d||e.errors.length>_d;return t?{...e,createdIds:e.createdIds.slice(0,_d),errors:e.errors.slice(0,_d),truncated:t}:e})}:s}function tO(s){return{query:async e=>s.tooling.query(e),queryMore:async e=>s.tooling.queryMore(e)}}function y$(s){return s.objectResults.flatMap(t=>t.errors)[0]??"The seed wrote no records."}var w$=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"]),Ud=class{constructor(e){this.deps=e;this.seedTemplateStore=new sn(e.configStore),this.templateManager=new Ld(()=>crypto.randomUUID(),()=>new Date().toISOString(),this.seedTemplateStore),this.personaManager=new Fd}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-QO4MPHZD.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 nd({org:n,objects:r,writes:o,readAutomation:c=>i===void 0?new fe(Yk).withTimeout("seed automation",()=>d.read(e,c)):typeof i.unread=="string"?Promise.reject(new Error(i.unread)):Promise.resolve(i),readLimits:()=>Sr(t),...a?{deliverability:a}:{},...i===void 0?{readDeliverability:()=>Ee(this.deps.orgManager.getOrg(e))==="production"?Promise.resolve(qt):Wt(t)}:{}})}setMuteLeases(e){this.muteLeases=e}muteLeases={};setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}beforeRunCheckpoints;checkpointProgress(e){return(t,r,n,o)=>{Le(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=$(Rm,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,he(n,t.orgId),Bv(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){E(this.deps,"seed:automation","seed:automation:error",e,r,{retryable:!0})}}async handle(e){if(!w$.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}`),!!$(Om,e,"seed:error",this.deps))try{let{listScenarioPacks:t,nodeScenarioPackFiles:r}=await import("./chunk-VZLJZEV2.mjs"),n=this.workspaceFolders(),o=await t(r(),n);this.answerScenario(e,"seed:scenario:packs:response",{packs:o,workspace:n.length>0})}catch(t){E(this.deps,"seed:scenario:packs","seed:error",e,t)}}async handleScenarioPrepare(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Im,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-DB5RVDC5.mjs"),{seedObjectAccess:a}=await import("./chunk-MTM4KG3T.mjs"),d=await o(async u=>(await r.query(u)).records),c=await i(a(r),u=>r.describe(u)),l=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",{...l})}catch(r){E(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=$(Am,e,"seed:error",this.deps);if(!t)return;let{compileScenario:r,ScenarioCompileError:n}=await import("./chunk-RZKJQOOC.mjs"),o;try{o=r(t.pack,t.options)}catch(a){if(!(a instanceof n))throw a;E(this.deps,"seed:scenario:execute","seed:error",e,a,{code:"SCENARIO_INVALID",retryable:!1});return}let i=To.safeParse(o.template);if(!i.success){E(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(u=>u.openCase!==void 0),a=new Set(i.map(u=>u.openCase?.caseKey)),d=Object.keys(r).filter(u=>a.has(u)).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 l=this.runCreations;if(!l)return{...c,companion:{kind:"failed",message:"The runs are not kept in this window."}};try{let{nodeScenarioSidecarFiles:u,scenarioRunSidecar:f,writeScenarioRunSidecar:p}=await import("./chunk-QXB6U3ZP.mjs");return await p(u(),l.storagePath,f({runId:e.operationId,pack:o,compiled:n,options:t.options,caseIds:r})),{...c,companion:{kind:"kept"}}}catch(u){let f=O(u);return this.deps.log(`[WARN] seed:scenario:execute ${e.operationId}: the companion file could not be written, so its test file cannot be: ${f}`),{...c,companion:{kind:"failed",message:f}}}}async handleScenarioAgents(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Tm,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-DB5RVDC5.mjs"),{scenarioProjectOf:a}=await import("./chunk-PGRY365W.mjs"),d=await n(i(tO(r))),c=await o(l=>r.describe(l));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){E(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=$(Em,e,"seed:error",this.deps);if(t)try{let{nodeScenarioPackFiles:r,saveScenarioPack:n}=await import("./chunk-VZLJZEV2.mjs"),o=await n(r(),this.workspaceFolders(),t.pack,t.overwrite===!0);this.answerScenario(e,"seed:scenario:save:response",{outcome:o})}catch(r){E(this.deps,"seed:scenario:save","seed:error",e,r)}}async handleScenarioTestFile(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Pm,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-L47JCNP3.mjs"),{toolingQueryAll:l}=await import("./chunk-DB5RVDC5.mjs"),{findScenarioPack:u,nodeScenarioPackFiles:f}=await import("./chunk-VZLJZEV2.mjs"),{nodeScenarioSidecarFiles:p}=await import("./chunk-QXB6U3ZP.mjs"),{scenarioProjectOf:g,writeRunTestFile:h}=await import("./chunk-PGRY365W.mjs"),m=this.workspaceFolders(),y=await h({sidecar:p(),spec:c()},{runId:t.runId,storagePath:n.storagePath,project:await g(m),alias:he(i,o.targetOrgId),choice:t.choice,...t.overwrite!==void 0?{overwrite:t.overwrite}:{},readCatalog:()=>d(l(tO(a))),findPack:(R,k)=>u(f(),m,R,k)});r(y)}catch(n){E(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=$(Sm,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){E(this.deps,"seed:template:save","seed:error",e,r)}}async handleTemplateLoad(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(cu,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){E(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){E(this.deps,"seed:template:list","seed:error",e,t)}}async handleTemplateDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(cu,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){E(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){E(this.deps,"seed:list-personas","seed:error",e,t)}}async handleCreatePersona(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(km,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){E(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: ${O(r)}`),"[]"}}:async()=>"[]"}async handleDescribeGlobal(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(bm,e,"seed:error",this.deps);if(!t)return;let r=t,n=lt(this.deps);try{let o=await B(r.orgId,this.deps.orgRegistry,this.deps.orgManager),d=(await new fe(n.timeouts.describeGlobal).withTimeout("describe-global",()=>o.describeGlobal())).sobjects.filter(l=>l.createable).filter(l=>!Fi(l.name)).map(l=>({apiName:l.name,label:l.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){E(this.deps,"seed:describe-global","seed:error",e,o)}}async handleDescribeObject(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(vm,e,"seed:error",this.deps);if(!t)return;let r=t,n=lt(this.deps);try{let o=await B(r.orgId,this.deps.orgRegistry,this.deps.orgManager),i=bt(r.objectApiName),d=await new fe(n.timeouts.describe).withTimeout("describe-object",()=>o.describe(i)),c=d.fields.filter(f=>f.createable).map(f=>({fieldApiName:f.name,label:f.label,type:f.type,required:!f.nillable&&!f.defaultedOnCreate,picklistValues:f.picklistValues?.map(p=>p.value)??[],referenceTo:f.referenceTo??[],length:f.length,integerDigits:Pg(f),objectApiName:r.objectApiName})),l=Fv(i,d.recordTypeInfos,i===Oo?await Wu(o):[]),u=A(this.deps,e,"seed:describe-object:response",{objectApiName:r.objectApiName,objectLabel:d.label,fields:c,recordTypes:l});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`)}catch(o){E(this.deps,"seed:describe-object","seed:error",e,o)}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(wm,e,"seed:error",this.deps);if(!t)return;let r=t;if(r.dryRun===!0){E(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,g$,r!==void 0);if("refusal"in i){let{refusal:l}=i;E(this.deps,"seed:execute","seed:error",e,new Error(l.message),{code:l.code,retryable:!1,...l.extraPayload?{extraPayload:l.extraPayload}:{}}),l.failed&&De(this.deps,n,l.message,!1,{context:o,...l.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,O(i));let a=eO(i,n,this.deps.log);E(this.deps,"seed:execute","seed:error",e,i,{code:Ao(i),retryable:!0,extraPayload:a}),De(this.deps,n,O(i),!0,{extraPayload:a,context:o})}}async clearSeed(e,t,r,n,o=!1,i=!1){let a=W=>{i||Z(this.deps,W)},d=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200,c=e.template.objects.map(W=>({...W,batchSize:W.batchSize??d}));Object.assign(r,Gr(c));let l=await B(e.orgId,this.deps.orgRegistry,this.deps.orgManager),u={...e.template,objects:c},f=u.objects.some(W=>W.objectApiName===Oo)?_v(u,await Wu(l)):{template:u,personObjects:[]};if("refusal"in f)return{refusal:{code:"RECORD_TYPES_MIXED",message:f.refusal}};let p={orgId:e.orgId,template:f.template,personObjects:f.personObjects,locale:await Uv(e.locale,l)},g=e.template.objects.reduce((W,se)=>W+se.recordCount,0),h=[],m=W=>{h.push(W),this.deps.log(`[WARN] seed:execute ${t}: ${W}`)},y=this.deps.orgManager.getOrg(p.orgId),R=he(y,p.orgId),k=f.template.objects.map(W=>({objectApiName:W.objectApiName,recordCount:W.recordCount})),w=this.targetAutomation,I=await new fe(Yk).withTimeout("seed automation",()=>w.read(p.orgId,k.map(W=>W.objectApiName))).catch(W=>({unread:O(W)})),P=Hv(f.template,o),b;if("muteAutomation"in e&&e.muteAutomation===!0)try{b=await Ot(async()=>Lt(l),I,{...this.muteLeases,writes:P})}catch(W){if(!xt(W))throw W;return a({action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",code:W.code}),{refusal:{code:W.code,message:W.message,extraPayload:{},failed:{authored:!0}}}}b&&(p.mute=b);let S=Gv(e.fit,g);S&&(p.fit=S);let{describedFieldsOf:C,requiredForAccountKinds:v}=await import("./chunk-CDWZGQAJ.mjs"),T=0,D=C(async W=>(T++,l.describe(W))),z=qv(I,b?.plan,P,await Wv(f.template,I,D.unset)),H=await ar({read:I,...b?.plan?{plan:b.plan}:{},writes:P,readDeliverability:()=>Ee(y)==="production"?Promise.resolve(qt):Wt(l),accepted:!1,target:R,run:"seed",keepsAddresses:!0}),Y={read:H,accepted:!1};p.emails=Y;let U=H.gate.verdict==="asks",M;if(e.checkpointFirst!==void 0){let W={module:"seed",orgId:p.orgId,operationId:t,written:k.filter(se=>se.recordCount>0).map(se=>se.objectApiName),running:z.running??{firing:[]},request:e.checkpointFirst};try{M=await di(this.beforeRunCheckpoints,W)}catch(se){if(!(se instanceof zt))throw se;return a({action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",code:se.code}),{refusal:{code:se.code,message:se.message,extraPayload:{},failed:{authored:!0}}}}}let{seedObjectAccess:L,templateTheOrgTakes:ee}=await import("./chunk-MTM4KG3T.mjs"),Q=await ee(f.template,L(l)),q=Iv(As(this.deps.services),f.template),V=await Ov(Q,{describeCreateableFields:D.createable,describeRequiredFields:v(D,f.personObjects)},q),we={duplicateRules:Fo(I),partition:q,slices:V,slicesRead:T,bulkThreshold:lt(this.deps).bulk.threshold,automationRead:Tn(I)},ie=await Cv(l,Q,f.personObjects,he(y,p.orgId),M?.planned,{...En(H.ofRun),...lb(b?.plan)},we,z.room);if(ie.check.verdict==="unread"&&m(`the data storage the org has left could not be read (${ie.check.unread}): whether the records fit is not known`),ie.refusal){let W=ie.refusedFor==="checkpoint",se=W?An:ie.refusedFor==="apiRequests"?No:qu,te=W?ie.checkpointRefusal?.code:void 0;a({action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",code:se,...te!==void 0?{details:{checkpointRefusal:te}}:{}});let ue=ie.check,x=W?void 0:zv($v(ie),Q,f.personObjects,z.room,we);return{refusal:{code:se,message:ie.refusal,extraPayload:{...ue.verdict==="unread"||se!==qu?{}:{estimateMB:Number(qs(ue.estimateMB)),remainingMB:ue.remainingMB,maxMB:ue.maxMB,org:he(y,p.orgId)},...te!==void 0?{checkpointRefusal:te}:{},...x?{fit:x}:{}},failed:{authored:!0}}}}let re=await this.readAutomation(p.orgId,l,k.map(W=>W.objectApiName),R,P,b?.automation??I,H.gate.deliverability),Ae=od(re,k,R);for(let W of Ae.unknown??[])m(W);if(Ae.refusal)return a({action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",code:zu}),{refusal:{code:zu,message:Ae.refusal,extraPayload:{...Ae.figures?{...Ae.figures}:{},...o?{scenario:!0}:{}},failed:{authored:!0}}};if(i)return{preview:{records:Q.objects.reduce((W,se)=>W+se.recordCount,0),objects:Q.objects.length,storage:ie.check,apiRequests:ie.api,automation:Gu(re,R),warnings:h},storage:ie,asks:ie.check.verdict==="unread"||ie.api.verdict==="near"||M!==void 0||U,emailsAsked:U,emails:H};let me=this.deps.infraServices?.productionGuard;if(!me)return Z(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",code:be.code}),{refusal:{code:be.code,message:be.message,failed:{authored:!1}}};let Je={orgId:p.orgId,orgTier:Ee(y),operation:"insert",objectName:"SeedData",recordCount:g,module:"seed"},{check:Ne,decision:Fe}=await Ze(me,Je);if((Fe==="refused"||Fe==="declined")&&Z(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",guard:Fe}),Fe==="refused")throw mn(Ne.blockedReason??Ne.impactSummary);if(Fe==="declined")return{refusal:{code:$t.declined,message:"Operation cancelled by user (confirmation declined).",failed:{authored:!1}}};if(ie.check.verdict==="unread"||ie.api.verdict==="near"||M!==void 0||U){let W=await n.ask(me,{stage:"write",module:"seed",org:R,orgTier:Ee(y),objects:f.template.objects.map(se=>({objectApiName:se.objectApiName,rows:se.recordCount})).sort((se,te)=>te.rows-se.rows),total:g,storage:Pn(ie.check),counted:!0,...jo(ie.api),...M?{checkpoint:M.planned}:{},...H.gate.confirmation});if(W==="confirmed"&&U&&(Y.accepted=!0),W==="declined")return Z(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",guard:Fe,code:Zo,...an(Y)}),{refusal:{code:Zo,message:"The seed was cancelled before it wrote anything. Nothing was written.",failed:{authored:!0}}};if(W==="unavailable"&&U){let se=Qk(H,R,n.unanswered);return Z(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",guard:Fe,code:se.code,...an(Y)}),{refusal:{...se,failed:{authored:!0}}}}if(W==="unavailable"&&M!==void 0)return Z(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",guard:Fe,code:St.unanswered}),{refusal:{code:St.unanswered,message:`The seed needed an answer before it wrote \u2014 the checkpoint it takes first reads whole tables of ${R} \u2014 and there was no one to ask. Nothing was written.`,failed:{authored:!0}}};if(W==="unavailable"&&n.unanswered==="refuse")return Z(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",guard:Fe,code:St.unanswered}),{refusal:{code:St.unanswered,message:Zk(ie,R),failed:{authored:!0}}};W==="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:l,run:p,plannedRecords:g,guardDecision:Fe,automation:re,orgName:R,warnings:h,...M?{checkpoint:M}:{}}}beginSeed(e,t,r,n,o,i,a){this.deps.infraServices?.performanceTracker?.start(r,"seed"),ze(this.deps,r,"seed",o),this.liveTracker?.register(r,"seed",o,t.plannedRecords);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(St.orgUnknown,`The org the seed writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was written.`);let r=HS(Ee(t),e.answer,he(t,e.orgId));if(r)throw r;let n=Xo(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 vt("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=he(this.deps.orgManager.getOrg(e.orgId),e.orgId);if(i.emailsAsked){let d=Qk(i.emails,a,o.unanswered);throw ur(d.code,d.message)}throw ur(St.unanswered,Zk(i.storage,a))}return i.preview}async seedForPipeline(e,t){let r=this.pipelineSeedOf(e),n=yn("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 Sa(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 Z(this.deps,{action:"seed_execute",module:"seed",operationId:o,orgId:e.orgId,outcome:"stopped",guard:d.guardDecision,code:Rt}),new vt("The seed was cancelled before it wrote anything. Nothing was written.");let c=Gu(d.automation,d.orgName);for(let m of c)this.deps.log(`[INFO] seed:execute ${o}: ${m}`);let l,u=`Pipeline seed of ${r.template.name}`,{abortController:f,execution:p}=this.beginSeed(n,d,o,i,u,{pipeline:e.pipeline,ended:m=>{l=m}});this.registry?.register(o,"seed",u,p,f);let g=()=>{this.registry?this.registry.abort(o):f.abort()};t?.addEventListener("abort",g,{once:!0});try{await p}finally{t?.removeEventListener("abort",g)}let h=l;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(O(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,l){let u=lt(this.deps),f=new Date().toISOString(),p,g=!1,h={},m=r.template.name,y={origin:"generator",...typeof m=="string"?{label:m}:{}};try{let R=mr(this.deps),k=new qa({retryConfig:u.retry,signal:o.signal,onRetry:(ae,Re,Ue)=>{this.deps.log(`[RETRY] seed insert attempt=${ae} code=${Re.originalError.statusCode} delay=${Ue}ms`)}}),w=this.deps,I=crypto.randomUUID(),P=d?this.deps.orgManager.getOrg(r.orgId)?.orgId:void 0,b=this.runCreations?.recorder({runId:I,targetOrgId:r.orgId,startedAt:f,...d?{pipeline:d.pipeline}:{},...P?{targetOrganizationId:P}:{}});kr(b,()=>t.identity(),`seed:execute ${n}`);let S={base:0,total:0},C=(ae,Re,Ue)=>{let He=S.base+ae,st=Math.max(S.total,He,Re,1),Ve=Math.round(He/st*100);Le(w,n,Ve,He,st,Ue),this.liveTracker?.updateProgress(n,Ve,He,st,Ue)},v=ov({conn:t,bulkThreshold:u.bulk.threshold,bulkManager:R,retry:k,signal:o.signal,label:`seed:execute ${n}`,log:ae=>this.deps.log(ae),onProgress:C,...b?{calls:{sending:(ae,Re,Ue)=>b.sending(ae,Re,Ue),answered:(ae,Re)=>b.answered(ae,Re)}}:{}}),T=async(ae,Re,Ue,He)=>{Ue.length>0&&(g=!0);let st=await v(ae,Re,Ue,He);return b?.note(Re,st.successIds),st},D=ae=>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: ${O(ae)}`),{SeedValidator:z}=await import("./chunk-ISAUCWYK.mjs"),{DataPlanBuilder:H}=await import("./chunk-UOHZW2L4.mjs"),{FieldMapper:Y}=await import("./chunk-E3RQ575Y.mjs"),{ReferenceLinker:U}=await import("./chunk-T36DZJPH.mjs"),{AIDataGenerator:M}=await import("./chunk-LWES2KZE.mjs"),{FakerFallback:L}=await import("./chunk-NFEBX75O.mjs"),{readExistingParentIds:ee,readPresentParentIds:Q}=await import("./chunk-262TP6UU.mjs"),{seedObjectAccess:q}=await import("./chunk-MTM4KG3T.mjs"),{describedFieldsOf:V,requiredForAccountKinds:we}=await import("./chunk-CDWZGQAJ.mjs"),{seedTargetOf:ie}=await import("./chunk-3V4YH5KO.mjs"),re=c?(await import("./chunk-6KOUYHEY.mjs")).seedKnowledge:void 0,Ae=new M(this.buildSeedCallAI()),me=new L(r.locale),Je=new Y({aiGenerator:Ae,fakerFallback:me}),Ne=new U,Fe=new z,W=new H,{SeedGrappeAdapter:se}=await import("./chunk-PTTHSSQO.mjs"),te=As(this.deps.services),ue=V(ae=>t.describe(ae)),x={validator:Fe,describeCreateableFields:ue.createable,describeVisibleFields:ue.visible,describeComputedFields:ue.computed,describePicklistValues:ue.picklistValues,describeFieldLengths:ue.lengths,describeRequiredFields:we(ue,r.personObjects),objectAccess:q(t),readExistingParentIds:(ae,Re,Ue)=>ee(t,ae,Re,Ue),readPresentParentIds:(ae,Re)=>Q(t,ae,Re),describeKeyPrefix:ue.keyPrefix,...ie(t),planBuilder:W,fieldMapper:Je,referenceLinker:Ne,insert:T,generateId:()=>crypto.randomUUID(),now:()=>new Date().toISOString(),services:this.deps.services,grappeAdapter:new se(()=>crypto.randomUUID(),te?.grappeSize),grappeConfig:te,onGrappeEvent:ae=>ta(this.deps,ae),onProgress:ae=>{S.base=ae.processedRecords,S.total=ae.totalRecords,C(0,ae.totalRecords,`Insert ${ae.objectApiName}`)},signal:o.signal,...c&&re?{onRowIds:(ae,Re)=>{ae==="Case"&&Object.assign(h,Re)},knowledge:re({org:t,plan:{publish:!0,links:c.compiled.closedCaseArticles},...b?{journal:b}:{},signal:o.signal})}:{}};if(!this.deps.services)throw new Error("SeedOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let N=this.deps.services.seedOrchestrator(x),X=r.template;Le(this.deps,n,0,0,1,"Validating template and building plan");let F;this.runningRuns.add(I);let de=r.mute,J=de?.muted;try{l&&(p=await ci(this.beforeRunCheckpoints,l,I,o.signal,this.checkpointProgress(n)),b?.checkpoint?.(p));let ae=de?.prepared?await de.prepared.acquire(I):void 0;ae&&(J=ae.outcome);let Re=ae&&r.emails?r.emails.read.afterLease(ae.outcome,r.emails.accepted):void 0;if(ae&&Re)throw J=await ae.release(),new zt(Re.code,Re.message);F=await N.execute(X,r.orgId,I).finally(async()=>{ae&&(J=await ae.release())}),J&&(F={...F,mutedAutomation:J});let Ue=await Dn(this.beforeRunCheckpoints,p,g,this.deps.log,`seed:execute ${n}`);p=void 0,Ue&&(F={...F,checkpoint:Ue})}catch(ae){throw await b?.end({status:"failure",finishedAt:new Date().toISOString(),objectResults:[]}).catch(D),this.runningRuns.delete(I),ae}await b?.end({finishedAt:new Date().toISOString(),status:F.status,...F.cancelled?{cancelled:!0}:{},objectResults:F.objectResults}).catch(D),c&&(F={...F,scenario:await this.keepScenario(F,c,h)}),this.runningRuns.delete(I),F.cancelled||Le(this.deps,n,100,1,1,"Seed complete");let le=F.totalRecordsCreated;this.deps.infraServices?.performanceTracker?.update(n,le,1),this.deps.infraServices?.performanceTracker?.complete(n),F.cancelled?(this.registry?.abort(n),pe(this.deps,n,{aborted:!0,totalRecords:le}),this.liveTracker?.cancel(n)):(pe(this.deps,n,{status:F.status,totalRecords:le}),F.status==="failure"?this.liveTracker?.fail(n,y$(F)):F.status==="partial"?this.liveTracker?.partial(n):this.liveTracker?.complete(n));let Pe=F.objectResults.some(ae=>ae.recordsCreated+ae.recordsFailed>0),je=F.cancelled===!0?Pe?"cancelled":"stopped":F.status;Z(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:je,...je==="stopped"?{code:nt}:{},guard:a,objects:F.objectResults.map(ae=>({...ht(ae.objectApiName),created:ae.recordsCreated,failed:ae.recordsFailed})),source:y,...F.mutedAutomation?{muted:ct(F.mutedAutomation)}:{},...F.checkpoint?.state==="taken"?{checkpointId:F.checkpoint.checkpointId}:{},...r.fit?{fit:r.fit}:{},...an(r.emails)});let We=A(this.deps,e,"seed:execute:response",m$(F));if(this.deps.broker.postToWebview(We),this.deps.log(`[TX] ${We.type} id=${We.id}`),d?.ended({result:F}),F.status==="failure"&&!F.cancelled)return{status:"failure"}}catch(R){this.deps.infraServices?.performanceTracker?.complete(n);let k=await Dn(this.beforeRunCheckpoints,p,g,this.deps.log,`seed:execute ${n}`),w=k?.state==="deleted"?`${O(R)} ${Yr}`:void 0,I=w!==void 0?new Error(w):R;if(R instanceof zt){if(R.code===nt)this.registry?.abort(n),pe(this.deps,n,{aborted:!0,totalRecords:0}),this.liveTracker?.cancel(n);else{let C=O(I);this.liveTracker?.fail(n,C),De(this.deps,n,C,!1,{context:i,authored:!0})}let S=R.refusal?.code;return Z(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:"stopped",guard:a,code:R.code,...S!==void 0||r.emails?.read.gate.audit!==void 0?{details:{...an(r.emails).details,...S!==void 0?{checkpointRefusal:S}:{}}}:{}}),E(this.deps,"seed:execute","seed:error",e,I,{code:R.code,retryable:!1,...S!==void 0?{extraPayload:{checkpointRefusal:S}}:{}}),d?.ended({error:R}),R.code===nt?void 0:{status:"failure"}}this.liveTracker?.fail(n,O(I));let P=xt(R)?R:void 0;Z(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:P?"stopped":"failure",guard:a,source:y,...P?{code:P.code}:{},...k?.state==="taken"?{checkpointId:k.checkpointId}:{},...r.fit?{fit:r.fit}:{},...an(r.emails)});let b=eO(R,n,this.deps.log);return E(this.deps,"seed:execute","seed:error",e,R,{...P?{code:P.code}:{},retryable:!0,extraPayload:{...b,...k?{checkpoint:k}:{}}}),De(this.deps,n,O(I),!0,{extraPayload:b,context:i}),d?.ended({error:I}),{status:"failure"}}}};function b$(s){if(s.length>512)throw new Error(`SOQL WHERE clause too long (${s.length} > 512 chars)`);return uh(s)}var ui=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 Es(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 ${qe(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 Es(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 ${qe(t)}${this.whereOf(r,n)}`}whereOf(e,t){let r=e?b$(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 pi=class{resolveInsertOrder(e,t){if(e.length===0)return[];let r=new Set(e),n=t.filter(u=>u.from!==u.to&&r.has(u.from)&&r.has(u.to)),o=new Map(e.map(u=>[u,new Set])),i=new Map(e.map(u=>[u,new Set])),a=new Map(e.map(u=>[u,new Set]));for(let u of n)o.get(u.to)?.add(u.from),u.required&&(qp(u)?a:i).get(u.to)?.add(u.from);let d=Xi(i).filter(u=>u.length>1);if(d.length>0)throw new Error(v$(d,n.filter(u=>!qp(u))));let c=new Map(e.map(u=>[u,new Set([...i.get(u)??[],...a.get(u)??[]])])),l=Xi(c).some(u=>u.length>1)?i:c;return R$(Xi(o),o,e).flatMap(u=>u.length>1?lh(u,l):u)}lookupsOf(e,t){return t.filter(r=>r.to===e&&!qp(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===tr&&a.name==="ActivityId")&&a.type==="reference"&&a.referenceTo){let d=ys(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 ou(r))n.push({from:o.sourceObject,to:o.targetObject,fieldApiName:o.relationshipName,relationshipType:"lookup",required:!0});return n}};function R$(s,e,t){let r=new Map;t.forEach((c,l)=>{r.has(c)||r.set(c,l)});let n=new Map;s.forEach((c,l)=>c.forEach(u=>n.set(u,l)));let o=s.map(c=>Math.min(...c.map(l=>r.get(l)??1/0))),i=s.map((c,l)=>{let u=new Set;for(let f of c)for(let p of e.get(f)??[]){let g=n.get(p);g!==void 0&&g!==l&&u.add(g)}return u}),a=new Set,d=[];for(;d.length<s.length;){let c=-1;for(let l=0;l<s.length;l++)a.has(l)||[...i[l]].some(u=>!a.has(u))||(c===-1||o[l]<o[c])&&(c=l);if(c===-1)break;a.add(c),d.push(s[c])}return d}function qp(s){return ou(new Set([s.from,s.to])).some(e=>e.sourceObject===s.from&&e.targetObject===s.to&&e.relationshipName===s.fieldApiName)}function v$(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(", ")}. ${S$(t)} must be set when the record is created, so no object of the cycle can be written first.`}function S$(s){return s.length<=1?s.join(""):`${s.slice(0,-1).join(", ")} and ${s[s.length-1]}`}function Wp(s){return s==="insert"||s==="upsert"}function Bd(s,e){return{sending:(t,r,n)=>{Wp(r)&&s.sending(t,n,r==="upsert"?{upsert:!0}:void 0)},opened:(t,r,n,o)=>{Wp(r)&&s.sending(t,n,{job:o,...r==="upsert"?{upsert:!0}:{}})},answered:(t,r,n)=>{if(!Wp(r))return;let o=td(r,n);s.answered(t,o),e?.(o.length)}}}var k$=new Set(["seed:clone:describe-source","seed:clone:preview","seed:clone:execute"]),O$=5,I$=10,A$=-1,nO="Operation blocked by Production Guard: ",dn={confirmationDeclined:"PRODUCTION_CONFIRMATION_DECLINED",guardBlocked:"PRODUCTION_GUARD_BLOCKED",failed:"CLONE_FAILED",emailsExceeded:"CLONE_EMAILS_EXCEEDED",apiBudgetExceeded:"API_BUDGET_EXCEEDED",storageExceeded:"CLONE_STORAGE_EXCEEDED"},T$=3;function E$(s,e){let t=s.filter(n=>n.recordCount>0).map(n=>({objectApiName:n.objectApiName,rows:n.recordCount,bytes:eo(n.objectApiName,{rows:n.recordCount})})).sort((n,o)=>o.bytes-n.bytes),r=vr({storageBytes:t.reduce((n,o)=>n+o.bytes,0)},e);if(r.verdict==="exceeds")return{estimateMB:r.estimateMB,remainingMB:r.remainingMB,maxMB:r.maxMB,heaviest:t.slice(0,T$).map(({objectApiName:n,rows:o,bytes:i})=>({objectApiName:n,rows:o,mb:i/(1024*1024)}))}}function oO(s){let e=s<10?100:10;return String(s<=0?0:Math.ceil(s*e-1e-9)/e)}function P$(s,e){let t=s.heaviest.map(r=>`${r.objectApiName} (${r.rows} records, ${oO(r.mb)} MB)`).join(", ");return`The clone was refused before it wrote anything: its records take about ${oO(s.estimateMB)} MB of data storage, and ${e} has ${s.remainingMB} MB left of ${s.maxMB} MB. 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). Nothing was written.`}var C$=6e4,$$={neutralized:!1,fields:[],values:0},x$="PREVIEWED_FOR_OTHER_ORGS",D$="NOT_PREVIEWED",N$="PREVIEW_NOT_HELD",j$=50,Wd=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-QO4MPHZD.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 nd({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:()=>Sr(t),...i?{deliverability:i}:{}});return od(d,a,n)}readTargetAutomation(e,t){let r=this.targetAutomation;return new fe(C$).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: ${O(n)}`),!1}finally{this.runningRuns.delete(t)}}stoppedForCheckpoint(e,t,r,n,o){let{operationId:i}=t;if(r.code===nt){Z(this.deps,{...t,outcome:"stopped",source:void 0,code:nt}),this.registry?.abort(i),pe(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}:{};Z(this.deps,{...t,outcome:"stopped",source:void 0,code:r.code,...a!==void 0?{details:d}:{}}),De(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(!k$.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=$(Cm,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=>!Fi(a.name)).map(a=>({apiName:a.name,label:a.label,recordCount:A$})),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){E(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=$(lu,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 ui({log:this.deps.log}),i=new pi,a=t.objects.map(w=>w.objectApiName),d=new Map(t.objects.map(w=>[w.objectApiName,w.whereClause])),c=new Map,l=new Map,u=[];for(let w of t.objects){let[I,P]=await Promise.all([qd("target",w.objectApiName,()=>n.describe(w.objectApiName)),qd("source",w.objectApiName,()=>o.describe(r,w.objectApiName))]);$e(n.limitInfo,`seed:clone:preview describe ${w.objectApiName} in the target`),$e(r.limitInfo,`seed:clone:preview describe ${w.objectApiName}`),c.set(w.objectApiName,I),l.set(w.objectApiName,P);let b=fh(w.objectApiName,iO(w.objectApiName,c.get(w.objectApiName),l.get(w.objectApiName)),d),[S,C,v]=await Promise.all([o.countRecords(r,w.objectApiName,w.whereClause,b),o.fetchSample(r,w.objectApiName,O$,w.whereClause,b),b.length>0?o.countRecords(r,w.objectApiName,w.whereClause):void 0]),T=v===void 0?0:v-S;u.push({objectApiName:w.objectApiName,recordCount:S,...T>0?{leftToThePlatform:T}:{},sampleRecords:C.map(D=>z$(D,I$))})}let f=i.buildEdgesFromDescribe(a,aO(c,l)),p=i.resolveInsertOrder(a,f),g=u.map(w=>({...w,relationships:i.lookupsOf(w.objectApiName,f)})),h=_$(i.lookupsFilledAfter(p,f),p),m=U$(p,l,c),y=H$(p,c,l),R={objects:g,insertOrder:p,...h.length>0?{filledAfterInsert:h}:{},...m.length>0?{sourceOnlyLookups:m}:{},...y.length>0?{targetOnlyRequiredLookups:y}:{}},k=A(this.deps,e,"seed:clone:preview:response",R);this.deps.broker.postToWebview(k),this.deps.log(`[TX] ${k.type} id=${k.id}`),this.rememberPreview(e.id,t,new Map(u.map(w=>[w.objectApiName,w.recordCount])),new Set(i.lookupsFilledAfter(p,f).map(w=>w.to)))}catch(r){let n=r instanceof zd?r:void 0;E(this.deps,"seed:clone:preview","seed:clone:error",e,r,{...n?{code:L$,retryable:!1,extraPayload:{objectApiName:n.objectApiName,org:he(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<=j$)break;this.previewedOrgs.delete(o)}}refusedAgainstItsPreview(e){if(e.previewId===void 0)return{code:D$,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:N$,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:x$,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=$(lu,e,"seed:clone:error",this.deps);if(!t)return;let r=this.refusedAgainstItsPreview(t);if(r!==void 0){E(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,...Gr(t.objects.map(w=>({objectApiName:w.objectApiName})))},a=new AbortController,d=()=>{},c=new Promise((w,I)=>{d=P=>P===void 0?w():I(P)});c.catch(()=>{}),this.registry?.register(n,"clone",`Clone ${t.objects.length} object(s)`,c,a);let l={action:"seed_clone",module:"seed",operationId:n,orgId:t.targetOrgId,outcome:"failure",source:{origin:"org",orgId:t.sourceOrgId}},u=!1,f,p=0,g,h=!1,m=[],y=!!(t.upsert&&t.externalIdField),R=fv(t.keepContactPoints===!0?{keepContactPoints:!0}:{}),k=()=>R?.report()??$$;try{let w=this.deps.infraServices?.productionGuard;if(!w){Z(this.deps,{...l,outcome:"stopped",source:void 0,code:be.code}),De(this.deps,n,be.message,!1,{context:i,extraPayload:{code:be.code}}),d(new Error(be.message));return}let I=this.deps.orgManager.getOrg(t.targetOrgId),P={orgId:t.targetOrgId,orgTier:Ee(I),operation:t.upsert?"upsert":"insert",objectName:t.objects.map(_=>_.objectApiName).join(", ")||"CloneData",recordCount:"unknown",module:"clone"},{check:b,decision:S}=await Ze(w,P);if(l.guard=S,(S==="refused"||S==="declined")&&Z(this.deps,{...l,outcome:"stopped",source:void 0}),S==="refused")throw new Error(`${nO}${b.blockedReason??b.impactSummary}`);if(S==="declined"){let _="Operation cancelled by user (confirmation declined).";De(this.deps,n,_,!1,{context:i,extraPayload:{code:dn.confirmationDeclined}}),d(new Error(_));return}let C=await B(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),v=await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),T=he(I,t.targetOrgId),D=this.previewedOrgs.get(t.previewId??""),z=D?.recordCounts,H=t.objects.map(_=>({objectApiName:_.objectApiName,recordCount:z?.get(_.objectApiName)??0})),Y=H.filter(_=>_.recordCount>0).map(_=>_.objectApiName),U=(_,K,ce)=>{let Oe=ce!==void 0?{checkpointRefusal:ce}:{};Z(this.deps,{...l,outcome:"stopped",source:void 0,code:_,...ce!==void 0?{details:Oe}:{}}),De(this.deps,n,K,!1,{context:i,authored:!0,extraPayload:{code:_,...Oe}}),d(new Error(K))},M,L=Y.length>0?await this.readTargetAutomation(t.targetOrgId,Y).catch(_=>({unread:O(_)})):{unread:"the clone sends no record"},ee=Y.length>0?await ar({read:L,writes:li(Y,!0),readDeliverability:()=>Ee(I)==="production"?Promise.resolve(qt):Wt(v),accepted:!1,target:T,run:"clone",keepsAddresses:t.keepContactPoints===!0}):void 0,Q=ee?.gate.verdict==="asks";if(t.checkpointFirst!==void 0){try{M=await di(this.beforeRunCheckpoints,{module:"seed",orgId:t.targetOrgId,operationId:n,written:Y,running:Hd(L,li(Y,!0)),request:t.checkpointFirst})}catch(K){if(!(K instanceof zt))throw K;U(K.code,K.message);return}let _=Na(M.planned);if(_){U(_.code,_.message,_.refusal.code);return}}let q=await this.emailGate(t.targetOrgId,v,H,T,L,ee?.gate.deliverability);for(let _ of q?.unknown??[])this.deps.log(`[WARN] seed:clone:execute ${n}: ${_}`);if(q?.refusal&&q.figures){let _=M$(q.figures);Z(this.deps,{...l,outcome:"stopped",source:void 0,code:dn.emailsExceeded}),De(this.deps,n,_,!1,{context:i,authored:!0,extraPayload:{code:dn.emailsExceeded,...q.figures}}),d(new Error(_));return}let V=await Rr(v).catch(_=>({unread:O(_)})),we="unread"in V?await dr(v).catch(_=>({unread:O(_)})):V.dailyApiRequests,ie=t.upsert?void 0:E$(H,V);if(ie){let _=P$(ie,T);Z(this.deps,{...l,outcome:"stopped",source:void 0,code:dn.storageExceeded}),De(this.deps,n,_,!1,{context:i,authored:!0,extraPayload:{code:dn.storageExceeded,org:T,...ie}}),d(new Error(_));return}let re=In({run:Ev(H.map(_=>({objectApiName:_.objectApiName,rows:_.recordCount})),{threshold:lt(this.deps).bulk.threshold,perCall:this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200),duplicateRules:Fo(L),...D?{secondPass:D.secondPass}:{},automationRead:Y.length>0?Tn(L):0}),...Mo(M?.planned),...En(ee?.ofRun)},we);re.verdict==="unread"&&this.deps.log(`[WARN] seed:clone:execute ${n}: the daily API requests the target has left could not be read (${re.unread})`);let Ae=Da(re,T);if(Ae){Z(this.deps,{...l,outcome:"stopped",source:void 0,code:dn.apiBudgetExceeded}),De(this.deps,n,Ae,!1,{context:i,authored:!0,extraPayload:{code:dn.apiBudgetExceeded}}),d(new Error(Ae));return}let me=!1;if(M||Q){let _=H.filter(ce=>ce.recordCount>0).map(ce=>({objectApiName:ce.objectApiName,rows:ce.recordCount})).sort((ce,Oe)=>Oe.rows-ce.rows),K=await w.confirmRun({stage:"write",module:"seed",org:T,orgTier:Ee(I),objects:_,total:_.reduce((ce,Oe)=>ce+Oe.rows,0),storage:Pn(vr({storageBytes:_.reduce((ce,Oe)=>ce+eo(Oe.objectApiName,{rows:Oe.rows}),0)},V)),counted:!0,...jo(re),...M?{checkpoint:M.planned}:{},...ee?.gate.confirmation});if(K!=="confirmed"){let ce=ee?.gate.stop;K!=="declined"&&!M&&ce?U(ce.code,ce.message):U(K==="declined"?Zo:St.unanswered,K==="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 ${T} \u2014 and there was no one to ask. Nothing was written.`);return}me=Q}if(l.details=an(ee?{read:ee,accepted:me}:void 0).details,ze(this.deps,n,"clone",`Clone ${t.objects.length} object(s)`),this.liveTracker?.register(n,"clone",`Clone ${t.objects.length} object(s)`),M)try{g=await ci(this.beforeRunCheckpoints,M,n,a.signal,(_,K,ce,Oe)=>{Le(this.deps,n,_,K,ce,Oe),this.liveTracker?.updateProgress(n,_,K,ce,Oe)})}catch(_){if(!(_ instanceof zt))throw _;this.stoppedForCheckpoint(e,l,_,i,Date.now()-o),d(_.code===nt?void 0:_);return}u=!0;let Je=lt(this.deps),Ne=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200;i.batchSize=Ne;let Fe=new Map,W={objects:0,records:0,of:1};f=this.runCreations?.recorder({runId:n,targetOrgId:t.targetOrgId,sourceOrgId:t.sourceOrgId,startedAt:new Date(o).toISOString(),origin:"clone"}),g&&f?.checkpoint?.(g),kr(f,()=>v.identity(),`seed:clone:execute ${n}`),f&&this.runningRuns.add(n);let se=new Cn({...f?{calls:Bd(f,_=>{p+=_})}:{},keyPrefixOf:_=>Fe.get(_)?.keyPrefix,connection:v,bulkExecutor:new Rn(Je.bulk.threshold),bulkManager:mr(this.deps),retryConfig:Je.retry,signal:a.signal,onProgress:(_,K,ce)=>{Le(this.deps,n,K>0?Math.round(_/K*100):0,_,K,ce),this.liveTracker?.updateProgress(n,Math.round((W.objects+_/Math.max(K,1))/W.of*100),W.records+_,0,ce)},log:_=>this.deps.log(_)}),te=new ui({log:this.deps.log}),ue=new pi,x=t.objects.map(_=>_.objectApiName),N=new Set(x),X=new Map,F=new Map,de=new Map;for(let _ of x){let[K,ce]=await Promise.all([qd("target",_,()=>v.describe(_)),qd("source",_,()=>te.describe(C,_))]);$e(v.limitInfo,`seed:clone:execute describe ${_}`),$e(C.limitInfo,`seed:clone:execute describe ${_} in the source`),X.set(_,K),F.set(_,ce),de.set(_,Or(K).fields??[]),Fe.set(_,{keyPrefix:K.keyPrefix??null,recordTypes:Mh(K.recordTypeInfos)})}let J=ue.buildEdgesFromDescribe(x,aO(X,F)),le=ue.resolveInsertOrder(x,J),Pe=ue.lookupsFilledAfter(le,J);W.of=Math.max(le.length,1);let je=new Map(t.objects.map(_=>[_.objectApiName,_])),We=new Map,ae=new Map,Re=new Map,Ue=[],He=new ph,st=0,Ve=!1,_n=new Map,Ht=[],ps=N.has(Yi),Qt=_=>jt(v,_),Ei=new Map,fo=new Map,go=Xn(yr(_=>jt(C,_)),async _=>F.get(_)??await te.describe(C,_)),Nr=new Map,Pi=async(_,K)=>{if(K.length===0)return;let ce=await go(_);for(let Oe of ce){let ye=!1;for(let Se of K)Oe in Se&&(ye||=Se[Oe]!==null&&Se[Oe]!==void 0,delete Se[Oe]);ye&&Nr.set(_,(Nr.get(_)??new Set).add(Oe))}},jr=async(_,K)=>{let ce=(X.get(_)?.fields??[]).filter(Se=>Se.type==="reference"),Oe=await vR({lookups:ce,rows:K,known:Ei,query:Qt});if(Oe.size===0)return;let ye=fo.get(_)??new Map;for(let Se of K)for(let{name:ge}of ce){let Ye=Se[ge];typeof Ye!="string"||!Oe.has(Ye)||(delete Se[ge],ye.set(ge,(ye.get(ge)??0)+1))}ye.size!==0&&(fo.set(_,ye),this.deps.log(`[INFO] seed:clone ${_}: 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): `+[...ye].map(([Se,ge])=>`${Se} on ${ge}`).join(", ")))},fs=async(_,K)=>{await Pi(_,K),await jr(_,K),R&&gv(R,_,de.get(_)??[],K,y?t.externalIdField:void 0),K.length>0&&(h=!0);try{return{outcomes:t.upsert&&t.externalIdField?await se.upsert(_,t.externalIdField,K,Ne):await se.insert(_,K,Ne),stopped:!1}}catch(ce){if(!(ce instanceof zo))throw ce;return{outcomes:ce.written,stopped:!0}}},fr=(_,K,ce,Oe)=>{_.forEach((ye,Se)=>{let ge=typeof K[Se]?.Id=="string"?K[Se].Id:"";if(ye.success){ce.insertedCount++,ge&&ye.id&&(We.set(ge,ye.id),ce.idMappings.push({sourceId:ge,targetId:ye.id}));let Ye=ye.id;if(Ye)for(let{fieldName:ne,sourceRefId:Ce}of Oe[Se]??[])Ue.push({objectApiName:ce.objectApiName,newId:Ye,sourceId:ge||void 0,fieldName:ne,sourceRefId:Ce})}else ye.existingId?(ce.linkedCount=(ce.linkedCount??0)+1,ge&&(We.set(ge,ye.existingId),ce.idMappings.push({sourceId:ge,targetId:ye.existingId}))):(ce.failedCount++,ce.errors.push({sourceId:ge,message:ye.errors[0]??"Unknown insert error"}))})},Ci=async _=>{let K=new Map((m.find(ge=>ge.objectApiName===tr)?.idMappings??[]).map(ge=>[ge.sourceId,ge.targetId])),ce=new Map;for(let[ge,Ye]of _n){let ne=K.get(ge);ne&&ce.set(Ye,ne)}let Oe=_.map(ge=>String(ge.Id)).filter(ge=>ce.has(ge));if(Oe.length===0)return new Map;let ye;try{ye=await hh(Qt,[...new Set(Oe.map(ge=>ce.get(ge)??""))])}catch(ge){return this.deps.log(`[seed:clone] tasks written with the clone's emails not looked up, written as read: ${O(ge)}`),new Map}let Se=new Map;for(let ge of Oe){let Ye=ye.get(ce.get(ge)??"");Ye&&Se.set(ge,Ye)}return Se},Nt=async(_,K,ce)=>{if(wh[_]===void 0)return new Map;let Oe;try{Oe=await bh(Qt,_,ce)}catch(Se){return this.deps.log(`[seed:clone] ${_}: the relations the target holds not looked up, written as read: ${O(Se)}`),new Map}let ye=new Map;for(let[Se,ge]of Oe){let Ye=K[Se]?.Id;typeof Ye=="string"&&ye.set(Ye,ge)}return ye},Un=async(_,K)=>{if(ae.size===0)return new Map;let ce=X.get(hr),Oe=[...new Set(K.flatMap(ne=>Object.keys(ne)))].filter(ne=>cO(ce,ne)),ye;try{ye=await yh(Qt,K.map((ne,Ce)=>({OpportunityId:ne.OpportunityId,[Is]:ne[Is],IsPrimary:_[Ce]?.IsPrimary})),ne=>ae.get(ne),Oe)}catch(ne){return this.deps.log(`[seed:clone] ${hr}: 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: ${O(ne)}`),new Map}let{found:Se,alike:ge}=ye;if(ge.length>0){this.deps.log(`[seed:clone] ${hr}: ${mh(ge.length)}`);for(let ne of ge)ae.delete(String(K[ne]?.OpportunityId))}let Ye=new Map;for(let[ne,Ce]of Se){let Be=_[ne]?.Id;typeof Be=="string"&&(Ye.set(Be,String(Ce.Id)),Re.set(Be,Ce),ae.delete(String(K[ne]?.OpportunityId)))}return Ye},gs=async(_,K)=>{let ce=X.get(hr),Oe=[];if(_.forEach(([ge,Ye],ne)=>{let Ce=Re.get(String(ge.Id))??{},Be=Object.entries(K[ne]??{}).filter(([kt,at])=>cO(ce,kt)&&at!==null&&at!==void 0&&String(Ce[kt]??"")!==String(at));Be.length>0&&Oe.push({Id:Ye,...Object.fromEntries(Be)})}),Oe.length===0||Ve||a.signal.aborted)return;let ye;try{ye=await se.update(hr,Oe,Ne)}catch(ge){if(!(ge instanceof zo))throw ge;Ve=!0,ye=ge.written}let Se=Oe.flatMap((ge,Ye)=>ye[Ye]?.success?[]:[`${ge.Id}: ${ye[Ye]?.errors[0]??"not updated"}`]);Se.length>0&&this.deps.log(`[seed:clone] ${hr}: linked, and left as the platform wrote them, without the fields of the source's roles: ${Se.slice(0,3).join(" | ")}`)},Hn=async()=>{ps=!1;let _=Ht.splice(0,Ht.length),K=m.find(ge=>ge.objectApiName===tr);if(_.length===0||!K||Ve)return;if(a.signal.aborted){Ve=!0;return}let ce=_.map(ge=>lO(tr,ge,X.get(tr),N,We)),Oe=dO(tr,_,ce,Pe,We),{outcomes:ye,stopped:Se}=await fs(tr,ce);fr(ye,_,K,Oe),W.records+=_.length,Se&&(Ve=!0)};for(let _=0;_<le.length;_++){if(a.signal.aborted){Ve=!0;break}let K=le[_],ce=je.get(K);Le(this.deps,n,Math.round(_/le.length*100),_,le.length,`Cloning ${K}`),W.objects=_,this.liveTracker?.updateProgress(n,Math.round(_/le.length*100),W.records,0,`Cloning ${K}`);let Oe;try{Oe=await te.fetchRecords(C,K,ce.whereClause)}catch(xe){st++,m.push({objectApiName:K,sourceCount:0,insertedCount:0,failedCount:0,idMappings:[],errors:[{sourceId:"",message:O(xe)}]});continue}let ye=He.keep(K,Oe,iO(K,X.get(K),F.get(K)).map(({name:xe})=>xe)),Se=Oe.length-ye.length;if(K===tr)for(let xe of ye){let Qe=xe.ActivityId;typeof xe.Id=="string"&&typeof Qe=="string"&&Qe!==""&&_n.set(xe.Id,Qe)}let ge=ye.map(xe=>lO(K,xe,X.get(K),N,We)),Ye=W$(ye,X.get(K));Ye.length>0&&this.deps.log(`[INFO] seed:clone ${K}: ${Ye.length} field(s) the target does not have left out \u2014 ${Ye.join(", ")}`);let ne=dO(K,ye,ge,Pe,We),Ce=Lh(K,ge,Fe.get(K)?.recordTypes??[]);if(Ce.length>0){st++,m.push({objectApiName:K,sourceCount:Oe.length,insertedCount:0,failedCount:ye.length,...Se>0?{leftToThePlatform:Se}:{},idMappings:[],errors:Ce.map(xe=>{let Qe=ye.find((rt,qn)=>Fh(ge[qn],[xe]));return{sourceId:typeof Qe?.Id=="string"?Qe.Id:xe.recordTypeId,message:_h(xe)}})});continue}if(K===tr&&ps){let xe=ye.map(Qe=>gh(Qe));Ht.push(...ye.filter((Qe,rt)=>xe[rt])),ye=ye.filter((Qe,rt)=>!xe[rt]),ge=ge.filter((Qe,rt)=>!xe[rt]),ne=ne.filter((Qe,rt)=>!xe[rt])}let Be=K===Yi?await Ci(ye):K===hr?await Un(ye,ge):await Nt(K,ye,ge),kt=[],at=[];if(Be.size>0){let xe=ye.map(Qe=>!Be.has(String(Qe.Id)));ye.forEach((Qe,rt)=>{xe[rt]||(kt.push([Qe,Be.get(String(Qe.Id))??""]),at.push(ge[rt]))}),ye=ye.filter((Qe,rt)=>xe[rt]),ge=ge.filter((Qe,rt)=>xe[rt]),ne=ne.filter((Qe,rt)=>xe[rt])}if(a.signal.aborted){Ve=!0;break}let{outcomes:mt,stopped:Fr}=await fs(K,ge);if(Fr&&(Ve=!0,mt.length===0))break;if(K===G$&&mt.forEach((xe,Qe)=>{let rt=ge[Qe]?.[Is];xe.success&&xe.id&&xe.created!==!1&&typeof rt=="string"&&rt!==""&&ae.set(xe.id,rt)}),K===hr&&kt.length>0&&await gs(kt,at),kt.length>0){let xe=X.get(K),Qe=await Rh(K,kt,rt=>xe?.fields.find(qn=>qn.name===rt)?.updateable!==!1,async rt=>{try{return await se.update(K,rt,Ne)}catch(qn){if(!(qn instanceof zo))throw qn;return Ve=!0,qn.written}},()=>Ve||a.signal.aborted);Qe&&this.deps.log(`[seed:clone] ${K}: ${Qe}`)}let mo={objectApiName:K,sourceCount:Oe.length,insertedCount:0,failedCount:0,linkedCount:Be.size,...K===hr&&Be.size>0?{writtenByThePlatform:Be.size}:{},...Se>0?{leftToThePlatform:Se}:{},...Ye.length>0?{fieldsNotInTarget:Ye}:{},idMappings:[],errors:[]};for(let[xe,Qe]of Be)We.set(xe,Qe),mo.idMappings.push({sourceId:xe,targetId:Qe});if(fr(mt,ye,mo,ne),m.push(mo),W.records+=ye.length,Ve)break;K===Yi&&await Hn()}await Hn();let Mr;if(Ue.length>0&&(a.signal.aborted&&(Ve=!0),Mr=Ve?q$(Ue):await B$({owed:Ue,idMap:We,targetConn:v,targetOrgId:t.targetOrgId,stopped:()=>a.signal.aborted,report:_=>{Le(this.deps,n,100,W.records,W.records,_),this.liveTracker?.updateProgress(n,100,W.records,0,_)}}),a.signal.aborted&&(Ve=!0),f&&Mr.filled>0)){let _=new Map;for(let{objectApiName:K,newId:ce}of Ue)_.set(K,[..._.get(K)??[],ce]);for(let[K,ce]of _)f.wroteAgain(K,ce)}for(let _ of m){let K=fo.get(_.objectApiName);K&&(_.lookupsNotCarried=[...K].map(([Oe,ye])=>({field:Oe,records:ye})));let ce=Nr.get(_.objectApiName);ce&&(_.encryptedLeftOut=[...ce].sort())}let Dl=m.reduce((_,K)=>_+K.sourceCount,0),Bn=m.reduce((_,K)=>_+K.insertedCount,0),Me=m.reduce((_,K)=>_+(K.linkedCount??0),0),Xe=m.reduce((_,K)=>_+(K.leftToThePlatform??0),0),Ke=m.reduce((_,K)=>_+K.failedCount,0),it=Ke===0&&st===0?"success":Bn+Me>0?"partial":"failure",Et=Mr!==void 0&&Mr.filled<Mr.owed,tt=k(),gt=(Ve||Et)&&it==="success"?"partial":it,Lr=await this.endKept(f,n,{status:gt,cancelled:Ve});f=void 0;let Zt=await Dn(this.beforeRunCheckpoints,g,h,this.deps.log,`seed:clone:execute ${n}`);g=void 0;let yt={status:gt,objectResults:m,totalSourceRecords:Dl,totalInserted:Bn,totalLinked:Me,...Xe>0?{totalLeftToThePlatform:Xe}:{},totalFailed:Ke,...Mr?{secondPass:Mr}:{},durationMs:Date.now()-o,...Ve?{cancelled:!0}:{},contactPoints:tt,...Lr&&p>0?{runId:n}:{}};u=!1;let Jt=Ve?Bn+Ke>0?"cancelled":"stopped":yt.status;Z(this.deps,{...sO(l,Jt,m,y,tt),...Jt==="stopped"?{code:nt}:{},...Zt?.state==="taken"?{checkpointId:Zt.checkpointId}:{}});let Vt=!Ve&&yt.status==="failure"?"No record could be cloned.":void 0;Ve?(this.registry?.abort(n),pe(this.deps,n,{aborted:!0,totalInserted:Bn,totalFailed:Ke}),this.liveTracker?.cancel(n)):(pe(this.deps,n,{status:yt.status,totalInserted:Bn,totalFailed:Ke}),Vt!==void 0?this.liveTracker?.fail(n,Vt):yt.status==="partial"?this.liveTracker?.partial(n):this.liveTracker?.complete(n));let ho={...yt,...Zt?{checkpoint:Zt}:{}},Pt=A(this.deps,e,"seed:clone:execute:response",ho);this.deps.broker.postToWebview(Pt),this.deps.log(`[TX] ${Pt.type} id=${Pt.id} status=${yt.status}`),d(Vt===void 0?void 0:new Error(Vt))}catch(w){let I=await Dn(this.beforeRunCheckpoints,g,h,this.deps.log,`seed:clone:execute ${n}`);u&&Z(this.deps,{...sO(l,"failure",m,y,k()),...I?.state==="taken"?{checkpointId:I.checkpointId}:{}}),await this.endKept(f,n,{status:"failure",cancelled:!1});let P=I?.state==="deleted"?`${O(w)} ${Yr}`:O(w);this.deps.log(`[ERR] seed:clone:execute: ${P}`),De(this.deps,n,O(w),!0,{context:i,extraPayload:{code:P.startsWith(nO)?dn.guardBlocked:dn.failed,...I?{checkpoint:I}:{}}}),this.liveTracker?.fail(n,P),d(w)}}};function M$(s){let e=[`narrow the filters of ${s.objects.join(", ")} or leave them out`,`turn off ${s.senders.map(t=>`"${t}"`).join(", ")}`,...s.bypasses.map(t=>"give the user the clone writes as "+(t.permissionSet?`the permission set ${t.permissionSet}, whose ${t.permission}`:`a permission set holding ${t.permission}, which`)+" keeps them quiet")];return`The clone was refused before it wrote anything: its records would make ${s.org} send about ${Zb(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, ${e.join("; or ")}. Nothing was written.`}function sO(s,e,t,r,n){return{...s,details:{...s.details,...Ts(n).details},outcome:e,objects:t.map(o=>({...ht(o.objectApiName),...r?{upserted:o.insertedCount}:{created:o.insertedCount},failed:o.failedCount})),carried:Object.fromEntries(t.map(o=>[o.objectApiName,o.idMappings.length]))}}function iO(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)&&ys(s,n.name,n.nillable)).map(n=>({name:n.name,referenceTo:n.referenceTo??[]}))}async function qd(s,e,t){try{return await t()}catch(r){let n=O(r);throw s==="target"&&F$(r,n)?new zd(e,n):new Error(`${e} could not be described in the ${s} org: ${n}`)}}var L$="OBJECT_NOT_IN_TARGET",zd=class extends Error{constructor(t,r){super(`${t} is not in the target org, or the user SandForge connects as there may not see it (${r}): untick it to clone the others, or deploy it to the target first (Compare, Deploy from Diff) and give that user access to it.`);this.objectApiName=t;this.name="ObjectNotInTargetError"}objectApiName};function F$(s,e){return s?.errorCode==="NOT_FOUND"||/\bNOT_FOUND\b|requested resource does not exist|INVALID_TYPE/.test(e)}function aO(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 _$(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 U$(s,e,t){let r=new Set(s);return s.flatMap(n=>{let o=Gd(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 H$(s,e,t){return s.flatMap(r=>{let n=Gd(t.get(r));return n?(e.get(r)?.fields??[]).filter(o=>o.type==="reference"&&!n.has(o.name)&&o.createable!==!1&&o.defaultedOnCreate!==!0&&ys(r,o.name,o.nillable)).flatMap(o=>(o.referenceTo??[]).map(i=>({objectApiName:r,field:o.name,referenceTo:i}))):[]})}function dO(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,l)=>{let u=[];for(let f of a){let p=e[l]?.[f];typeof p!="string"||p===""||n.has(p)||f in c&&(!i.has(f)&&!d.has(p)||(delete c[f],u.push({fieldName:f,sourceRefId:p})))}return u})}async function B$(s){let{owed:e,targetConn:t}=s,{patchCycleFkUpdates:r}=await import("./chunk-CN5HGFG4.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:Li()});return(Array.isArray(d)?d:[d]).map((c,l)=>{let u=a[l]?.Id;return{id:c.id??(typeof u=="string"?u:""),success:c.success,errors:(c.success?[]:c.errors).map(hw)}})},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 q$(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 Gd(s){let e=new Set((s?.fields??[]).map(t=>t.name));return e.size>0?e:null}function W$(s,e){let t=Gd(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 z$(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 G$="Opportunity";function cO(s,e){if(e==="OpportunityId"||e===Is)return!1;let t=s?.fields.find(r=>r.name===e);return t!==void 0&&t.updateable!==!1}function lO(s,e,t,r,n){let o=new Set((t?.fields??[]).filter(d=>d.createable===!1).map(d=>d.name)),i=Gd(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(l=>r.has(l)))continue;let c=a[d.name];typeof c=="string"&&n.has(c)&&(a[d.name]=n.get(c))}for(let d of Qi(s,a))delete a[d];return a}var J$=new Set(["double","currency","percent","int","integer"]),Jd=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 l=i.get(c.sfFieldApiName);if(!l)continue;let u=d[c.csvHeader]??"";if(u===""&&!l.nillable&&l.defaultValue===null){o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"missing_required",message:`Required field "${c.sfFieldApiName}" is empty`,value:u});continue}if(u!==""){if(J$.has(l.type.toLowerCase())){let f=parseFloat(u);isNaN(f)&&o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"type_mismatch",message:`Expected numeric value for field "${c.sfFieldApiName}", got "${u}"`,value:u})}l.length&&l.length>0&&u.length>l.length&&o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"length_exceeded",message:`Value exceeds max length ${l.length} for field "${c.sfFieldApiName}" (got ${u.length})`,value:u}),l.type.toLowerCase()==="picklist"&&l.picklistValues&&l.picklistValues.length>0&&(l.picklistValues.map(p=>p.value).includes(u)||o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"invalid_picklist",message:`Invalid picklist value "${u}" for field "${c.sfFieldApiName}"`,value:u}))}}}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 l=e[c][a.csvHeader]??"";if(l==="")continue;let u=d.get(l);u!==void 0?o.push({row:c+1,column:a.csvHeader,field:n,errorType:"duplicate_external_id",message:`Duplicate external ID "${l}" (also in row ${u})`,value:l}):d.set(l,c+1)}}}return{valid:o.length===0,errors:o,warningCount:0}}};var V$=new Set(["seed:csv:validate","seed:csv:execute"]),X$=100,uO="IMPORT_CANCELLED",K$=6e4,zp="CSV_STORAGE_EXCEEDED";function Y$(s){let e=s<10?100:10;return String(s<=0?0:Math.ceil(s*e-1e-9)/e)}function Q$(s,e,t){let r=e>0?eo(s,{rows:e})/e:0;return r>0?Math.max(0,Math.floor(t*1024*1024/r)):0}var Vd=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-QO4MPHZD.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async handle(e){if(!V$.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: ${O(n)}`),!1}finally{this.runningRuns.delete(t)}}stoppedForCheckpoint(e,t,r,n){let{operationId:o}=t;if(r.code===nt){Z(this.deps,{...t,outcome:"stopped",source:void 0,code:uO}),this.registry?.abort(o),pe(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}:{};Z(this.deps,{...t,outcome:"stopped",source:void 0,code:r.code,...i!==void 0?{details:a}:{}}),E(this.deps,"seed:csv:execute","seed:csv:error",e,r,{code:r.code,retryable:!1,...i!==void 0?{extraPayload:a}:{}}),De(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=$(uu,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 Jd().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){E(this.deps,"seed:csv:validate","seed:csv:error",e,r)}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(uu,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,l,u=0,f,p=!1;try{let g=this.deps.infraServices?.productionGuard;if(!g){Z(this.deps,{...d,outcome:"stopped",source:void 0,code:be.code}),E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(be.message),{code:be.code,retryable:!1}),De(this.deps,r,be.message,!1,{context:n,extraPayload:{code:be.code}}),i(new Error(be.message));return}let h=this.deps.orgManager.getOrg(t.orgId),m={orgId:t.orgId,orgTier:Ee(h),operation:t.externalIdField?"upsert":"insert",objectName:t.objectApiName,recordCount:t.records.length,module:"seed"},{check:y,decision:R}=await Ze(g,m);if(d.guard=R,(R==="refused"||R==="declined")&&Z(this.deps,{...d,outcome:"stopped",source:void 0}),R==="refused")throw mn(y.blockedReason??y.impactSummary);if(R==="declined"){let te="Operation cancelled by user (confirmation declined).";E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(te),{code:$t.declined}),De(this.deps,r,te,!1,{context:n}),i(new Error(te));return}let k=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager),w=he(h,t.orgId),I=(te,ue,x)=>{let N=x!==void 0?{checkpointRefusal:x}:{};Z(this.deps,{...d,outcome:"stopped",source:void 0,code:te,...x!==void 0?{details:N}:{}}),E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(ue),{code:te,retryable:!1,...x!==void 0?{extraPayload:N}:{}}),De(this.deps,r,ue,!1,{context:n,authored:!0,extraPayload:{code:te,...N}}),i(new Error(ue))},P=this.targetAutomation,b=li([t.objectApiName],!!t.externalIdField),S=await new fe(K$).withTimeout("csv automation",()=>P.read(t.orgId,[t.objectApiName])).catch(te=>({unread:O(te)}));typeof S.unread=="string"&&this.deps.log(`[WARN] seed:csv:execute ${r}: what the org runs on ${t.objectApiName} could not be read (${S.unread}): it is asked about its emails, and a checkpoint holds the object alone`);let C=await ar({read:S,writes:b,readDeliverability:()=>Ee(h)==="production"?Promise.resolve(qt):Wt(k),accepted:!1,target:w,run:"seed",keepsAddresses:!0}),v=C.gate.verdict==="asks",T;if(t.checkpointFirst!==void 0){try{T=await di(this.beforeRunCheckpoints,{module:"seed",orgId:t.orgId,operationId:r,written:[t.objectApiName],running:Hd(S,b),request:t.checkpointFirst})}catch(ue){if(!(ue instanceof zt))throw ue;I(ue.code,ue.message);return}let te=Na(T.planned);if(te){I(te.code,te.message,te.refusal.code);return}}let D=await Rr(k).catch(te=>({unread:O(te)})),z="unread"in D?await dr(k).catch(te=>({unread:O(te)})):D.dailyApiRequests,H=vr({storageBytes:eo(t.objectApiName,{rows:t.records.length})},D);if(!t.externalIdField&&H.verdict==="exceeds"){let te=t.records.length,ue=Q$(t.objectApiName,te,H.remainingMB),x=`The import was refused before it wrote anything: its ${te} rows take about ${Y$(H.estimateMB)} MB of data storage, and ${w} has ${H.remainingMB} MB left of ${H.maxMB} MB, room for about ${ue} of them: split the file and import one part at a time, freeing data storage in between as needed. Nothing was written.`;Z(this.deps,{...d,outcome:"stopped",source:void 0,code:zp});let N={org:w,rows:te,fitting:ue,estimateMB:H.estimateMB,remainingMB:H.remainingMB,maxMB:H.maxMB};E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(x),{code:zp,retryable:!1,extraPayload:N}),De(this.deps,r,x,!1,{context:n,authored:!0,extraPayload:{code:zp,...N}}),i(new Error(x));return}let Y=In({run:Av([{objectApiName:t.objectApiName,rows:t.records.length}],{threshold:lt(this.deps).bulk.threshold,perCall:this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200),duplicateRules:Fo(S)})+Tv(0,Tn(S)),...Mo(T?.planned),...En(C.ofRun)},z);Y.verdict==="unread"&&this.deps.log(`[WARN] seed:csv:execute ${r}: the daily API requests the org has left could not be read (${Y.unread})`);let U=Da(Y,he(h,t.orgId));if(U){Z(this.deps,{...d,outcome:"stopped",source:void 0,code:No}),E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(U),{code:No,retryable:!1}),De(this.deps,r,U,!1,{context:n,authored:!0,extraPayload:{code:No}}),i(new Error(U));return}let M=!1;if(T||v){let te=t.records.length,ue=await g.confirmRun({stage:"write",module:"seed",org:w,orgTier:Ee(h),objects:[{objectApiName:t.objectApiName,rows:te}],total:te,storage:Pn(vr({storageBytes:eo(t.objectApiName,{rows:te})},D)),...jo(Y),...T?{checkpoint:T.planned}:{},...C.gate.confirmation});if(ue!=="confirmed"){let x=C.gate.stop;ue!=="declined"&&!T&&x?I(x.code,x.message):I(ue==="declined"?Zo:St.unanswered,ue==="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 ${w} \u2014 and there was no one to ask. Nothing was written.`);return}M=v}if(d.details=an({read:C,accepted:M}).details,ze(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),T)try{f=await ci(this.beforeRunCheckpoints,T,r,o.signal,(te,ue,x,N)=>{Le(this.deps,r,te,ue,x,N),this.liveTracker?.updateProgress(r,te,ue,x,N)})}catch(te){if(!(te instanceof zt))throw te;this.stoppedForCheckpoint(e,d,te,n),i(te.code===nt?void 0:te);return}c=!0;let L=lt(this.deps),ee=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200;n.batchSize=ee,l=this.runCreations?.recorder({runId:r,targetOrgId:t.orgId,startedAt:new Date().toISOString(),origin:"csv"}),f&&l?.checkpoint?.(f),kr(l,()=>k.identity(),`seed:csv:execute ${r}`),l&&this.runningRuns.add(r);let Q=new Cn({connection:k,bulkExecutor:new Rn(L.bulk.threshold),bulkManager:mr(this.deps),retryConfig:L.retry,signal:o.signal,onProgress:(te,ue,x)=>{let N=ue>0?Math.round(te/ue*100):0;Le(this.deps,r,N,te,ue,x),this.liveTracker?.updateProgress(r,N,te,ue,x)},log:te=>this.deps.log(te),...l?{calls:Bd(l,te=>{u+=te})}:{}}),q=t.records.map(te=>Z$(te,t.columnMappings)),V=o.signal.aborted,we=[];if(!V){q.length>0&&(p=!0);try{we=t.externalIdField?await Q.upsert(t.objectApiName,t.externalIdField,q,ee):await Q.insert(t.objectApiName,q,ee)}catch(te){if(!(te instanceof zo))throw te;V=!0,we=te.written}}let ie=[],re=0;for(let te of we)te.success?re++:ie.length<X$&&ie.push(te.errors[0]??"Unknown insert error");let Ae=we.length-re,me=Ae===0?"success":re>0?"partial":"failure",Je=!V&&me==="failure"?ie[0]??"No row could be imported.":void 0;c=!1;let Ne=await Dn(this.beforeRunCheckpoints,f,p,this.deps.log,`seed:csv:execute ${r}`);f=void 0,V&&we.length===0?Z(this.deps,{...d,outcome:"stopped",source:void 0,code:uO}):Z(this.deps,{...d,outcome:V?"cancelled":me,objects:[{...ht(t.objectApiName),...t.externalIdField?{upserted:re}:{created:re},failed:Ae}],...Ne?.state==="taken"?{checkpointId:Ne.checkpointId}:{}});let Fe=await this.endKept(l,r,{status:V&&me==="success"?"partial":me,cancelled:V});l=void 0;let W={insertedCount:re,failedCount:Ae,errors:ie,...V?{cancelled:!0}:{},...Fe&&u>0?{runId:r}:{},...Ne?{checkpoint:Ne}:{}};V?(this.registry?.abort(r),pe(this.deps,r,{aborted:!0,insertedCount:re,failedCount:Ae}),this.liveTracker?.cancel(r)):(pe(this.deps,r,{status:me,insertedCount:re,failedCount:Ae}),Je!==void 0?this.liveTracker?.fail(r,Je):me==="partial"?this.liveTracker?.partial(r):this.liveTracker?.complete(r));let se=A(this.deps,e,"seed:csv:execute:response",W);this.deps.broker.postToWebview(se),this.deps.log(`[TX] ${se.type} id=${se.id} inserted=${re} failed=${Ae}`),i(Je===void 0?void 0:new Error(Je))}catch(g){let h=await Dn(this.beforeRunCheckpoints,f,p,this.deps.log,`seed:csv:execute ${r}`);c&&Z(this.deps,{...d,...h?.state==="taken"?{checkpointId:h.checkpointId}:{}}),await this.endKept(l,r,{status:"failure",cancelled:!1});let m=h?.state==="deleted"?`${O(g)} ${Yr}`:O(g);E(this.deps,"seed:csv:execute","seed:csv:error",e,g,{code:Ao(g),retryable:!0,...h?{extraPayload:{checkpoint:h}}:{}}),De(this.deps,r,m,!0,{context:n}),this.liveTracker?.fail(r,m),i(g)}}};function Z$(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]=ex(n))}return t}function ex(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 tx={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"])},rx=[{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 Gp(s,e){let t=s.toLowerCase(),r=e.toLowerCase();if(t===r)return!0;let n=tx[t];return n?n.has(r):r==="string"}var Xd=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 l=i.get(d),u=a.get(c);if(!l||!u)continue;let f=this.checkTypeCompatibility(d,l.type,c,u.type);f.compatible?f.reason&&o.push(f):n.push(f)}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&&pO(a)){r.push({recordIndex:n,field:i.apiName,message:`Required field '${i.apiName}' is missing or empty`});continue}if(pO(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=Gp(o,i),d=rx.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"||!nx(e))return`Expected valid ${r} string`;break}}};function pO(s){return s==null||s===""}function nx(s){let e=Date.parse(s);return!isNaN(e)}var Kd=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 Jp=3e4,fO=6e4,Vp="Nothing was read or written.",gO="Nothing was read.",hO="the checkpoints of this window are not open to the Sync page",sx=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"]),mO={insert:0,update:1,upsert:2,delete:3};function Kp(s,e){let t=s.objects??[],r="insert";for(let o of t)mO[o.operation]>mO[r]&&(r=o.operation);s.mode==="delta"&&s.propagateDeletes===!0&&(r="delete");let n=t.map(o=>o.objectApiName);return{orgId:s.targetOrgId,orgTier:Ee(e),operation:r,objectName:n.length>0?n.join(", "):"SyncData",recordCount:"unknown",module:"sync"}}function ix(s){return s.map(e=>{let t={...ht(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 ax=new Set(["direct","rename"]),Xp=20,dx=G({fields:ve(G({name:j(),type:j(),createable:Ge(),updateable:Ge()}).loose())});function yO(s,e,t){let r=dx.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 wO(s){if(s==="ask")return{emailsLiftedBy:"Untick Mute automation to be asked about them and sync all the same"};let e=Vw();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 Yd=class{constructor(e){this.deps=e;this.syncConfigStore=new It(e.configStore)}deps;activeOperationIds=new Set;dmlTracker=new ra;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-QO4MPHZD.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",Qr);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):Qr}readCap(){return Za(this.deps.services?.getSandforgeSetting?.("sync.maxRecordsPerObject",void 0))}writeGateFor(e,t,r,n,o,i){let a=this.deps.orgManager.getOrg(e.targetOrgId),d=this.targetAutomation,c=this.deps.infraServices?.productionGuard,l=wO(r),u=this.readCap(),f=xv(e,async p=>{let{totalSize:g}=await t.query(p);return Math.min(g,u)});return Dv({readStorage:()=>new fe(Jp).withTimeout("sync:limits",()=>Rr(t)),readApiBudget:()=>new fe(Jp).withTimeout("sync:limits",()=>dr(t)),readAutomation:n??(p=>new fe(fO).withTimeout("sync:automation",()=>d.read(e.targetOrgId,p))),readLimits:()=>new fe(Jp).withTimeout("sync:limits",()=>Sr(t)),readDeliverability:()=>Ee(a)==="production"?Promise.resolve(qt):Wt(t),emails:{target:he(a,e.targetOrgId),accepted:l.emailsAccepted===!0,keepsAddresses:e.keepContactPoints===!0},confirmAboveRecords:this.confirmAboveRecords(),bulkThreshold:lt(this.deps).bulk.threshold,...o?{checkpointFirst:o}:{},...i?{mutePlan:i}:{},...f?{countTarget:f}:{}},{policy:r,org:he(a,e.targetOrgId),orgTier:Ee(a),...c?{confirm:p=>c.confirmRun(p)}:{},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,l;return{gate:{scope:async(u,f)=>{if(!o)throw new Error(hO);return a={module:"sync",orgId:e.targetOrgId,operationId:t,written:[...u],running:f,request:r},d=await o.scope(a,i),l=d.refusal,d},take:async u=>{if(!o||!a)throw new Error(hO);let f=await o.take(a,i,{planned:u,...n?{signal:n.signal,onProgress:p=>{let g=Do(p.percentage),h=Math.round(p.percentage),{processedObjects:m,totalObjects:y}=p;Le(this.deps,t,h,m,y,g),this.liveTracker?.updateProgress(t,h,m,y,g)}}:{}});return f.taken?(c=f.checkpoint,n?.recorder?.checkpoint?.(f.checkpoint)):"refusal"in f&&(l=f.refusal),f}},planned:()=>d,taken:()=>c,refusal:()=>l}}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: ${O(o)}`),n}}isRunning(e){return this.activeOperationIds.has(e)}async handle(e){if(!sx.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=Ro(t.objects);return i.length===0?!1:(E(this.deps,r,n,e,new Error(`${vo(i)} ${o}`),{code:Ui,extraPayload:{rules:i}}),!0)}async handleConfigSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Qh,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(Yg(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){E(this.deps,"sync:config:save","sync:error",e,r)}}async handleConfigLoad(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(oa,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){E(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){E(this.deps,"sync:config:list","sync:error",e,t)}}async handleConfigDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(oa,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}: ${O(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){E(this.deps,"sync:config:delete","sync:error",e,r)}}async handleConfigResetDelta(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(oa,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){E(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 jw(e.idMap(),t=>this.syncConfigStore.isSaved(t))}recordRun(e,t,r,n,o,i){let a=ix(r.objectResults??[]),d=a.some(l=>l.created+l.updated+l.deleted+l.failed+(l.upserted??0)>0),c=r.cancelled===!0?d?"cancelled":"stopped":r.status;Z(this.deps,{action:"sync_execute",module:"sync",operationId:t,orgId:e.targetOrgId,outcome:c,...c==="stopped"?{code:nt}:{},guard:n,objects:a,source:{origin:"org",orgId:e.sourceOrgId},details:{triggeredBy:o,...Yn(i)},...r.mutedAutomation?{muted:ct(r.mutedAutomation)}:{},...r.checkpoint?.state==="taken"?{checkpointId:r.checkpoint.checkpointId}:{}})}recordRefused(e,t,r){Z(this.deps,{action:"sync_execute",module:"sync",operationId:e,orgId:t,outcome:"stopped",code:r})}recordStopped(e,t,r){Z(this.deps,{action:"sync_execute",module:"sync",operationId:e,orgId:t,outcome:"stopped",guard:r})}buildGuardRequest(e){return Kp(e,this.deps.orgManager.getOrg(e.targetOrgId))}async assertFieldTypesMatch(e,t,r,n){let o=new Xd,i=[],a=l=>({apiName:l.name,type:l.type});for(let l of e.objects){if(l.operation==="delete")continue;let u=l.objectApiName,f=new fe(n),[p,g]=await Promise.all([f.withTimeout(`describe-source-${u}`,()=>Yt(e.sourceOrgId,u,()=>t.describe(u))),f.withTimeout(`describe-target-${u}`,()=>Yt(e.targetOrgId,u,()=>r.describe(u)))]),h=yO(p,u,"source").map(a),m=yO(g,u,"target").filter(w=>w.createable||w.updateable).map(a),y=pv(l,{creatable:new Set(m.map(w=>w.apiName))}),R=qh(y.fieldMappings,y.excludedFields),k=[Object.fromEntries(h.filter(w=>!R.has(w.apiName.toLowerCase())).map(w=>[w.apiName,w.apiName])),...l.fieldMappings.filter(w=>ax.has(w.type)).map(w=>({[w.sourceField]:w.targetField}))];for(let w of k)for(let I of o.validateMapping(h,m,w).errors)i.push(`${u}.${I.sourceField} (${I.sourceType}) -> ${u}.${I.targetField} (${I.targetType})`)}if(i.length===0)return;let d=i.slice(0,Xp).join("; "),c=i.length>Xp?` and ${i.length-Xp} 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=$(Zh,e,"sync:error",this.deps);if(!t)return;let r=lt(this.deps);try{let n=await B(t.orgId,this.deps.orgRegistry,this.deps.orgManager),o=new fe(r.timeouts.describeGlobal),i=await o.withTimeout("describe-global",()=>n.describeGlobal());$e(n.limitInfo,"sync:describe-global");let a=i.sobjects.filter(u=>u.queryable&&!na(u.name)),d,c=[];if(t.targetOrgId===void 0)d=a.filter(u=>u.createable).map(u=>u.name);else{let u=await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),f=await o.withTimeout("describe-global",()=>u.describeGlobal());$e(u.limitInfo,"sync:describe-global target");let p=new Map(f.sobjects.map(g=>[g.name,{createable:g.createable,updateable:g.updateable}]));d=[];for(let g of a){let h=p.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 l=A(this.deps,e,"sync:describe-global:response",{objects:d,...c.length>0?{unwritable:c}:{}});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`)}catch(n){E(this.deps,"sync:describe-global","sync:error",e,n)}}async handleDescribeFields(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(em,e,"sync:error",this.deps);if(!t)return;let r=t,n=lt(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 fe(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 l=f=>f.filter(p=>p.createable).map(p=>({apiName:p.name,label:p.label,type:p.type})),u=A(this.deps,e,"sync:describe-fields:response",{objectApiName:r.objectApiName,sourceFields:l(d.fields),targetFields:l(c.fields)});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`)}catch(o){E(this.deps,"sync:describe-fields","sync:error",e,o)}}async handleWriteOrder(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(au,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=lt(this.deps).timeouts.describe,i=new Map;for(let l of r.objects){if(l.operation==="delete")continue;let u=l.objectApiName;try{let f=await new fe(o).withTimeout(`describe-target-${u}`,()=>Yt(r.targetOrgId,u,()=>n.describe(u)));i.set(u,wv(l,Or(f)))}catch{}}let{order:a}=bv(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){E(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=Xn(yr(async a=>(await n.query(a)).records),a=>new fe(t).withTimeout(`describe-source-${a}`,()=>Yt(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=$(wn,e,"sync:error",this.deps);t&&(this.refusedFieldless(e,t.config,"sync:execute","sync:error",Vp)||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=$(au,e,"sync:error",this.deps);if(!t||this.refusedFieldless(e,t.config,"sync:simulate","sync:error",gO))return;let r=e.id,n=t.config,o=`Simulation of a sync of ${n.objects.length} object(s), writing nothing`,i=new AbortController;ze(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=lt(this.deps),d={module:"sync",operation:e.type,...Gr(t.objects)};try{let c=await this.readersFor(t,n.signal),{DataSync:l}=await import("./chunk-AG24QMSY.mjs"),{ConflictResolver:u}=await import("./chunk-CHCHAE4B.mjs"),{FieldMappingService:f}=await import("./chunk-L3I6DAHX.mjs"),{TransformPipeline:p}=await import("./chunk-UIR77ZJD.mjs"),{toolingQueriesOver:g,toolingValidationRules:h}=await import("./chunk-TQJ5NPRC.mjs"),{toolingRetrievesOver:m}=await import("./chunk-QO4MPHZD.mjs"),y=c.targetConn.tooling,R=async()=>{throw new Error("A simulation writes nothing: the write it reached was refused.")},k=new l({insert:R,update:R,upsert:R,delete:R,describeTargetFields:c.describeTargetFields});if(!this.deps.services)throw new Error("SyncOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let w=o?this.runCheckpointOf(t,r,o):void 0,I=this.deps.services.syncOrchestrator({dataSync:k,conflictResolver:new u,fieldMapping:new f,transformPipeline:new p,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.targetConn,"ask",void 0,w?.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 T=>(await rr({query:async D=>y.query(D),queryMore:async D=>y.queryMore(D)},T)).records,g(c.targetConn),m(c.targetConn)),onSimulationProgress:(T,D,z)=>{let H=Math.round(T/D*100),Y=`Simulating ${z}`;Le(this.deps,r,H,T,D,Y),this.liveTracker?.updateProgress(r,H,T,D,Y)}});await this.assertFieldTypesMatch(t,c.sourceConn,c.targetConn,a.timeouts.describe);let P=await I.simulate(t),b=w?.planned(),S=[...c.cutAtReadCap],C={...P,...b?{checkpoint:b}:{},readCap:c.readCap,...S.length>0?{cutAtReadCap:S}:{},operationId:r};C.cancelled?this.endCancelled(r):C.error?(this.liveTracker?.fail(r,C.error),De(this.deps,r,C.error,!0,{context:d})):(Le(this.deps,r,100,1,1,"Simulation complete"),pe(this.deps,r,{status:"success",simulated:!0}),this.liveTracker?.complete(r)),this.deps.log(`[sync] simulation ${r} ${C.cancelled?"stopped":"finished"}: `+C.objects.map(T=>`${T.objectApiName} insert=${T.insert} update=${T.update} delete=${T.delete} skipped=${T.skipped} refused=${T.refused} conflicts=${T.conflicts}`).join("; "));let v=A(this.deps,e,"sync:simulate:response",C);return this.deps.broker.postToWebview(v),this.deps.log(`[TX] ${v.type} id=${v.id}`),C}catch(c){return this.liveTracker?.fail(r,O(c)),E(this.deps,"sync:simulate","sync:error",e,c),De(this.deps,r,O(c),!0,{context:d}),i?.(c),null}}async simulateForPipeline(e,t){let r=wn.safeParse({config:e});if(!r.success)throw new Error(`Pipeline sync config failed validation: ${r.error.issues.map(p=>p.message).join("; ")}`);let n=Ro(r.data.config.objects);if(n.length>0)throw Object.assign(new Error(`${vo(n)} ${gO}`),{code:Ui});let o=yn("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(p=>({...p,batchSize:p.batchSize??a}))},c=`Pipeline simulation of a sync of ${d.objects.length} object(s), writing nothing`,l=new AbortController,u=()=>l.abort();t?.aborted&&l.abort(),t?.addEventListener("abort",u,{once:!0}),ze(this.deps,i,"sync",c),this.liveTracker?.register(i,"sync",c);let f;try{let p=this.simulateSync(o,d,i,l,void 0,h=>{f=h});this.registry?.register(i,"sync",c,p.then(h=>({status:h===null||h.error?"failure":"success"})),l);let g=await p;if(g===null)throw f instanceof Error?f:new Error(O(f));return g}finally{t?.removeEventListener("abort",u)}}async handleRunControl(e,t){this.deps.log(`[RX] ${e.type} id=${e.id}`);let r=$(Yh,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=lt(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 qa({retryConfig:r.retry}),c=(v,T)=>async(D,z,H)=>{let Y=bt(z.objectApiName),U="",M=Cs(z.where,H?.changedSince);M&&(U+=` WHERE ${M}`),z.orderBy&&(U+=` ORDER BY ${nu(z.orderBy)}`);let L=!1,ee=await d.execute(async()=>{L=!1;let q=(await v.describe(Y)).fields.map(ie=>ie.name),V=q.length>0?q:["Id"],we={query:async ie=>v.query(ie),queryMore:async ie=>v.queryMore(ie)};return Es(`SELECT ${V.join(", ")} FROM ${Y}${U}`,async ie=>{let re=await rr(we,ie,i);return L||=re.truncated,re.records})});if(!ee.success)throw ee.error??new Error("Query failed after retries");$e(v.limitInfo,`sync:execute query ${Y}`);let Q=ee.result??[];if(L){H?.onBoundReached?.();let q=Q.length>=i?`${i} records (sandforge.sync.maxRecordsPerObject)`:`${Math.max(500,Math.ceil(i/200))} pages`,V=T===e.sourceOrgId?"source":"target";V==="source"&&a.add(z.objectApiName);let we=V==="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 ${Y} (${V}): read stopped at ${Q.length} record(s) \u2014 bound: ${q}. ${we}.`),Ie(this.deps,"warning","Sync",`${Y}: only ${Q.length} record(s) were read from the ${V} (bound: ${q}) \u2014 ${we}. `+vv(V,i,Rv))}return Q},l=async(v,T,D)=>{let H=`SELECT COUNT() FROM ${bt(T.objectApiName)}`,Y=Cs(T.where,D?.changedSince);Y&&(H+=` WHERE ${Y}`);let{totalSize:U}=await n.query(H);return Math.min(U,i)},u=async(v,T)=>{let D=bt(v.objectApiName),z=Cs(v.where,T?.changedSince),H=`SELECT COUNT() FROM ${D} WHERE IsPersonAccount = true`+(z?` AND (${z})`:"");try{return(await n.query(H)).totalSize}catch{return 0}},f=new Map,p=async v=>{let T=f.get(v);if(T)return T;let D=await o.describe(v),z=Or(D);return f.set(v,z),z},g=async v=>Or(await o.describe(v)),h=async v=>(await rr({query:async T=>o.query(T),queryMore:async T=>o.queryMore(T)},v)).records,m=Uh({query:async v=>o.query(v),queryMore:async v=>o.queryMore(v)},t),y=async(v,T,D,z)=>{let H=await m(v,T,D,z);return $e(o.limitInfo,`sync:simulate lookup ${T.objectApiName}`),H},R=Wh({query:async(v,T)=>n.query(v,T),queryMore:async v=>n.queryMore(v)},{query:async v=>o.query(v),queryMore:async v=>o.queryMore(v)},t),k=v=>({pages:{query:async T=>v.query(T),queryMore:async T=>v.queryMore(T)},transport:v,create:async(T,D)=>v.sobject(T).create(D,{headers:Li()})}),w=async(v,T)=>{let z=`SELECT Id FROM ${bt(v.objectApiName)}`,H=Cs(v.where,T);H&&(z+=` WHERE ${H}`),v.orderBy&&(z+=` ORDER BY ${nu(v.orderBy)}`);let{records:Y}=await rr(k(n).pages,z,i);return Y.flatMap(U=>typeof U.Id=="string"?[U.Id]:[])},I={copy:iv({[e.sourceOrgId]:k(n),[e.targetOrgId]:k(o)}),sourceIds:w,store:this.fileStoreFor(),...e.files!==void 0&&sv(this.deps.infraServices?.productionGuard,e.targetOrgId,this.deps.orgManager.getOrg(e.targetOrgId))?{deleteFromTarget:async(v,T)=>mw(await o.sobject(v).destroy(T),v).map(D=>({id:D.id,success:D.success,errors:D.errors}))}:{}},P=async()=>{let{readSyncRecordTypes:v}=await import("./chunk-2KTGDYUH.mjs");return v(k(n).pages,k(o).pages)},b=async()=>{let{readRunCurrencies:v}=await import("./chunk-OETEC3P7.mjs");return v(async T=>(await n.query(T)).records,async T=>(await o.query(T)).records,{source:async T=>(await n.tooling.query(T)).records,target:async T=>(await o.tooling.query(T)).records})},S=async()=>{let{readStandardPricebooks:v}=await import("./chunk-ZB5E7NHU.mjs");return v(async T=>(await n.query(T)).records,async T=>(await o.query(T)).records)},C=Xn(yr(async v=>(await n.query(v)).records),v=>Yt(e.sourceOrgId,v,()=>n.describe(v)));return{sourceConn:n,targetConn:o,querySource:c(n,e.sourceOrgId),queryTarget:c(o,e.targetOrgId),maskedSourceFields:C,countSource:l,describeTargetFields:p,describeTargetFieldsAgain:g,queryTargetRows:h,recordTypes:P,currencies:b,standardPricebooks:S,findInTarget:y,readSourceIds:v=>w(v),countPersonAccounts:u,deltaReads:R,files:I,readCap:i,cutAtReadCap:a}}async rerunFromSnapshot(e,t){this.deps.log(`[RX] sync:history:rerun id=${e.id}`);let r=$(wn,{...e,payload:{config:t}},"sync:history:error",this.deps);r&&(this.refusedFieldless(e,r.config,"sync:history:rerun","sync:history:error",Vp)||await this.startExecution(e,r.config,"rerun"))}async executeScheduled(e,t="schedule"){let r=wn.safeParse({config:e});if(!r.success)throw new Error(`Scheduled sync config failed validation: ${r.error.issues.map(m=>m.message).join("; ")}`);let n=Ro(r.data.config.objects);if(n.length>0)throw Object.assign(new Error(`${vo(n)} ${Vp}`),{code:Ui});let o=t==="pipeline"?yn("sync:pipeline",crypto.randomUUID(),"sync:execute"):yn("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,be.code),ea();let{check:l,decision:u}=await Ze(c,this.buildGuardRequest(d)),f=u;if((u==="refused"||u==="declined")&&this.recordStopped(i,d.targetOrgId,u),u==="refused")throw new Error(`Operation blocked by Production Guard: ${l.blockedReason??l.impactSummary}`);if(u==="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 p=`${t==="pipeline"?"Pipeline":"Scheduled"} sync of ${d.objects?.length??0} object(s)`;ze(this.deps,i,"sync",p),this.liveTracker?.register(i,"sync",p,0,{pausable:!0});let g=new AbortController,h=this.executeSync(o,d,i,g,t,f);return this.registry?.register(i,"sync",p,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,l=t,u={...l,objects:l.objects.map(k=>({...k,batchSize:k.batchSize??c}))};Object.assign(a,Gr(u.objects));let f=this.deps.infraServices?.productionGuard;if(!f){this.recordRefused(i,u.targetOrgId,be.code),E(this.deps,"sync:execute","sync:error",e,new Error(be.message),{code:be.code}),De(this.deps,i,be.message,!1,{context:a});return}let{check:p,decision:g}=await Ze(f,this.buildGuardRequest(u)),h=g;if((g==="refused"||g==="declined")&&this.recordStopped(i,u.targetOrgId,g),g==="refused")throw mn(p.blockedReason??p.impactSummary);if(g==="declined"){let k="Operation cancelled by user (confirmation declined).";E(this.deps,"sync:execute","sync:error",e,new Error(k),{code:$t.declined}),De(this.deps,i,k,!1,{context:a});return}if(d?.signal.aborted){this.answerCancelledBeforeStart(e,u,g);return}if(this.dmlTracker.isDuplicate(i)){this.deps.log(`[WARN] Duplicate sync operation detected: ${i}`),E(this.deps,"sync:execute","sync:error",e,new Error(`Duplicate operation: ${i}`)),De(this.deps,i,`Duplicate operation: ${i}`,!1,{context:a});return}this.dmlTracker.register(i,"sync","upsert",u.objects?.length??0),this.activeOperationIds.add(i),this.deps.infraServices?.performanceTracker?.start(i,"sync");let m=`Sync ${u.objects?.length??0} object(s)`;ze(this.deps,i,"sync",m),this.liveTracker?.register(i,"sync",m,0,{pausable:!0});let y=new AbortController,R=this.executeSync(e,u,i,y,r,h,n,o);this.registry?this.registry.register(i,"sync",m,R,y):await R}catch(c){this.dmlTracker.markFailed(i),E(this.deps,"sync:execute","sync:error",e,c,{code:Ao(c)}),De(this.deps,i,O(c),!0,{context:a})}finally{d?.release()}}answerCancelledBeforeStart(e,t,r){Z(this.deps,{action:"sync_execute",module:"sync",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:r,code:Rt});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),pe(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},l=lt(this.deps),u,f,p=!1,g,h=b=>({measure:S=>b.measure(S),hold:async S=>{let C=await b.hold(S);return g=C.answer.emails,C}}),m=new Kd;this.pauseGates.set(r,m);let y=o==="pipeline"?this.deps.orgManager.getOrg(c.targetOrgId)?.orgId:void 0,R=this.runCreations?.recorder({runId:r,configId:c.id,configName:c.name??"",sourceOrgId:c.sourceOrgId,targetOrgId:c.targetOrgId,...y?{targetOrganizationId:y}:{}}),k=this.backupRecords,w=R&&k?Ya({runId:r,orgId:c.targetOrgId,files:k,meta:this.deps.configStore}):void 0,I=d?this.runCheckpointOf(c,r,d,{signal:n.signal,...R?{recorder:R}:{}}):void 0,P=()=>{try{w?.close()}catch(b){this.deps.log(`[WARN] sync ${r}: the backup of what it wrote over could not be listed whole: `+O(b))}};try{let b=await this.readersFor(c,n.signal),{sourceConn:S,targetConn:C}=b;kr(R,()=>C.identity(),`sync ${r}`);let v=b.queryTargetRows,T=R&&w?Qa({query:v,backup:w,recorder:R,describe:b.describeTargetFields,viewsEncrypted:yr(v)}):void 0,D=new Rn(l.bulk.threshold),z=mr(this.deps),H=new Cn({connection:C,bulkExecutor:D,bulkManager:z,retryConfig:l.retry,signal:n.signal,pauseGate:m,onProgress:(W,se,te)=>{let ue=Math.round(W/se*100);Le(this.deps,r,ue,W,se,te),this.liveTracker?.updateProgress(r,ue,W,se,te)},log:W=>this.deps.log(W),...R?{calls:rd(R,T)}:{}}),{DataSync:Y}=await import("./chunk-AG24QMSY.mjs"),{ConflictResolver:U}=await import("./chunk-CHCHAE4B.mjs"),{FieldMappingService:M}=await import("./chunk-L3I6DAHX.mjs"),{TransformPipeline:L}=await import("./chunk-UIR77ZJD.mjs"),ee=W=>{W.length>0&&(p=!0)},Q=new Y({upsert:(W,se,te,ue)=>(ee(te),H.upsert(W,se,te,ue)),insert:(W,se,te)=>(ee(se),H.insert(W,se,te)),update:(W,se,te)=>(ee(se),H.update(W,se,te)),delete:(W,se,te)=>(ee(se),H.delete(W,se,te)),describeTargetFields:b.describeTargetFields}),q=new U,V=new M,we=new L,ie={dataSync:Q,conflictResolver:q,fieldMapping:V,transformPipeline:we,querySource:b.querySource,maskedSourceFields:b.maskedSourceFields,queryTarget:b.queryTarget,services:this.deps.services,grappeConfig:As(this.deps.services),onGrappeEvent:W=>ta(this.deps,W),countSource:b.countSource,countPersonAccounts:b.countPersonAccounts,describeTargetFields:b.describeTargetFields,describeTargetFieldsAgain:b.describeTargetFieldsAgain,leaseOfTheGate:()=>f?.lease(),queryTargetRows:v,readSourceIds:b.readSourceIds,findInTarget:b.findInTarget,writeGate:(()=>{let W=o==="schedule"||o==="pipeline"?"unattended":"ask";if(!a)return h(this.writeGateFor(c,C,W,void 0,I?.gate));let se=this.targetAutomation;return f=jv((ue,x)=>this.writeGateFor(c,C,W,ue,I?.gate,x),ue=>new fe(fO).withTimeout("sync:automation",()=>se.read(c.targetOrgId,ue)),ue=>Ot(async()=>Lt(C),ue,{...this.muteLeases,writes:Nv}),r,{target:he(this.deps.orgManager.getOrg(c.targetOrgId),c.targetOrgId),liftedBy:wO(W).emailsLiftedBy}),h(f.gate)})(),recordTypes:b.recordTypes,currencies:b.currencies,standardPricebooks:b.standardPricebooks,signal:n.signal,pauseGate:m,deltaStore:this.deltaStoreFor(),deltaReads:b.deltaReads,files:{...b.files,onProgress:(W,se)=>{Le(this.deps,r,W,0,0,se),this.liveTracker?.updateProgress(r,W,0,0,se)}},...R?{creations:R}:{},idMap:this.idMapFor()};if(!this.deps.services)throw new Error("SyncOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let re=this.deps.services.syncOrchestrator(ie);await this.assertFieldTypesMatch(c,S,C,l.timeouts.describe),Le(this.deps,r,10,0,1,"Initializing sync");let Ae=await re.execute(c).finally(async()=>{u=await f?.release()}),me=await this.settleRunCheckpoint(I,p,r),Je=[...b.cutAtReadCap],Ne={...Ae,...Je.length>0?{status:Ae.status==="success"?"partial":Ae.status,readCap:b.readCap,cutAtReadCap:Je}:{},...u?{mutedAutomation:u}:{},...me?{checkpoint:me}:{}};if(await R?.end({status:Ne.status,cancelled:Ne.cancelled===!0}),P(),Ne.cancelled?this.endCancelled(r):(Le(this.deps,r,100,1,1,"Sync complete"),pe(this.deps,r,{status:Ne.status??"completed"}),Ne.status==="failure"?this.liveTracker?.fail(r,Ne.error??"No record could be synced."):Ne.status==="partial"?this.liveTracker?.partial(r):this.liveTracker?.complete(r)),this.dmlTracker.markCompleted(r),c.files){let W=Ne.objectResults.flatMap(se=>se.files?[se.files]:[]);this.deps.log(`[sync] ${r} files: ${av(W)}`)}$e(S.limitInfo,"sync:execute completion (source)"),$e(C.limitInfo,"sync:execute completion (target)");try{this.historyLogger?.logExecution(c,Ne,o)}catch(W){this.deps.log(`[WARN] sync history logging failed: ${O(W)}`)}this.recordRun(c,r,Ne,i,o,g);let Fe=A(this.deps,e,"sync:execute:response",Ne);return this.deps.broker.postToWebview(Fe),this.deps.log(`[TX] ${Fe.type} id=${Fe.id}`),Ne}catch(b){await R?.end({status:"failure"}),P(),this.dmlTracker.markFailed(r);let S=await this.settleRunCheckpoint(I,p,r),C=S?.state==="deleted";if(this.liveTracker?.fail(r,O(b)),b instanceof yv){let z=I?.refusal(),H=C?`${b.message} ${Yr}`:b.message,Y={...z?{checkpointRefusal:z.code}:{},...S?{checkpoint:S}:{}};return Z(this.deps,{action:"sync_execute",module:"sync",operationId:r,orgId:c.targetOrgId,outcome:"stopped",guard:i,code:b.code,details:{triggeredBy:o,...z?{checkpointRefusal:z.code}:{},...Yn(g)}}),E(this.deps,"sync:execute","sync:error",e,b,{code:b.code,extraPayload:Y}),De(this.deps,r,H,!1,{context:{module:"sync",operation:e.type,...Gr(c.objects)}}),{...b.result,configId:c.id,operationId:r,status:"failure",timestamp:new Date().toISOString(),error:H,...S?{checkpoint:S}:{}}}ks(b)&&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}`):ks(b)&&o==="rerun"&&this.deps.log(`[OFFLINE] sync replay failed again \u2014 not re-queued (replay outcomes surface via operation:failed): ${r}`);let v=C?new Error(`${O(b)} ${Yr}`):b;E(this.deps,"sync:execute","sync:error",e,b,{...S?{extraPayload:{checkpoint:S}}:{}}),De(this.deps,r,O(v),!0,{context:{module:"sync",operation:e.type,...Gr(c.objects)}});let D={...(b instanceof mv?b.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:O(v),...S?{checkpoint:S}:{}};try{this.historyLogger?.logExecution(c,D,o)}catch(z){this.deps.log(`[WARN] sync history logging failed: ${O(z)}`)}return this.recordRun(c,r,D,i,o,g),D}finally{this.pauseGates.delete(r),this.activeOperationIds.has(r)&&(this.deps.infraServices?.performanceTracker?.complete(r),this.activeOperationIds.delete(r))}}};var cx=new Set(["sync:history:list","sync:history:detail","sync:history:rerun","sync:history:export"]),Qd=class{constructor(e,t,r){this.deps=e;this.historyStore=t;this.syncOps=r}deps;historyStore;syncOps;async handle(e){if(!cx.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){E(this.deps,"sync:history:list","sync:history:error",e,t)}}handleDetail(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(du,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){E(this.deps,"sync:history:detail","sync:history:error",e,r)}}handleExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(gm,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){E(this.deps,"sync:history:export","sync:history:error",e,r)}}async handleRerun(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(du,e,"sync:history:error",this.deps);if(!t)return;let r=this.historyStore.load(t.entryId);if(!r){E(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 lx=1e4;async function bO(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=>Mt(c).filter(l=>t.has(l.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,l)=>o.indexOf(c.objectApiName)-o.indexOf(l.objectApiName)),a,d=[];for(let{objectApiName:c,ids:l}of i){let u=l.slice(0,lx),f;try{f=await e.countInTarget(c,u)+(l.length-u.length)}catch(p){a??=p instanceof Error?p.message:String(p),f=l.length}f>0&&d.push({objectApiName:c,count:f})}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 ux=new Set(["sync:removal:info","sync:removal:list","sync:remove","sync:remove:sweep","sync:remove:automation","sync:earlier-copies"]),px=6e4,fx=12e4,RO=6e4,gx=6e4,vO="The run is still writing in another window: remove it once it has ended there.",Zd=class{constructor(e,t,r,n=Co){this.deps=e;this.history=t;this.isRunning=r;this.self=n;this.configs=new It(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)&&Vn(e,this.self)}stillWriting(e){return this.isRunning(e.runId)||Vn(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-QO4MPHZD.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>B(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async handle(e){if(!ux.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 Ee(t)}infoOf(e,t=[]){let r=Mt(e),n=Fw(e,t),o=r.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length})),i=$o(e),a=this.keptBack(i),d=Ru(e),c=vu(e),l=Fs(e),u={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:Ls(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(R=>`${m}.${R}`))}:{},...l.length>0?{bringBack:l.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length}))}:{},...e.removal?.undo?{removed:e.removal.undo}:{},...n.length>0?{writtenAgain:n}:{}},f=e.removal?.undo?Mt(e,!0):[],p=f.length>0?{...u,createdByObject:f.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length}))}:u,g=r.length>0||i.length>0||l.length>0?r:f;if(g.length===0&&i.length===0&&l.length===0)return p;let h=this.refusalOf(e,g,[...i,...l]);return h?{...p,refusal:h}:p}keptBack(e){return tb(e,t=>this.deps.configStore.get(`backup:${t}`),eb(this.deps.services))}removalStepsOf(e,t=!1){let r=o=>[...new Set(o.map(({objectApiName:i})=>i))],n=r(Mt(e,t));return{bringBack:r(Fs(e)),giveBack:r(this.keptBack($o(e)).kept),setToDraft:or(n),delete:vn(n)}}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:vO};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:be.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 fe(gx).withTimeout(r,async()=>{let o=await B(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=sr(o,r);return Wa(t,e,Jn(o),()=>i.serverTime())});for(let o of za(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: ${O(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=$(sm,e,"sync:remove:error",this.deps);if(t)try{let r=await this.runOf(t.runId),o=r!==void 0&&(Mt(r).length>0||$o(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){E(this.deps,"sync:removal:info","sync:remove:error",e,r)}}async handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(im,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)&&(Ls(d)>0||Ru(d)>0||vu(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){E(this.deps,"sync:removal:list","sync:remove:error",e,n)}}async handleEarlierCopies(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(am,e,"sync:remove:error",this.deps);if(t)try{let r=this.creations,n=await bO(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=bt(i),l=0;for(let u of Ds(a.filter(Vr)))l+=(await d.query(`SELECT COUNT() FROM ${c} WHERE Id IN (${u})`)).totalSize;return l}}),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){E(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(l=>l.objectApiName).filter(l=>!Mw.includes(l)))],a;try{a=await new fe(px).withTimeout(`${r} automation`,()=>o.read(t.targetOrgId,i))}catch(l){a={error:O(l)}}let d=sr(e,r),c=await Ja(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 Bo({...c,ties:{...c.ties,...await Xa(t,c.writtenBetween,await this.creations?.list().catch(()=>[])??[],this.otherModuleRuns)}},d)}async localRunsOn(e){return Va(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=$(cm,e,"sync:remove:sweep:error",this.deps);if(!t)return;let r=(n,o)=>E(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 fe(fx).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 _o(Zr(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){E(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=$(lm,e,"sync:remove:automation:error",this.deps);if(!t)return;let r=(n,o)=>E(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=bs(this.removalStepsOf(n,t.again===!0),t.sweptObjects??[]),i=[...new Set(Object.values(o).flat())],a=this.targetAutomation,d=await new fe(RO).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 wr;E(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 qo({input:async()=>{if(n instanceof Error)throw n;return n},org:Zr(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=Ho(o,"");delete a.forgeId,Z(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:Wo(i)}:{},objects:Uo(o),details:{...a,runId:r.runId}})},keepMade:async(o,i,a)=>{await this.creations?.updateRemoval(r.runId,d=>Ka(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: ${O(d)}`)})}})}refuse(e,t,r,n=!1){E(this.deps,"sync:remove","sync:remove:error",e,new Error(t),{code:r,...n?{retryable:n}:{}})}recordNotRemoved(e,t,r,n={}){Z(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=$(dm,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){E(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,vO,"RUNNING");return}let o=t.again===!0;if(Mt(n,o).length===0&&$o(n).length===0&&Fs(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=Mt(r,a),c=[...$o(r),...Fs(r)],l=d.reduce((b,S)=>b+S.ids.length,0),u=c.reduce((b,S)=>b+S.ids.length,0),f=r.targetOrgId,p=this.deps.infraServices?.productionGuard;if(!p){this.recordNotRemoved(e,r,"stopped",{code:be.code}),this.refuse(e,be.message,be.code);return}let{check:g,decision:h}=await Ze(p,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}`,$t.blocked):this.refuse(e,"Operation cancelled by user (confirmation declined).",$t.declined,!0);return}if(o?.signal.aborted){this.recordNotRemoved(e,r,"stopped",{guard:h,code:Rt});let b={runId:r.runId,status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(A(this.deps,e,"sync:remove:response",{result:b,operationId:e.id}));return}let m=e.id,y=u>0?`Removing ${l} record(s) and file(s) a Sync run created, and giving ${u} record(s) it wrote over or deleted their values back`:`Removing ${l} record(s) and file(s) a Sync run created`,R=new AbortController,k=()=>{},w=new Promise((b,S)=>{k=C=>C===void 0?b():S(C)});w.catch(()=>{}),ze(this.deps,m,"sync",y),this.registry?.register(m,"sync",y,w,R),this.liveTracker?.register(m,"sync",y,l+u);let I,P;try{let b=await B(f,this.deps.orgRegistry,this.deps.orgManager),S=n.sweep?await this.sweepInputOf(b,r,"sync:remove sweep",R.signal).catch(ie=>new Error(O(ie))):void 0;P=S?await this.sweepOfRemoval({conn:b,run:r,input:S,includeChanged:i,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,signal:R.signal,guard:p,operationId:m}):void 0;let C=P;await C?.ask();let v;if(n.muteAutomation===!0){let ie=bs(this.removalStepsOf(r,a),C?.takes??[]),re=[...new Set(Object.values(ie).flat())],Ae=this.targetAutomation,me=await new fe(RO).withTimeout("sync:remove:automation",()=>Ae.read(r.targetOrgId,re,{undeletes:!0})).catch(Je=>({unread:O(Je)}));v=await Ot(async()=>Lt(b),me,{...this.muteLeases,writes:qr(ie)})}let T,D=v?.muted,z=async()=>{let ie=v?.prepared;!ie||R.signal.aborted||(T=await ie.acquire(m),D=T.outcome)},H=sr(b,"sync:remove"),Y=await Ga(H,r.created),{result:U,notes:M,earlierStamped:L,duplicateSets:ee}=await wa({run:r,org:H,includeChanged:i,...a?{again:a}:{},store:t,configs:this.configs,links:t.idMap(),...this.backups?{backups:this.backups}:{},earlierRuns:Lw(r,await t.list().catch(()=>[])),undelete:ie=>b.soap.undelete(ie),...C?{sweep:ie=>C.first(ie),afterRemoval:ie=>C.afterRemoval(ie),automationMade:C.automationMade}:{},...r.runUserId?{runUserId:r.runUserId}:{},onUndeletable:zr(this.deps,f,"sync:remove"),beforeFirstWrite:z,signal:R.signal,onProgress:(ie,re,Ae)=>{let me=Math.min(100,Math.round(ie/Math.max(re,1)*100));Le(this.deps,m,me,ie,re,Ae),R.signal.aborted||this.registry?.updateProgress(m,me),this.liveTracker?.updateProgress(m,me,ie,re,Ae)}}).finally(async()=>{T&&(D=await T.release())}),Q=await P?.settle(),q=U.status==="cancelled"?{}:await Y.take(ee);for(let ie of[...M,...q.note?[q.note]:[]])this.deps.log(`[WARN] sync:remove ${m}: ${ie}`);for(let{runId:ie,records:re}of L??[])this.deps.log(`[INFO] sync:remove ${m}: ${re} record(s) given back hold the values of the earlier run ${ie} again, stamped on it`);let V={...U,objects:q.object?[...U.objects,q.object]:U.objects,status:Eo(U.status,Q),...Q?{sweep:Q}:{},...D?{mutedAutomation:D}:{}};Z(this.deps,{action:"cleanup_delete",module:"sync",operationId:m,orgId:f,outcome:Po(U),guard:h,objects:ya(Sn(V.objects),V.restored??[],V.undeleted??[]),...V.leftBy?{leftBy:V.leftBy}:{},...D?{muted:ct(D)}:{},details:{runId:r.runId}});let we=A(this.deps,e,"sync:remove:response",{result:V,operationId:m});this.deps.broker.postToWebview(we),this.deps.log(`[TX] ${we.type} id=${we.id} status=${V.status}`),V.status==="cancelled"||V.sweep?.status==="cancelled"?(pe(this.deps,m,{aborted:!0}),this.liveTracker?.cancel(m)):(pe(this.deps,m,{status:V.status}),V.status==="failure"?(I=new Error("Nothing this run created could be removed."),this.liveTracker?.fail(m,"Nothing this run created could be removed.")):V.status==="partial"?this.liveTracker?.partial(m):this.liveTracker?.complete(m))}catch(b){I=b,await P?.settle().catch(()=>{});let S=xt(b)?b:void 0;this.recordNotRemoved(e,r,S?"stopped":"failure",{guard:h,...S?{code:S.code}:{}}),E(this.deps,"sync:remove","sync:remove:error",e,b,{code:S?.code??"REMOVE_ERROR",retryable:!0}),pe(this.deps,m,{status:"failure"}),this.liveTracker?.fail(m,O(b))}finally{k(I)}}};var hx=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,mx=/^[A-Za-z][A-Za-z0-9_]*$/;function ec(s,e,t){if(!hx.test(t)||!mx.test(e))return{ok:!1,reason:"not-a-record"};let r=xn(s);return r.ok?{ok:!0,url:new URL(`/lightning/r/${e}/${t}/view`,r.url.origin).toString()}:r}var yx=new Set(["seed:removal:info","seed:removal:list","seed:remove","seed:remove:sweep","seed:open-record"]),SO=6e4,wx=12e4,bx=6e4,kO="The seed is still writing: remove it once it has ended.",OO="The seed is still writing in another window: remove it once it has ended there.",tc=class{constructor(e,t,r=()=>!1,n=Co){this.deps=e;this.isRunning=r;this.self=n;this.externalBrowser=t??new $r}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)&&Vn(e,this.self)}setRunCreations(e){this.creations=e}setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-QO4MPHZD.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 yx.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:open-record"?await this.handleOpenRecord(e):await this.handleRemove(e),!0):!1}tierOf(e){let t=this.deps.orgManager.getOrg(e);return Ee(t)}infoOf(e){let t=Mt(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:Ls(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?Mt(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-QXB6U3ZP.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:kO};if(this.elsewhere(e))return{code:"RUNNING",message:OO};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:be.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 fe(bx).withTimeout(r,async()=>{let o=await B(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=sr(o,r);return Wa(t,e,Jn(o),()=>i.serverTime())});for(let o of za(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: ${O(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=$(um,e,"seed:remove:error",this.deps);if(t)try{let r=await this.runOf(t.runId),n=A(this.deps,e,"seed:removal:info:response",{info:r?await this.withScenario(this.infoOf(r)):null});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){E(this.deps,"seed:removal:info","seed:remove:error",e,r)}}async handleOpenRecord(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(jm,e,"seed:open-record:error",this.deps);if(!t)return;let r=(n,o)=>{E(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:u,ids:f}of n.created){let p=f.find(g=>g.slice(0,15)===o);if(p){i={objectApiName:u,id:p};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=ec(a.instanceUrl,i.objectApiName,i.id);if(!d.ok){let u=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 "${he(a)}": ${u}.`,d.reason==="not-a-record"?"NOT_CREATED":"INVALID_INSTANCE_URL");return}let c=await this.externalBrowser.open(d.url),l=A(this.deps,e,"seed:open-record:response",c);this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id} status=${c.status}`)}catch(n){E(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){E(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 fe(SO).withTimeout(`${r} automation`,()=>o.read(t.targetOrgId,t.created.map(c=>c.objectApiName)))}catch(c){i={error:O(c)}}let a=sr(e,r),d=await Ja(a,t.created,i,n,void 0,[],{...t.runUserId?{runUserId:t.runUserId}:{},ties:{}});return Bo({...d,ties:{...d.ties,...await Xa(t,d.writtenBetween,await this.creations?.list().catch(()=>[])??[],this.otherModuleRuns)}},a)}async localRunsOn(e){return Va(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=$(fm,e,"seed:remove:sweep:error",this.deps);if(!t)return;let r=(n,o)=>E(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 fe(wx).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 _o(Zr(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){E(this.deps,"seed:remove:sweep","seed:remove:sweep:error",e,n,{code:"SWEEP_ERROR",retryable:!0})}}sweepOfRemoval(e){let{conn:t,run:r}=e;return qo({input:()=>this.sweepInputOf(t,r,"seed:remove sweep",e.signal),org:Zr(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=Ho(n,"");delete i.forgeId,Z(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:Wo(o)}:{},objects:Uo(n),details:{...i,runId:r.runId}})},keepMade:async(n,o,i)=>{await this.creations?.updateRemoval(r.runId,a=>Ka(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: ${O(a)}`)})}})}refuse(e,t,r,n=!1){E(this.deps,"seed:remove","seed:remove:error",e,new Error(t),{code:r,...n?{retryable:n}:{}})}recordNotRemoved(e,t,r,n={}){Z(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=$(pm,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,"Nothing this run created is kept: it created nothing, or was dropped to make room for newer seeds. To take its records back, rewind the org to a checkpoint taken before it, or empty its objects (DataOps, Cleanup, Empty objects), which deletes all their records.","NOT_KEPT");return}let o=t.again===!0;if(Mt(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,kO,"RUNNING");return}if(this.elsewhere(n)){this.refuse(e,OO,"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=Mt(r,a),c=d.reduce((I,P)=>I+P.ids.length,0),l=r.targetOrgId,u=this.deps.infraServices?.productionGuard;if(!u){this.recordNotRemoved(e,r,"stopped",{code:be.code}),this.refuse(e,be.message,be.code);return}let{check:f,decision:p}=await Ze(u,{orgId:l,orgTier:this.tierOf(l),operation:"delete",objectName:d.map(I=>I.objectApiName).join(", "),recordCount:c,module:"seed"});if(p==="refused"||p==="declined"){this.recordNotRemoved(e,r,"stopped",{guard:p}),p==="refused"?this.refuse(e,`Operation blocked by Production Guard: ${f.blockedReason??f.impactSummary}`,$t.blocked):this.refuse(e,"Operation cancelled by user (confirmation declined).",$t.declined,!0);return}if(o?.signal.aborted){this.recordNotRemoved(e,r,"stopped",{guard:p,code:Rt});let I={runId:r.runId,status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(A(this.deps,e,"seed:remove:response",{result:I,operationId:e.id}));return}let g=e.id,h=`Removing ${c} record(s) a Seed run created`,m=new AbortController,y=()=>{},R=new Promise((I,P)=>{y=b=>b===void 0?I():P(b)});R.catch(()=>{}),ze(this.deps,g,"seed",h),this.registry?.register(g,"seed",h,R,m),this.liveTracker?.register(g,"seed",h,c);let k,w;try{let I=await B(l,this.deps.orgRegistry,this.deps.orgManager);w=n.sweep?await this.sweepOfRemoval({conn:I,run:r,includeChanged:i,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,signal:m.signal,guard:u,operationId:g}):void 0;let P=w;await P?.ask();let b;if(n.muteAutomation===!0){let Q=[...new Set(d.map(re=>re.objectApiName))],q=bs({setToDraft:or(Q),delete:vn(Q)},P?.takes??[]),V=q.delete??[],we=this.targetAutomation,ie=await new fe(SO).withTimeout("seed:remove automation",()=>we.read(r.targetOrgId,V)).catch(re=>({unread:O(re)}));b=await Ot(async()=>Lt(I),ie,{...this.muteLeases,writes:qr(q)})}let S,C=b?.muted,v=async()=>{let Q=b?.prepared;!Q||m.signal.aborted||(S=await Q.acquire(g),C=S.outcome)},T=sr(I,"seed:remove"),D=await Ga(T,r.created),{result:z,notes:H,duplicateSets:Y}=await wa({run:r,org:T,includeChanged:i,...a?{again:a}:{},store:t,...P?{sweep:Q=>P.first(Q),afterRemoval:Q=>P.afterRemoval(Q),automationMade:P.automationMade}:{},...r.runUserId?{runUserId:r.runUserId}:{},onUndeletable:zr(this.deps,l,"seed:remove"),beforeFirstWrite:v,signal:m.signal,onProgress:(Q,q,V)=>{let we=Math.min(100,Math.round(Q/Math.max(q,1)*100));Le(this.deps,g,we,Q,q,V),m.signal.aborted||this.registry?.updateProgress(g,we),this.liveTracker?.updateProgress(g,we,Q,q,V)}}).finally(async()=>{S&&(C=await S.release())}),U=await w?.settle(),M=z.status==="cancelled"?{}:await D.take(Y);for(let Q of[...H,...M.note?[M.note]:[]])this.deps.log(`[WARN] seed:remove ${g}: ${Q}`);let L={runId:z.runId,status:Eo(z.status,U),includeChanged:z.includeChanged,objects:M.object?[...z.objects,M.object]:z.objects,finishedAt:z.finishedAt,...z.leftBy?{leftBy:z.leftBy}:{},...U?{sweep:U}:{},...C?{mutedAutomation:C}:{}};Z(this.deps,{action:"cleanup_delete",module:"seed",operationId:g,orgId:l,outcome:Po(z),guard:p,objects:Sn(L.objects),...L.leftBy?{leftBy:L.leftBy}:{},...C?{muted:ct(C)}:{},details:{runId:r.runId}});let ee=A(this.deps,e,"seed:remove:response",{result:L,operationId:g});this.deps.broker.postToWebview(ee),this.deps.log(`[TX] ${ee.type} id=${ee.id} status=${L.status}`),L.status==="cancelled"||L.sweep?.status==="cancelled"?(pe(this.deps,g,{aborted:!0}),this.liveTracker?.cancel(g)):(pe(this.deps,g,{status:L.status}),L.status==="failure"?(k=new Error("Nothing this run created could be removed."),this.liveTracker?.fail(g,"Nothing this run created could be removed.")):L.status==="partial"?this.liveTracker?.partial(g):this.liveTracker?.complete(g))}catch(I){k=I,await w?.settle().catch(()=>{});let P=xt(I)?I:void 0;this.recordNotRemoved(e,r,P?"stopped":"failure",{guard:p,...P?{code:P.code}:{}}),E(this.deps,"seed:remove","seed:remove:error",e,I,{code:P?.code??"REMOVE_ERROR",retryable:!0}),pe(this.deps,g,{status:"failure"}),this.liveTracker?.fail(g,O(I))}finally{y(k)}}};var rc="sync:history:all",IO="syncHistory";var nc=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(rc,n,IO)}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(rc,r,IO),!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(rc)}loadAll(){let e=this.configStore.get(rc);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 Rx=/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+:/;function vx(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))Rx.test(r)||e.includes(r)?t++:e.push(r);return t===0?{...s,errors:e}:{...s,errors:e,refusalsDropped:(s.refusalsDropped??0)+t}}var oc=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(vx)},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 Sx={Report:"ReportFolder",Dashboard:"DashboardFolder",EmailTemplate:"EmailTemplateFolder"},kx=new Set(["compare:execute","compare:permissions","compare:snapshots","compare:drift","compare:validate-deployment","compare:deploy"]),Ox=5;function Ix(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 sc=class{constructor(e,t={}){this.deps=e;this.options=t}deps;options;validations=new Map;async handle(e){if(!kx.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=$(zm,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-WJAZ5LHL.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){E(this.deps,"compare:validate-deployment","compare:error",e,new Error("A managed package installed "+c.managed.map(f=>`${f.componentType} ${f.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(f=>({componentType:f.componentType,fullName:f.fullName}))}});return}let l=c.retrieved.length>0?await i.deployPackage(i.metadataApiOf(o),c.zipFile,i.deployOptions(!0,t.testLevel,r),{waiting:a,onProgress:d}):void 0,u=i.deploymentReport(l,c,{sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,checkOnly:!0,testLevel:t.testLevel,runTests:r});u.success&&u.deployId&&this.keepValidation(u.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:u}),u)}catch(n){E(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=$(Gm,e,"compare:error",this.deps);if(!t)return;let r=this.validations.get(t.validationId);if(!r){E(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){E(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-WJAZ5LHL.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)}),d=i.deploymentReport(a,{missing:[],problems:[]},{sourceOrgId:r.sourceOrgId,targetOrgId:r.targetOrgId,checkOnly:!1,testLevel:r.testLevel,runTests:r.runTests});Z(this.deps,{action:"metadata_deploy",module:"compare",operationId:e.id,orgId:r.targetOrgId,outcome:d.success?"success":"failure",guard:n,objects:Ix(d),source:{origin:"org",orgId:r.sourceOrgId}}),this.post(A(this.deps,e,"compare:deploy:response",{report:d}),d)}catch(o){n&&Z(this.deps,{action:"metadata_deploy",module:"compare",operationId:e.id,orgId:r.targetOrgId,outcome:"failure",guard:n}),E(this.deps,"compare:deploy","compare:error",e,o,{code:await this.deployErrorCode(o)})}}async passGuard(e,t,r,n){let o=this.deps.infraServices?.productionGuard??new Xw,i=this.deps.orgManager.getOrg(t),a={orgId:t,orgTier:Ee(i),operation:"deploy",objectName:[...new Set(r.map(l=>l.componentType))].join(", "),recordCount:r.length,module:"compare"};if(n){let l=o.check(a);if(l.allowed)return"allowed";this.refuse(e,l.blockedReason??l.impactSummary);return}let{check:d,decision:c}=await Ze(o,a);if((c==="refused"||c==="declined")&&Z(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"){E(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){E(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>Ox;){let r=this.validations.keys().next().value;if(r===void 0)break;this.validations.delete(r)}}progressTo(e){return t=>Le(this.deps,e.id,t.total>0?Math.round(t.done/t.total*100):0,t.done,t.total,t.step)}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{DeploymentStillRunning:t}=await import("./chunk-WJAZ5LHL.mjs");return e instanceof t?"STILL_RUNNING":"DEPLOY_ERROR"}async handleCompareStart(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(xs,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){E(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-F2424IKX.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,R=async I=>{t?.throwIfAborted();let P=await m.metadata.list(I);return $e(m.limitInfo,`compare:metadata list ${String(h)}`),Array.isArray(P)?P:[]},k=Sx[h],w=k?(await R([{type:k}])).map(I=>({type:h,folder:I.fullName})):[{type:h}];for(let I=0;I<w.length;I+=3)for(let P of await R(w.slice(I,I+3)))y.set(P.fullName,JSON.stringify(P));return y},l=a(g=>g===e.sourceOrgId?r:n,t),u=new i(c,d,l);if(!this.deps.services)throw new Error("CompareHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let f=this.deps.services.compareOrchestrator({metadataCompare:u,diffEngine:d,services:this.deps.services}),p={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 f.execute(p,t)}async handlePermissions(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(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 jt(h,"SELECT Id, Name, Label, IsOwnedByProfile FROM PermissionSet WHERE IsOwnedByProfile = false");$e(h.limitInfo,`compare:permissions ${m}`);let R=await jt(h,"SELECT Id, Name FROM Profile");return $e(h.limitInfo,`compare:permissions profiles ${m}`),{permSets:y,profiles:R}},[a,d]=await Promise.all([i(n,"source"),i(o,"target")]),c=new Set(a.permSets.map(h=>h.Name)),l=new Set(d.permSets.map(h=>h.Name)),u=new Set(a.profiles.map(h=>h.Name)),f=new Set(d.profiles.map(h=>h.Name)),p={permissionSets:{sourceOnly:a.permSets.filter(h=>!l.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=>l.has(h.Name)).map(h=>({name:h.Name,label:h.Label}))},profiles:{sourceOnly:a.profiles.filter(h=>!f.has(h.Name)).map(h=>({name:h.Name})),targetOnly:d.profiles.filter(h=>!u.has(h.Name)).map(h=>({name:h.Name})),shared:a.profiles.filter(h=>f.has(h.Name)).map(h=>({name:h.Name}))}},g=A(this.deps,e,"compare:permissions:response",{permissions:p});this.deps.broker.postToWebview(g),this.deps.log(`[TX] ${g.type} id=${g.id}`)}catch(n){E(this.deps,"compare:permissions","compare:error",e,n)}}async handleSnapshots(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(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(p,g)=>{let h=await p.describeGlobal();$e(p.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(p=>p.name)),l=new Set(d.objects.map(p=>p.name)),u={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(p=>!l.has(p.name)).map(p=>p.name),targetOnly:d.objects.filter(p=>!c.has(p.name)).map(p=>p.name),sharedCount:a.objects.filter(p=>l.has(p.name)).length},capturedAt:new Date().toISOString()},f=A(this.deps,e,"compare:snapshots:response",{snapshot:u});this.deps.broker.postToWebview(f),this.deps.log(`[TX] ${f.type} id=${f.id}`)}catch(n){E(this.deps,"compare:snapshots","compare:error",e,n)}}async handleDrift(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(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(p,g)=>{let h={},m=await jt(p,"SELECT Name, LanguageLocaleKey, DefaultLocaleSidKey, TimeZoneSidKey, FiscalYearStartMonth FROM Organization LIMIT 1");if($e(p.limitInfo,`compare:drift companyInfo ${g}`),m[0])for(let[y,R]of Object.entries(m[0]))y!=="attributes"&&y!=="Id"&&(h[`Organization.${y}`]=String(R));return h},[a,d]=await Promise.all([i(n,"source"),i(o,"target")]),c=new Set([...Object.keys(a),...Object.keys(d)]),l=[];for(let p of c){let g=a[p],h=d[p];g===void 0?l.push({setting:p,sourceValue:"",targetValue:h??"",status:"missing_source"}):h===void 0?l.push({setting:p,sourceValue:g,targetValue:"",status:"missing_target"}):g!==h?l.push({setting:p,sourceValue:g,targetValue:h,status:"drift"}):l.push({setting:p,sourceValue:g,targetValue:h,status:"match"})}let u={items:l,totalChecked:l.length,driftCount:l.filter(p=>p.status==="drift").length,matchCount:l.filter(p=>p.status==="match").length,missingCount:l.filter(p=>p.status==="missing_source"||p.status==="missing_target").length,detectedAt:new Date().toISOString()},f=A(this.deps,e,"compare:drift:response",{drift:u});this.deps.broker.postToWebview(f),this.deps.log(`[TX] ${f.type} id=${f.id}`)}catch(n){E(this.deps,"compare:drift","compare:error",e,n)}}};import{randomBytes as Hx}from"node:crypto";function AO(s,e,t){return s==="delete"?{...ht(e),deleted:t.done,failed:t.failed}:{...ht(e),updated:t.done,failed:t.failed}}async function ic(s,e,t){let r=crypto.randomUUID(),n=s.infraServices?.productionGuard;if(!n)return Z(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,outcome:"stopped",code:be.code}),{ran:!1,operationId:r,code:be.code,message:be.message};let o=s.orgManager.getOrg(e.orgId),{check:i,decision:a}=await Ze(n,{orgId:e.orgId,orgTier:Ee(o),operation:e.operation,objectName:e.objectNames.join(", "),recordCount:e.recordCount,module:"dataops"}),d=a;if(a==="refused"||a==="declined")return Z(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)."};ze(s,r,"dataops",e.description);let c=new AbortController,l=()=>{},u=new Promise((h,m)=>{l=y=>y===void 0?h():m(y)});u.catch(()=>{}),s.infraServices?.backgroundRegistry?.register(r,"dataops",e.description,u,c);let f=ir(t,r,"dataops",e.description,e.recordCount),p=[],g=0;try{let h=await e.run((R,k)=>{p.push({objectApiName:R,counts:k}),g+=k.done+k.failed;let w=Math.min(100,Math.round(g/Math.max(e.recordCount,1)*100)),I=`${R}: ${k.done} done, ${k.failed} refused`;Le(s,r,w,g,e.recordCount,I),f.progress(w,g,e.recordCount,I)},c.signal);await e.beforeEnd?.();let m=gu(h),y=c.signal.aborted;if(Z(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,...y?m.done+m.failed>0?{outcome:"cancelled"}:{outcome:"stopped",code:nt}:{outcome:m.status},...d?{guard:d}:{},objects:h.map(R=>AO(e.operation,R.objectApiName,R.counts))}),y)return s.infraServices?.backgroundRegistry?.abort(r),pe(s,r,{aborted:!0,done:m.done,failed:m.failed}),f.cancel(),l(),{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(pe(s,r,{status:m.status,done:m.done,failed:m.failed}),m.status==="failure"){let R=`The org refused the ${m.failed} record(s)`;f.fail(R),l(new Error(R))}else m.status==="partial"?f.partial():f.complete(),l();return{ran:!0,operationId:r,outcome:m,...d?{guard:d}:{}}}catch(h){await e.beforeEnd?.();let m=O(h);return Z(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,outcome:"failure",...d?{guard:d}:{},objects:p.map(y=>AO(e.operation,y.objectApiName,y.counts))}),De(s,r,m,!0,{context:{module:"dataops",operation:e.origin,objectName:e.objectNames.join(", ")}}),f.fail(m),l(h),{ran:!0,operationId:r,outcome:{...gu(p),status:"failure"},...d?{guard:d}:{},error:m}}}var TO=100;async function Tx(s,e,t){let r=new Map,n=[],o=t.map(a=>qe(a.name)).filter(a=>a!=="Id"),i=[];for(let a=0;a<o.length;a+=TO)i.push(o.slice(a,a+TO));i.length===0&&i.push([]);for(let a of i){let d=await s.query(`SELECT ${["Id",...a].join(", ")} FROM ${e} ORDER BY Id DESC LIMIT ${200}`);for(let c of d.records){if(typeof c!="object"||c===null)continue;let l={...c};delete l.attributes;let u=typeof l.Id=="string"?l.Id:void 0;if(!u)continue;let f=r.get(u);f?Object.assign(f,l):(r.set(u,l),n.push(u))}}return n.map(a=>r.get(a))}async function Ex(s,e,t){let r,n;try{if(r=nr.parse(await s.describe(qe(t))),n=qe(r.name),r.queryable===!1)throw new Error(`${n} cannot be queried.`)}catch(g){return{status:"failed",objectApiName:t,message:O(g)}}let o=_s(e,n,r.fields),i=new Set(o.map(g=>g.field.name)),a=r.fields.filter(g=>Hw(g)&&Bw(g)||i.has(g.name)),d=[],c;try{d=await Tx(s,n,a)}catch(g){c=O(g)}let l=c?o:_s(e,n,r.fields,d),u=e.getPatterns(),f=l.map(g=>{let h=qw(g.field),m=d.map(R=>R[g.field.name]),y=g.detectedBy==="content"?u[g.pattern]:void 0;return{fieldApiName:g.field.name,label:g.field.label,classification:g.classification,detectedBy:g.detectedBy,pattern:g.pattern,filled:m.filter(Ra).length,...y?{matched:m.filter(R=>typeof R=="string"&&y.test(R)).length}:{},...h?{searchedFor:h}:{}}}).sort((g,h)=>h.filled-g.filled||g.label.localeCompare(h.label)),p=Ww(r);return{status:"scanned",objectApiName:t,label:r.label,sampled:d.length,fields:f,nameField:p?{fieldApiName:p.name,label:p.label}:null,...c!==void 0?{sampleError:c}:{}}}async function EO(s,e,t,r=()=>new Date){let n=r().toISOString(),o=[];for(let i of t.objects)o.push(await Ex(s,e,i));return{orgId:t.orgId,scannedAt:n,sampleSize:200,objects:o}}async function Px(s,e,t,r){let n=t.fields.filter(Uw).map(d=>d.name),o=await bn(s,t.name,n,r),i=_s(e,t.name,t.fields,o),a=Gw(t,i);return{objectApiName:t.name,records:o,erased:a.fields,plan:{objectApiName:t.name,label:t.label,records:o.length,fields:a.fields.map(d=>({fieldApiName:d.field.name,label:d.field.label,method:d.method})),kept:a.kept.map(d=>({fieldApiName:d.name,label:d.label}))}}}async function PO(s,e,t,r){let n=[],o;for(let i of r){let a=nr.parse(await s.describe(qe(i.objectApiName))),d=l=>({objectApiName:a.name,plan:{objectApiName:a.name,label:a.label,records:0,refused:l}});if(t==="anonymize"){if(a.updateable!==!0){n.push(d(`The connected user may not edit ${a.label} records: erase them with Delete instead, or have an admin grant Edit on ${a.label} in a permission set.`));continue}n.push(await Px(s,e,a,i.ids));continue}if(a.deletable!==!0){n.push(d(`The connected user may not delete ${a.label} records: erase them with Anonymize in place instead, or have an admin grant Delete on ${a.label} in a permission set.`));continue}o??=await ca(s);let c=await la(s,a,i.ids,o);n.push({objectApiName:a.name,ids:[...i.ids],plan:{objectApiName:a.name,label:a.label,records:i.ids.length,related:c.related,uncounted:c.uncounted}})}return n}function ac(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 Cx(s,e){return e.map(t=>({objectApiName:s,fieldApiName:t.field.name,method:t.method,config:{}}))}async function CO(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 ua(s,i.objectApiName,i.ids,n);else{let d=i.erased??[],c=i.records??[];if(d.length===0||c.length===0)continue;let l=e.anonymize(c,Cx(i.objectApiName,d)),u=[],f=0;c.forEach((p,g)=>{let h={Id:p.Id};for(let m of d)Ra(p[m.field.name])&&(h[m.field.name]=l[g][m.field.name]??null);Object.keys(h).length>1?u.push(h):f++}),a=await aw(s,i.objectApiName,u,n),a.done+=f}o.push({objectApiName:i.objectApiName,counts:a}),r?.(i.objectApiName,a)}return o}var $O="dataops:subject-requests",$x="audit",xx=G({objectApiName:j(),done:Te().int().nonnegative(),failed:Te().int().nonnegative()}),Dx=$i("kind",[G({kind:wt("searched"),at:j(),searchedBy:ve(_e(["email","phone","name"])),objects:ve(G({objectApiName:j(),found:Te().int().nonnegative(),truncated:Ge()}))}),G({kind:wt("exported"),at:j(),records:Te().int().nonnegative()}),G({kind:wt("erased"),at:j(),mode:_e(["anonymize","delete"]),outcome:_e(["success","partial","failure","stopped"]),operationId:j(),objects:ve(xx)})]),Nx=G({requestId:j().min(1),orgId:j().min(1),openedAt:j(),events:ve(Dx)}),dc=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($O);return Array.isArray(e)?e.flatMap(t=>{let r=Nx.safeParse(t);return r.success?[r.data]:[]}):[]}write(e){this.configStore.set($O,e.slice(-this.limit),$x)}};function Mx(s){return ql(s).slice(-8)}function Lx(s){return`%${s.split("").join("%")}%`}function xO(s,e){return typeof s=="string"&&s.trim().toLowerCase()===e.trim().toLowerCase()}function Fx(s,e,t){let r=qe(s.name);if(e==="email"&&t.email){let n=t.email.trim();return{field:s,kind:e,soql:`${r} = '${er(n)}'`,matches:o=>xO(o,n)}}if(e==="phone"&&t.phone){let n=Mx(t.phone);return{field:s,kind:e,soql:`${r} LIKE '${Lx(n)}'`,matches:o=>typeof o=="string"&&ql(o).includes(n)}}if(e==="name"&&t.name){let n=t.name.trim();return{field:s,kind:e,soql:`${r} = '${er(n)}'`,matches:o=>xO(o,n)}}}async function _x(s,e,t){try{let r=nr.parse(await s.describe(qe(e))),n=qe(r.name);if(r.queryable===!1)throw new Error(`${n} cannot be queried.`);let o=zw(r).flatMap(({field:p,kind:g})=>{let h=Fx(p,g,t.identifiers);return h?[h]:[]});if(o.length===0)return{status:"skipped",objectApiName:e,label:r.label};let i=o.map(p=>({fieldApiName:p.field.name,label:p.field.label,kind:p.kind})),a=o.map(p=>p.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(p=>p.nameField===!0),l=[...new Set(["Id",...c?[c.name]:[],...o.map(p=>p.field.name)])].map(qe),u=await s.query(`SELECT ${l.join(", ")} FROM ${n} WHERE ${a} ORDER BY Id LIMIT ${t.limit}`),f=[];for(let p of u.records){if(typeof p!="object"||p===null)continue;let g=p;if(!Vr(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;f.push({id:g.Id,name:typeof m=="string"?m:null,matchedBy:h})}return{status:"searched",objectApiName:e,label:r.label,counted:d,records:f,truncated:d>t.limit,searched:i}}catch(r){return{status:"failed",objectApiName:e,message:Ux(O(r),t.identifiers)}}}function Ux(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 DO(s,e){let t=[];for(let r of e.objects)t.push(await _x(s,r,e));return t}var Bx=6e4,qx=new Set(["dataops:pii-inventory","dataops:dsr:search","dataops:dsr:export","dataops:dsr:erase","dataops:dsr:log"]),Wx=20;function zx(s){let e="payload"in s?s.payload:void 0;return typeof e=="object"&&e!==null&&"dryRun"in e?e.dryRun===!0:!1}function Gx(s){return typeof s=="object"&&s!==null&&"success"in s&&s.success===!0}function Jx(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)=>Gx(i)?[r[a]?.Id]:[])),n}catch(n){throw Yw(n)==="may-have-written"&&e.wrote(t,r.map(o=>o.Id)),n}}}}function Vx(s){return["email","name","phone"].filter(e=>s[e]!==void 0)}var cc=class{constructor(e,t){this.deps=e;this.saveDialog=t??new kn}deps;found=new Map;maskingKey=Hx(32).toString("hex");saveDialog;writing=new Qw;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=rb;setDuplicatesSettle(e){this.duplicatesSettleMs=e}ownReader(){return this.reader??=import("./chunk-QO4MPHZD.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 dc(this.deps.configStore)}get detector(){return this.deps.infraServices?.piiDetector??new va}async session(e,t){let r=await B(e,this.deps.orgRegistry,this.deps.orgManager);return da(r,t)}async handle(e){if(!qx.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(zx(e)?void 0:Zw(e,"orgId"),()=>this.handleErase(e)),!0;default:return this.handleLog(e),!0}}async handleInventory(e){let t=$(xm,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:pii-inventory"),n=await EO(r,this.detector,t),o=A(this.deps,e,"dataops:pii-inventory:response",{...n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} objects=${n.objects.length}`)}catch(r){E(this.deps,"dataops:pii-inventory","dataops:error",e,r)}}async handleSearch(e){let t=$(Dm,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 DO(i,{objects:n,identifiers:o,limit:200}),d=this.requestLog,c=t.requestId!==void 0&&d.has(t.requestId,r)?t.requestId:crypto.randomUUID(),l=new Date().toISOString(),u={orgId:r,objects:new Map};for(let h of a)h.status==="searched"&&u.objects.set(h.objectApiName,new Set(h.records.map(m=>m.id)));this.hold(c,u),d.record(c,r,{kind:"searched",at:l,searchedBy:Vx(o),objects:a.flatMap(h=>h.status==="searched"?[{objectApiName:h.objectApiName,found:h.records.length,truncated:h.truncated}]:[])});let f={requestId:c,orgId:r,searchedAt:l,limit:200,objects:a},p=A(this.deps,e,"dataops:dsr:search:response",{...f});this.deps.broker.postToWebview(p);let g=[...u.objects.values()].reduce((h,m)=>h+m.size,0);this.deps.log(`[TX] ${p.type} id=${p.id} records=${g}`)}catch(i){E(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>Wx;){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=$(Nm,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[u,f]of r.objects){if(f.size===0)continue;let p=nr.parse(await n.describe(u)),g=await bn(n,p.name,p.fields.map(h=>h.name),[...f]);o[u]=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 l=A(this.deps,e,"dataops:dsr:export:response",{requestId:t.requestId,records:i,saved:c});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id} ${c.status} records=${i}`)}catch(r){E(this.deps,"dataops:dsr:export","dataops:error",e,r)}}async handleErase(e){let t=$(Mm,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((L,ee)=>{let Q=a.objects.get(ee.objectApiName);return L+ee.ids.filter(q=>!Q?.has(q)).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 c=await this.session(r,"dataops:dsr:erase"),l=await PO(c,this.detector,o,t.records),u=l.map(L=>L.plan),f=ac(u);if(i){let L=A(this.deps,e,"dataops:dsr:erase:response",{requestId:n,mode:o,dryRun:i,plan:u,written:f});this.deps.broker.postToWebview(L),this.deps.log(`[TX] ${L.type} id=${L.id} plan objects=${u.length}`);return}let p=u.filter(L=>!L.refused&&L.records>0),g=p.reduce((L,ee)=>L+ee.records,0);if(g===0){let L=u.flatMap(ee=>ee.refused?[ee.refused]:[]);throw new Error(L.length>0?`Nothing can be erased. ${L.join(" ")}`:"Nothing is left to erase: the records found are no longer in the org.")}let h=he(this.deps.orgManager.getOrg(r),r),m=await B(r,this.deps.orgRegistry,this.deps.orgManager),y=this.targetAutomation,R=await Kr({act:o==="delete"?"cleanup":"masking",target:h,objects:f,org:xo(m,L=>new fe(Bx).withTimeout("dataops automation",()=>y.read(r,L)),Ee(this.deps.orgManager.getOrg(r))==="production"),accord:t,mayMute:!0,muteLeases:this.muteLeases,voice:"erasure"}),k=On(R.answer),w=k?{refused:k}:await Qn(R,e.id,t.acceptEmails===!0,"erasure");if("refused"in w){let L=crypto.randomUUID();Z(this.deps,{action:"subject_erase",module:"dataops",operationId:L,orgId:r,outcome:"stopped",code:w.refused.code}),this.requestLog.record(n,r,{kind:"erased",at:new Date().toISOString(),mode:o,outcome:"stopped",operationId:L,objects:[]}),E(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(w.refused.message),{code:w.refused.code,...k?Oa(k):{}});return}let I=w.held,P={},b=async()=>{if(!(!I||P.back)){P.back=await I.release();for(let L of Xt(P.back,h))this.deps.log(`[INFO] ${L}`)}},S=o==="anonymize"?ob({query:async L=>m.query(L),serverTime:async()=>(await m.soap.getServerTimestamp()).timestamp},nb(R.answer.automation,f.map(L=>L.objectApiName)),{settleMs:this.duplicatesSettleMs}):void 0,C={},v=async()=>{await b(),!C.read&&(C.read=!0,C.duplicates=await S?.read())},T=()=>ib(C.duplicates,h,"erasure"),D=()=>I?{mutedAutomation:P.back??I.outcome}:{},z=new Tb(void 0,this.maskingKey),H=await ic(this.deps,{orgId:r,operation:o==="delete"?"delete":"update",objectNames:p.map(L=>L.objectApiName),recordCount:g,action:"subject_erase",description:`Erase ${g} record(s) of a subject request`,origin:"dataops:dsr:erase",run:(L,ee)=>CO(S?Jx(c,S):c,z,l,L,ee),beforeEnd:v},this.liveTracker).finally(b),Y=new Date().toISOString();if(!H.ran){this.requestLog.record(n,r,{kind:"erased",at:Y,mode:o,outcome:"stopped",operationId:H.operationId,objects:[]}),E(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(H.message),{...H.code?{code:H.code}:{},extraPayload:D()});return}this.requestLog.record(n,r,{kind:"erased",at:Y,mode:o,outcome:H.outcome.status,operationId:H.operationId,objects:H.outcome.objects});let{duplicates:U}=C;if(H.error!==void 0){let L=T();E(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(L?`${H.error} ${L}`:H.error),{...H.cancelled?{code:nt}:{},extraPayload:{...D(),...U?{duplicates:U}:{}}});return}let M=A(this.deps,e,"dataops:dsr:erase:response",{requestId:n,mode:o,dryRun:i,plan:u,outcome:H.outcome,...D(),...U?{duplicates:U}:{}});this.deps.broker.postToWebview(M),this.deps.log(`[TX] ${M.type} id=${M.id} ${H.outcome.status} done=${H.outcome.done} failed=${H.outcome.failed}`),sb(U)&&Ie(this.deps,"warning","Erase",T())}catch(a){E(this.deps,"dataops:dsr:erase","dataops:error",e,a)}}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){E(this.deps,"dataops:dsr:log","dataops:error",e,t)}}};var Xx=new Set(["User","Group","RecordType","BusinessHours","Profile","UserRole"]);function FO(s){return s.type==="reference"&&hu(s)&&s.nillable===!0&&s.filterable===!0&&s.referenceTo?.length===1&&!Xx.has(s.referenceTo[0])}function _O(s,e){return e>0&&s/e>=.9}async function Kx(s,e,t){let r,n,o;try{if(r=nr.parse(await s.describe(qe(e.objectApiName))),n=qe(r.name),r.queryable===!1)throw new Error(`${n} cannot be queried.`);o=(await s.query(`SELECT COUNT() FROM ${n}`)).totalSize}catch(p){return{status:"failed",objectApiName:e.objectApiName,message:O(p)}}let i=r.fields.filter(mu).sort((p,g)=>p.label.localeCompare(g.label)),a=r.fields.filter(FO),d=[...a,...r.fields.filter(p=>hu(p)&&!a.includes(p))],[c,l,u]=await Promise.all([uw(s,n,d,o),pw(s,n,i,e.duplicateKey,o),gw(s,n,r.fields,t,o)]),f=c.fields.filter(p=>a.some(g=>g.name===p.fieldApiName)&&_O(p.filled,o)&&p.filled<o).map(p=>{let g=a.find(h=>h.name===p.fieldApiName);return{fieldApiName:p.fieldApiName,label:p.label,referenceTo:g?.referenceTo?.[0]??"",filled:p.filled,empty:o-p.filled}}).sort((p,g)=>g.empty-p.empty||p.label.localeCompare(g.label));return{status:"scanned",objectApiName:e.objectApiName,label:r.label,totalRecords:o,fields:c.fields,unmeasured:c.unmeasured,stale:u.stale,orphans:f,duplicates:l.duplicates,keyFields:i.map(p=>({fieldApiName:p.name,label:p.label})),errors:[...c.errors,...l.errors,...u.errors],deletable:r.deletable===!0}}async function UO(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 Kx(s,o,e.staleDays));return{orgId:e.orgId,staleDays:e.staleDays,scannedAt:r,orphanThreshold:.9,bounds:{duplicateGroupLimit:dw,duplicateSample:cw,singleFieldQueries:lw},objects:n}}function Yx(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 Yp(s,e,t,r){let n=(s?.skip??0)+e;return e>0&&n<t?{skip:n,...r}:void 0}function jO(s){return s.flatMap(e=>{let t=typeof e=="object"&&e!==null?e.Id:void 0;return Vr(t)?[t]:[]})}function Qx(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"?`'${er(e)}'`:void 0}}function Zx(s,e){let t=String(e??"");return typeof e=="string"&&s!=="date"?t.toLowerCase():t}var MO=100,eD=2e3;async function tD(s,e,t,r){let n=qe(e.name),o=qe(t.name),i=await fw(s,n,t.name),a=i.rows.reduce((u,f)=>u+f.count-1,0),d=i.rows.map(u=>Qx(t.type,u.value));if(d.some(u=>u===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(u=>u.name==="LastModifiedDate"),l=[];for(let u=0;u<d.length&&l.length<r;u+=MO){let f=d.slice(u,u+MO).join(", "),p=await s.query(`SELECT Id, ${o}${c?", LastModifiedDate":""} FROM ${n} WHERE ${o} IN (${f}) ORDER BY Id LIMIT ${eD}`),g=new Map;for(let h of p.records){if(typeof h!="object"||h===null)continue;let m=h;if(!Vr(m.Id))continue;let y=Zx(t.type,m[t.name]),R=g.get(y)??[];R.push({id:m.Id,modified:typeof m.LastModifiedDate=="string"?m.LastModifiedDate:""}),g.set(y,R)}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(l.length>=r)break;l.push(m.id)}}}return{total:a,ids:l}}async function Qp(s,e,t,r,n){let o=nr.parse(await s.describe(qe(e))),i=qe(o.name),a=p=>o.fields.find(g=>g.name.toLowerCase()===p.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 p=`LastModifiedDate < LAST_N_DAYS:${t.days}`,g=(await s.query(`SELECT COUNT() FROM ${i} WHERE ${p}`)).totalSize,h=n?.modified!==void 0?Yx(n.modified):void 0,m=h!==void 0&&n?.id!==void 0&&Vr(n.id)?` AND (LastModifiedDate > ${h} OR (LastModifiedDate = ${h} AND Id > '${n.id}'))`:"",y=await s.query(`SELECT Id, LastModifiedDate FROM ${i} WHERE ${p}${m} ORDER BY LastModifiedDate, Id LIMIT ${r}`),R=jO(y.records),k=y.records.at(-1),w=Yp(n,R.length,g,{id:R.at(-1),...typeof k?.LastModifiedDate=="string"?{modified:k.LastModifiedDate}:{}});return{object:o,total:g,ids:R,truncated:(n?.skip??0)+R.length<g,...w?{next:w}:{}}}if(t.kind==="orphans"){let p=a(t.fieldApiName);if(!p||!FO(p))throw new Error(`${t.fieldApiName} is not a lookup of ${o.label} that can leave a record without its parent.`);let g=qe(p.name),h=(await s.query(`SELECT COUNT() FROM ${i}`)).totalSize,m=(await s.query(`SELECT COUNT() FROM ${i} WHERE ${g} = null`)).totalSize;if(!_O(h-m,h))throw new Error(`${p.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&&Vr(n.id)?` AND Id > '${n.id}'`:"",R=await s.query(`SELECT Id FROM ${i} WHERE ${g} = null${y} ORDER BY Id LIMIT ${r}`),k=jO(R.records),w=Yp(n,k.length,m,{id:k.at(-1)});return{object:o,total:m,ids:k,truncated:(n?.skip??0)+k.length<m,...w?{next:w}:{}}}let d=a(t.keyField);if(!d||!mu(d))throw new Error(`${t.keyField} is not a field ${o.label} records can be grouped by.`);let c=n?.skip??0,l=await tD(s,o,d,c+r),u=l.ids.slice(c),f=Yp(n,u.length,l.total,{});return{object:o,total:l.total,ids:u,truncated:c+u.length<l.total,...f?{next:f}:{}}}var rD=6e4,nD=new Set(["dataops:cleanup:scan","dataops:cleanup:export","dataops:cleanup:delete"]);function BO(s){switch(s.kind){case"stale":return`stale-${s.days}d`;case"orphans":return`orphans-${s.fieldApiName}`;default:return`duplicates-${s.keyField}`}}var lc=class{constructor(e,t){this.deps=e;this.saveDialog=t??new kn}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-QO4MPHZD.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 da(r,t)}async handle(e){if(!nD.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=$($m,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:cleanup:scan"),n=await UO(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){E(this.deps,"dataops:cleanup:scan","dataops:error",e,r)}}async handleExport(e){let t=$(Lm,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:cleanup:export"),n=await Qp(r,t.objectApiName,t.recommendation,1e3,t.after),o=await bn(r,n.object.name,n.object.fields.map(l=>l.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}-${BO(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){E(this.deps,"dataops:cleanup:export","dataops:error",e,r)}}async handleDelete(e){let t=$(Fm,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 Qp(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 b=await la(i,d,c,await ca(i)),S={objectApiName:d.name,label:d.label,records:c.length,related:b.related,uncounted:b.uncounted},C=A(this.deps,e,"dataops:cleanup:delete:response",{objectApiName:t.objectApiName,dryRun:o,plan:S,truncated:a.truncated,written:ac([S])});this.deps.broker.postToWebview(C),this.deps.log(`[TX] ${C.type} id=${C.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 l=await B(r,this.deps.orgRegistry,this.deps.orgManager),u=he(this.deps.orgManager.getOrg(r),r),f=this.targetAutomation,p=ka(t),g=await Kr({act:"cleanup",target:u,objects:[{objectApiName:d.name,records:c.length}],org:xo(l,b=>new fe(rD).withTimeout("dataops automation",()=>f.read(r,b)),Ee(this.deps.orgManager.getOrg(r))==="production"),accord:t,mayMute:!0,muteLeases:this.muteLeases,...p?{voice:p}:{}}),h=On(g.answer);if(h){E(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(h.message),{code:h.code,...Oa(h)});return}let m=await Qn(g,e.id,t.acceptEmails===!0,p);if("refused"in m){E(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(m.refused.message),{code:m.refused.code});return}let y=m.held,R={},k=async()=>{if(!(!y||R.back)){R.back=await y.release();for(let b of Xt(R.back,u))this.deps.log(`[INFO] ${b}`)}},w={objectApiName:d.name,label:d.label,records:c.length},I=await ic(this.deps,{orgId:r,operation:"delete",objectNames:[d.name],recordCount:c.length,action:"cleanup_delete",description:`Delete ${c.length} ${d.name} record(s): ${BO(n)}`,origin:"dataops:cleanup:delete",run:async(b,S)=>{let C=await ua(i,d.name,c,S);return b(d.name,C),[{objectApiName:d.name,counts:C}]},beforeEnd:k},this.liveTracker).finally(k);if(!I.ran){E(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(I.message),I.code?{code:I.code}:void 0);return}if(I.error!==void 0){E(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(I.error),I.cancelled?{code:nt}:void 0);return}let P=A(this.deps,e,"dataops:cleanup:delete:response",{objectApiName:t.objectApiName,dryRun:o,plan:w,truncated:a.truncated,outcome:I.outcome,...y?{mutedAutomation:R.back??y.outcome}:{}});this.deps.broker.postToWebview(P),this.deps.log(`[TX] ${P.type} id=${P.id} ${I.outcome.status} deleted=${I.outcome.done} failed=${I.outcome.failed}`)}catch(i){E(this.deps,"dataops:cleanup:delete","dataops:error",e,i)}}};import{join as iN}from"node:path";async function qO(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(u=>({objectApiName:u,reason:"permissionsUnread",detail:n.unread}))};let o=await s.describe(t),i={grants:n.grants,describes:o,...s.customSettings?{customSettings:s.customSettings}:{}},a=$b(t,i),d=a.length>0?[...o,...await s.describe(a)]:o,c=xb(t,{...i,describes:d}),l=[];for(let[u,f]of c)"access"in f||l.push({objectApiName:u,reason:f.reason,...f.detail!==void 0?{detail:f.detail}:{}});return{...r,unseen:l}}function WO(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 oD=1e4,GO={bulkDestroy:()=>Promise.reject(new Error("an estimate sends no job"))};function Zp(s){return Ms(GO,s,1,"hard")}var JO=9,sD=25;function VO(s,e,t){let r=e>0&&Ms(GO,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/Bt),jobs:[],toTheBin:!0};let n=Math.ceil(e/js),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 xr(s,e){return{apiRequests:s,seconds:s*e}}function fi(s){return s.reduce((e,t)=>({apiRequests:e.apiRequests+t.apiRequests,seconds:e.seconds+t.seconds}),{apiRequests:0,seconds:0})}function XO(s){return Math.max(1,Math.ceil(s/ku))}function KO(s){return s.notSent?{apiRequests:0,seconds:0}:fi([xr(XO(s.records),Zn),xr(1,Hs),xr(s.restCalls,Ca),...s.jobs.map(e=>({apiRequests:ww({stateReads:Rw(e)}),seconds:bw(e)}))])}function iD(s){return s<=0?{apiRequests:0,seconds:0}:fi([xr(1,Hs),xr(Math.ceil(s/ku),Zn),xr(Math.ceil(s/Bt),Ca),xr(Math.ceil(s/Bt),Zn)])}function aD(s){if(s<=0)return{apiRequests:0,seconds:0};let e=Math.ceil(s/Bt);return fi([xr(e,Ca),xr(e,Zn)])}var dD=.05,zO={check:2,connect:3};function uc(s,e,t,r=0){let n=t*zO.check+zO.connect,o=t*e+n+s.apiRequests+r,i=Math.ceil(o*dD);return{apiRequests:o+i,seconds:e*Hs+s.seconds,requests:{reads:e,readings:t,passes:s.apiRequests,margin:i,connecting:n,...r>0?{mute:r}:{}}}}function YO(s){let e=s.passes.map(({objectApiName:d,records:c})=>VO(d,Math.max(0,c),s.mode)),t=fi([iD(s.toDraft),xr(s.draftReads??0,Zn),...e.map(KO),...(s.refused??[]).map(aD)]),r=uc(t,Math.max(0,s.reads),s.readings??2),n=e.reduce((d,c)=>d+c.jobs.reduce((l,u)=>l+Math.ceil(u/oD),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*sD,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:In(r.apiRequests,s.apiBudget),...a?{batches:s.bulkBatches?In(n,s.bulkBatches):{verdict:"unread",estimate:n,unread:"the limits the org answered list no DailyBulkApiBatches"}}:{}}}function QO(s,e,t,r=0){let n=fi(e.map(o=>{let i=VO(o.objectApiName,Math.max(0,o.records),s),a=KO(i);if(!o.idsRead||i.notSent)return a;let d=XO(i.records);return{apiRequests:a.apiRequests-d,seconds:a.seconds-d*Zn}}));return uc(n,Math.max(0,t),1,Math.max(0,r)).apiRequests}var ef=3;function ZO(s,e,t=0){return uc({apiRequests:Math.max(0,s),seconds:0},Math.max(0,e),1,Math.max(0,t)).apiRequests}function eI(s,e,t,r=0){let n={apiRequests:s.requests.passes,seconds:s.seconds-s.requests.reads*Hs},o=uc(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:In(o.apiRequests,i)}}var cD=Cb.extend({relationshipName:j().nullish(),polymorphicForeignKey:Ge().optional()}),tI=xa.extend({deletable:Ge().optional(),fields:ve(cD)});function tf(s){return kb.has(s)}var rI={pricebook2:{field:"IsStandard",value:!0}};function nI(s){let e=rI[s.toLowerCase()];return e?`${e.field} = ${String(e.value)}`:void 0}function oo(s){let e=rI[s.toLowerCase()];return e?`${e.field} = ${String(!e.value)}`:void 0}var lD=new Set(["pricebook2","product2"]);function oI(s,e){return e!==void 0&&s.childSObject!==void 0&&s.field!==void 0&&Pb(s.childSObject,s.field,e)?"restricted":s.cascadeDelete===!0?"cascade":s.restrictedDelete===!0?"restricted":"lookup"}function rf(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)?pc(s,i,o.field):void 0;sI(a,r)||t.push({parent:r,child:e(o.childSObject),field:o.field,kind:oI(o,r)})}return t}var gi=5,uD=8;function sI(s,e){if(s?.polymorphicForeignKey===!0)return!1;let t=s?.referenceTo??[];return t.length>0&&!t.some(r=>r.toLowerCase()===e.toLowerCase())}function pD(s,e,t){let r=pc(s,e,t);return(r?.referenceTo?.length??0)>1||r?.polymorphicForeignKey===!0}function nf(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,l=new Set,u=(g,h)=>{let m=c.get(g)??new Set;m.add(h),c.set(g,m)},f=s.map(g=>({top:g,from:g,above:[]}));for(;f.length>0;){let g=[];for(let{top:h,from:m,above:y}of f){let R=o(m);if(!R){l.add(m);continue}for(let k of R.childRelationships??[]){if(oI(k,m)!=="cascade")continue;let w=n(k.childSObject),P=o(w)?.fields.find(v=>v.name.toLowerCase()===k.field.toLowerCase());if(sI(P,m))continue;let b=w.toLowerCase();if(!a.has(b)||b===m.toLowerCase()||y.some(v=>v.object.toLowerCase()===b))continue;let S=[{object:w,field:k.field,parent:m},...y],C=d.get(w)??[];if(S.length>1&&C.length>=uD){u(w,m);continue}d.set(w,[...C,{object:w,steps:S,emptied:h}]),!(i.has(b)||S.length>=gi)&&g.push({top:h,from:w,above:S})}}f=g}for(let g=!0;g;){g=!1;for(let[h,m]of d)for(let y of m)for(let[R,k]of y.steps.entries())R===0||!c.has(k.object)||y.steps.slice(0,R).some(I=>pD(t,I.object,I.field))||c.get(h)?.has(k.object)||(u(h,k.object),g=!0)}let p=[...d.keys()].filter(g=>!i.has(g.toLowerCase())).sort();return{emptied:new Set(s),routes:d,along:p,routesCut:new Map([...c].map(([g,h])=>[g,[...h].sort()])),undescribed:[...l].filter(g=>!i.has(g.toLowerCase())).sort()}}function es(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 fD(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 pc(s,e,t){let r=t.toLowerCase();return s.get(e)?.fields.find(n=>n.name.toLowerCase()===r)}function fc(s,e,t=oo,r=()=>{}){let n=[],o=(i,a,d,c)=>fD({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=pc(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,l=d.relationshipName??void 0,u=i===s.length-1,f=l?[...n,l].join("."):void 0,p=[...n,d.name].join(".");if(c)return f?o(`${f}.Type = '${a.parent}'`,u,p,a.parent):o(`${p} != null`,!1,p,a.parent);if(u){let g=t(a.parent);if(g===void 0&&!lD.has(a.parent.toLowerCase()))return o(`${p} != null`,!0,p,a.parent);if(!f)return o(`${p} != null`,!1,p,a.parent);let h=g!==void 0?` AND ${f}.${g}`:"";return o(`${f}.Id != null${h}`,!0,p,a.parent)}if(!l||i+1>=gi)return o(`${p} != null`,!1,p,a.parent);n.push(l)}}function iI(s,e,t){let r=[];for(let[n,o]of s.entries()){let i=e.has(o.object)?pc(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>=gi)return;r.push(i.relationshipName)}}function hi(s,e,t=oo,r){let n=s.map(a=>fc(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 aI(s,e,t,r,n,o=oo,i){let a={object:s,field:e,parent:t};if(r.emptied.has(t))return fc([a],n,o,i);let d=(r.routes.get(t)??[]).map(c=>({object:s,steps:[a,...c.steps],emptied:c.emptied}));return hi(d,n,o,i)}var lI=4,dI=100,gD=/^[A-Za-z0-9]+$/;function cI(s,e){let t=oo(s);if(t!==void 0)return t;if(e&&s.toLowerCase()===gr.toLowerCase())return`${Bs} = false`}var co="stopped before the org was asked";function uI(s,e,t="COUNT()"){let r=tf(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 ${qe(s)}${o}`,all:r}}var ao=class{statements=new Map;answers=new Map;ask(e,t){let r=uI(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 Ns([...this.statements].map(([n,{soql:o,all:i,atMost:a}])=>async()=>{if(t()){r=!0,this.answers.set(n,{unread:co});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:O(d)})}}),lI),r}answer(e){return this.answers.get(e)??{unread:co}}},mc=class{statements=new Map;answers=new Map;ask(e,t){let r=uI(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 Ns([...this.statements].map(([n,o])=>async()=>{if(t()){r=!0,this.answers.set(n,{counted:{unread:co}});return}try{let i=await e.readIds(n,o),a=i.ids.filter(d=>gD.test(d));this.answers.set(n,{counted:{records:i.totalSize},...a.length===i.totalSize?{ids:a}:{}})}catch(i){this.answers.set(n,{counted:{unread:O(i)}})}}),lI),r}answer(e){return this.answers.get(e)??{counted:{unread:co}}}};function af(s,e){return s.records===void 0?s:e.records===void 0?{unread:e.unread??co}:{records:Math.max(0,s.records-e.records),...e.atMost?{atLeast:!0}:{}}}function of(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 Nn(s){return s.records===0&&s.atLeast!==!0}function so(s){return s===void 0||s.records===void 0||s.records>0}function hc(s){return{unread:`${s}: the lookup its records go by is hidden from the user`}}function df(s){return s.records===void 0?s:{...s,atLeast:!0}}function mi(s){return s.records===void 0?s:{...s,atMost:!0}}function sf(s,e){let t=e.key?s.answer(e.key):hc(e.objectApiName),r=e.going?af(t,s.answer(e.going)):t,n=(r.records??0)>0;return e.more&&n&&(r={...r,atLeast:!0}),e.under&&n&&(r=df(r)),e.over&&n&&(r=mi(r)),r}function cf(s,e){return s.every(t=>e.get(t.emptied)!=="unnamed"&&t.steps.every(r=>e.get(r.parent)!=="unnamed"))}function hD(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 io(s){let e=s.filter(n=>n.records!==void 0);if(e.length===0)return s.length===0?{records:0}:{unread:s[0].unread??co};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 gc="Pricebook2";function mD(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 pI(s,e,t=()=>!1,r={undo:!0}){let{affected:n,order:o,relations:i,describes:a}=s,d=o.passes.map(x=>x.objectApiName),c=a.get(gr)?.fields.some(x=>x.name===Bs)===!0,l=x=>{let N=cI(x,c);if(!(x.toLowerCase()===gr.toLowerCase()&&n.emptied.has(Oo)))return N},u=x=>{let N=l(x);return N===void 0?[]:[N]},f=new Map,p=x=>f.get(x),g=x=>p(x),h=x=>fc(x,a,l,g),m=x=>hi(x,a,l,g),y=(x,N,X)=>aI(x,N,X,n,a,l,g),R=new ao,k=new Map;for(let x of d)k.set(x,R.ask(x,u(x)));let w=await R.run(e,t),I=new Map(d.map(x=>[x,R.answer(k.get(x)??"")])),P=x=>[...es(x,n)].some(N=>so(I.get(N))),b=x=>x.filter(N=>so(I.get(N.emptied))),S=x=>!n.emptied.has(x)&&n.routesCut.has(x),C=new ao,v=[];for(let{parent:x,child:N,field:X,kind:F}of i){if(F!=="restricted"||N===x||n.emptied.has(N)||!P(x))continue;let de=y(N,X,x),J=n.routes.has(N)?m(b(n.routes.get(N)??[])):void 0;v.push({objectApiName:N,field:X,parent:x,...de?{key:C.ask(N,[de])}:{},...de&&J?{going:C.ask(N,[J,de])}:{},...J&&S(N)?{over:!0}:{},...n.emptied.has(x)&&!n.routes.has(N)?{naming:""}:{}})}for(let{child:x,field:N,parent:X,rows:F}of Iu){if(F===void 0||!P(X)||n.emptied.has(x)||!n.routes.has(x))continue;let J=a.get(x)?.fields.some(Pe=>Pe.name===F.field)===!0?y(x,N,X):void 0;if(!J)continue;let le=`${F.field} = ${String(F.value)}`;v.push({objectApiName:x,field:N,parent:X,key:C.ask(x,[le,J]),along:!0,...n.emptied.has(X)?{naming:le}:{}})}w=await C.run(e,t)||w;let T=new mc,D=new Map,z=new Map;v.forEach((x,N)=>{if(x.naming===void 0||x.key===void 0||(sf(C,x).records??0)===0)return;let X=`Id IN (SELECT ${qe(x.field)} FROM ${qe(x.objectApiName)}${x.naming!==""?` WHERE ${x.naming}`:""})`;D.set(N,T.ask(x.parent,[...u(x.parent),X])),z.set(x.parent,[...z.get(x.parent)??[],X])}),w=await T.run(e,t)||w;for(let x of z.keys()){let N=[...D].filter(([F])=>v[F].parent===x).map(([,F])=>T.answer(F));if(N.every(F=>F.counted.records===0))continue;let X=new Set(N.flatMap(F=>F.ids??[]));f.set(x,N.every(F=>F.ids!==void 0)&&X.size<=dI?[...X]:"unnamed")}let H=x=>{let N={archived:new Map,kept:new Map,goneBefore:new Map,along:new Map,refusals:[],undoLost:[]};for(let J of o.passes){let le=J.objectApiName;if(!so(I.get(le)))continue;let Pe=u(le);tf(le)&&N.archived.set(le,x.ask(le,[...Pe,"IsArchived = true"]));let je=nI(le);je!==void 0&&N.kept.set(le,x.ask(le,[je]));let We=b(J.goneBefore);if(We.length>0){let Re=m(We);N.goneBefore.set(le,Re?{key:x.ask(le,[...Pe,Re]),unreadable:!1}:{unreadable:!0})}let ae=r.undo?b(J.sentBeforeTheirParent):[];for(let Re of ae){let Ue=h(Re.steps),He=Re.steps[0],st=Ue?[...Pe,Ue]:void 0;N.undoLost.push({objectApiName:le,field:He.field,parent:He.parent,reason:"unordered",...st?{key:x.ask(le,st),conditions:st}:{}})}}for(let J of n.along){let le=b(n.routes.get(J)??[]);if(le.length===0)continue;let Pe=le.map(We=>{let ae=h(We.steps);return{route:We,...ae?{key:x.ask(J,[ae])}:{}}}),je=le.length>1?m(le):void 0;N.along.set(J,{...je?{total:x.ask(J,[je])}:Pe[0].key?{total:Pe[0].key}:{},via:Pe})}let X=J=>o.passes.findIndex(le=>le.objectApiName===J);for(let J of r.undo?o.beforeParent:[]){if(J.reason==="customPrices"){if(!P(gc)||!P(J.parent)||X(gc)>X(J.parent))continue;let We=y(J.objectApiName,"Pricebook2Id",gc),ae=y(J.objectApiName,J.field,J.parent),Re=We&&ae?[We,ae]:void 0;N.undoLost.push({objectApiName:J.objectApiName,field:J.field,parent:J.parent,reason:"restricted",...Re?{key:x.ask(J.objectApiName,Re),conditions:Re}:{},...S(gc)||S(J.parent)?{under:!0}:{}});continue}if(!P(J.objectApiName)||!P(J.parent))continue;let le=y(J.objectApiName,J.field,J.parent),Pe=[];if(!n.emptied.has(J.objectApiName)){let We=m(b(n.routes.get(J.objectApiName)??[]));We&&Pe.push(We)}let je=S(J.objectApiName)||S(J.parent);N.undoLost.push({objectApiName:J.objectApiName,field:J.field,parent:J.parent,reason:"restricted",...le?{key:x.ask(J.objectApiName,[...Pe,le]),conditions:[...Pe,le]}:{},...je?{under:!0}:{}})}for(let{child:J,field:le,parent:Pe,rows:je}of Iu){if(je===void 0||!P(Pe)||!n.emptied.has(J))continue;let ae=a.get(J)?.fields.some(Ue=>Ue.name===je.field)===!0?y(J,le,Pe):void 0;if(!ae||!r.undo||!so(I.get(J)))continue;let Re=`${je.field} = ${String(je.value)}`;N.undoLost.push({objectApiName:J,field:le,parent:Pe,reason:"restricted",key:x.ask(J,[Re,ae]),conditions:[Re,ae],more:!0})}let F=(J,le,Pe,je=!1)=>{N.refusals.push({code:J,objectApiName:le,key:x.ask(le,Pe),...je?{under:!0}:{}})};for(let J of o.toDraft){if(!P(J))continue;let le="StatusCode != 'Draft'";if(n.emptied.has(J)){F("activatedOrder",J,[le]);continue}let Pe=b(n.routes.get(J)??[]),je=m(Pe);F(cf(Pe,f)?"activatedOrder":"activatedOrderLeft",J,je?[je,le]:[{soql:le,exact:!1}],je!==void 0&&S(J))}for(let[J,le]of N.kept)N.refusals.push({code:"standardPriceBook",objectApiName:J,key:le});n.emptied.has(Ki)&&so(I.get(Ki))&&(n.emptied.has(gr)||F("directContactRelation",Ki,[{soql:"IsDirect = true",exact:!n.routes.has(gr)}]));let de=a.get(gr);return n.emptied.has(gr)&&!n.emptied.has(Oo)&&so(I.get(gr))&&de?.fields.some(J=>J.name===Bs)===!0&&F("personAccountContact",gr,[`${Bs} = true`]),N},Y=new mc,U=new Map;if(f.size>0){let x=new Set;p=N=>(n.emptied.has(N)||x.add(N),f.get(N)),H(new ao),p=N=>f.get(N);for(let N of[...x].sort()){let X=b(n.routes.get(N)??[]),F=X.filter(le=>f.has(le.emptied));if(F.length===0)continue;let de=f.get(F[0].emptied),J=X.length===1&&Array.isArray(de)?iI(X[0].steps,a,de):void 0;J===void 0?f.set(N,"unnamed"):U.set(N,Y.ask(N,[J]))}w=await Y.run(e,t)||w;for(let[N,X]of U){let F=Y.answer(X);f.set(N,F.ids!==void 0&&F.ids.length<=dI?F.ids:"unnamed")}}let M=new ao,L=H(M);w=await M.run(e,t)||w;let ee=x=>sf(M,x),Q=new ao,q=new Map;for(let[x,N]of z)N.length===2&&f.get(x)==="unnamed"&&q.set(x,Q.ask(x,[...u(x),...N]));let V=new Map,we=new Map;for(let x of L.undoLost)we.set(x.objectApiName,[...we.get(x.objectApiName)??[],x]);for(let[x,N]of we){let X=N.filter(de=>!Nn(ee(de)));if(X.length<2)continue;let F=X.map(de=>de.conditions);F.some(de=>de===void 0)||V.set(x,Q.ask(x,[hD(F)]))}w=await Q.run(e,t)||w;let ie=v.map((x,N)=>{let X=D.get(N);return{objectApiName:x.objectApiName,field:x.field,parent:x.parent,records:sf(C,x),...X!==void 0?{keeps:T.answer(X).counted}:{}}}).filter(x=>!Nn(x.records)),re=x=>{let N=ie.flatMap(J=>J.parent===x&&J.keeps!==void 0?[J.keeps]:[]);if(N.length===0)return;let X=f.get(x);if(Array.isArray(X))return{records:X.length};let F=io(N),de=q.get(x);return de!==void 0?of(F,Q.answer(de)):N.length>1&&(F.records??0)>0?mi(F):F},Ae=ie.filter(x=>!Array.isArray(f.get(x.parent))&&v.some(N=>N.along===!0&&N.objectApiName===x.objectApiName&&N.field===x.field&&N.parent===x.parent)),me=ie.filter(x=>v.some(N=>N.along===!0&&N.objectApiName===x.objectApiName&&N.field===x.field&&N.parent===x.parent)),Je=o.passes.map(x=>{let N=x.objectApiName,X=cI(N,c),F=I.get(N)??{unread:co};if(!so(F))return{objectApiName:N,...X!==void 0?{rows:X}:{},records:F,sent:F};let de=L.goneBefore.get(N),J=de===void 0?F:de.unreadable||de.key===void 0?hc(N):n.routesCut.has(N)?mi(af(F,M.answer(de.key))):af(F,M.answer(de.key)),le=L.archived.get(N),Pe=L.kept.get(N),je=re(N);return{objectApiName:N,...X!==void 0?{rows:X}:{},records:F,sent:J,...le?{archived:M.answer(le)}:{},...Pe?{kept:M.answer(Pe)}:{},...je&&!Nn(je)?{blocked:je}:{}}}),Ne=r.undo?Je.filter(x=>a.get(x.objectApiName)?.undeletable===!1&&!Nn(x.sent)).map(x=>({objectApiName:x.objectApiName,reason:"notRestorable",records:x.sent})):[],Fe=[...L.along].map(([x,{total:N,via:X}])=>{let F=N?M.answer(N):hc(x),de=n.routesCut.get(x),J=Ae.filter(ae=>ae.objectApiName===x),le=me.filter(ae=>ae.objectApiName===x),Pe=J.length>0?io(J.map(ae=>ae.records)):void 0,je=le.length>0?io(le.map(ae=>ae.records)):void 0,We=Pe?of(F,Pe):F;return{objectApiName:x,records:de?df(We):We,via:X.map(({route:ae,key:Re})=>{let Ue=Re?M.answer(Re):hc(x),He=ae.steps[0],st=J.filter(Ve=>Ve.field===He.field&&Ve.parent===He.parent);return{field:He.field,parent:He.parent,emptied:ae.emptied,records:st.length>0?of(Ue,io(st.map(Ve=>Ve.records))):Ue}}).filter(ae=>!Nn(ae.records)),...je&&!Nn(je)?{blocking:je}:{},...de?{routesNotRead:[...de]}:{}}}).filter(x=>!Nn(x.records)),W=(x,N)=>x.map(X=>({...N(X),records:ee(X)})).filter(X=>!Nn(X.records)),se=mD([...W(L.undoLost,x=>({objectApiName:x.objectApiName,...x.field!==void 0?{field:x.field}:{},...x.parent!==void 0?{parent:x.parent}:{},reason:x.reason})),...Ne]),te=new Map;for(let x of se)te.set(x.objectApiName,[...te.get(x.objectApiName)??[],x]);let ue=io([...te].map(([x,N])=>{let X=V.get(x),F=N.filter(J=>J.reason==="notRestorable");if(X===void 0){let J=io(N.map(le=>le.records));return N.length>1&&(J.records??0)>0?mi(J):J}let de=Q.answer(X);return N.some(J=>J.reason!=="notRestorable"&&J.records.atLeast)&&(de.records??0)>0&&(de=df(de)),F.length>0?mi(io([de,...F.map(J=>J.records)])):de}));return{objects:Je,along:Fe,refusals:W(L.refusals,x=>({code:x.code,objectApiName:x.objectApiName})),blockers:ie,undoLost:se,undoLostRecords:ue,kept:f,statements:R.size+C.size+T.size+Y.size+M.size+Q.size,...w?{stopped:!0}:{}}}var hI={lookup:0,cascade:1,restricted:2,customPrices:2},fI="Pricebook2",lf="Product2",gI="PricebookEntry";function yD(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 es(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=es(i,s),l=s.emptied.has(i)?[i]:[...c],u=!1;for(let f of es(o,s))if(!c.has(f))for(let p of l)p!==f&&(t.push({first:p,then:f,reason:"restricted"}),u=!0);u&&r.push({objectApiName:i,field:a,parent:o,reason:"restricted"})}return s.emptied.has(fI)&&s.emptied.has(lf)&&(t.push({first:fI,then:lf,reason:"customPrices"}),n(gI)&&r.push({objectApiName:gI,field:"Product2Id",parent:lf,reason:"customPrices"})),{constraints:t,beforeParent:r}}function wD(s){return Object.hasOwn(hI,s)}function mI(s,e){let{constraints:t,beforeParent:r}=yD(s,e),n=[...s.emptied].sort(),o=new Map(n.map(u=>[u,[]]));for(let{first:u,then:f,reason:p}of t)p==="cascade"?o.get(u)?.push({childSObject:f,field:p,cascadeDelete:!0}):o.get(f)?.push({childSObject:u,field:p});let i=new Map(n.map(u=>[u,{name:u,fields:[],childRelationships:o.get(u)??[]}])),a=Ah(n,i,({field:u})=>{let f=wD(u)?u:"lookup";return{first:f==="cascade"?"parent":"child",firmness:hI[f]}}),d=new Map(a.map((u,f)=>[u,f])),c=(u,f)=>(d.get(u)??0)<(d.get(f)??0);return{passes:a.map(u=>{let f=s.routes.get(u)??[];return{objectApiName:u,goneBefore:f.filter(p=>c(p.emptied,u)),sentBeforeTheirParent:f.filter(p=>!c(p.emptied,u))}}),beforeParent:r,unordered:bD(t.filter(({first:u,then:f})=>!c(u,f))),toDraft:or([...n,...s.along])}}function bD(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 RD(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 vD=(s,e,t)=>{let r=Ib(s,e,"empty",t.customSettings?{customSettings:Oh}:{});return{candidates:r.candidates,leftOut:r.leftOut.map(({objectApiName:n,reason:o,detail:i})=>({objectApiName:n,reason:RD(o),...i===void 0?{}:{detail:i}}))}},SD=new Set([Sh,kh].map(s=>s.toLowerCase()));function yI(s,e){return s.objectApiName<e.objectApiName?-1:s.objectApiName>e.objectApiName?1:0}function kD(s,e){if(s.customSetting===!0&&e.customSettings!==!0)return"customSetting";if(SD.has(s.name.toLowerCase())&&e.files!==!0)return"files";if(Ih(s.name)!==void 0&&e.managedPackages!==!0)return"managedPackage";if(s.undeletable===!1&&e.unrestorable!==!0)return"notRestorable"}function yc(s,e,t,r=vD){let n=r(s,e,{customSettings:!0}),o=new Map(s.map(u=>[u.name.toLowerCase(),u])),i=new Set(n.candidates.map(u=>u.toLowerCase())),a=new Map(n.leftOut.map(u=>[u.objectApiName.toLowerCase(),u])),d=[],c=[],l=u=>{let f=a.get(u.name.toLowerCase());return f?{...f,objectApiName:u.name}:{objectApiName:u.name,reason:"notDeletable"}};if(t.mode==="objects"){let u=new Set;for(let f of t.objects??[]){let p=f.toLowerCase();if(u.has(p))continue;u.add(p);let g=o.get(p);g?i.has(p)?d.push(g.name):c.push(l(g)):c.push({objectApiName:f,reason:"notFound"})}}else{let u=new Set((t.excluded??[]).map(f=>f.toLowerCase()));for(let f of t.excluded??[])o.has(f.toLowerCase())||c.push({objectApiName:f,reason:"notFound"});for(let f of o.values()){let p=f.name.toLowerCase();if(u.has(p)){c.push({objectApiName:f.name,reason:"excludedByUser"});continue}if(!i.has(p)){c.push(l(f));continue}let g=kD(f,t);g===void 0?d.push(f.name):c.push({objectApiName:f.name,reason:g})}}return d.sort(),c.sort(yI),{mode:t.mode,objects:d,leftOut:c,worked:[...n.candidates].sort()}}function wI(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(yI)}}async function uf(s,e,t,r){await Ns(e.map(n=>async()=>{try{t.set(n,tI.parse(await s.describe(n)))}catch(o){r.set(n,O(o))}}),6)}function ID(s,e){if(e!=="hard")return s;let t=s.objects.filter(r=>!Zp(r));return t.length===0?s:{...s,objects:s.objects.filter(Zp),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 lo(s){return s.records}async function bI(s,e){let t=yc(s.global,s.tooling,s.request,s.rule),r=new Map,n=new Map;await uf(e,t.objects,r,n);let o=ID(wI(t,r,n),s.deleteMode),i=new Map([...t.worked,...s.global.map(S=>S.name)].map(S=>[S.toLowerCase(),S])),a=S=>i.get(S.toLowerCase())??S,d=nf(o.objects,t.worked,r);for(let S=0;S<gi;S++){let C=d.undescribed.filter(v=>!r.has(v)&&!n.has(v));if(C.length===0)break;await uf(e,C,r,n),d=nf(o.objects,t.worked,r)}let c=S=>d.emptied.has(S)||d.routes.has(S),l=[...new Set(rf(r,a).filter(({kind:S,parent:C,child:v})=>S==="restricted"&&c(C)&&!c(v)).map(({child:S})=>S))].filter(S=>!r.has(S)&&!n.has(S));await uf(e,l,r,n);let u=rf(r,a),f=mI(d,u),p=await pI({affected:d,order:f,relations:u,describes:r},e,s.stopped,{undo:s.deleteMode==="recycle"}),g=[...p.objects.filter(S=>lo(S.records)===void 0),...p.along.filter(S=>lo(S.records)===void 0)].map(S=>S.objectApiName),h=[...p.objects.map(S=>Math.max(0,(lo(S.records)??0)-(S.blocked?.records??0))),...p.along.map(S=>lo(S.records)??0)].filter(S=>S>0),m=h.reduce((S,C)=>S+C,0),y=p.along.some(S=>S.records.atLeast===!0)||p.objects.some(S=>S.blocked?.atMost===!0),R=p.refusals.filter(S=>S.code==="activatedOrder").reduce((S,C)=>S+(lo(C.records)??0),0),k=f.toDraft.filter(S=>!d.emptied.has(S)).map(S=>{let C=d.routes.get(S)??[];if(!cf(C,p.kept))return{objectApiName:S};let v=hi(C,r,void 0,T=>p.kept.get(T));return{objectApiName:S,...v?{condition:v.soql}:{}}}),w=S=>S.records===void 0||S.records>0,I=p.objects.filter(S=>w(S.records)).length+p.along.filter(S=>w(S.records)).length,P=JO+r.size+n.size+p.statements+2*I,b=YO({mode:s.deleteMode,passes:p.objects.map(S=>({objectApiName:S.objectApiName,records:lo(or([S.objectApiName]).length>0?S.records:S.sent)??0})),toDraft:R,deleted:m,reads:P,draftReads:k.filter(S=>S.condition!==void 0).length,refused:p.blockers.map(S=>lo(S.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:p.objects,along:p.along,leftOut:o.leftOut,refusals:p.refusals,blockers:p.blockers,beforeParent:f.beforeParent,unordered:f.unordered,undoLost:p.undoLost,undoLostRecords:p.undoLostRecords,undo:s.deleteMode==="recycle",affected:[...d.emptied,...d.along].sort(),toDraftAlong:k,cost:b,total:{records:m,objects:h.length,uncounted:g,...y?{atLeast:!0}:{}},statements:p.statements,...p.stopped?{stopped:!0}:{}}}var AD=5,TD=js,wc=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!==Ow};this.refused.has(r)||this.refused.size<TD?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=[...Iw(this.objectApiName,e),...Aw(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,AD)}}};async function RI(s,e,t){let{mode:r}=t,n=()=>t.signal?.aborted===!0,o=t.splitting??pa(),i=e.objects.reduce((h,m)=>h+m.count,0),a=[],d=0,c=[],l=h=>{let m=a.find(y=>y.objectApiName===h);if(!m){let y=e.objects.find(R=>R.objectApiName===h);m=new wc(h,y?.count??0),a.push(m)}return m},u=async(h,m)=>{await ma(s,c,{note:(R,k,w,I)=>l(R).note(w?ha(R,k,I,c):k)});let y=a.map(R=>R.result(o,h));if(h)for(let{objectApiName:R,count:k}of e.objects)y.some(w=>w.objectApiName===R)||y.push({...new wc(R,k).result(o,!1),...k>0?{notReached:k}:{}});return{hard:r==="hard",objects:y,cancelled:h,...m!==void 0?{hardRefused:m}:{}}},f=(h,m)=>Tw(s,h.objectApiName,m,{mode:r,stopped:n,splitting:o,...t.signal?{signal:t.signal}:{},...t.wait?{wait:t.wait}:{},settle:(y,R)=>{let k=h.deleted+h.gone+h.refused.size+h.refusedUnkept;h.settle(y,R),t.onSettled?.(h.objectApiName,y,R),d+=h.deleted+h.gone+h.refused.size+h.refusedUnkept-k,t.onProgress?.(d,i,h.objectApiName)}});if(r==="hard"&&s.bulkHardDestroy===void 0)return u(!0,kw);if(t.toDraft!==!1){let h=await ga(s,e.objects,e,()=>!0,n,async()=>new Set);if(c=h.drafted,h.cancelled)return u(!0)}for(let{objectApiName:h,count:m}of e.objects){if(n())return u(!0);let y=l(h),R=Ms(s,h,m,r),k=[],w=async()=>{let I=k;return k=[],f(y,I)};for await(let I of e.pages(h)){if(n())return u(!0);if(k.push(...I),R&&k.length<js)continue;let P=await w();if(P.stopped)return u(!0,P.hardRefused)}if(k.length>0){if(n())return u(!0);let I=await w();if(I.stopped)return u(!0,I.hardRefused)}}let p;if(await Ew(a,{stopped:n,idsOf:(h,m)=>m===0?h.toSendAgain():h.heldByDependents(),send:async(h,m)=>{let y=await f(h,[...m]);return p=y.hardRefused,y.stopped},deleted:h=>h.deleted}))return u(!0,p);for(let h of a){if(n())return u(!0);let{gone:m,unchecked:y,failure:R}=await Pw([...h.refused.keys()],k=>bn(s,h.objectApiName,[],k),()=>!0);for(let k of m)h.refused.delete(k),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`+(R?` \u2014 ${R}`:"."))}return u(!1)}function ED(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 PD(s){return/CreatedDate/.test(O(s))}function pf(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 CD(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 $D(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 vI(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 Ea,d=new Map;if(s.resumed){for await(let M of e.lines())if(M.kind==="settled"){for(let L of[...M.deleted,...M.gone])a.add(L);d.set(M.objectApiName,(d.get(M.objectApiName)??0)+M.deleted.length+M.gone.length)}}let c=new AbortController,l=s.signal?AbortSignal.any([s.signal,c.signal]):c.signal,u=()=>l.aborted,f,p=!1,g=ED(r.readAt),h=new Map(r.passes.map(M=>[M.objectApiName,M])),m=M=>h.get(M)?.rows??oo(M),y=new Map,R=new Map,k=()=>r.passes.reduce((M,L)=>M+Math.max(0,(R.get(L.objectApiName)??L.sent??L.records??0)-(d.get(L.objectApiName)??0)),0),w=async(M,L)=>{let ee=async Q=>{let q=await Ob(t.ids,M,[{objectApiName:L.objectApiName,...Q!==void 0?{filter:Q}:{}}],{signal:l});return q.stopped?void 0:q.spool};try{let Q=await ee(pf([L.filter,L.own,g]));return Q?{spool:Q,sinceRead:!0}:void 0}catch(Q){if(!PD(Q))throw Q;i.push(`${L.objectApiName} has no CreatedDate: its records were read whole, those made after the simulation among them.`);let q=await ee(pf([L.filter,L.own]));return q?{spool:q,sinceRead:!1}:void 0}},I=M=>{let L=y.get(M);if(L)return L;let ee=(async()=>{let Q=r.passes.findIndex(me=>me.objectApiName===M),q=e.idsDirOf(Q,M),V=o.spooled.get(M);if(s.resumed&&V)return R.set(M,V.count),{spool:await Pa.open(q,$a),count:V.count,sinceRead:V.sinceRead};if(u())return;let we=m(M),ie=await w(q,{objectApiName:M,...we!==void 0?{own:we}:{}});if(!ie)return;let re=ie.spool.count,Ae=h.get(M)?.records;if(Ae!==void 0&&re>Ae){f={code:"ORG_CHANGED",message:`${M} now holds ${re.toLocaleString("en-US")} records to delete, where the simulation counted ${Ae.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:M,place:Q,count:re,sinceRead:ie.sinceRead}),R.set(M,re),{spool:ie.spool,count:re,sinceRead:ie.sinceRead}})();return y.set(M,ee),ee},P={objects:r.passes.map(M=>({objectApiName:M.objectApiName,count:M.sent??M.records??0})),pages:M=>({async*[Symbol.asyncIterator](){let L=await I(M);if(L)for await(let ee of L.spool.pages(M)){let Q=a.size>0?ee.filter(q=>!a.has(q)):ee;Q.length>0&&(yield Q)}}})},b=Promise.resolve(),S,C=(M,L,ee)=>{let Q=[],q=[];L.forEach((V,we)=>{let ie=ee[we]?.kind;ie==="deleted"?Q.push(V):ie==="gone"&&q.push(V)}),Q.length>0&&(p=!0),Q.length+q.length!==0&&(b=b.then(async()=>{if(S===void 0)try{await e.settled(M,Q,q)}catch(V){S=O(V),c.abort()}}))},v=[];for(let[M,L]of r.toDraftAlong.entries()){if(L.condition===void 0||u())continue;let ee=e.idsDirOf(r.passes.length+M,L.objectApiName),Q=await w(ee,{objectApiName:L.objectApiName,filter:L.condition});if(!Q)break;let{drafted:q}=await ga(t.deletion,[{objectApiName:L.objectApiName}],Q.spool,()=>!0,u,async()=>new Set);v.push(...q)}let T=await RI(t.deletion,P,{mode:r.deleteMode,signal:l,...s.splitting?{splitting:s.splitting}:{},...s.wait?{wait:s.wait}:{},onSettled:C,onProgress:(M,L,ee)=>{let Q=Math.max(M,k());s.onProgress?.({percentage:Q>0?Math.min(99,Math.round(M/Q*100)):99,step:`${ee}: ${M.toLocaleString("en-US")} of about ${Q.toLocaleString("en-US")} settled`})}}).finally(async()=>{await b,await ma(t.deletion,v,{note:(M,L,ee,Q)=>i.push(ha(M,L,Q,v))})});S!==void 0&&i.push(`The journal of this emptying could not be written (${S}): it stopped there, so that its Undo misses nothing it deleted.`);let D=new Map;for(let[M,L]of y)D.set(M,await L.catch(()=>{}));let z=T.objects.map(M=>CD(M,D.get(M.objectApiName),h.get(M.objectApiName)?.records,T.cancelled));if(!T.cancelled)for(let M of z){if(!D.get(M.objectApiName)?.sinceRead)continue;let ee=m(M.objectApiName),Q=g.replace("CreatedDate <","CreatedDate >=");try{let q=await t.deletion.query(`SELECT COUNT() FROM ${qe(M.objectApiName)} WHERE ${pf([ee,Q])}`);q.totalSize>0&&(M.madeSince=q.totalSize)}catch(q){i.push(`Whether ${M.objectApiName} records were made after the simulation could not be read: `+O(q))}}let H=T.cancelled&&f===void 0&&S===void 0,Y=f!==void 0||S!==void 0?p?"partial":"failure":$D(z,H,T.hardRefused,s.resumed&&o.deletedAny),U=z.reduce((M,L)=>M+L.refused,0);return s.resumed&&Y==="partial"&&!p&&U>0&&i.push(`The org refused again the ${U.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:Y,hard:T.hard,passes:z,...T.hardRefused!==void 0?{hardRefused:T.hardRefused}:{},...f!==void 0?{changed:f}:{},deletedAny:p,notes:i}}var xD=/Entity is not in the recycle bin/,DD=/INSUFFICIENT_ACCESS/,ND=5,SI=5e4;function bc(s){return s.slice(0,15)}function ff(s){let e=new Set;for(let t of s){let r=t?.Id;typeof r=="string"&&e.add(bc(r))}return e}function jD(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 MD(s){return{objectApiName:s,planned:0,undeleted:0,alreadyBack:0,notInBin:0,othersDeletion:0,refused:0,reasons:[]}}function yi(s,e){s.reasons.length<ND&&!s.reasons.includes(e)&&s.reasons.push(e)}async function*LD(s,e,t){let r=t?new Ea: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 Pa.open(s.idsDirOf(t.place,e),$a);for await(let o of n.pages(e)){let i=o.filter(a=>!r.has(a));i.length>0&&(yield i)}}async function kI(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 OI(s,e){let t=s.spooledIn.get(e);return t!==void 0&&s.unendedAttempt!==void 0&&t.attempt===s.unendedAttempt?t:void 0}function FD(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 II(s){let e=await kI(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/Bt)*ef);let o=OI(e,r);o&&(n+=o.count,t+=Math.ceil(o.count/Bt)*ef);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)/Bt)}return t}async function AI(s){let{journal:e,org:t}=s,r=e.head,n=[],o=()=>s.signal?.aborted===!0,i=await kI(e),a=[],d=new Map,c=!1,l=[...r.passes].reverse();for(let[h,{objectApiName:m}]of l.entries()){let y=MD(m);a.push(y);let R=qe(m),k=OI(i,m);for await(let w of LD(e,m,k)){y.planned+=w.length;for(let I=0;I<w.length;I+=Bt){let P=w.slice(I,I+Bt);if(c||o()){c=!0,y.notReached=(y.notReached??0)+P.length;continue}let[b]=Ds(P,Bt),S,C;try{S=ff((await t.queryDeleted(`SELECT Id FROM ${R} WHERE Id IN (${b}) AND IsDeleted = true`)).records),C=ff((await t.query(`SELECT Id FROM ${R} WHERE Id IN (${b})`)).records)}catch(D){y.refused+=P.length,yi(y,`The recycle bin could not be read: ${O(D)}`);continue}let v=P.filter(D=>S.has(bc(D)));for(let D of P)S.has(bc(D))||(C.has(bc(D))?y.alreadyBack++:(y.notInBin++,yi(y,"No longer in the recycle bin, nor in the org: emptied from the bin, or pushed out of it.")));if(v.length===0)continue;let T;try{let D=await s.undelete(v),z=Array.isArray(D)?D:[D];T=v.map((H,Y)=>z[Y]??{success:!1})}catch(D){let z=O(D);T=v.map(()=>({success:!1,errors:[z]}))}T.forEach((D,z)=>{if(D.success===!0){y.undeleted++;return}let H=jD(D);if(xD.test(H)){y.notInBin++;let Y=d.get(m)??[];Y.length<SI&&Y.push(v[z]),d.set(m,Y),yi(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 DD.test(H)?(y.othersDeletion++,yi(y,`Deleted by another user than the one bringing it back: only Modify All Data brings back another's deletions (${H})`)):(y.refused++,yi(y,H))})}s.onProgress?.({percentage:Math.round((h+1)/Math.max(1,l.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 ${SI.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=qe(h.objectApiName);try{let R=0;for(let w of Ds(m,Bt)){let I=await t.query(`SELECT Id FROM ${y} WHERE Id IN (${w})`);R+=ff(I.records).size}let k=Math.min(R,h.notInBin);h.notInBin-=k,h.alreadyBack+=k}catch(R){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 (${O(R)}): they are counted as not back.`)}}let u=i.wentThrough?FD(e):[],f=a.reduce((h,m)=>h+m.undeleted+m.alreadyBack,0),p=a.reduce((h,m)=>h+m.notInBin+m.othersDeletion+m.refused+(m.notReached??0),0)+u.length;return{status:c?"cancelled":p===0?"success":f>0?"partial":"failure",objects:a.filter(h=>h.planned>0),notes:n,...u.length>0?{previewedLost:u}:{}}}var pr="Nothing was deleted.";function vc(s){return{query:e=>s.query(e),queryMore:e=>s.queryMore(e)}}var gf=G({Max:Te(),Remaining:Te()}).loose(),_D=G({DailyApiRequests:gf.optional(),DailyBulkApiBatches:gf.optional(),DataStorageMB:gf.optional()}).loose();async function UD(s){try{let e=_D.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:O(e)}}}}async function EI(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 yf(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 HD(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 BD(s,e){let t=[];for(let r of e)try{let n=xa.safeParse(await s.describe(r));n.success&&t.push(n.data)}catch{}return t}function PI(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. ${pr}`}}function ts(s,e={}){let[t,...r]=s;return{ran:!1,refusal:t,...r.length>0?{alsoRefused:r}:{},...e}}async function hf(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 Ir)return;throw o}let n=await r.state();return n.open?{runId:t.runId,startedAt:n.head.startedAt,journal:r}:void 0}function CI(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. ${pr}`}}function qD(s){return s.reason==="notRestorable"?`${s.objectApiName}, which Salesforce does not bring back`:`${s.objectApiName} before ${s.parent??"their parent"}`}function $I(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 WD(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=$I(s),r=`${t.atLeast?"at least ":""}${t.records.toLocaleString("en-US")}`,n=[...new Set(e.map(qD))],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. "+pr}}function zD(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. ${pr}`}),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. ${pr}`}),t}function Rc(s){return s.records}function GD(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=Rc(o.records);if(!i){(a===void 0||a>0)&&t.push(`${o.objectApiName} is now emptied too`);continue}a===void 0&&Rc(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=Rc(o.records),d=i?Rc(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=>$I(c).records,i=c=>new Set(c.undoLost.map(l=>`${l.objectApiName}.${l.field??""}.${l.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 TI(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. ${pr}`}}function mf(s,e,t){let r=t.automation?Wr(t.automation,t.mutePlan,qr(t.steps)):{firing:[]};return{module:"empty",written:yf(e),running:{firing:r.firing},request:{},orgId:s.orgId,operationId:s.operationId}}async function xI(s,e){let{org:t,orgName:r}=s,n=s.requestsSent?.()??0,o=vc(t),i=await to(o,{orgName:r,registered:s.registered,mode:e.request.mode});if(!i.allowed)return{previewed:!1,refusal:i.refusal};let a=await jI(s,e.request,e.deleteMode),d=await Kr({act:"empty",target:r,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{},...NI(a.preview)}),c=await hf(s.store,i.org.id),l=e.checkpointFirst===!0&&s.checkpoints?await s.checkpoints.scope(mf(s,a.preview,d.answer),{operationId:s.operationId}):void 0,u=s.requestsSent!==void 0?s.requestsSent()-n:void 0,f=DI(a,u,2,Xr(d.mute?.plan)),p={previewId:JD(s.now?.()??new Date),readAt:f.readAt,orgName:r,tier:i.tier,preview:f.preview,request:e.request,organizationId:i.org.id,access:f.access,hardDelete:{permitted:f.permissions.hardDelete,...f.permissions.unread!==void 0?{unread:f.permissions.unread}:{}},peopleActive:VD(f.people),...l?{checkpoint:l}:{},...c?{openRun:{runId:c.runId,startedAt:c.startedAt}}:{}},g=await LI(s,i.org.id,f,{deleteMode:e.deleteMode,acceptNoUndo:e.acceptNoUndo===!0,...e.acceptPeopleActive===!0?{peopleAccepted:!0}:{},automation:d.answer,...l?{checkpoint:l}:{},...c?{open:c.runId}:{}});return{previewed:!0,kept:p,automation:d.answer,refusals:g,...u!==void 0?{requestsSent:u}:{}}}function DI(s,e,t,r){let n=e??s.preview.cost.requests.reads;return{...s,preview:{...s.preview,cost:eI(s.preview.cost,n,t,r)}}}function JD(s){return tp(s).replace(/^em-/,"ep-")}function NI(s){let e=HD(s);return{objects:e.objects,writes:{steps:e.steps,written:e.written}}}async function jI(s,e,t){let{org:r}=s,n=vc(r),o=await r.serverTime(),i=G({sobjects:ve(Zi)}).loose().parse(await r.describeGlobal()).sobjects,a=await r.toolingObjects(),d=await UD(r),c=await bI({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),l=await Gs(n),u=yf(c),f=new Set(i.filter(R=>R.customSetting===!0).map(R=>R.name)),p=await qO({permissions:l,objects:u,customSettings:u.filter(R=>f.has(R)),grants:async()=>Db(n,()=>r.userId()),describe:R=>BD(r,R)}),g=await r.userId(),h=new Date(Date.parse(o)-Vu).toISOString(),m=await Xu(r,u,[g,...await EI(r)],h),y=s.voice==="page"?await Kv(r,m):m;return{readAt:o,preview:c,permissions:l,access:p,people:y}}function VD(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 MI(s){return s.voice==="page"?"page":"flags"}async function LI(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(CI(s.orgName,r.open)),t.preview.stopped&&n.push({code:"PREVIEW_STOPPED",message:`The simulation was stopped before every count was in: simulate again. ${Xv}`}),r.deleteMode==="hard"&&!t.permissions.hardDelete&&n.push(Ju(t.permissions));let i=Ku(s.orgName,t.people,{...r.peopleAccepted!==void 0?{accepted:r.peopleAccepted}:{},voice:MI(s)});i&&n.push(i);let a=r.acceptNoUndo?void 0:WD(t.preview);a&&n.push(a),n.push(...zD(t.preview,s.orgName)),r.checkpoint?.refusal&&n.push({...r.checkpoint.refusal});let d=On(r.automation);return d&&n.push({code:d.code,message:d.message},...d.alsoRefused),n}function XD(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 KD(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 YD(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 QD(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 ZD(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 FI(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=vc(t),a=await to(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,l=await hf(s.store,d);if(e.resumeRunId!==void 0){if(!l||l.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. ${pr}`}};if(c=l.journal,c.head.mode==="org"&&a.tier==="staging"){let v=await to(i,{orgName:r,registered:s.registered,mode:"org"});if(!v.allowed)return{ran:!1,refusal:v.refusal}}}else if(e.confirmed&&e.confirmed.organizationId.slice(0,15)!==d.slice(0,15))return{ran:!1,refusal:TI(r,["it is another org than the one the simulation read \u2014 a refreshed sandbox is a new org"])};let u=e.confirmed,f=c?c.head.deleteMode:u?.preview.deleteMode??"recycle",p=[],g,h,m,y;if(u){g=await jI(s,u.request,f);let v=[...GD(u.preview,g.preview),...WO(u.access,g.access).map(T=>`the user is no longer proven to see every record of ${T}`)];if(v.length>0&&p.push(TI(r,v)),g.preview.total.records===0&&g.preview.total.uncounted.length===0&&v.length===0)return{ran:!0,result:XD(n())};h=await Kr({act:"empty",target:r,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{},...NI(g.preview)}),e.checkpointFirst===!0&&(m=s.checkpoints?await s.checkpoints.scope(mf(s,g.preview,h.answer),{operationId:s.operationId}):void 0,m||p.push({code:"CHECKPOINT_REFUSED",message:`Checkpoints cannot be taken from here: run without Checkpoint first. ${pr}`})),g=DI(g,s.requestsSent!==void 0?s.requestsSent()-o:void 0,1,Xr(h.mute?.plan)),p.push(...await LI(s,d,g,{deleteMode:f,acceptNoUndo:e.acceptNoUndo===!0,...e.acceptPeopleActive===!0?{peopleAccepted:(u.peopleActive.who??[]).map(T=>T.userId)}:{},automation:h.answer,...m?{checkpoint:m}:{},...l?{open:l.runId}:{}}))}else{let v=c.head,T=await Gs(i);f==="hard"&&!T.hardDelete&&p.push(Ju(T));let D=await s.runWriting?.(d);D!==void 0&&p.push({code:"RUN_WRITING",message:D});let z=v.passes.map(Q=>Q.objectApiName),H=await t.userId(),Y=await t.serverTime(),U=await Xu(t,z,[H,...await EI(t)],new Date(Date.parse(Y)-Vu).toISOString()),M=Ku(r,U,{...e.acceptPeopleActive===!0?{accepted:!0}:{},voice:MI(s)});M&&p.push(M);let L=v.passes.map(Q=>({objectApiName:Q.objectApiName,records:Q.sent??Q.records??0})).filter(Q=>Q.records>0);h=await Kr({act:"empty",target:r,objects:L,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{}});let ee=On(h.answer);ee&&p.push({code:ee.code,message:ee.message},...ee.alsoRefused),y=QO(f,await QD(c),s.requestsSent!==void 0?s.requestsSent()-o:0,Xr(h.mute?.plan))}if(p.length>0)return ts(p);let R=u&&g?g.preview:void 0,k=R?R.total.records:c.head.passes.reduce((v,T)=>v+(T.records??0),0),w=R?yf(R):c.head.passes.map(v=>v.objectApiName),I=await s.askGuard({operation:f==="hard"?"hardDelete":"delete",objectNames:w,recordCount:k});if(I.decision==="refused"||I.decision==="declined")return ts([{code:"GUARD",message:I.decision==="refused"?`Production Guard refused the emptying: ${I.reason??"no reason given"}. ${pr}`:`The emptying was declined at Production Guard's confirmation. ${pr}`}],{guard:I.decision});let P=I.decision,b;if(m&&s.checkpoints&&R){let v=await s.checkpoints.take(mf(s,R,h.answer),{operationId:s.operationId},{planned:m,...s.signal?{signal:s.signal}:{},onProgress:({percentage:T})=>s.onProgress?.(Math.round(T/10),`Taking the checkpoint first (${Math.round(T)}%)`)});if(!v.taken)return ts(["stopped"in v?{code:"CANCELLED",message:`The emptying was stopped while its checkpoint was taken. ${pr}`}:{code:v.refusal.code,message:v.refusal.message}],{guard:P});b=v.checkpoint}let S=async v=>{if(!b||b.state!=="taken"||!s.checkpoints)return b;try{return await s.checkpoints.settle(b,v)}catch{return b}},C=s.lock(d);if("busy"in C)return await S(!1),ts([PI(r,C.busy)],{guard:P});try{let v=await hf(s.store,d);if(!c&&v)return await S(!1),ts([CI(r,v.runId)],{guard:P});let T=await Qn(h,s.operationId,e.accord.acceptEmails===!0,s.voice);if("refused"in T)return await S(!1),ts([{code:T.refused.code,message:T.refused.message}],{guard:P});let D=T.held,z=n(),H=c??await s.store.begin(d,{runId:tp(z),orgName:r,startedAt:z.toISOString(),readAt:u.readAt,previewId:u.previewId,mode:R.mode,deleteMode:f,request:KD(u.request),passes:R.passes.map(re=>({objectApiName:re.objectApiName,...re.records.records!==void 0?{records:re.records.records}:{},...re.sent.records!==void 0?{sent:re.sent.records}:{},...re.rows!==void 0?{rows:re.rows}:{}})),toDraftAlong:R.toDraftAlong,beforeParent:R.beforeParent,...f==="recycle"?{undoLost:YD(R)}:{}}),Y=R&&R.cost.api.verdict!=="unread"?fa(R.cost.api).splitAllowance:void 0,U,M,L=[];try{U=await vI({org:{deletion:t,ids:t},journal:H,resumed:c!==void 0,...s.signal?{signal:s.signal}:{},splitting:pa(Y),now:n,onProgress:({percentage:re,step:Ae})=>s.onProgress?.(re,Ae)})}catch(re){throw await H.ended("failure",[],n()).catch(()=>{}),re}finally{let re=t.lostJobs?.()??[];if(re.length>0&&t.stillRunning){let Ae=await t.stillRunning(re);Ae.length>0&&L.push(`${Ae.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.`)}D&&(M=await D.release(),L.push(...Xt(M,r).map(Ae=>Ae.trim())))}let ee=U.passes,Q=n();await H.ended(U.status,ee,Q,U.hardRefused);let q=await S(U.deletedAny),V=[];if(U.status==="success"||U.status==="partial")for(let re of await s.store.runsOf(d))re.runId>=H.head.runId||(await s.store.remove(d,re.runId),V.push(re.runId));let we=await H.state();return{ran:!0,result:{runId:H.head.runId,status:U.status,hard:U.hard,passes:ee,totals:ZD(ee),...U.hardRefused!==void 0?{hardRefused:U.hardRefused}:{},undo:U.hard?{offered:!1,why:"hard"}:we.deletedAny?{offered:!0}:{offered:!1,why:"nothingDeleted"},...c?{resumed:!0}:{},notes:[...U.notes,...U.changed?[U.changed.message]:[],...L],...M?{mutedAutomation:M}:{},...q?{checkpoint:q}:{},...V.length>0?{removedRuns:V}:{},...s.requestsSent!==void 0?{requestsSent:s.requestsSent()-o}:{},...y!==void 0?{requestsEstimate:y}:{},startedAt:z.toISOString(),finishedAt:Q.toISOString()},guard:P}}finally{C.lock.release()}}async function _I(s,e){let{org:t,orgName:r}=s,n=s.now??(()=>new Date),o=s.requestsSent?.()??0,i=vc(t),a=await to(i,{orgName:r,registered:s.registered,mode:"objects"});if(!a.allowed)return{ran:!1,refusal:a.refusal};let d=a.org.id,c=(w,I)=>({ran:!1,refusal:{code:w,message:`${I} Nothing was brought back.`}}),l;try{l=await s.store.open(d,e.runId)}catch(w){if(w instanceof Ir)return c("RUN_GONE",w.message);throw w}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 f=await l.state();if(l.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(f.undone)return c("UNDO_UNAVAILABLE",`${e.runId} was undone already.`);let p=await s.runWriting?.(d),g=[];p!==void 0&&g.push({code:"RUN_WRITING",message:p});let h=l.head.passes.map(w=>({objectApiName:w.objectApiName,records:w.records??0})),m=await Kr({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(w=>w.objectApiName)},written:[]}}),y=On(m.answer);if(y&&g.push({code:y.code,message:y.message},...y.alsoRefused),g.length>0){let[w,...I]=g;return{ran:!1,refusal:w,...I.length>0?{alsoRefused:I}:{}}}let R=ZO(await II(l),s.requestsSent!==void 0?s.requestsSent()-o:0,Xr(m.mute?.plan)),k=s.lock(d);if("busy"in k)return{ran:!1,refusal:PI(r,k.busy)};try{let w=await Qn(m,s.operationId,e.accord.acceptEmails===!0,s.voice);if("refused"in w)return{ran:!1,refusal:{code:w.refused.code,message:w.refused.message}};let I,P;try{P=await AI({org:t,undelete:S=>t.undelete(S),journal:l,...s.signal?{signal:s.signal}:{},onProgress:({percentage:S,step:C})=>s.onProgress?.(S,C)})}finally{w.held&&(I=await w.held.release())}let b=n();return P.status!=="cancelled"&&await l.undone(P.status,b),{ran:!0,result:{runId:e.runId,status:P.status,objects:P.objects,notes:[...P.notes,...I?Xt(I,r).map(S=>S.trim()):[]],...I?{mutedAutomation:I}:{},...s.requestsSent!==void 0?{requestsSent:s.requestsSent()-o}:{},requestsEstimate:R,...P.previewedLost?{previewedLost:P.previewedLost}:{},finishedAt:b.toISOString()}}}finally{k.lock.release()}}function eN(s){let e=Jn(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=yw(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 UI(s,e,t){let r=Vi(s),n=Sw(s,t),o=eN(s),i=[],a=new BR(async(l,u)=>(await Jn(s).bulk2.job("ingest",{id:u}).check()).state),d=l=>async(u,f,p)=>{try{return await vw(o.bulk,u,f,p,l)}catch(g){let h=o.last();throw h.closed&&i.push({orgId:e,objectApiName:u,...h.jobId?{jobId:h.jobId}:{}}),g}},c=l=>({totalSize:l.totalSize,done:l.done,records:l.records,...l.nextRecordsUrl?{nextRecordsUrl:l.nextRecordsUrl}:{}});return{describe:l=>s.describe(l),count:async l=>(await s.query(l)).totalSize,countAll:async l=>(await s.query(l,{scanAll:!0})).totalSize,readIds:async(l,u)=>{let f=await s.query(l,{scanAll:u});return{totalSize:f.totalSize,ids:f.records.flatMap(p=>typeof p.Id=="string"?[p.Id]:[])}},query:async(l,u)=>c(await s.query(l,{scanAll:u?.scanAll===!0})),queryMore:async l=>c(await s.queryMore(l)),queryDeleted:l=>n.queryDeleted(l),describeGlobal:()=>s.describeGlobal(),toolingObjects:async()=>{try{return(await s.tooling.describeGlobal()).sobjects.map(l=>l.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:(l,u)=>n.update(l,u),destroy:(l,u)=>n.destroy(l,u),bulkDestroy:d("delete"),bulkHardDestroy:d("hardDelete"),undelete:l=>s.soap.undelete(l),lostJobs:()=>[...i],stillRunning:l=>a.stillRunning(l),requestsSent:r}}import{readdir as tN,readFile as rN,rm as HI,stat as BI,writeFile as nN}from"node:fs/promises";import{join as Sc}from"node:path";var WI=/^ep-\d{8}-\d{6}-[a-z0-9]{4}$/,oN=50;function kc(s){return WI.test(s)}var qI=G({records:Te().optional(),unread:j().optional()}).loose(),sN=G({v:wt(1),orgId:j().min(1),kept:G({previewId:j().regex(WI),readAt:j(),orgName:j(),organizationId:j().min(15).max(18),request:G({mode:_e(["objects","org"])}).loose(),preview:G({mode:_e(["objects","org"]),deleteMode:_e(["recycle","hard"]),passes:ve(G({objectApiName:j(),records:qI}).loose()),along:ve(G({objectApiName:j(),records:qI}).loose()),undoLost:ve(G({objectApiName:j()}).loose()),total:G({records:Te()}).loose()}).loose(),access:G({kind:_e(["org","perObject"])}).loose(),peopleActive:G({people:Te(),who:ve(G({userId:j()}).loose()).optional()}).loose()}).loose()}),Oc=class{constructor(e,t=Aa){this.root=e;this.keepMs=t}root;keepMs;async keep(e,t,r=Date.now()){if(!kc(t.previewId))throw new Error(`Not a preview's id: ${t.previewId}`);await Ta(this.root),await nN(Sc(this.root,`${t.previewId}.json`),JSON.stringify({v:1,orgId:e,kept:t}),{mode:Ia}),await this.sweep(r)}async read(e,t=Date.now()){if(!kc(e))return;let r=Sc(this.root,`${e}.json`);try{if((await BI(r)).mtimeMs+this.keepMs<=t)return;let n=sN.safeParse(JSON.parse(await rN(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){kc(e)&&await HI(Sc(this.root,`${e}.json`),{force:!0})}async sweep(e){let t;try{t=await tN(this.root)}catch{return}let r=t.filter(o=>o.endsWith(".json")&&kc(o.slice(0,-5))).sort(),n=Math.max(0,r.length-oN);for(let[o,i]of r.entries()){let a=Sc(this.root,i);try{(o<n||(await BI(a)).mtimeMs+this.keepMs<=e)&&await HI(a,{force:!0})}catch{}}}};var aN=6e4,dN=20,rs="dataops",cN=new Set(["dataops:empty:scope","dataops:empty:preview","dataops:empty:run","dataops:empty:cancel","dataops:empty:undo"]),cn=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 lN(s){return s.passes.filter(e=>e.deleted+e.refused+(e.notReached??0)>0).map(e=>({...ht(e.objectApiName),deleted:e.deleted,failed:e.refused,...(e.notReached??0)>0?{notSent:e.notReached}:{}}))}function uN(s){return s.objects.filter(e=>e.undeleted+e.notInBin+e.othersDeletion+e.refused>0).map(e=>({...ht(e.objectApiName),created:e.undeleted,failed:e.notInBin+e.othersDeletion+e.refused,...(e.notReached??0)>0?{notSent:e.notReached}:{}}))}function pN(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 Ic=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)=>UI(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(!cN.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-QO4MPHZD.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=hb({root:fb()});if("refusal"in e)throw new cn({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 dd(rp()),previews:new Oc(iN(rp(),"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=he(i,e),c=this.ownStores(),l=this.orgOf(a,e),u=[],f,p=()=>this.targetAutomation?Promise.resolve(this.targetAutomation):(f??=this.countingReader(m=>u.push(Vi(m))),f),g=ka(r),h=this.runWriting?.(e,d,t);return{org:l,...l.requestsSent?{requestsSent:()=>(l.requestsSent?.()??0)+u.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:xo(a,async m=>{let y=await p();return new fe(aN).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:be.message};let{check:R,decision:k}=await Ze(y,{orgId:e,orgTier:Ee(i),operation:m.operation,objectName:m.objectNames.join(", "),recordCount:m.recordCount,module:rs});return{decision:k,...k==="refused"?{reason:R.blockedReason??R.impactSummary}:{}}},operationId:t,tool:"panel",...n?{signal:n}:{},...o?{onProgress:o}:{}}}fail(e,t,r){if(t instanceof cn){E(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}E(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=$(_m,e,"dataops:error",this.deps);if(t)try{let{orgId:r,...n}=t,o=await this.contextOf(r,e.id,{}),i={query:u=>o.org.query(u)},a=await to(i,{orgName:o.orgName,registered:o.registered,mode:n.mode});if(!a.allowed)throw new cn(a.refusal);let d=G({sobjects:ve(Zi)}).loose().parse(await o.org.describeGlobal()).sobjects,c=yc(d,await o.org.toolingObjects(),n),l=await Gs(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:l.hardDelete,...l.unread!==void 0?{unread:l.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>dN;){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<=Aa?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=$(Um,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 xI(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 cn(o.refusal);await this.keep(t.orgId,o.kept),this.respond(e,"dataops:empty:preview:response",{...pN(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=$(Bm,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,l=new AbortController;this.running.set(d,l),this.writing.set(d,t);let u=()=>{},f=new Promise((h,m)=>{u=y=>y===void 0?h():m(y)});f.catch(()=>{}),ze(this.deps,d,rs,r),c?.register(d,rs,r,f,l);let p=ir(this.liveTracker,d,rs,r),g=(h,m)=>{Le(this.deps,d,h,0,0,m),l.signal.aborted||c?.updateProgress(d,h),p.progress(h,0,0,m)};try{let h=await this.contextOf(t,d,a,l.signal,g),m=await n(h);if(!m.ran)throw o("stopped",{code:m.refusal.code,...m.guard?{guard:m.guard}:{}}),pe(this.deps,d,{status:"refused",code:m.refusal.code}),p.fail(m.refusal.message),u(new Error(m.refusal.message)),new cn(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),pe(this.deps,d,{aborted:!0}),p.cancel(),u();else if(y.status==="failure"){let R="Nothing the emptying set out to do went through: its result says why.";pe(this.deps,d,{status:y.status}),p.fail(R),u(new Error(R))}else pe(this.deps,d,{status:y.status}),y.status==="success"?p.complete():p.partial(),u()}catch(h){throw h instanceof cn||(o("failure",{}),pe(this.deps,d,{status:"failure"}),p.fail(h instanceof Error?h.message:String(h)),u(h)),h}finally{this.running.delete(d),this.writing.delete(d)}}async handleRun(e){let t=$(Hm,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 cn({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=>FI(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)=>Z(this.deps,{action:"cleanup_delete",module:rs,operationId:e.id,orgId:t.orgId,outcome:o,...i.guard?{guard:i.guard}:{},...i.code!==void 0?{code:i.code}:{},...i.result?{objects:lN(i.result)}:{},...i.result?.mutedAutomation?{muted:ct(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=$(qm,e,"dataops:error",this.deps);if(t)try{await this.writeAct(e,t.orgId,`Undoing the emptying ${t.runId}`,r=>_I(r,{runId:t.runId,accord:t}),(r,n)=>Z(this.deps,{action:"empty_undo",module:rs,operationId:e.id,orgId:t.orgId,outcome:r,...n.code!==void 0?{code:n.code}:{},...n.result?{objects:uN(n.result)}:{},...n.result?.mutedAutomation?{muted:ct(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 bN}from"node:os";var zI=6e4,fN=2*6e4,gN=50,hN=2880*6e4,mN=60*6e4,yN=250,GI="pipeline-triggers",wN=G({cron:j().optional(),timezone:j().optional(),nextRunAt:Te().optional(),lastFiredAt:Te().optional(),lastOutcome:_e(["started","missed"]).optional()});function wi(s,e){return`pipeline-trigger:${s}:${e}`}var Ac=class{constructor(e){this.deps=e;this.now=e.now??(()=>Date.now()),this.newId=e.newId??(()=>globalThis.crypto.randomUUID())}deps;engine=new Zv;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)}:{}},l=this.engine.idleReason(i,this.orgOf(i),t);l||(o??=await this.problemsOf(r),o.length>0&&(l={idle:"cannotRun",detail:o.join(" ")})),!l&&!this.started&&(l={idle:"stopped"});let u;if(!l&&d==="schedule"){let f=this.planOf(i,a)??this.engine.nextRun(i,t);typeof f=="number"?u=f:l=f}e.push(l?{...c,idle:l.idle,...l.detail?{detail:l.detail}:{}}:{...c,armed:!0,...u!==void 0?{nextRunAt:new Date(u).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: ${O(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>=mN&&(this.lastPrune=e,this.deps.claims.prune(hN));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(wi(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 l=c?this.unplan(i,d):this.lookAt(i,d,e,t,a??[]);l!==void 0&&(o===void 0||l<o)&&(o=l)}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,gN),c=[a,...d.times],l=c[c.length-1],u=!n&&r-l<=fN?l:void 0,f=u===void 0?c:c.slice(0,-1),p=this.plan(e,t,i,r),g=f.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,...p!==void 0?{nextRunAt:new Date(p).toISOString()}:{}})}return u!==void 0&&this.deps.claims.claim(this.dueKey(e,t,u))&&(o.length>0?this.refuseStart(e,t,"schedule",u,o,{...p!==void 0?{nextRunAt:new Date(p).toISOString()}:{}}):this.fire(e,t,"schedule",u)),p}refuseStart(e,t,r,n,o,i){let a=o.join(" "),d=wi(e.id,t.id),c=r==="schedule"?this.refusedMisses.get(d):void 0,l=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,l);let u={reason:"cannotRun",count:l.count,...l.count>1?{lastDueAt:new Date(n).toISOString()}:{},detail:a};this.recordMissed(e,r,l.firstDueAt,u,l.runId),this.remember(e,t,{lastFiredAt:n,lastOutcome:"missed"}),!(l.count>1)&&this.deps.report({kind:"missed",pipelineName:e.name,triggeredBy:r,dueAt:new Date(n).toISOString(),missed:u,...i})}dueKey(e,t,r){return`due:${e.id}:${t.id}:${r}`}fire(e,t,r,n,o){let i=wi(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(u=>{u?.status==="failed"&&this.deps.report({kind:"failed",pipelineName:e.name,triggeredBy:r,error:u.error??"the run failed",...o?{sandboxName:o}:{}})},u=>{this.deps.report({kind:"failed",pipelineName:e.name,triggeredBy:r,error:O(u),...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 l={reason:"busy",count:c.count,busySince:c.busySince,...c.count>1?{lastDueAt:new Date(c.lastDueAt).toISOString()}:{}};this.recordMissed(e,r,c.firstDueAt,l,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:l,...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(GI)))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?zI:this.soonest-this.now(),t=Math.min(Math.max(e,yN),zI);this.timer=setTimeout(()=>{this.look()},t),this.timer.unref?.()}triggersOf(e){return(Array.isArray(e.triggers)?e.triggers:[]).flatMap(r=>{let n=Qv.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: ${O(t)}.`]}}read(e,t){let r=wN.safeParse(this.deps.store.get(wi(e,t)));return r.success?r.data:{}}write(e,t,r){this.deps.store.set(wi(e,t),r,GI)}};function ns(){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 T1=65*6e4;var JI=[{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 wf(s,e){return`${s}\0${e}`}var Tc=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=wf(e.operationId,e.stepId),o={...e,expiresAt:new Date(r().getTime()+e.timeoutMs).toISOString()};return new Promise(i=>{let a=l=>{this.waiting.get(n)?.settle===a&&(this.waiting.delete(n),clearTimeout(c),t?.removeEventListener("abort",d),i(l))},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(l=>{if(l===void 0)return;let u=typeof l=="string"?{decision:l,via:void 0}:l,f=u.decision==="approve"?"approved":"rejected",p=u.via??"notification";this.answer(e.operationId,e.stepId,f,p)||this.deps.tooLate?.(o)},()=>{})})}answer(e,t,r,n){let o=this.waiting.get(wf(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(wf(e,t))}};var VI=50,QI={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 RN(s,e){return`Pipeline "${s}" is already running: the run started ${QI[e.triggeredBy]} at ${e.startedAt} has not ended. A pipeline runs once at a time.`}function vN(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 SN={approved:"success",rejected:"stopped",timedOut:"stopped",cancelled:"cancelled"};function XI(){try{return Ph(bN().username)}catch{return}}function kN(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 KI="A simulation of a pipeline is not available here: nothing ran. Run it, or simulate it again once SandForge has finished starting.",YI={release:()=>{}};function bf(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 ON=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"]),Ec=class{constructor(e){this.deps=e}deps;pipelineMarketplace;stepRunners;claims=ns();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??yS()}takeRunLock(e,t,r){if(typeof e.id!="string"||e.id==="")return YI;try{let n=bS(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] ${vS(n.tookOver)}`),n.lock)}catch(n){return this.deps.log(`[WARN] the run lock of pipeline "${e.name}" could not be taken (${O(n)}): a run from the command line is not kept apart from this one.`),YI}}setLiveOperationTracker(e){this.liveTracker=e}approvals(){let e=this.deps.services;return this.approvalGate??=new Tc({...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:XI}),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 Js(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 Io(this.deps.configStore).append({id:crypto.randomUUID(),action:"pipeline_approval",module:"automation",operationId:r,outcome:SN[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 ${O(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 Ac({pipelines:()=>this.savedPipelines(),problems:e=>this.pipelineProblems(e),org:e=>{let t=this.deps.orgManager.getOrg(e);return t?{name:he(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=aa.safeParse(o);return i.success?[i.data]:(t.set(n,fu(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] ${sp(n.busy,e.name)}`),{started:!1,busy:{startedAt:n.busy.acquiredAt,triggeredBy:n.busy.triggeredBy}};let o=`${Cg}${crypto.randomUUID()}`;return{started:!0,run:this.runPipeline(e,{},t,o).catch(a=>{throw this.deps.log(`[ERR] ${t} run of "${e.name}": ${O(a)}`),De(this.deps,o,O(a),!1,{context:{module:"automation",operation:"pipeline:execute"}}),a}).finally(()=>{n.release(),r.release()})}}async handle(e){if(!ON.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=$(Ky,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)){E(this.deps,"pipeline:execute","pipeline:error",e,new Error(KI),{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){E(this.deps,"pipeline:execute","pipeline:error",e,new Error(RN(i.name,d.busy)),{code:"PIPELINE_RUNNING",retryable:!0});return}let c=this.takeRunLock(i,"manual",a);if("busy"in c){d.release(),E(this.deps,"pipeline:execute","pipeline:error",e,new Error(sp(c.busy,i.name)),{code:"PIPELINE_RUNNING",retryable:!0});return}try{let l=await this.runPipeline(i,r.variables??{},"manual",n,{dryRun:a}),u=A(this.deps,e,"pipeline:run:response",{...l,...a?{dryRun:!0}:{}});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`)}catch(l){E(this.deps,"pipeline:execute","pipeline:error",e,l),De(this.deps,n,O(l),!1,{context:o})}finally{c.release(),d.release()}}handlePipelineApproval(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(tw,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 bf(e.steps)){let o=Ct.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: ${O(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: ${O(e)}`)}}savedPipeline(e){let t=aa.safeParse(this.deps.configStore.get(`pipeline:saved:${e}`));return t.success?t.data:void 0}async describeRewindStep(e,t){let r=this.stepRunners,n=Ct.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&&Vs(t.config)===i.digest}:void 0;return r?{info:ik(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=$(rw,e,"pipeline:error",this.deps);if(t)try{let r=this.savedPipeline(t.pipelineId),n=[];for(let i of bf(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){E(this.deps,"pipeline:rewind-steps","pipeline:error",e,r)}}async handleRewindGrant(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(nw,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=bf(d?.steps??[]).find(h=>h.id===n);if(!c)return a("NOT_SAVED");let l=Ct.safeParse(c.config);if(!l.success)return a("CONFIG_INVALID",{reason:l.error.issues[0]?.message??""});let u=this.deps.orgManager.getOrg(l.data.orgId);if(!u)return a("ORG_UNKNOWN");if(o!==he(u))return a("TYPED_MISMATCH");let{info:f,checkpoint:p}=await this.describeRewindStep(r,c);if(!f.valid)return a("CHECKPOINT_INVALID",{why:f.why??"missing"});if(!p?.kept||p.organizationId===void 0)return a("CHECKPOINT_INVALID",{why:"missing"});let g=XI();this.rewindGrants().write({pipelineId:r,stepId:n,organizationId:p.organizationId,checkpointId:l.data.checkpointId,digest:Vs(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 ${he(u)}, to checkpoint ${l.data.checkpointId}`),i({granted:!0,pipelineId:r,stepId:n,step:(await this.describeRewindStep(r,c)).info})}catch(d){E(this.deps,"pipeline:rewind-grant","pipeline:error",e,d)}}handleRewindRevoke(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ow,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){E(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?nk(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){E(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?ok(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){E(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?QS(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){E(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-JAV6F6OA.mjs"),{StepExecutor:i}=await import("./chunk-U4YFYSF3.mjs"),{ConditionalRouter:a}=await import("./chunk-YEVB7LVK.mjs"),{PipelineHistory:d}=await import("./chunk-ZHJP7L3K.mjs"),c=new i,l=e??{operationId:"",holdBudget:()=>{}};c.wrapHandler("delay",p=>(g,h)=>this.untimed(()=>p(g,h),l));let u;if(this.stepRunners){let{runSync:p,seed:g,anonymize:h,takeCheckpoint:m,rewind:y,backup:R}=this.stepRunners,{simulateSync:k,previewSeed:w,previewMasking:I,estimateTake:P,previewRewind:b}=this.stepRunners,S=await this.checkpointsOf(t),C=this.rewindGrants();u={...this.stepRunners,...t?.id?{pipelineId:t.id}:{},...l.triggeredBy?{trigger:l.triggeredBy}:{},rewindGrant:(v,T)=>C.verify(v,T),checkpointKept:v=>S.get(v),...p?{runSync:(v,T,D)=>this.runSyncUntimed(p,v,T,D,l)}:{},backup:(v,T)=>this.untimed(()=>R(v,T),l),...g?{seed:(v,T)=>this.untimed(()=>g(v,T),l)}:{},...h?{anonymize:(v,T)=>this.untimed(()=>h(v,T),l)}:{},...m?{takeCheckpoint:(v,T)=>this.untimed(()=>m(v,T),l)}:{},...y?{rewind:(v,T)=>this.untimed(()=>y(v,T),l)}:{},...k?{simulateSync:(v,T)=>this.untimed(()=>k(v,T),l)}:{},...w?{previewSeed:(v,T)=>this.untimed(()=>w(v,T),l)}:{},...I?{previewMasking:(v,T)=>this.untimed(()=>I(v,T),l)}:{},...P?{estimateTake:(v,T)=>this.untimed(()=>P(v,T),l)}:{},...b?{previewRewind:(v,T)=>this.untimed(()=>b(v,T),l)}:{},...this.approvals().canAsk?{askApproval:(v,T)=>this.askApproval(v,T,l)}:{}},ak(c,u)}if(l.dryRun){if(!this.dryRunApplier||!u)throw new Error(KI);await this.dryRunApplier(c,u)}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,l=!1,u=kN(d,()=>{l=!0,c.abort()}),f=await this.buildOrchestrator({operationId:n,holdBudget:b=>b?u.hold():u.resume(),triggeredBy:r,...i?{dryRun:!0}:{}},e);this.deps.infraServices?.performanceTracker?.start(n,"automation");let p=`${i?"Pipeline simulation":"Pipeline"}: ${e.name}`;ze(this.deps,n,"automation",p);let g=ir(this.liveTracker,n,"automation",p,e.steps.length),h=b=>l&&b.status==="stopped"?{...b,status:"failed"}:b,m=(b,S)=>{let C=S,v=f.getActiveRuns(),T=e.steps.length,D=v[0]?.stepResults.length??0,z=Math.round(D/T*100),H=`Step: ${C.stepResult.stepName} (${C.stepResult.status})`;Le(this.deps,n,z,D,T,H),g.progress(z,D,T,H)},y=(b,S)=>{let{stepId:C}=S;this.postStepUpdate({operationId:n,stepId:C,status:"running"})},R=(b,S)=>{let C=h(S.stepResult);this.postStepUpdate({operationId:n,stepId:C.stepId,status:C.status==="failed"||C.status==="skipped"||C.status==="stopped"?C.status:"completed",...C.duration!==void 0?{duration:C.duration}:{},...C.summary!==void 0?{summary:C.summary}:{},...C.error!==void 0?{error:C.error}:{}})};f.on("stepCompleted",m),f.on("stepStarted",y),f.on("stepCompleted",R),f.on("stepSkipped",R),u.start();let k=()=>{};this.deps.infraServices?.backgroundRegistry?.register(n,"automation",p,new Promise((b,S)=>{k=C=>C?S(C):b()}),c);let w;try{w=await f.execute(e,t,r,c.signal)}catch(b){throw k(new Error(O(b))),g.fail(O(b)),b}finally{u.end(),f.off?.("stepCompleted",m),f.off?.("stepStarted",y),f.off?.("stepCompleted",R),f.off?.("stepSkipped",R)}let I=l&&w.status==="cancelled",P=I?{...w,status:"failed",error:`Pipeline ran out of time: sandforge.pipeline.timeout stopped it after ${d} ms.`,stepResults:w.stepResults.map(h)}:w;return k(P.status==="failed"?new Error(P.error??"Pipeline failed"):void 0),P.status==="failed"?g.fail(P.error??"Pipeline failed"):P.status==="cancelled"?g.cancel():P.status==="completed_with_warnings"?g.partial():g.complete(),this.deps.infraServices?.performanceTracker?.complete(n),i||this.recordRun(P,e),P.status==="failed"?De(this.deps,n,P.error??"Pipeline failed",I,{context:a}):pe(this.deps,n,{status:P.status,stepResults:P.stepResults.length}),P}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(vN)},{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: ${O(r)}`)}}trimHistory(){let e=Object.entries(this.deps.configStore.getByCategory("pipeline-history"));if(e.length<=VI)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-VI))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 It(r).load(o),seedTemplate:o=>new sn(r).load(o),maskingTemplate:o=>new ba(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=aa.safeParse(r);if(!n.success||n.data.runsOutside===void 0)continue;let o=n.data;try{let i=jS(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: ${O(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 NS({...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=$(Qy,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){E(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:JI});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){E(this.deps,"pipeline:list","pipeline:error",e,t)}}commandLineRuns(){try{return this.commandLineHistory??=AS(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: ${O(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){E(this.deps,"pipeline:history","pipeline:error",e,t)}}handlePipelineSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=$(Zy,e,"pipeline:error",this.deps);if(!t)return;let r=t,n=r.config.runsOutside;if(n!==void 0){let l=Yy.safeParse(n);if(!l.success){E(this.deps,"pipeline:save","pipeline:error",e,new Error(`The pipeline was not saved: runsOutside.${fu(l.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(l=>({...typeof l.id=="string"?{id:l.id}:{},...l.type==="rewind"?{type:"rewind"}:{},config:typeof l.config=="object"&&l.config!==null?l.config:{}})));for(let l of d)this.deps.log(`[INFO] pipeline:save ${o}: the confirmation of Rewind step ${l} 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){E(this.deps,"pipeline:save","pipeline:error",e,t)}}handlePipelineDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=$(ew,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;E(this.deps,"pipeline:delete","pipeline:error",e,new Error(`Pipeline "${d}" is running: the run started ${QI[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){E(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=$(sw,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: ${O(t)}`);let r=A(this.deps,e,"marketplace:list:response",{success:!1,error:O(t)});this.deps.broker.postToWebview(r)}}handleMarketplaceInstall(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(iw,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: ${O(n)}`);let o=A(this.deps,e,"marketplace:install:response",{success:!1,error:O(n)});this.deps.broker.postToWebview(o)}}};var os=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 uo(s,e){return e.aborted?(s.catch(()=>{}),Promise.reject(ZI())):new Promise((t,r)=>{let n=()=>r(ZI());e.addEventListener("abort",n,{once:!0}),s.then(o=>{e.removeEventListener("abort",n),t(o)},o=>{e.removeEventListener("abort",n),r(o)})})}function ZI(){return Object.assign(new Error("Stopped before its answer came."),{code:"CANCELLED"})}var eA=200,Rf=50,vf="ai.enabled",Sf="ai.errorResolution",tA="ai:conversations:index",rA="ai",Pc="ai.anthropic.key",IN=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"]),Cc=class{constructor(e){this.deps=e}deps;aiAssistant;asking=new os;setAIAssistant(e){this.aiAssistant=e}async handle(e){if(!IN.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(tA)??[]}saveIndex(e){this.deps.configStore.set(tA,e,rA)}loadConversation(e){return this.deps.configStore.get(this.conversationKey(e))}saveConversation(e){this.deps.configStore.set(this.conversationKey(e.id),e,rA),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<=Rf)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-Rf).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 (${Rf} 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<=eA)return e;let t=e.filter(o=>o.role==="system"),r=e.filter(o=>o.role!=="system"),n=eA-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=$(wy,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=O(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=$(ia,e,"ai:error",this.deps);t&&this.asking.abort(t.conversationId)}handleConversationCreate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(by,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=$(ia,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=$(ia,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(Pc),r=A(this.deps,e,"ai:status:response",{enabled:!!this.aiAssistant&&t,provider:this.aiAssistant?Sg:"none",model:this.aiAssistant?Og(this.deps.services?.getSandforgeSetting?.("ai.model",kg.MODEL)):"",budget:this.aiAssistant?this.deps.services?.sessionBudget?.getState():void 0,hasKey:t,errorResolution:this.deps.services?.getSandforgeSetting?.(Sf,!0)??!0});this.deps.broker.postToWebview(r),this.deps.log("[TX] ai:status:response")}async enableAIFeature(){await this.writeSetting("ai:save-key",vf,!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: ${O(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: ${O(r)}`)}}async handleSaveKey(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Ry,e,"ai:error",this.deps);if(!t)return;let{apiKey:r,errorResolution:n}=t;try{let o=await this.deps.secretVault.hasSecret(Pc);await this.deps.secretVault.storeSecret(Pc,r),(!o||n!==void 0)&&await this.writeSetting("ai:save-key",Sf,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=O(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=$(vy,e,"ai:error",this.deps);if(!t)return;let r=[];t.errorResolution!==void 0&&r.push([Sf,t.errorResolution]),t.enabled!==void 0&&r.push([vf,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(Pc);let t=this.deleteAllConversations();await this.writeSetting("ai:remove-key",vf,!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=O(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 AN=new Set(["ai:anomaly-scan"]),$c=class{constructor(e){this.deps=e}deps;ruleModules;setRuleModules(e){this.ruleModules=e}async handle(e){return AN.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=$(Sy,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=bt(n),d=o??fn.anomalyScan,c=`SELECT FIELDS(ALL) FROM ${a} LIMIT ${d}`,l=await jh(i,a,c),u=l.records,f={records:u,fields:Object.keys(u[0]??{})},p=this.ruleModules.anomalyDetector.detectAnomalies(f,n),g=A(this.deps,e,"ai:anomaly-scan:response",{success:!0,anomalies:p.anomalies.map(h=>({field:h.field,type:h.type,description:h.description,severity:h.severity})),sample:{read:u.length,limit:l.limit??d}});this.deps.broker.postToWebview(g)}catch(i){this.deps.log(`[ERR] ai:anomaly-scan: ${O(i)}`);let a=A(this.deps,e,"ai:anomaly-scan:response",{success:!1,error:O(i)});this.deps.broker.postToWebview(a)}}};function nA(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"")}function TN(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 EN(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=nA(r);n&&!e.has(n)&&e.set(n,t.name)}return e}function oA(s,e,t=5){if(t<=0)return[];let r=EN(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 l=n.slice(a,a+c).join(""),u=TN(nA(l)).map(f=>r.get(f)).find(f=>f!==void 0);if(u){if(!i.has(u)&&(i.add(u),o.push(u),o.length>=t))return o;a+=c-1;break}}}return o}var PN={sync:"Sync",seed:"Seed",dataops:"DataOps"};function sA(s){if(s.code==="STEP_NOT_RUNNABLE")return`A pipeline cannot run a ${s.stepType} step, so the draft leaves it out.`;let e=PN[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 CN=new Set(["WHERE","USING","WITH","GROUP","ORDER","LIMIT","OFFSET","FOR","UPDATE"]),$N=new Set(["WITH","GROUP","ORDER","LIMIT","OFFSET","FOR","UPDATE"]),xN=new Set(["AND","OR","NOT","WHERE"]),DN=/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/,NN=/^([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)(?:\s+[A-Za-z_]\w*)?$/,jN=/^[A-Za-z_]\w*\s*\(([^()]*)\)(?:\s+[A-Za-z_]\w*)?$/,MN=/([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*(?:!=|<>|<=|>=|=|<|>|\bNOT\s+IN\b|\bIN\b|\bLIKE\b|\bINCLUDES\b|\bEXCLUDES\b)/gi;function LN(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 iA=/\(\s*SELECT\b/iy;function FN(s){let e="",t=0;for(;t<s.length;){if(iA.lastIndex=t,s[t]!=="("||!iA.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 _N(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 UN(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 HN(s){let e=NN.exec(s);if(e)return e[1];let t=jN.exec(s);if(t){let r=t[1].trim();return DN.test(r)?r:null}return null}function BN(s){let e=FN(LN(s)).replace(/\bTYPEOF\b[\s\S]*?\bEND\b/gi,"()"),t=_N(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&&!CN.has(d)&&!c.includes(",")&&i.add(d);let l=[],u=e.slice(t[0].end,t[n].start);for(let h of UN(u)){let m=HN(h.trim());m&&l.push(m)}let f=t.findIndex((h,m)=>m>n+1&&h.word.toUpperCase()==="WHERE");if(f>=0){let h=t.findIndex((y,R)=>R>f&&$N.has(r(R)??"")),m=e.slice(t[f].end,h<0?e.length:t[h].start);for(let y of m.matchAll(MN))xN.has(y[1].toUpperCase())||l.push(y[1])}let p=new Set,g=[];for(let h of l){let[m,...y]=h.split("."),R=y.length>0&&i.has(m.toUpperCase())?y.join("."):h,k=R.toUpperCase();p.has(k)||(p.add(k),g.push(R))}return{objectApiName:o,fieldRefs:g}}async function aA(s,e){let t=BN(s);if(!t)return{fieldsChecked:0,problems:[{kind:"no-from"}]};let r=t.objectApiName.toLowerCase(),n=e.catalog.find(l=>l.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(l){return{rootObject:n.name,rootLabel:n.label,fieldsChecked:0,problems:[{kind:"describe-failed",object:n.name,detail:O(l)}]}}let i=new Set(o.fields.map(l=>l.name.toLowerCase())),a=new Set(o.fields.flatMap(l=>l.relationshipName?[l.relationshipName.toLowerCase()]:[])),d=[],c=new Set;for(let l of t.fieldRefs){let[u,...f]=l.split(".");f.length===0?i.has(u.toLowerCase())||d.push({kind:"field-missing",object:n.name,field:u}):!a.has(u.toLowerCase())&&!c.has(u.toLowerCase())&&(c.add(u.toLowerCase()),d.push({kind:"relationship-missing",object:n.name,relationship:u}))}if(d.length===0)try{await e.explain(s)}catch(l){d.push({kind:"org-refused",detail:O(l)})}return{rootObject:n.name,rootLabel:o.label||n.label,fieldsChecked:t.fieldRefs.length,problems:d}}function kf(s){return zN().text(s)}var WN=new Set;function zN(){let s=Mv(),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=Lv({text:o},WN,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 Ut=_l,Gt=_l.text,dA="{firstName}, {lastName}, {company}, {email} and {caseSubject}";var $J=[`- "id" and each topic's "key": lower-case letters and digits in words joined by single hyphens, starting with a letter, ${Ut.maxKeyLength} characters at most.`,`- "name": at most ${Gt.name} characters. "businessContext": what the company does and who its customers are, in two or three sentences, at most ${Gt.businessContext} characters.`,`- "customers": "count" is 10 unless the scenario asks for another number, at least the number of topics and at most ${Ut.maxCustomers}; "industry" is the customers' industry as an Account Industry value of Salesforce (Retail, Telecommunications, Technology...), at most ${Gt.industry} characters.`,`- "topics": ${Ut.topics.min} to ${Ut.topics.max}, five unless the scenario calls for more or fewer: the subjects customers write to support about. "label": at most ${Gt.label} characters.`,`- "utterances": ${Ut.utterances.min} to ${Ut.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 ${Gt.utterance} characters. They may name the customer and the case with ${dA}, 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 ${Gt.articleTitle} characters, "summary" at most ${Gt.articleSummary}, "body" plain-text paragraphs of 600 to 1,500 characters. No placeholder.`,`- "outOfScope": ${Ut.outOfScope.min} to ${Ut.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 ${Gt.utterance} characters. No placeholder.`,"- No word in braces but the placeholders named here, where they are allowed."];var xJ=[`- "article": what the agent answers the topic from. "title" at most ${Gt.articleTitle} characters and none of the titles above; "summary" at most ${Gt.articleSummary}; "body" plain-text paragraphs of 1,200 to 3,000 characters, at most ${Gt.articleBody}: the policy or the procedure, with the figures, delays and conditions customers ask about. No placeholder in the article.`,`- "facts": ${Ut.facts.min} to ${Ut.facts.max}, each a sentence of the body copied word for word, at most ${Gt.fact} characters: what an answer drawn from the article has to say.`,`- "caseTemplates": ${Ut.caseTemplates.min} to ${Ut.caseTemplates.max}, two unless the topic needs more: cases customers open on the topic. "subject" at most ${Gt.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" ${Ut.resolutionSteps.min} to ${Ut.resolutionSteps.max} steps, each a comment of the agent who resolved the case, under 400 characters. "description", "followUp" and "resolution" may name ${dA}.`,"- No word in braces but the placeholders named here, where they are allowed."];var GN=new Set(["ai:forge-plan","ai:generate-pipeline","ai:scenario-draft","ai:tool:cancel"]),Of={success:!1,code:"CANCELLED"},cA="AI not configured. Set your API key in Settings > AI.";function JN(s){switch(s){case"Production":return"production";case"Sandbox":return"sandbox";case"Developer":return"developer";case"Scratch":return"scratch";default:return"production"}}var xc=class{constructor(e){this.deps=e}deps;aiModules;drafting=new os;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(!GN.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=$(Iy,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=$(ky,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:cA}));return}let a=await uo(this.connect(r),o.signal),d=await uo(this.loadCatalog(r,a),o.signal),c=t.soql??"",l;if(n!==void 0&&i){let{result:f}=await this.draft(i,n,r,a,d,o.signal);c=f.soql,l=f.explanation}let u=await uo(aA(c,{catalog:d,describe:async f=>{let p=await this.describeObject(r,a,f);return{name:p.apiName,label:p.label,fields:p.fields.map(g=>({name:g.apiName,relationshipName:g.relationshipName}))}},explain:f=>a.request(`/query/?explain=${encodeURIComponent(f)}`)}),o.signal);this.deps.broker.postToWebview(A(this.deps,e,"ai:forge-plan:response",{success:u.problems.length===0,soql:c,...l?{explanation:l}:{},...u.rootObject?{rootObject:u.rootObject}:{},...u.rootLabel?{rootLabel:u.rootLabel}:{},fieldsChecked:u.fieldsChecked,problems:u.problems}))}catch(i){if(o.signal.aborted){this.deps.broker.postToWebview(A(this.deps,e,"ai:forge-plan:response",{...Of})),this.deps.log("[TX] ai:forge-plan:response cancelled");return}this.deps.log(`[ERR] ai:forge-plan: ${O(i)}`),this.deps.broker.postToWebview(A(this.deps,e,"ai:forge-plan:response",{success:!1,error:O(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=oA(t,o),d=await uo(this.describeObjects(r,n,a),i),c={objects:d.length>0?d:o.map(u=>({apiName:u.name,label:u.label,fields:[]}))};return{result:await uo(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}: ${O(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=$(Oy,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(l=>{let u=this.deps.orgManager.getOrg(l);return{orgId:l,alias:u?.alias??l,type:JN(u?.orgType)}}),{suggestions:a=[],...d}=await uo(this.aiModules.pipelineGenerator.generatePipeline(r,i,{signal:o.signal}),o.signal);if(d.steps.length===0&&a.length>0){let l=a.map(sA).join(" ");this.deps.log(`[ERR] ai:generate-pipeline: ${l}`),this.deps.broker.postToWebview(A(this.deps,e,"ai:generate-pipeline:response",{success:!1,error:l,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",{...Of})),this.deps.log("[TX] ai:generate-pipeline:response cancelled");return}this.deps.log(`[ERR] ai:generate-pipeline: ${O(i)}`);let a=A(this.deps,e,"ai:generate-pipeline:response",{success:!1,error:O(i)});this.deps.broker.postToWebview(a)}finally{o.end()}}async handleScenarioDraft(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Ay,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:kf(t.text)});return}let n=this.aiModules?.scenarioDrafter;if(!n){r({success:!1,code:"AI_NOT_CONFIGURED",error:cA,sentText:kf(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(VN(i))}catch(i){this.deps.log(`[ERR] ai:scenario-draft: ${O(i)}`),r({success:!1,error:O(i)})}finally{o.end()}}};function VN(s){switch(s.kind){case"complete":return{success:!0,sentText:s.sentText,pack:s.pack};case"stopped":return{...Of,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 XN=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"]),Dc=class{chatHandler;analysisHandler;toolsHandler;subHandlers;constructor(e){this.chatHandler=new Cc(e),this.analysisHandler=new $c(e),this.toolsHandler=new xc(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(!XN.has(e.type))return!1;for(let t of this.subHandlers)if(await t.handle(e))return!0;return!1}};function lA(s,e,t){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}}}}function uA(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 KN=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"]),YN=10,If=3e4,fA=6e4;function gA(s){return`autopilot:${s}`}var Af=(s,e)=>e==="insert"||e==="update",Nc={code:"AUTOPILOT_NOT_READY",message:"Autopilot module is not initialized."},ss={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."},QN=new Set(["autopilot:pause","autopilot:resume","autopilot:skip-node"]),jc=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-QO4MPHZD.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!==gA(r))}async handle(e){if(!KN.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){E(this.deps,e.type,"autopilot:error",e,new Error(Nc.message),{code:Nc.code}),QN.has(e.type)&&Ie(this.deps,"error","Autopilot",Nc.message,{code:Nc.code})}resolveCurrentOperation(){return this.currentOperationId!==void 0?this.operations.get(this.currentOperationId):void 0}evictOldOperations(){for(;this.operations.size>YN;){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=$(ay,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){E(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=$(dy,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){E(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=$(cy,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 l=A(this.deps,e,"autopilot:schema-result",{graph:c});this.deps.broker.postToWebview(l)}catch(i){this.operations.delete(e.id),this.currentOperationId===e.id&&(this.currentOperationId=n),E(this.deps,"autopilot:scan-schema","autopilot:error",e,i),Ie(this.deps,"error","Autopilot",`Schema scan failed: ${O(i)}`)}}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){Ie(this.deps,"error","Autopilot","No schema scan result available. Run scan-schema first.");return}let r=$(ly,e,"autopilot:error",this.deps);if(!r)return;let n=r;try{let o=n.complianceFramework!=="none"&&t.scanResult?aR(this.deps.infraServices?.piiDetector??new va,t.scanResult.objectDescribes):[],{profile:i,rules:a}=this.orchestrator.buildCompliance(n.complianceFramework,[],o);t.profile=i,t.rules=a;let d=this.orchestrator.generatePlan(t.graph,n.complianceFramework,a,t.scanResult?.scope);t.plan=d,t.fit&&(t.fit={...t.fit,plan:this.orchestrator.generatePlan(t.fit.graph,n.complianceFramework,a,t.fit.scan.scope)}),await this.sendPlanReady(e,t)}catch(o){E(this.deps,"autopilot:generate-plan","autopilot:error",e,o),Ie(this.deps,"error","Autopilot",`Plan generation failed: ${O(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;try{d=a?await this.planWriteGate(t.targetOrgId,Nu(o,a.recordCounts,a.personAccounts),r??await this.readTargetDataStorage(t.targetOrgId)):void 0}catch(l){this.deps.log(`[WARN] ${e.type}: what the plan comes to against the target could not be told (${O(l)})`)}if((t.fit??t).plan!==o)return;let c=A(this.deps,e,"autopilot:plan-ready",{plan:o,graph:i,...d?{writeGate:d}:{},...n?{fitNotApplied:n}:{}});this.deps.broker.postToWebview(c)}async planWriteGate(e,t,r,n){let o=await wR(t,r,()=>this.readTargetApiBudget(e),n);return lA(t,vr(t,r),o)}refuseFit(e,t,r,n){E(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=$(py,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,Lo.NO_PLAN,"No execution plan available. Run generate-plan first.");return}let{targetOrgId:c}=n;if(this.writingTargets.has(c)){this.refuseFit(e,ss.code,ss.message);return}try{let l=await this.readTargetAutomation(c,o),u=r.muteAutomation===!0?await this.planMute(c,l).catch(R=>{if(!xt(R))throw R}):void 0,f=await this.readTargetDataStorage(c),p=r.checkpointFirst!==void 0?await this.checkpointFirstOf(e,c,o,r.checkpointFirst,{read:l,...u?{mute:u}:{}},new AbortController().signal):void 0,g=iR({storage:f,...r.mode.withinMB!==void 0?{withinMB:r.mode.withinMB}:{},..."unread"in f?{}:{api:f.dailyApiRequests??{unread:"the target's /limits did not list them"}},otherRequests:Mo(p&&"estimate"in p?p.estimate:void 0)});if("unread"in g){this.refuseFit(e,Lo.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:l,...u?.plan?{mutePlan:u.plan}:{},describeLookups:async R=>hR((await m.describe(R)).fields)})}catch(R){let k=O(R);this.refuseFit(e,Lo.READ_REFUSED,`The plan could not be fitted: the source refused a read of it (${k}).`,{reason:k});return}if(n.plan!==o||this.currentOperationId!==n.id||this.writingTargets.has(c)){this.refuseFit(e,Lo.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,f);return}y.report.cannotFit===void 0&&(n.fit=void 0),await this.sendPlanReady(e,n,f,y.report)}catch(l){E(this.deps,"autopilot:fit-plan","autopilot:error",e,l)}}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,Lo.NO_PLAN,"No execution plan available. Run generate-plan first.");return}if(this.writingTargets.has(t.targetOrgId)){this.refuseFit(e,ss.code,ss.message);return}t.fit=void 0;try{await this.sendPlanReady(e,t)}catch(r){E(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){Ie(this.deps,"error","Autopilot","No execution plan available. Run generate-plan first.");return}let r=$(uy,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,l=this.deps.infraServices?.productionGuard;if(!l){Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:be.code}),E(this.deps,"autopilot:execute","autopilot:error",e,new Error(be.message),{code:be.code});return}if(this.writingTargets.has(t.targetOrgId)){E(this.deps,"autopilot:execute","autopilot:error",e,new Error(ss.message),{code:ss.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,l)}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 l=Array.from(i.recordCounts.values()).reduce((q,V)=>q+V,0),u=a?uA(a.report,l,[...t.scanResult?.recordCounts.values()??[]].reduce((q,V)=>q+V,0)):void 0,f=new AbortController,p=()=>{},g=new Promise((q,V)=>{p=we=>we===void 0?q():V(we)});g.catch(()=>{}),this.registry?.register(e.id,"autopilot","Autopilot run",g,f);let h=this.deps.orgManager.getOrg(t.targetOrgId),m={orgId:t.targetOrgId,orgTier:Ee(h),operation:"insert",objectName:r.waves[0]?.objects[0]??"AutopilotData",recordCount:l,module:"autopilot"},{check:y,decision:R}=await Ze(c,m),k=R;if((R==="refused"||R==="declined")&&Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:R,...u?{fit:u}:{}}),R==="refused"){let q=mn(y.blockedReason??y.impactSummary);E(this.deps,"autopilot:execute","autopilot:error",e,q,{code:$t.blocked}),p(q);return}if(R==="declined"){let q="Operation cancelled by user (confirmation declined).";E(this.deps,"autopilot:execute","autopilot:error",e,new Error(q),{code:$t.declined}),p(new Error(q));return}let w=Nu(r,i.recordCounts,i.personAccounts),I,P;if(d.muteAutomation===!0)try{({mute:I,read:P}=await this.runMute(t.targetOrgId,r))}catch(q){if(!xt(q))throw q;Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:k,...u?{fit:u}:{},code:q.code}),E(this.deps,"autopilot:execute","autopilot:error",e,q,{code:q.code}),p(q);return}let b;if(d.checkpointFirst!==void 0&&w.totalRows>0){P??=await this.readTargetAutomation(t.targetOrgId,r);let q=await this.checkpointFirstOf(e,t.targetOrgId,r,d.checkpointFirst,{read:P,mute:I},f.signal);if("refused"in q){Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:k,...u?{fit:u}:{},code:Ws.CHECKPOINT_REFUSED});let V=new Error(q.refused);E(this.deps,"autopilot:execute","autopilot:error",e,V,{code:Ws.CHECKPOINT_REFUSED}),p(V);return}b=q}w.totalRows>0&&(P??=await this.readTargetAutomation(t.targetOrgId,r));let S=await this.targetEmails(t.targetOrgId,r,w,I?I.automation:P),C=new Set(w.objects.map(({objectApiName:q})=>q)),v=(q,V)=>C.has(q)&&Af(q,V),T=he(h,t.targetOrgId),D=P?await ar({read:P,...I?.plan?{plan:I.plan}:{},writes:v,readDeliverability:async()=>m.orgTier==="production"?qt:Wt(await B(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager)),accepted:!1,target:T,run:"autopilot",keepsAddresses:d.keepContactPoints===!0}):void 0,z=await bR({plan:w,storage:await this.readTargetDataStorage(t.targetOrgId),readApiBudget:()=>this.readTargetApiBudget(t.targetOrgId),confirmAboveRecords:this.confirmAboveRecords(),emails:S.checks,...S.unread!==void 0?{emailsUncounted:S.unread}:{},org:T,orgTier:m.orgTier,confirm:q=>c.confirmRun(q),...b?{checkpointFirst:b}:{},readBack:yR(w),mute:Xr(I?.plan),...D?{runEmails:D}:{}});if(!z.go){Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:k,...u?{fit:u}:{},code:z.code,details:Yn(z.emails)});let q=new Error(z.message);E(this.deps,"autopilot:execute","autopilot:error",e,q,{code:Ws[z.code],...await this.fitOffer(t,z,w,b)}),p(q);return}this.liveTracker?.register(e.id,"autopilot","Autopilot run",l),this.executingOperations.add(t.id);let H=new Map,Y=!1,U=I?.muted,M=z.checkpoint,L,ee=!1,Q=q=>{Y||(Y=!0,Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:q,guard:k,objects:[...H.values()],source:{origin:"org",orgId:t.sourceOrgId},...q==="stopped"?{code:nt}:{},...U?{muted:ct(U)}:{},...L?.state==="taken"?{checkpointId:L.checkpointId}:{},...u?{fit:u}:{},details:Yn(z.emails)}))};try{d.grappeThreshold&&this.deps.log(`[GRAPPE] autopilot threshold set to ${d.grappeThreshold}`);for(let N of r.waves)for(let X of N.objects)this.sendNodeProgress(e,String(X),"processing",N.order);let q=new Map;for(let N of r.waves)for(let X of N.objects)q.set(String(X),N.order);let V=I?.prepared?await I.prepared.acquire(e.id).catch(N=>{if(!xt(N))throw N;return N}):void 0;if(xt(V)){M&&(L=await this.settleCheckpoint(M,!1)),Y=!0,Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:k,...u?{fit:u}:{},code:V.code}),this.liveTracker?.fail(e.id,V.message),E(this.deps,"autopilot:execute","autopilot:error",e,V,{code:V.code,...L?{extraPayload:{checkpoint:L}}:{}}),p(V);return}V&&(U=V.outcome);let we=V?D?.afterLease(V.outcome,z.emails?.accepted===!0):void 0;if(V&&we){U=await V.release(),M&&(L=await this.settleCheckpoint(M,!1)),Y=!0,Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:k,code:we.code,muted:ct(U),details:Yn(z.emails)});let N=ub(we.message,"autopilot","Untick Mute automation to be asked about them and run it all the same"),X=new Error(N);this.liveTracker?.fail(e.id,N),E(this.deps,"autopilot:execute","autopilot:error",e,X,{code:Ws.EMAILS_NOT_ACCEPTED,...L?{extraPayload:{checkpoint:L}}:{}}),p(X);return}ee=!0;let re=await this.orchestrator.executePlan(r,n,o,i.recordCounts,N=>{let X=String(N.objectApiName);H.set(X,{...ht(X),...N.type==="node-completed"?{created:N.successCount,failed:N.failureCount}:{created:N.partialSuccessCount,failed:N.failureCount??0}});let F=[...H.values()].reduce((de,J)=>de+J.created+J.failed,0);this.liveTracker?.updateProgress(e.id,l>0?Math.round(F/l*100):0,F,l,X),N.type==="node-completed"?this.sendNodeProgress(e,X,"completed",q.get(X)??0,{recordCount:N.successCount,failureCount:N.failureCount,linkedCount:N.linkedCount,refusals:N.refusals,apiCallsUsed:N.apiCallsUsed}):this.sendNodeProgress(e,X,"failed",q.get(X)??0,{recordCount:N.partialSuccessCount,failureCount:N.failureCount,linkedCount:N.linkedCount,refusals:N.refusals,error:N.errors[0]??`Execution failed for ${X}`})},f.signal,i.parentIds,{...d.keepContactPoints===!0?{keepContactPoints:!0}:{},...V?{lease:{assigned:V.outcome.assigned.length,giveBack:()=>V.release()}}:{},...a?{fit:a.run}:{}}).finally(async()=>{V&&(U=await V.release())});M&&(L=await this.settleCheckpoint(M,re.totalSuccess>0));let Ae=new Set(re.completedObjects),me=new Set(re.failedObjects),Je=new Set(re.skippedObjects),Ne=new Set(re.stoppedObjects??[]),Fe=[],W=0,se=[],te=[];for(let N of r.waves)for(let X of N.objects){let F=String(X),de=re.objectOutcomes?.[F],J=re.statuses?.[F],le=re.lookups?.[F],Pe=(de?.leftToThePlatform??[]).reduce((He,st)=>He+st.count,0),je={...de?{recordCount:de.written,failureCount:de.failed,linkedCount:de.linked,refusals:de.refusals,...Pe>0?{leftToThePlatform:Pe}:{},...de.currenciesReplaced?{currenciesReplaced:de.currenciesReplaced}:{},...de.pricesSettled?{pricesSettled:de.pricesSettled}:{},...de.recordTypeGiven?{recordTypeGiven:de.recordTypeGiven}:{},...de.cutSinceFit!==void 0?{cutSinceFit:de.cutSinceFit}:{},...de.sentAgainForALock?{sentAgainForALock:de.sentAgainForALock}:{}}:{},...J?{statusesApplied:J.applied,statusRefusals:J.refusals}:{},...le?{lookupsFilled:le.filled,lookupRefusals:le.refusals}:{}};if(Ae.has(F))this.sendNodeProgress(e,F,"completed",N.order,{recordCount:i.recordCounts.get(F)??0,failureCount:0,...je});else if(me.has(F))this.sendNodeProgress(e,F,"failed",N.order,{...je,error:re.nodeErrors?.[F]??`Execution failed for ${F}`});else if(Je.has(F)){let He=i.recordCounts.get(F)??0;H.set(F,{...ht(F),skipped:"counted",...He>0?{notSent:He}:{}}),this.sendNodeProgress(e,F,"skipped",N.order,{recordCount:0,failureCount:0,...He>0?{notSent:He}:{}})}else if(Ne.has(F)){let He=de?.notSent??0;W+=de?.heldForTheirTask??0,H.set(F,{...ht(F),created:de?.written??0,failed:de?.failed??0,...He>0?{notSent:He}:{}}),this.sendNodeProgress(e,F,"stopped",N.order,{...je,recordCount:de?.written??0,failureCount:de?.failed??0,...He>0?{notSent:He}:{}})}let We=()=>H.get(F)??{...ht(F),created:de?.written??0,failed:de?.failed??0},ae=de?.lookupsLeftEmpty??0,Re=de?.statusesNotGivenBack??0;if(ae+Re>0){let He={...ae>0?{lookupsLeftEmpty:ae}:{},...Re>0?{statusesNotGivenBack:Re}:{}};Fe.push({objectApiName:F,...He}),H.set(F,{...We(),...He})}le?.leftEmpty!==void 0&&(se.push({objectApiName:F,records:le.leftEmpty,refusals:le.refusals}),H.set(F,{...We(),lookupsNotFilled:le.leftEmpty}));let Ue=J?.leftDraft??0;J&&Ue>0&&(te.push({objectApiName:F,records:Ue,refusals:J.refusals}),H.set(F,{...We(),statusesNotApplied:Ue}))}let ue=gR(re);Q(re.stopped?re.totalSuccess+re.totalFailure>0?"cancelled":"stopped":ue);let x=A(this.deps,e,"autopilot:completed",{status:ue,totalRecords:re.totalSuccess+re.totalFailure+re.totalSkipped,totalSuccessCount:re.totalSuccess,totalFailureCount:re.totalFailure,totalElapsedMs:re.elapsedMs,totalApiCalls:0,...U?{mutedAutomation:U}:{},...L?{checkpoint:L}:{},...re.cutSinceFit!==void 0?{cutSinceFit:re.cutSinceFit}:{},...se.length>0?{lookupsNotFilled:se}:{},...te.length>0?{statusesNotApplied:te}:{},...re.stopped?{stopped:!0,notWritten:re.stoppedObjects??[],...Fe.length>0?{leftByStop:Fe}:{},...W>0?{emailsHeldForTheirTask:W}:{}}:{}});this.deps.broker.postToWebview(x),re.stopped?this.liveTracker?.cancel(e.id):ue==="failure"?this.liveTracker?.fail(e.id,re.fatalError??"No record could be written."):ue==="partial"?this.liveTracker?.partial(e.id):this.liveTracker?.complete(e.id),p()}catch(q){this.liveTracker?.fail(e.id,O(q)),p(q),M&&L===void 0&&(L=await this.settleCheckpoint(M,ee)),Q("failure"),E(this.deps,"autopilot:execute","autopilot:error",e,q,L?{extraPayload:{checkpoint:L}}:void 0),Ie(this.deps,"error","Autopilot",`Execution failed: ${O(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),Di):5e4}confirmAboveRecords(){let e=this.deps.services?.getSandforgeSetting?.("safety.confirmAboveRecords",Qr);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):Qr}async readTargetDataStorage(e){try{let t=await B(e,this.deps.orgRegistry,this.deps.orgManager);return await new fe(If).withTimeout("autopilot:limits",()=>Rr(t))}catch(t){return{unread:O(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 Ot(async()=>Lt(await B(e,this.deps.orgRegistry,this.deps.orgManager)),t,{...this.muteLeases,writes:Af})}async readTargetAutomation(e,t){let r=this.targetAutomation;return new fe(fA).withTimeout("autopilot:automation",()=>r.read(e,La(t))).catch(n=>({unread:O(n)}))}async checkpointFirstOf(e,t,r,n,o,i){let a=this.beforeRunCheckpoints;if(!a)return{refused:br(new Error("SandForge's checkpoints are not set up in this window"))};let{read:d,mute:c}=o,l="objects"in d?Wr(d,c?.plan,Af):{firing:[]},u={module:"autopilot",orgId:t,operationId:e.id,written:La(r),running:l,request:n},f={operationId:gA(e.id)};try{return{estimate:await a.scope(u,f),take:g=>a.take(u,f,{planned:g,signal:i})}}catch(p){return{refused:br(p)}}}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 (${O(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:he(a,o),estimateMB:i.estimateMB,...i.verdict==="unread"?{}:{remainingMB:i.remainingMB,maxMB:i.maxMB}};try{let c=await this.planWriteGate(o,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 (${O(c)})`),{extraPayload:d}}}async readTargetApiBudget(e){let t=await B(e,this.deps.orgRegistry,this.deps.orgManager);return new fe(If).withTimeout("autopilot:limits",()=>dr(t))}async targetEmails(e,t,r,n){let o=this.targetAutomation,i=await mR({plan:r,objects:La(t),readAutomation:a=>n?"objects"in n?Promise.resolve(n):Promise.reject(new Error(n.unread)):new fe(fA).withTimeout("autopilot:automation",()=>o.read(e,a)),readLimits:async()=>{let a=await B(e,this.deps.orgRegistry,this.deps.orgManager);return new fe(If).withTimeout("autopilot:limits",()=>Sr(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()){Ie(this.deps,"warning","Autopilot","No autopilot execution in progress.");return}try{this.orchestrator.pause();for(let t of this.runningRequests)this.liveTracker?.pause(t);Ie(this.deps,"info","Autopilot","Execution paused.")}catch(t){E(this.deps,"autopilot:pause","autopilot:error",e,t),Ie(this.deps,"error","Autopilot",`Pause failed: ${O(t)}`)}}handleResume(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}if(!this.hasExecutingOperation()){Ie(this.deps,"warning","Autopilot","No autopilot execution in progress.");return}try{this.orchestrator.resume();for(let t of this.runningRequests)this.liveTracker?.resume(t);Ie(this.deps,"info","Autopilot","Execution resumed.")}catch(t){E(this.deps,"autopilot:resume","autopilot:error",e,t),Ie(this.deps,"error","Autopilot",`Resume failed: ${O(t)}`)}}handleSkipNode(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=$(fy,e,"autopilot:error",this.deps);if(!t)return;let r=t;if(!this.hasExecutingOperation()){Ie(this.deps,"warning","Autopilot","No autopilot execution in progress.");return}try{this.orchestrator.skip(r.objectApiName),Ie(this.deps,"info","Autopilot",`Skipped node: ${r.objectApiName}`)}catch(n){E(this.deps,"autopilot:skip-node","autopilot:error",e,n),Ie(this.deps,"error","Autopilot",`Skip failed: ${O(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){Ie(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){E(this.deps,"autopilot:compliance-report","autopilot:error",e,r),Ie(this.deps,"error","Autopilot",`Report generation failed: ${O(r)}`)}}};import{dirname as Cf}from"node:path";import{AsyncLocalStorage as ZN}from"node:async_hooks";var ej=new ZN;async function hA(s){let e=new Map;return{result:await ej.run(e,s),sent:e}}function mA(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 Tf from"node:path";var Mc="forge:imported-templates",tj=10,yA="forge",rj=G({folder:j().min(1),templates:ve(pn()),replacing:ve(j())});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 bi(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 Ef(s,e){return Tf.resolve(s)===Tf.resolve(e)}function Pf(s){let e=s.get(Mc);if(!Array.isArray(e))return[];let t=[];for(let r of e){let n=rj.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 Lc(s,e){return Pf(s).find(t=>Ef(t.folder,e))}function wA(s,e,t,r){if(t.length===0)return;let n=Pf(s),o=n.findIndex(d=>Ef(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(Mc,n.slice(-tj),yA)}function bA(s,e){let t=Pf(s).filter(r=>!Ef(r.folder,e));t.length>0?s.set(Mc,t,yA):s.delete(Mc)}function nj(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 oj(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:nj(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 RA(s){let{leftOut:e,...t}=s.graph,r=new Map;for(let u of e??[])r.set(u.reason,(r.get(u.reason)??0)+1);let n=[...r].map(([u,f])=>({reason:u,count:f})).sort((u,f)=>f.count-u.count||u.reason.localeCompare(f.reason)),{idRemapWithTheirRecord:o,sample:i,config:a,...d}=s,c=s.remapInJournal?void 0:o,l=a?.sample?{...a.sample}:void 0;return l&&delete l.plan,{...d,graph:{...t,edges:[],withoutEdges:!0},...a?{config:l?{...a,sample:l}:a}:{},...i?{sample:oj(i)}:{},...n.length>0?{leftOutCounts:n}:{},...c?{idRemapWithTheirRecord:c}:{}}}var vA="SELECT Id, Name, Username FROM User WHERE IsActive = true AND UserType = 'Standard' ORDER BY Name LIMIT 2001";function SA(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 jf=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/,po=j().min(1).max(128),ij=G({recordId:j().regex(jf,"Invalid Salesforce record ID"),orgId:po}),Ln=ug.superRefine((s,e)=>{if(s.inputMode!=="org"&&s.depth!=="all"&&s.sample===void 0)return;let t=Ml(s);t!==void 0&&e.addIssue({code:"custom",message:t,path:["inputMode"]});let r=aj(s.sample);r!==void 0&&e.addIssue({code:"custom",message:r.message,path:r.path})});function aj(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 dj=G({config:Ln}),cj=G({graph:_r,config:Ln,anonymizationRules:Ni.optional(),files:fg.optional(),retryOf:j().min(1).max(200).optional(),reviewSkipped:Ge().optional(),muteAutomation:Ge().optional(),checkpointFirst:Vh.optional()}).superRefine((s,e)=>{let t=pg(s.config,s.files);t!==void 0&&e.addIssue({code:"custom",message:t,path:["files"]})});function lj(s,e){let t=s.check(e);return{check:t,decision:t.allowed?"allowed":"refused"}}var kA="FILES_NOT_ACCEPTED",OA="RETRY_UNAVAILABLE",uj="GRAPH_WITHOUT_EDGES",pj="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.",fj="WHOLE_ORG_DIRECT",gj="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.",hj="WHOLE_ORG_REHEARSAL",mj="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.",yj="A clone of the whole org keeps its journal on disk, which could not be opened. Nothing was written.",$f="JOURNAL_UNAVAILABLE",wj="RESUME_TARGET_UNREAD",un=class extends Error{constructor(t,r){super(r);this.code=t;this.name="ForgeRunRefusal"}code};function IA(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:O(s),lift:t}}function bj(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 _c="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.",is="JOURNAL_GONE",jn=`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. ${_c}`,as="RUN_NOT_IN_HISTORY",xf="REMOVAL_RUNNING",Ri="RUN_WRITING",Rj="VERIFY_RUNNING",AA="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.",vj="RESUME_UNAVAILABLE",TA="remove the records it created (Forge \u2192 Recent runs), then run the clone again. Nothing was read or written.",EA="RESUME_TARGET_CHANGED",Df="RESUME_CHANGED",Sj=G({forgeId:j().min(1).max(200),graph:_r.optional(),config:Ln.optional(),muteAutomation:Ge().optional()}).strict(),PA=new Set(["cancelled","failure","interrupted"]),Mn="Forge execution was aborted before it started. Nothing was written.",Nf="FORGE_RUNNING",kj="FORGE_STOP_AMBIGUOUS",Oj={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.`}},Ij=G({requestId:j().min(1).max(200).optional()}).optional(),Aj=G({template:Ll}),Tj=G({forgeId:j().min(1).max(200),includeChanged:Ge().optional(),sweep:Ge().optional(),again:Ge().optional(),muteAutomation:Ge().optional(),sweepLate:Ge().optional(),sweepUntied:Ge().optional()}),Ej=G({forgeId:j().min(1).max(200),again:Ge().optional(),sweptObjects:Jh.optional()}),Pj=G({forgeId:j().min(1).max(200)}),Cj=G({forgeId:j().min(1).max(200),recordId:j().regex(jf,"Invalid Salesforce record ID")}).strict(),$j=G({forgeId:j().min(1).max(200)}).strict(),xj=G({forgeId:j().min(1).max(200)}).strict(),Dj=5e3,Nj=G({templateId:j().min(1).max(200)}),jj=G({graph:_r,config:Ln}),Mj=G({framework:j().min(1).max(50),graph:_r,config:Ln,anonymizationRules:Ni.optional()}),Lj=G({sourceOrgId:po,targetOrgId:po,objectApiNames:ve(j().regex(/^[A-Za-z][A-Za-z0-9_]*$/).max(80)).max(100)}),Fj=G({graph:_r,config:Ln,anonymizationRules:Ni.optional()}),_j=G({targetOrgId:po,graph:_r}),Uj=G({graph:_r,config:Ln}),Hj=G({orgId:po}),Bj=G({targetOrgId:po,objectApiNames:ve(j().min(1).max(255)).max(5e3)}),qj=G({graph:_r,config:Ln,muteAutomation:Ge().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"]}),Wj=G({sourceOrgId:po,soqlQuery:j().min(1).max(2e4),maxRoots:Te().int().min(1).max(cg).optional()}),zj=[[/ 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."]],Gj=[[/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"]],qA=new Set(["SAMPLE_DRAW_INVALID","SAMPLE_DRAW_EMPTY"]);function Jj(s){if(s.code==="ROOTS_EXCEEDED")return new ut(s.code,Gj.reduce((t,[r,n])=>t.replace(r,n),s.message));if(!qA.has(s.code))return s;let e=zj.reduce((t,[r,n])=>t.replace(r,n),s.message);return new ut(s.code,e,void 0,void 0,void 0,{...s.sample?{sample:s.sample}:{}})}var Vj="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.",Xj="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.",Kj=16;function CA(s){let e=s.fit();return e?{fit:e}:{}}function Fc(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 Yj(){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 ot(s,e,t,r){return $(s,e,t,r)}var Qj={holder:s=>YR(s),take:(s,e)=>{let t=KR(s,{...e,ranFrom:"editor"});return"busy"in t?t:{release:()=>t.lock.release()}}};function vi(s){return s.charAt(0).toUpperCase()+s.slice(1)}function Zj(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 $A(s){return s.successCount+s.updatedCount>0}function xA(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 e0(s){let e=new Set([...s.created,...s.unattributed??[]].flatMap(({ids:r})=>r.map(n=>n.slice(0,15)))),t=new Set(s.remap.withTheirRecord??[]);return s.remap.linked.filter(r=>{let n=s.remap.table[r];return!t.has(r)&&n!==void 0&&e.has(n.slice(0,15))}).length}function t0(s,e){let t=s.remap.createdByObject.reduce((d,c)=>d+c.sourceIds.length,0),r=Object.keys(s.remap.table).length,n=e0(s),o=new Set(s.remap.withTheirRecord??[]),i=s.remap.linked.filter(d=>o.has(d)),a=r>_a?{idRemapTable:{},idRemapExisting:[],idRemapCreated:[],idRemapByObject:s.remap.createdByObject.map(({objectApiName:d,sourceIds:c})=>({objectApiName:d,created:c.length,linked:0})),remapInJournal:!0,...i.length>0?{withTheirRecordCount:i.length}:{}}:{idRemapTable:s.remap.table,idRemapExisting:s.remap.linked,idRemapCreated:s.remap.createdByObject,...i.length>0?{idRemapWithTheirRecord:i}:{}};return{forgeId:s.parts>1?`${s.journalId}-${s.parts-1}`:s.journalId,status:"partial",interrupted:!0,graph:e,duration:0,timestamp:s.partStartedAt,idRemapCount:r,...a,createdCount:t,linkedExistingCount:s.remap.linked.length,...n>0?{linkedToCreatedCount:n}:{},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 r0=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: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"]),DA=3e4,n0=6e4,o0=3e4,s0=6e4,Si=6e4,i0=12e4;function NA(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 jA="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,l0=8,ds=3e4,u0=3e4,MA="forge:templates",LA="forge:history";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(l=>{let u=a[l];return u!==void 0?[u]:[]}),c=i.wroteToEarlierParts??[];return c.length===0&&d.length===0?[]:[{span:WA(i.writtenBetween,i),...c.length>0?{wrote:c}:{},...d.length>0?{linked:d}:{}}]})}function WA(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=vn(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 Fu(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 FA="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=Kw,o=e.inputMode==="org"?void 0:e.maxRecordsPerObject,i=jl(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 _A(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 UA(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 HA(s,e){return s.apiCalls===void 0?s:{...s,apiCalls:s.apiCalls+e}}function BA(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 Uc=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 Hc=class s{constructor(e,t,r){this.deps=e;this.externalBrowser=t??new $r,this.saveDialog=r??new kn}deps;abortController=null;stops=new qR;executeOperationId=null;writingTo=null;orchestrator;planGenerator;complianceService;metadataDiff;targetAutomation;targetGaps;requestsSent;muteOrgOf;muteLeases;lostBulkJobs;beforeRunCheckpoints;rehearser;rehearseOperationId=null;templateStore;removalPlans;runJournal;otherModuleRuns=()=>Promise.resolve([]);journalsRunning=new Set;journalLocks=Qj;describeGlobalCache=new zs({defaultTtl:5*6e4,maxSize:16,maxSizeBytes:50*1024*1024});dmlTracker=new ra;removing=new Set;trials=new VR;simulations=new Mb;sampleSimulations=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.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,l)=>{i=u=>{u===void 0?c():l(u instanceof Error?u:new Error(String(u)))}}),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(!r0.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: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(MA);return{templates:Array.isArray(e)?e.filter(ln):[]}}return this.withImportedTemplates(this.templateStore)}async withImportedTemplates(e){let t=Lc(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=O(n);return oe.warn(`Imported forge templates not written into .sandforge/: ${o}`),{templates:await e.list(),importNotMerged:o}}return bA(this.deps.configStore,e.workspacePath),oe.info("Merged an imported set of forge templates into .sandforge/"),{templates:r}}async saveTemplates(e){if(!this.templateStore){this.deps.configStore.set(MA,e,FA);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(LA)??[]}saveHistory(e){this.deps.configStore.set(LA,e,FA)}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=ot(ij,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 w=await o.describeGlobal();$e(o.limitInfo,"forge:preview describeGlobal"),a=w.sobjects.map(I=>({name:I.name,label:I.label,keyPrefix:I.keyPrefix??null})),this.describeGlobalCache.set(n,a)}let d=a.find(w=>w.keyPrefix===i),c=he(this.deps.orgManager.getOrg(n),n),l=(w,I)=>{this.deps.broker.postToWebview(A(this.deps,e,"forge:preview:error",{code:w,orgName:c,message:I}))};if(!d){l("UNKNOWN_KEY_PREFIX",`No object of ${c} has ids starting "${i}": the record is read from the source org picked.`);return}let u=await Nh(o,d.name,`SELECT FIELDS(STANDARD) FROM ${d.name} WHERE Id = '${er(r)}' LIMIT 1`);if($e(o.limitInfo,`forge:preview query ${d.name}`),!u||u.length===0){l("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 f=u[0],p=new Set(["attributes","Id"]),g=Object.entries(f).filter(([w])=>!p.has(w)).filter(([,w])=>w!=null&&String(w)!=="").slice(0,8).map(([w,I])=>({name:w,value:String(I)})),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 R=y*.001,k=A(this.deps,e,"forge:preview:response",{objectApiName:d.name,objectLabel:d.label,recordId:r,fields:g,estimatedRecordCount:y,totalFieldCount:m,estimatedSize:R});this.deps.broker.postToWebview(k)}catch(o){E(this.deps,"forge:preview","forge:preview:error",e,o,{code:"PREVIEW_ERROR"})}}async handleDiscover(e){if(!this.orchestrator){E(this.deps,"forge:discover","forge:discover:error",e,new Error("Forge module is not initialized"),{code:"NOT_INITIALIZED"});return}let t=ot(dj,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 u of a)this.stopDiscovery(u);ze(this.deps,o,"forge","Discovering object graph");let d=this.trackRun(o,"Discovering object graph",n),c,l=Fc(u=>{let f=A(this.deps,e,"forge:discover:progress",u);this.deps.broker.postToWebview(f)},100);try{oe.info("Forge discover started");let u=this.orchestrator,{result:f,sent:p}=await hA(()=>u.discover(r,{...r.inputMode==="org"?{}:{maxNodes:r.maxNodes},signal:n.signal,onProgress:y=>{l(y)}}));if(l.flush(),n.signal.aborted){pe(this.deps,o,{aborted:!0}),this.answerStoppedDiscovery(e,i);return}let g=mA(p,r),h=UA(r,f);this.discoverySent.delete(h),g&&this.discoverySent.set(h,g);for(let y of this.discoverySent.keys()){if(this.discoverySent.size<=l0)break;this.discoverySent.delete(y)}let m=A(this.deps,e,"forge:discover:response",{graph:g?{...f,discoveryRequests:g}:f});this.deps.broker.replyToRequester(m),pe(this.deps,o,{nodeCount:f.nodes?.length??0}),oe.info("Forge discover finished",{objects:f.nodes?.length??0,records:f.totalRecords})}catch(u){if(l.flush(),n.signal.aborted){pe(this.deps,o,{aborted:!0}),this.answerStoppedDiscovery(e,i);return}c=u,E(this.deps,"forge:discover","forge:discover:error",e,u,{code:"DISCOVER_ERROR",retryable:!0}),De(this.deps,o,O(u),!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}=Oj[t.stop??"stopped"];E(this.deps,"forge:discover","forge:discover:error",e,new Error(n),{code:r,retryable:!0})}async handleExecute(e,t){if(!this.orchestrator){E(this.deps,"forge:execute","forge:execute:error",e,new Error("Forge module is not initialized"),{code:"NOT_INITIALIZED"});return}let r=t?t.startedWith:ot(cj,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),l=t?t.forgeId:r.retryOf,u=l!==void 0?Zj(l,this.loadHistory()):void 0,f=l===void 0?r.checkpointFirst:void 0;l!==void 0&&r.checkpointFirst!==void 0&&oe.info("Forge run: no checkpoint taken for a retry or a resume, which takes up a run that wrote",{checkpoint:u?.checkpointId??"none"});let p=c.dryRun===!0,g=Hu(n,c),h=jb(c),m=new XR(c,{reviewSkipped:a===!0,...this.trials.before(g)}),y=c.inputMode==="org",R=y&&c.sample!==void 0,k=(Me,Xe)=>{p||Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:Me,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(Xe),{code:Me})};if(n.withoutEdges===!0){k(uj,pj);return}if(y&&a===!0){k(fj,gj);return}let w=y?_R(n):void 0;if(w){k(w.code,w.message);return}let I=i?dg(c.anonymizePII,i.acceptedAsIs):null;if(I){Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:kA,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(I),{code:kA});return}let P,b,S;if(l!==void 0&&!t){let Me=await this.runToRetry(l,c.targetOrgId);if("refused"in Me){Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:OA,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(Me.refused),{code:OA});return}P=Me.written,b=Me.journalId!==void 0?{journalId:Me.journalId}:{},S=Me.roots}let C=this.deps.infraServices?.productionGuard;if(!C){Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:be.code,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(be.message),{code:be.code});return}let v=this.deps.orgManager.getOrg(c.targetOrgId),T=Ee(v),D=he(v,c.targetOrgId);if(T==="production"){this.refuseAtGate(e,c.targetOrgId,new ut("PRODUCTION_TARGET",`${D} 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 z=await this.ownerMapRefusal(c);if(z){p||Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:z.code,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,z,{code:z.code,retryable:!0});return}let H={orgId:c.targetOrgId,orgTier:T,operation:"insert",...k0(n,c),module:"forge"},Y=new AbortController,U=this.stops.awaitGuard(e.id,Y),{check:M,decision:L}=p?lj(C,H):await Ze(C,H).finally(U);p&&U();let ee=L;if(M.warnings.length>0&&oe.warn("Forge run: Production Guard warnings",{warnings:M.warnings}),(L==="refused"||L==="declined")&&Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",guard:L,context:m.context()}),L==="refused"){E(this.deps,"forge:execute","forge:execute:error",e,new Error(`Operation blocked by Production Guard: ${M.blockedReason??M.impactSummary}`),{code:"GUARD_BLOCKED"});return}if(L==="declined"){E(this.deps,"forge:execute","forge:execute:error",e,new Error("Operation cancelled by user (confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}if(Y.signal.aborted){Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",guard:L,code:Rt,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(Mn),{code:Rt,retryable:!0});return}let Q=`${c.sourceOrgId}:${c.targetOrgId}:${c.recordId??""}`,q=n.nodes?.map(Me=>Me.objectApiName).join(",")??"",V=`forge:${Q}:${q}:${n.totalRecords??0}`+(l!==void 0?`:${t?"resume":"retry"}:${l}`:""),we=this.dmlTracker.isDuplicate(V)?this.dmlTracker.get(V):void 0,ie=this.lastWriteAt.get(V),re=ie!==void 0&&Date.now()-ie<s.DUPLICATE_COOLDOWN_MS;if(we?.status==="pending"||re){oe.warn("Duplicate forge execution detected",{operationId:V}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(`Duplicate forge operation: ${V}`),{code:"DUPLICATE"});return}if(this.executeOperationId!==null){Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",guard:L,code:Nf,context:m.context()}),E(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:Nf,retryable:!0});return}let Ae=n.totalRecords??0;we?(we.status="pending",we.recordCount=Ae,we.registeredAt=new Date().toISOString()):this.dmlTracker.register(V,"forge","upsert",Ae),this.abortController=Y;let me=`forge-execute-${this.deps.nextId()}`,Je=p?"Simulating forge operation":"Executing forge operation";ze(this.deps,me,"forge",Je);let Ne=this.trackRun(me,Je,Y,!0);this.liveTracker?.register(me,"forge",Je),this.executeOperationId=me,this.writingTo=p?null:c.targetOrgId,this.stops.beginRun(e.id,Y);let Fe=Date.now(),W,se,te,ue,x,N=!1,X=()=>{N||!se||(N=!0,se.close())},F={keep:!1},de=!1,J,le=async()=>{if(!W||de)return;de=!0;let Me=W,Xe=F;X(),await(Xe.keep?this.runJournal?.stop(Me,Xe.status,Xe.forgeId):this.runJournal?.end(Me))?.catch(Ke=>{oe.warn(`Forge run journal not ${Xe.keep?"kept":"dropped"}: ${O(Ke)}`)}),this.journalsRunning.delete(Me),J?.release(),J=void 0},Pe={requests:0},je,We=()=>{let Me=this.requestsSent?.();return Me===void 0||je===void 0?void 0:Pe.requests+Me-je},ae,Re=!1,Ue=[],He,st=0,Ve,_n,Ht,ps,Qt=[],Ei,fo=()=>(Ei??=this.jobsStillRunning(c.targetOrgId,ps,Pe).then(Me=>{Qt=Me}),Ei),go,Nr={firing:[]},Pi,jr,fs,fr,Ci=!1,Nt,Un,gs=Fc(Me=>{let Xe=A(this.deps,e,"forge:progress",Me);this.deps.broker.postToWebview(Xe)},100),Hn=Fc(Me=>{this.deps.broker.postToWebview(A(this.deps,e,"forge:sampling:progress",{...Me}))},100),Mr=this.liveProgressOf(me,n),Dl=Yj(),Bn=this.orchestrator.on("forge:progress",Me=>{let Xe=Dl(Me),Ke=We(),it=Ke===void 0?Xe:{...Xe,apiCalls:Ke};Mr(it);let Et=it.status;if(Et==="done"||Et==="error"||Et==="skipped"||Et==="stopped"){gs.flush();let tt=A(this.deps,e,"forge:progress",it);this.deps.broker.postToWebview(tt);return}gs(it)});try{oe.info("Forge execute started",{source:he(this.deps.orgManager.getOrg(c.sourceOrgId),"unknown org"),target:he(this.deps.orgManager.getOrg(c.targetOrgId),"unknown org")});let Me=this.maxRecordsPerObject(),Xe=$u(n,{leftOut:new Set(n.nodes.filter(Bi).map(ne=>ne.objectApiName)),retry:l!==void 0}),Ke=new Set(Xe.map(ne=>ne.objectApiName)),it=(ne,Ce)=>Ce==="insert"||Ce==="update"&&Ke.has(ne);if(p){if(f!==void 0||y||R){let ne=await this.automationBeforeTheRun(c.targetOrgId,n);if("automation"in ne){let Ce=d===!0?await Ot(()=>this.muteOrg(c.targetOrgId),ne.automation,{...this.muteLeases,writes:it}).then(Be=>Be.plan,Be=>{oe.warn(`Forge simulation: the mute could not be planned (${O(Be)})`)}):void 0;Nr=Wr(ne.automation,Ce,it),Pi=Ce}}}else{let ne=await this.automationBeforeTheRun(c.targetOrgId,n);st=Tn("automation"in ne?ne.automation:ne);let Ce=ne,Be;if(d===!0){let mt=await Ot(()=>this.muteOrg(c.targetOrgId),"automation"in ne?ne.automation:ne,{...this.muteLeases,writes:it});_n=mt.prepared,Ht=mt.muted,Be=mt.plan,"automation"in ne&&mt.automation&&(Ce={...ne,automation:mt.automation})}if("automation"in ne&&(Nr=Wr(ne.automation,Be,it)),He=Ce,"automation"in Ce&&(Ue=Fg(Ce.automation)),Y.signal.aborted)throw Re=!0,new Error(Mn);if(m.automationRead(Ce,Xe),fr=await ar({read:"automation"in ne?ne.automation:ne,...Be?{plan:Be}:{},writes:it,applyAssignmentRules:c.applyAssignmentRules===!0,readDeliverability:()=>this.readDeliverability(c.targetOrgId,Y.signal),accepted:!1,target:D,run:"clone",keepsAddresses:c.keepContactPoints===!0}),Pe.requests+=fr.ofRun.read?.requests??0,Y.signal.aborted)throw Re=!0,new Error(Mn);m.emailsRead(fr.gate.audit);let kt=await this.confirmAutomation(C,{orgId:c.targetOrgId,org:D,orgTier:T,username:v?.username},Ce,Xe,a===!0,fr.gate.confirmation);kt==="confirmed"&&(m.confirm("automation"),fr.gate.verdict==="asks"&&(Ci=!0,m.confirm("emails"))),ee=Kn(ee,kt);let at=y?[]:Nb(n,c.maxRecordsPerObject,Me);if(at.length>0){if(Y.signal.aborted)throw Re=!0,new Error(Mn);let mt=await this.confirmReadCeiling(C,{org:D,orgTier:T,source:he(this.deps.orgManager.getOrg(c.sourceOrgId),c.sourceOrgId)},at,Me);mt==="confirmed"&&m.confirm("volume"),ee=Kn(ee,mt)}}if(Y.signal.aborted)throw Re=!0,new Error(Mn);let Et=p?void 0:this.runUserOf(c.targetOrgId),tt=await this.loadRecordTypeMappings(c,Y.signal,Pe);if(Y.signal.aborted)throw Re=!0,new Error(Mn);te=await Et,Fe=Date.now(),je=this.requestsSent?.(),ps=this.lostBulkJobs?.count;let gt=p?void 0:this.runJournal,Lr;if(gt){let ne=t?.journalId??`forge-run-${Fe}`,Ce;try{Ce=this.journalLocks.take(gt.pathOf(ne),{journalId:ne,target:D,...t?{resumes:!0}:{}})}catch(at){oe.warn(`Forge run journal: its lock not taken (${O(at)})`)}if(Ce&&"busy"in Ce)throw new un(Ri,`${vi(Ha(Ce.busy))}: taken up now, two runs would write it; ${Ba(Ce.busy)}, then resume it. Nothing was written.`);J=Ce,W=ne,this.journalsRunning.add(ne);let Be=at=>new un(wj,`${D} could not be read for the insert calls the run had under way when it stopped (${O(at)}): taken up without them, the run would write their records twice. Reconnect ${D} on Organizations if its session expired, then resume the run again. Nothing was written.`);if(se=await(t?gt.resuming(ne).then(async()=>{let at=await B(c.targetOrgId,this.deps.orgRegistry,this.deps.orgManager).catch(xe=>{throw Be(xe)}),mt={},Fr=await gt.reconcile(ne,bj(Mu(at),mt)).catch(xe=>{throw mt.err!==void 0?Be(mt.err):xe});for(let xe of Lu(Fr,D))oe.info(`Forge resume: ${xe.trim()}`);ue=Fr.uncertain,x=Fr.underway;let mo=this.loadHistory().find(xe=>xe.forgeId===t.forgeId);mo&&Fr.found.length>0&&await this.withRowsFoundAfterStop(mo,Fr.found)}):gt.begin(ne,c.targetOrgId,new Date(Fe),{...this.resumeHeadOf(n,c,o,Me),...d===!0?{muteAutomation:!0}:{},...i?{files:i}:{}},te)).then(()=>gt.open(ne)).catch(at=>{oe.warn(`Forge run journal not started: ${O(at)}`),Lr={err:at}}),t&&!se){let at=Lr?.err;if(at instanceof un)throw at;let{reason:mt,lift:Fr}=IA(at);throw new un($f,`The journal of the run to resume, in ${Cf(gt.pathOf(ne))}, could not be opened (${mt}). ${Fr}, then resume it again. Nothing was written.`)}}if(y&&!p&&!se){if(!gt||!W||Lr===void 0)throw new un($f,yj);let{reason:ne,lift:Ce}=IA(Lr.err);throw new un($f,`A clone of the whole org keeps its journal on disk, in ${Cf(gt.pathOf(W))}, which could not be opened (${ne}). ${Ce}, then run it again. Nothing was written.`)}R&&(Nt=await this.sampleOf({graph:n,config:c,anonymizationRules:o,readCeiling:Me,dryRun:p,...W!==void 0?{journalId:W}:{},resumes:t!==void 0,...b?{retried:b}:{},volumeCase:h,target:D,lookup:Pe,room:()=>Du(Nr,it).perRecord,onProgress:Hn}));let Zt=await this.rootsOfTheRun({graph:n,config:c,anonymizationRules:o,readCeiling:Me,dryRun:p,resumes:t!==void 0,...S?{retried:S}:{},lookup:Pe});if(Y.signal.aborted)throw Re=!0,new Error(Mn);let yt,Jt=y?LR(c):void 0,Vt=this.writeGate({guard:C,targetOrgId:c.targetOrgId,org:D,source:he(this.deps.orgManager.getOrg(c.sourceOrgId),c.sourceOrgId),orgTier:T,lookup:Pe,emailsPerInsert:Ue,...He!==void 0?{automation:He}:{},...En(fr?.ofRun),sentBefore:st+(this.discoverySent.get(UA(c,n))?.target??0),mute:Xr(_n?.plan??Pi),mayBeInTarget:ue,...x&&x.length>0?{jobsUnderway:x}:{},...p?{}:{simulated:this.simulations.of(h)},updatedAfterInsert:[...Ke],automationRoom:()=>Du(Nr,it).perRecord,...y?{wholeOrg:{source:he(this.deps.orgManager.getOrg(c.sourceOrgId),c.sourceOrgId),sourceOrgId:c.sourceOrgId,graph:n,anonymizePII:c.anonymizePII,...Jt?{carried:Jt}:{}}}:{},...f!==void 0?{checkpoint:{ask:{module:"forge",orgId:c.targetOrgId,operationId:me,running:Nr,request:f},own:{operationId:me},signal:Y.signal,onEstimate:ne=>{fs=ne},onTaken:ne=>{jr=ne,gt&&W&&se&&gt.keepCheckpoint(W,ne).catch(Ce=>{oe.warn(`Forge run journal: the checkpoint taken first not named (${O(Ce)})`)})},onProgress:ne=>{let Ce=Do(ne);Le(this.deps,me,ne,0,0,Ce),this.liveTracker?.updateProgress(me,ne,0,0,Ce)}}}:{},onSimulated:ne=>{Ve=ne},...R?{sampled:ne=>{Hn.flush();let Ce=Nt?.drawnAgain,Be=Ce||Nt?.ofTheRunRetried?{...ne,plan:{...ne.plan,...Ce?{drawnAgain:Ce}:{},...Nt?.ofTheRunRetried?{ofTheRunRetried:!0}:{}}}:ne;return m.sampled(Be),Be}}:y?{onSampleOffer:ne=>{Un=ne}}:{},onConfirmed:()=>{ee=Kn(ee,"confirmed"),m.confirm("volume")}}),ho=await this.orchestrator.execute(n,c,{recordTypeMappings:tt,anonymizationRules:o,files:i,writtenBefore:P,stream:{ceiling:Me,...se?{store:se,summaryBound:_a}:{},...Nt?{sample:Nt.stream}:{}},...te?{runUserId:te}:{},...Zt?{roots:Zt}:{},beforeWrite:async ne=>{let Ce=await Vt(ne);if(!_n||ne.dryRun||yt)return Ce;let Be=await _n.acquire(me);yt=Be,Ht=Be.outcome;let kt=fr?.afterLease(Be.outcome,Ci);if(kt)throw new ut(kt.code,kt.message);return{...Ce,lease:{assigned:Be.outcome.assigned.length,giveBack:async()=>(await fo(),Be.release())}}}}).catch(ne=>{if(!UR(ne))throw ne;return go=ne.dryRun,O0(n,Fe,ne.dryRun)}).finally(X).finally(async()=>{yt&&(await fo(),Ht=await yt.release())}),Pt=BA(HA(ho,Pe.requests),Nt),_=Pt.remapInJournal&&se&&W?{journalId:W,journalPart:Math.max(0,se.partCount-1)}:{},K=Ht?{mutedAutomation:Ht,...Qt.length>0?{bulkJobsPastMute:Qt,errors:[...Pt.errors??[],...Uu(Qt)]}:{}}:{},ce=p?fs:jr?await this.settleCheckpoint(jr,(Pt.createdCount??Pt.idRemapCount-(Pt.linkedExistingCount??0))+(Pt.updatedCount??0)>0):u,Oe=ce?{checkpoint:ce}:{},ye=t&&!p&&se&&W?await this.wroteToEarlierPartsOf(Pt,W,se.partCount-1):{},Se=l!==void 0?{...Pt,..._,...K,...Oe,retryOf:l,...t?{resumed:!0}:{},...ye}:{...Pt,..._,...K,...Oe};"journalId"in _&&!p&&(F={keep:!0,status:"success",forgeId:Se.forgeId});let ge=Se.createdCount??Se.idRemapCount-(Se.linkedExistingCount??0);Se.status!=="failure"&&ge>0&&this.noteForgeWrite(V),Se.status==="failure"&&(ae=new Error("Forge execution finished with a failure status.")),p?(this.trials.note("simulation",g),Ve&&this.simulations.note(h,Ve),Nt&&go?.sample&&this.noteSampleSimulation(h,Nt.fingerprint)):(Z(this.deps,{action:"forge_execute",module:"forge",operationId:me,orgId:c.targetOrgId,outcome:Se.status,guard:ee,objects:su(Se),source:{origin:"org",orgId:c.sourceOrgId},carried:iu(Se),...Ts(Se.contactPoints),...CA(m),context:m.context(Se.decisionsApplied),...Ht?{muted:ct(Ht)}:{},...ce?.state==="taken"?{checkpointId:ce.checkpointId}:{}}),this.addToHistory(Se,c)),oe.info("Forge execute finished",v0(Se)),await le(),Hn.flush();let Ye=A(this.deps,e,"forge:execute:response",{result:Se,operationId:me,...go?{wholeOrgDryRun:go}:{},...Un?{sampleOffer:Un}:{}});this.deps.broker.postToWebview(Ye),this.dmlTracker.markCompleted(V),pe(this.deps,me,{status:Se.status}),Se.status==="failure"?this.liveTracker?.fail(me,"Forge execution finished with a failure status."):Se.status==="partial"?this.liveTracker?.partial(me):this.liveTracker?.complete(me)}catch(Me){Hn.flush();let Xe=Jb(Me,t?"resume":"draw")??Me,Ke=Ma(Xe)?Xe:oR(Xe),it=xt(Xe)?Xe:void 0;(Ke?.code==="AUTOMATION_DECLINED"||Ke?.code==="READ_DECLINED"||Ke?.code==="WRITE_DECLINED")&&(ee=Kn(ee,"declined"));let Et=Re||A0(Xe)||Ke!==void 0||it!==void 0;Et||(ae=Xe);let tt=Ke||it?void 0:kR(Xe),gt=tt?xh(tt):void 0,Lr=gt?su(gt):[],Zt=Re||Ke||it?"stopped":Et?Dh(tt,Lr):"failure",yt=Ke?Ke.code:it?it.code:Re?Rt:Zt==="stopped"?nt:Xe instanceof un?Xe.code:void 0,Jt=jr?await this.settleCheckpoint(jr,tt?$A(tt):!(Re||Ke||it)):u;oe.info("Forge execute stopped",{outcome:Zt,...yt?{code:yt}:{},...tt?{created:tt.successCount,linked:tt.linkedCount,failed:tt.failedCount}:{}});let Vt=tt&&!p?this.keepStoppedRun(BA(tt,Nt),n,c,{startedAt:Fe,cancelled:Et,retryOf:l,resumed:t!==void 0,callsBefore:Pe.requests,...se&&W?{journalId:W,journalPart:Math.max(0,se.partCount-1)}:{},...Jt?{checkpoint:Jt}:{},...te?{runUserId:te}:{},...Qt.length>0?{bulkJobsPastMute:Qt}:{},...t&&se&&W?await this.wroteToEarlierPartsOf({idRemapTable:tt.remapTable,idRemapCreated:tt.createdByObject,...tt.remapInJournal?{remapInJournal:!0}:{}},W,se.partCount-1):{}}):void 0;se&&W&&Vt?F={keep:!0,status:Et?"cancelled":"failure",forgeId:Vt.forgeId}:t&&(F={keep:!0,...t.end}),p||Z(this.deps,{action:"forge_execute",module:"forge",operationId:me,orgId:c.targetOrgId,outcome:Zt,...yt?{code:yt}:{},guard:ee,...gt?{objects:Lr,source:{origin:"org",orgId:c.sourceOrgId},carried:iu(gt)}:{},...Ts(tt?.contactPoints),...CA(m),context:m.context(tt?.decisionsApplied),...Ht?{muted:ct(Ht)}:{},...Jt?.state==="taken"?{checkpointId:Jt.checkpointId}:{}}),this.dmlTracker.markFailed(V),this.lastWriteAt.delete(V),Nt?.adoptedFrom!==void 0&&W!==void 0&&!F.keep&&!(tt&&$A(tt))&&await this.giveThePlanBack(W,Nt.adoptedFrom),await le();let ho=jr&&Jt?{checkpoint:Jt}:{},Pt=Ke&&Ma(Ke)?Jj(Ke):Xe;E(this.deps,"forge:execute","forge:execute:error",e,Pt,{code:yt??(Et?nt:"EXECUTE_ERROR"),retryable:!(Ke&&Ma(Ke)&&qA.has(Ke.code)),...Vt?{extraPayload:{result:F.keep?{...Vt,resumable:!0}:Vt}}:Ke?.stop?{extraPayload:{gate:Ke.stop,...ho,...Un?{sampleOffer:Un}:{}}}:jr?{extraPayload:ho}:{}}),Et?(this.deps.infraServices?.backgroundRegistry?.abort(me),pe(this.deps,me,{aborted:!0}),this.liveTracker?.cancel(me)):(De(this.deps,me,O(Xe),!0),this.liveTracker?.fail(me,O(Xe))),F.keep&&this.liveTracker?.offerResume(me,F.forgeId)}finally{await le(),J?.release(),Ne(ae),this.executeOperationId===me&&(this.executeOperationId=null,this.writingTo=null),this.stops.endRun(e.id),Bn(),gs.flush(),this.abortController=null}}addToHistory(e,t){let r={...t.inputMode==="org"?RA(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=HA($h(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??[],...Uu(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(Hr(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<=_a?{wroteToEarlierParts:i}:{}}catch(i){return oe.warn(`Forge run journal not read for what the part wrote: ${O(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 SR(t,async n=>(await r.query(n)).records)}catch(r){oe.warn(`Forge run: the users its owners are mapped to could not be read first (${O(r)})`);return}}runUserOf(e){return JR(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 oe.warn(`Forge run: the checkpoint '${e.name}' taken before it is kept, as it could not be settled (${O(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(l=>l.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:Vj}:{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=>{oe.warn(`Forge retry: the journal of the run retried could not be read (${O(a)})`)}))?.roots;if(i&&i.objectApiName.toLowerCase()===t.objectApiName.toLowerCase()&&Ou(i.ids)===i.sha256)return i}if(!t.ids||t.idsLeftOut!==void 0||t.ids.length!==t.asked)return;let n=vb(t.ids.map(o=>o.source));if(Ou(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),oe.info("Forge paused")}handleResume(e){this.orchestrator?.resume(),this.executeOperationId&&this.liveTracker?.resume(this.executeOperationId),oe.info("Forge resumed")}handleAbort(e){let t=ot(Ij,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"){oe.info("Forge stop: no operation under way answers it");return}E(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:kj});return}oe.info("Forge stopped",{what:r.stops.kind})}refuseAtGate(e,t,r,n,o){Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:t,outcome:"stopped",...n?{guard:n}:{},code:r.code,...o?{context:o}:{}}),E(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=_A(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([...vn(t,n,{userKept:o}),...r])],d=i?await new fe(Si).withTimeout("forge:undo-automation",()=>i.read(e,a)).catch(l=>({unread:O(l)})):{unread:"no reader of the target org's automation is set up"},c=new Set(or(t));return Ot(()=>this.muteOrg(e),d,{...this.muteLeases,writes:(l,u)=>u==="delete"||u==="update"&&c.has(l)})}async muteOrg(e){return this.muteOrgOf?this.muteOrgOf(e):Lt(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(_A(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(Bi).map(d=>d.objectApiName));try{return{automation:await new fe(Si).withTimeout("forge:automation",()=>i.readForGraph(e,t,a)),reused:!1}}catch(d){return{unread:O(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?Pu(a):[],l=a?Cu(a,d):[],u=a?xu(a):[{part:"automation",reason:"unread"in r?r.unread:""}];oe.info("Forge target automation before the run",{..."reused"in r?{reused:r.reused}:{},firedOnInsert:c.length,firedOnUpdate:l.length,unread:u.map(y=>y.part)});let f=c.length===0&&l.length===0&&u.length===0,p=a?_g(a):[],g=i.deliverability!==void 0;if(f&&!g&&!(o&&p.length>0))return"allowed";let h=a&&!f?rR(a,d):[],m=await e.confirmRun({stage:"automation",org:t.org,orgTier:t.orgTier,fired:c,firedOnUpdate:l,updateSteps:tR(n.filter(y=>l.some(R=>R.objectApiName===y.objectApiName))),unread:u,bypass:h,assign:a&&!f?nR(a,h,t.username?{alias:t.org,username:t.username}:void 0):[],...p.length>0?{removal:p}:{},...i});if(m==="confirmed")return"confirmed";throw this.readAutomationAgain(t.orgId),m==="declined"?new ut("AUTOMATION_DECLINED",f&&!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 ut("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){oe.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 ut("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 ut("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",Au);return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.floor(e),Di):Au}confirmAboveRecords(){let e=this.deps.services?.getSandforgeSetting?.("safety.confirmAboveRecords",Qr);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):Qr}async readTargetEmailLimits(e){try{let t=await B(e,this.deps.orgRegistry,this.deps.orgManager);return await new fe(ds).withTimeout("forge:limits",()=>Sr(t))}catch(t){return{unread:O(t)}}}async readTargetDataStorage(e){try{let t=await B(e,this.deps.orgRegistry,this.deps.orgManager);return await new fe(ds).withTimeout("forge:limits",()=>Rr(t))}catch(t){return{unread:O(t)}}}async readTargetApiBudget(e){try{let t=await B(e,this.deps.orgRegistry,this.deps.orgManager);return await new fe(ds).withTimeout("forge:limits",()=>dr(t))}catch(t){return{unread:O(t)}}}async readSourceApiBudget(e,t){t.requests++;try{let r=await B(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager);return await new fe(ds).withTimeout("forge:limits",()=>dr(r))}catch(r){return{unread:O(r)}}}limitsTransportOf(e,t){return{request:async r=>{t.requests++;let n=await B(e,this.deps.orgRegistry,this.deps.orgManager);return new fe(ds).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[];oe.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,()=>{r.requests++});return i.length>0&&oe.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(Xj);let n=this.setupFingerprintOf(e.graph,t,e.anonymizationRules,e.readCeiling),o=new Date,i,a,d,c=!1,l,u=h=>{if(!(h instanceof OR))throw h};if(e.dryRun||e.journalId===void 0)i=IR(r,n);else if(e.retried&&!e.resumes){i=Fa(r,e.journalId);let h=e.retried.journalId,m=h!==void 0?await ju.open(Fa(r,h),{fingerprint:n}).catch(u):void 0;m?(a=await PR(m,r,e.journalId),c=!0):d="planGone"}else if(i=Fa(r,e.journalId),!e.resumes){let h=await AR(r,n,o);if(h instanceof ju)a=await TR(h,r,e.journalId).catch(u),a?l=h.dir:d="planTaken";else if(h==="tooOld")d="tooOld";else{let m=this.sampleSimulations.get(e.volumeCase);m!==void 0&&(d=m===n?"planTaken":"setUpOtherwise")}}await CR(r,o).catch(h=>{oe.warn(`Forge sample: the plans of past simulations were not swept (${O(h)})`)});let f;if(!a&&!e.resumes){let h=await this.readSourceApiBudget(t,e.lookup);"unread"in h||(f=h.remaining)}let p=t.sample?.withinMB;return{stream:{options:t.sample??{},budget:async()=>{e.lookup.requests++;let h=await this.readTargetDataStorage(t.targetOrgId),m=zb({storage:h,bounds:p!==void 0?{withinMB:p}:{},target:e.target});if(m)throw ut.of(m);let y=Ua({storage:h,...p!==void 0?{withinMB:p}:{},automation:e.room()});if(!y)throw new Error("No budget of the sample could be read. Nothing was written.");return y},keepAt:i,fingerprint:n,...a?{plan:a}:{},...f!==void 0?{sourceRequestsLeft:f}:{},onProgress:e.onProgress},fingerprint:n,...d?{drawnAgain:d}:{},...c?{ofTheRunRetried:!0}:{},...l!==void 0?{adoptedFrom:l}:{}}}async giveThePlanBack(e,t){let r=this.runJournal?.storagePath;r!==void 0&&await ER(r,e,t).catch(n=>{oe.warn(`Forge sample: the plan of the simulation was not put back (${O(n)})`)})}noteSampleSimulation(e,t){this.sampleSimulations.delete(e),this.sampleSimulations.set(e,t);for(let r of this.sampleSimulations.keys()){if(this.sampleSimulations.size<=Kj)break;this.sampleSimulations.delete(r)}}writeGate(e){let t=e.checkpoint,r=n=>t&&{...t.ask,written:n.objects.filter(({rows:o})=>o>0).map(o=>o.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 U=Eu(n.objects,i);e.onSimulated?.(U);let M=r(U),L;t&&M&&this.beforeRunCheckpoints&&U.totalRows>0&&(L=await this.beforeRunCheckpoints.scope(M,t.own).then(Q=>(t.onEstimate(Q),Q),Q=>{oe.warn(`Forge simulation: ${br(Q)}`)}));let ee=await Wb({objects:n.objects,measures:i,graph:o.graph,anonymizePII:o.anonymizePII,...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{},...L?{checkpoint:L}:{},...n.readBack!==void 0?{readBack:n.readBack}:{},...e.mute!==void 0?{mute:e.mute}:{},...e.deliverability!==void 0?{deliverability:e.deliverability}:{},...e.sentBefore!==void 0?{sentBefore:()=>({target:e.sentBefore??0})}:{},target:{org:e.org,limits:this.limitsTransportOf(e.targetOrgId,e.lookup)},source:{org:o.source,limits:this.limitsTransportOf(o.sourceOrgId,e.lookup)},...a?{sample:a}:{},...e.automationRoom?{automation:e.automationRoom()}:{}});if(!a&&ee.storage.verdict==="exceeds"){let Q=Ua({storage:ee.storage});Q&&e.onSampleOffer?.(Q.budget)}throw oe.info("Forge write gate: the dry run of a clone of the whole org",{records:ee.totalRows,objects:ee.wouldInsert.length,targetRequests:ee.targetRequests.estimate,sourceRequests:ee.sourceRequests.estimate,...ee.bulkBatches?{bulkBatches:ee.bulkBatches.estimate}:{},wouldBeRefused:ee.wouldBeRefused.map(Q=>Q.code)}),new FR(ee)}if(n.dryRun){let U=Tu(n.objects);e.onSimulated?.(U);let M=r(U);return t&&M&&this.beforeRunCheckpoints&&U.totalRows>0&&await this.beforeRunCheckpoints.scope(M,t.own).then(t.onEstimate,L=>{oe.warn(`Forge simulation: ${br(L)}`)}),{}}let d=i?Ub(i.readWholeOver):void 0;if(d)throw ut.of(d);let c=i?Eu(n.objects,i):Tu(n.objects);if(c.totalRows===0)return{};e.lookup.requests++;let l=await this.readTargetDataStorage(e.targetOrgId),u=vr(c,l,e.automationRoom?qb(c,e.automationRoom()):0);if(a){let U=Gb({sample:a,storage:l,target:e.org});if(U)throw ut.of(U)}let f=this.confirmAboveRecords(),p=f>0&&c.totalRows>f?f:void 0,g=Jw(e.orgTier),h=g!==void 0&&c.totalRows>g?g:void 0;oe.info("Forge write gate",{records:c.totalRows,objects:Object.fromEntries(c.objects.slice(0,20).map(U=>[U.objectApiName,U.rows])),storageEstimateMB:qs(u.estimateMB),...u.verdict==="unread"?{storageUnread:u.unread}:{storageRemainingMB:u.remainingMB,storageMaxMB:u.maxMB},storage:u.verdict});let m=sR(u,e.org);if(m&&u.verdict==="exceeds"){if(o&&!a&&!("unread"in l)){let M=Ua({storage:l});M&&e.onSampleOffer?.(M.budget)}let U=n.roots&&!o?Rb(u,e.org,n.roots):void 0;throw U?ut.of(U):new ut("STORAGE_EXCEEDED",`${m} Nothing was written.`,{estimateMB:Number(qs(u.estimateMB)),remainingMB:u.remainingMB})}u.verdict==="near"?oe.warn("Forge write gate: the records take more than 80 % of the data storage the target has left"):u.verdict==="unread"&&oe.warn("Forge write gate: the data storage the target has left could not be read"),h!==void 0&&oe.warn(`Forge write gate: more than ${h} records, a large volume`);let y=i?Hb(i.files,l,e.org):void 0;if(y?.stop)throw ut.of(y.stop);let R;"unread"in l?(e.lookup.requests++,R=await this.readTargetApiBudget(e.targetOrgId)):R=l.dailyApiRequests;let k=r(c),w;if(t&&k){let U=this.beforeRunCheckpoints;if(!U)throw new ut(An,br(new Error("SandForge's checkpoints are not set up in this window")));w=await U.scope(k,t.own).catch(M=>{throw new ut(An,br(M))})}let I=o?await this.readSourceApiBudget(o,e.lookup):void 0,P=Bb({plan:c,...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{},...n.readBack!==void 0?{readBack:n.readBack}:{},...w?{checkpoint:w}:{},...e.mute!==void 0?{mute:e.mute}:{},...e.deliverability!==void 0?{deliverability:e.deliverability}:{},...e.sentBefore!==void 0?{sentBefore:e.sentBefore}:{},budget:R,target:e.org,...o&&i?{wholeOrg:{measures:i,bulkBatches:"unread"in l?l:l.dailyBulkApiBatches,sourceBudget:I,source:o.source}}:{}});if(oe.info("Forge write gate: API requests",{estimate:P.api.estimate,verdict:P.api.verdict,...P.api.verdict==="unread"?{unread:P.api.unread}:{remaining:P.api.remaining,max:P.api.max},...P.api.parts?{parts:P.api.parts}:{}}),P.stop)throw ut.of(P.stop);let b=fa(P.api),S=o&&i&&P.wholeOrg?HR({run:o,measures:i,plan:c,budget:{api:P.api,wholeOrg:P.wholeOrg},...y?.files?{files:y.files}:{},...a?{sample:a,now:Date.now()}:{}}):void 0;S&&oe.info("Forge write gate: a clone of the whole org",{sourceRequests:P.wholeOrg?.source.estimate,sourceApi:P.wholeOrg?.source.verdict,jobs:S.bulk?.jobs??0,...P.wholeOrg?.bulkBatches?{bulkBatches:P.wholeOrg.bulkBatches.estimate}:{},durationSeconds:Math.round(S.durationSeconds),managedPackages:S.managedPackages?.length??0,personalAsIs:S.personalAsIs?.length??0});let C=async()=>{let U=this.beforeRunCheckpoints;if(!t||!k||!w||!U)return;let M=w,L=await ja(()=>U.take(k,t.own,{planned:M,signal:t.signal,onProgress:({percentage:ee})=>t.onProgress?.(ee)}));if("stop"in L)throw L.stop.code===An?ut.of({...L.stop,code:An}):Object.assign(new Error(L.stop.message),{name:"ForgeAbortedError"});t.onTaken(L.checkpoint)},v=[],T=[];if(e.emailsPerInsert.length>0){e.lookup.requests++;for(let U of Vb(c,e.emailsPerInsert,await this.readTargetEmailLimits(e.targetOrgId)))U.verdict==="exceeds"?v.push(Yb(U)):U.verdict==="unread"&&T.push(Qb(U));T.length>0&&oe.warn("Forge write gate: a daily email limit of the target could not be read",{limits:T.map(({limit:U,emails:M})=>({limit:U,emails:M}))}),v.length>0&&oe.warn("Forge write gate: the records take the target past a daily email limit",{limits:v.map(({limit:U,emails:M,remaining:L})=>({limit:U,emails:M,remaining:L}))})}let D=e.automation===void 0?void 0:"automation"in e.automation?Kb(e.automation.automation,Xb(c)):`the target's automation: ${e.automation.unread}`;D!==void 0&&oe.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:U})=>U>0),H=e.simulated?Lb(e.simulated,c.totalRows):void 0;if(H?.farAbove&&oe.warn("Forge write gate: far more records than the last simulation of the case",{records:c.totalRows,simulated:H.total}),p===void 0&&u.verdict==="fits"&&v.length===0&&T.length===0&&D===void 0&&z.length===0&&H?.farAbove!==!0&&!P.asks)return await C(),b;let Y=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:U,rows:M})=>({objectApiName:U,rows:M})),total:c.totalRows,...p!==void 0?{aboveRecords:p}:{},...h!==void 0?{largeVolume:h}:{},storage:Pn(u),...c.leftOut?{leftOut:c.leftOut}:{},...n.objects.some(U=>U.counted)?{counted:!0}:{},...v.length>0?{emails:v}:{},...T.length>0?{emailsUnread:T}:{},...D!==void 0?{emailsUncounted:D}:{},...Fb(c),..._b(c),...z.length>0?{mayBeInTarget:z.map(({objectApiName:U,rows:M})=>({objectApiName:U,rows:M}))}:{},...z.length>0&&e.jobsUnderway&&e.jobsUnderway.length>0?{jobsUnderway:h0(e.jobsUnderway)}:{},...n.capped?{capped:n.capped}:{},...H?{simulated:H}:{},...S?{wholeOrg:S,...P.confirmation.checkpoint?{checkpoint:P.confirmation.checkpoint}:{}}:P.confirmation});if(Y==="confirmed")return e.onConfirmed(),await C(),b;throw Y==="declined"?new ut("WRITE_DECLINED","Forge execution was cancelled before it wrote the records it had read. Nothing was written."):new ut("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 fe(u0).withTimeout("forge:record-types",()=>this.readRecordTypeMappings(e,r));return await Promise.race([i,o])}catch(i){oe.warn(`[forge] Record types could not be read from both orgs (${O(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),{records:a}=await rr({query:async d=>(t.requests++,i.query(d)),queryMore:async d=>(t.requests++,i.queryMore(d))},cR);return lR(a)}));for(let o of uR(r,n))oe.warn(`[forge] ${pR(o)}`);return new fR().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=>Ll.safeParse(o).success),...r===void 0?{}:{importNotMerged:r}});this.deps.broker.postToWebview(n)}async handleSaveTemplate(e){let t=ot(Aj,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){E(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=ot(Nj,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){E(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(l){oe.warn(`Forge removal plans could not be read: ${O(l)}`)}let o=await this.journalsPresent([...t.flatMap(l=>l.remapInJournal&&l.journalId?[l.journalId]:[]),...n.flatMap(l=>l.inJournal?[l.inJournal.journalId]:[])]),i=t.map(l=>({...l,...r.has(l.forgeId)?{resumable:!0}:{},...l.remapInJournal&&!(l.journalId&&o.has(l.journalId))?{journalGone:!0}:{}})),a=new Set(i.map(l=>l.forgeId)),d=n.filter(l=>!a.has(l.forgeId)&&Br(l).length>0).map(l=>l.inJournal&&!o.has(l.inJournal.journalId)?{...l,journalGone:!0}:l);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=ot(Tj,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,l=i&&r.sweepUntied===!0,u=(I,P)=>this.refuseUndo(e,I,P),f=this.loadHistory().find(I=>I.forgeId===n),p=f?void 0:await this.keptRemovalPlan(n),g,h={},m=f?.targetOrgId??p?.targetOrgId,y=f?f.journalId:p?.inJournal?.journalId;if(y){let I=this.journalBusy(y,"remove");if(I){u(I,Ri);return}if(this.removing.has(n)){u("The records of this run are being removed already: its result shows under the run once it ends.",xf);return}let P=this.lockToRemove(y,m);if(P&&"busy"in P){u(P.busy,Ri);return}P&&(t.lock=P)}if(m&&y&&(!f||f.idRemapCreated)){if(this.removing.has(n)){u("The records of this run are being removed already: its result shows under the run once it ends.",xf);return}this.removing.add(n);try{let I=await this.callsLookedForBeforeRemoval({forgeId:n,targetOrgId:m,journalId:y,removedBefore:(f??p)?.undo!==void 0});if("unread"in I){u(I.unread,"IN_FLIGHT_UNREAD");return}g=I.reconciled,h=I,g&&g.found.length>0&&(f?f=await this.withRowsFoundAfterStop(f,g.found):p&&(p=await this.planWithRowsFoundAfterStop(p,g.found)))}finally{this.removing.delete(n)}}let R,k,w=()=>{};if(f){let I=Date.parse(f.timestamp);if(!f.idRemapCreated||!f.targetOrgId||Number.isNaN(I)){u(`This run was recorded before Forge kept what a run created: its records cannot be removed from the history. ${_c}`,"NOT_RECORDED");return}let P=f.remapInJournal&&f.journalId&&f.journalPart!==void 0?{journalId:f.journalId,part:f.journalPart}:void 0,b=w0(f.mayHaveBeenWritten,{...h,reconciled:g});if(R={...f,targetOrgId:f.targetOrgId,unreachable:y0(f.mayHaveBeenWritten,g),...b?{notLookedFor:b}:{},...P?{inJournal:P}:{}},f.remapInJournal){if(k=[],a||gn(f).length>0){let S=await this.journalRecordsOf(P,f.undo,a);if("gone"in S){u(S.gone,is);return}k=S.records,w=S.close}}else k=a?Hr(f):ws(f)}else if(p){if(i){u(jA,"SWEEP_UNAVAILABLE");return}R={...p,unreachable:g&&g.calls>0?Fu(g):p.mayHaveBeenWritten??0,...h.callsNotLookedFor?{notLookedFor:{callsAfterRemoval:h.callsNotLookedFor}}:{}};let{inJournal:I}=p;if(I&&(a||Br(p).length>0)){let P=await this.journalRecordsOf(I,p.undo,a);if("gone"in P){u(P.gone,is);return}k=P.records,w=P.close}else k=a?p.objects.map(({objectApiName:P,ids:b})=>({objectApiName:P,ids:[...b]})):Jl(p)}else{u("This run is no longer in the Forge history.",as);return}try{let I=yu(k),P=i&&R.undo!==void 0;if(I===0&&!P){R.undo?u(`The records this run created were already removed, on ${R.undo.removedAt}.`,"ALREADY_REMOVED"):u("This run created no record to remove.","NOTHING_TO_REMOVE");return}if(this.removing.has(n)){u("The records of this run are being removed already: its result shows under the run once it ends.",xf);return}this.removing.add(n);let b=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(e.id);try{await this.removeRun(e,R,k,{includeChanged:o,again:a,muteAutomation:d,sweepLate:c,sweepUntied:l,...!i&&f?.config?.inputMode==="org"?{wholeOrgNotSwept:!0}:{}},i?f:void 0,b)}finally{this.removing.delete(n),b?.release()}}finally{w()}}async journalRecordsOf(e,t,r=!1){let n=this.runJournal;if(!n||!e)return{gone:jn};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 oe.warn(`Forge run journal could not be read: ${O(o)}`),{gone:jn}}}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 oe.warn(`Forge run journals could not be listed: ${O(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){oe.warn(`Forge run journals could not be dropped: ${O(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:jn};try{let n=await r.idsOf(e.journalId,e.journalPart);if(!n)return{gone:jn};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 oe.warn(`Forge run journal could not be read: ${O(n)}`),{gone:jn}}}async planRecordsOf(e,t=!1){let r=this.runJournal;if(!r)return{gone:jn};try{let{journalId:n,part:o}=e.inJournal,i=await r.idsOf(n,o);if(!i)return{gone:jn};let a={idRemapTable:i.table,idRemapExisting:i.existing,idRemapCreated:i.createdByObject};if(t)return{records:Hr(a)};let d=await r.leftOf(n,o);return{records:ws({...a,...e.undo?{undo:e.undo}:{},...d?{removalLeft:d}:{}})}}catch(n){return oe.warn(`Forge run journal could not be read: ${O(n)}`),{gone:jn}}}async keptRemovalPlan(e){try{return await this.removalPlans?.get(e)}catch(t){oe.warn(`Forge removal plans could not be read: ${O(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=he(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,Mu(i));for(let d of Lu(a,o,"removal"))oe.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 (${O(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){oe.warn(`Forge run not dated from its journal: ${O(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((l,{rows:u})=>l+u,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 l=await r.idsOf(n,o).catch(()=>{});if(!l)return e;d={...e,idRemapTable:l.table,idRemapExisting:l.existing,idRemapCreated:l.createdByObject,idRemapCount:Object.keys(l.table).length,createdCount:l.createdByObject.reduce((u,{sourceIds:f})=>u+f.length,0),...a?{idRemapByObject:a}:{}}}this.saveHistory(this.loadHistory().map(l=>l.forgeId===d.forgeId?d:l));let c=Hi(d);return c&&await this.removalPlans?.put(c).catch(l=>{oe.warn(`Forge removal plan not kept: ${O(l)}`)}),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=>{oe.warn(`Forge removal plan not kept: ${O(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=$R.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=t0(r,n.graph);this.addToHistory(o,n.config),await e.stop(r.journalId,"interrupted",o.forgeId)}else r.endBefore?await e.stop(r.journalId,r.endBefore.status,r.endBefore.forgeId):await e.forget(r.journalId)}}catch(t){oe.warn(`Forge run journals could not be read: ${O(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||!PA.has(o.status))continue}catch{continue}xA(n,e)===void 0&&t.add(n.forgeId)}return t}async runToResume(e){let t=this.loadHistory(),r=t.find(u=>u.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: ${TA}`,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||!PA.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=xA(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),l=c?.resume?.startedWith;return!c?.resume||!l||c.targetOrgId!==n?{refused:`The journal of this run does not say how it was set up: ${TA}`,targetOrgId:n}:{entry:r,journalId:r.journalId,head:{...c.resume,startedWith:l},targetOrgId:c.targetOrgId,end:a}}async handleResumeRun(e){let t=ot(Sj,e,"forge:execute:error",this.deps);if(!t)return;let r=(y,R,k)=>{k&&Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:k,outcome:"stopped",code:y}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(R),{code:y})},n=await this.runToResume(t.forgeId);if("refused"in n){r(vj,n.refused,n.targetOrgId);return}let{entry:o,journalId:i,head:a,targetOrgId:d,end:c}=n,l=this.deps.orgManager.getOrg(d);if(!l){r(EA,"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&&l.orgId&&l.orgId.slice(0,15)!==a.targetSalesforceOrgId.slice(0,15)){r(EA,`${he(l,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:u,config:f,anonymizationRules:p}=a.startedWith,g=Ml(f);if(g!==void 0){r(Df,`${g}. Nothing was read or written.`,d);return}let h=this.maxRecordsPerObject(),m=y=>MR(a.fingerprint,y.graph,this.runSetupOf(y.config,p,h,a.targetSalesforceOrgId));if(!m({graph:u,config:f})){r(Df,"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(Df,"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:u,config:f,...p?{anonymizationRules:p}:{},...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&&jf.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 jR(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=Hi(e),o=[...n?[r.put(n)]:[],...t.flatMap(i=>{let a=Hi(i);return a&&Br(a).length>0?[r.putIfAbsent(a)]:[]})];Promise.all(o).catch(i=>{oe.warn(`Forge removal plan not kept: ${O(i)}`)})}refuseUndo(e,t,r){E(this.deps,"forge:undo","forge:undo:error",e,new Error(t),{code:r})}async handleOpenRecord(e){let t=ot(Cj,e,"forge:open-record:error",this.deps);if(!t)return;let r=(l,u)=>{E(this.deps,"forge:open-record","forge:open-record:error",e,new Error(l),{code:u})},n=this.loadHistory().find(l=>l.forgeId===t.forgeId);if(!n){r("This run is no longer in the Forge history.",as);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,is);return}let i=t.recordId.slice(0,15),a;for(let{objectApiName:l,ids:u}of Hr(o.entry)){let f=u.find(p=>p.slice(0,15)===i);if(f){a={objectApiName:l,id:f};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(AA,"ORG_NOT_FOUND");return}let c=ec(d.instanceUrl,a.objectApiName,a.id);if(!c.ok){let l=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 "${he(d)}": ${l}.`,c.reason==="not-a-record"?"NOT_CREATED":"INVALID_INSTANCE_URL");return}try{let l=await this.externalBrowser.open(c.url),u=A(this.deps,e,"forge:open-record:response",l);this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id} status=${l.status}`)}catch(l){E(this.deps,"forge:open-record","forge:open-record:error",e,l)}}async handleVerify(e){let t=ot($j,e,"forge:verify:error",this.deps);if(!t)return;let{forgeId:r}=t,n=(l,u)=>{E(this.deps,"forge:verify:request","forge:verify:error",e,new Error(l),{code:u})},o=this.loadHistory().find(l=>l.forgeId===r);if(!o){n("This run is no longer in the Forge history.",as);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. ${_c}`,"NOT_RECORDED");return}let a=o;if(o.remapInJournal&&gn(o).length>0){let l=await this.withIdsOf(o,!0);if("gone"in l){n(l.gone,is);return}a=l.entry}let d=o.remapInJournal&&a===o?[]:ws(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(AA,"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.",Rj);return}this.verifying.add(r);let c=`forge-verify-${this.deps.nextId()}`;try{let l=await B(i,this.deps.orgRegistry,this.deps.orgManager),u=new ev({target:Bu(l,"forge:verify"),source:await this.verificationSource(o.sourceOrgId)}),f=o.writtenBetween??await this.datedByItsJournal({journalId:o.journalId,part:o.journalPart,scope:"part"},l),p=await u.verify({records:d,remapTable:a.idRemapTable??{},...f?{runStartedAt:new Date(f.first),runEndedAt:new Date(f.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:nv(o.writtenWithoutFields??[]),...o.lookupsLeftEmptyByFilter?{leftEmptyByFilter:o.lookupsLeftEmptyByFilter}:{},leftEmptyByTheRun:rv(o.config?.inputMode==="org"),...a.idRemapWithTheirRecord?{withTheirRecord:a.idRemapWithTheirRecord}:{}});this.saveHistory(this.loadHistory().map(h=>h.forgeId===r?{...h,verification:p}:h)),Z(this.deps,{action:"forge_verify",module:"forge",operationId:c,orgId:i,outcome:p.verdict==="verified"?"success":"partial",verdict:p.verdict,details:{forgeId:r,...tv(p)}});let g=A(this.deps,e,"forge:verify:response",{verification:p});this.deps.broker.postToWebview(g),this.deps.log(`[TX] ${g.type} id=${g.id} verdict=${p.verdict}`)}catch(l){Z(this.deps,{action:"forge_verify",module:"forge",operationId:c,orgId:i,outcome:"failure",details:{forgeId:r}}),E(this.deps,"forge:verify:request","forge:verify:error",e,l,{code:"VERIFY_ERROR",retryable:!0})}finally{this.verifying.delete(r)}}async handleExportIds(e){let t=ot(xj,e,"forge:export-ids:error",this.deps);if(!t)return;let r=(c,l)=>{E(this.deps,"forge:export-ids:request","forge:export-ids:error",e,new Error(c),{code:l})},n=this.loadHistory().find(c=>c.forgeId===t.forgeId);if(!n){r("This run is no longer in the Forge history.",as);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,is);return}i=Ng(c.entry)}let d=new Date().toISOString().slice(0,10);try{let c=await this.saveDialog.saveStream(`sandforge-forge-id-map-${d}.csv`,async f=>{await f(jg([]));let p=0,g=[];for(let h of i)g.push(h),!(g.length<Dj)&&(await f(`
18
- ${Vl(g)}`),p+=g.length,g=[]);return g.length>0&&await f(`
19
- ${Vl(g)}`),p+g.length},["csv"]),l=c.status==="saved"?{status:"saved",path:c.path,rows:c.result}:c,u=A(this.deps,e,"forge:export-ids:response",l);this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.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){oe.warn(`Forge run journal could not be read: ${O(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 Bu(t,"forge:verify source")}catch(t){return{unavailable:`The org this run read from could not be reached: ${O(t)}`}}}async removeRun(e,t,r,n,o,i){let{includeChanged:a,again:d}=n,{forgeId:c,targetOrgId:l}=t,u=yu(r),f=(v,T)=>this.refuseUndo(e,v,T),p=this.deps.infraServices?.productionGuard;if(!p){Z(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:l,outcome:"stopped",code:be.code}),f(be.message,be.code);return}let g=this.deps.orgManager.getOrg(l),h=Ee(g),{check:m,decision:y}=u>0?await Ze(p,{orgId:l,orgTier:h,operation:"delete",objectName:wu(r).join(", "),recordCount:u,module:"forge"}):{check:void 0,decision:"allowed"};if(m&&(y==="refused"||y==="declined")){Z(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:l,outcome:"stopped",guard:y}),y==="refused"?f(`Operation blocked by Production Guard: ${m.blockedReason??m.impactSummary}`,"GUARD_BLOCKED"):E(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){Z(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:l,outcome:"stopped",guard:y,code:Rt});let v={forgeId:c,status:"cancelled",includeChanged:a,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(A(this.deps,e,"forge:undo:response",{result:v,operationId:e.id}));return}let R=e.id,k=u>0?`Removing ${u} record(s) a Forge run created`:"Sweeping what the target\u2019s automation created during a Forge run",w=new AbortController;ze(this.deps,R,"forge",k);let I=this.trackRun(R,k,w);this.liveTracker?.register(R,"forge",k,u);let P,b,S,C;try{let v=await B(l,this.deps.orgRegistry,this.deps.orgManager),{inJournal:T}=t,D=t.writtenBetween??await this.datedByItsJournal({journalId:t.journalId??T?.journalId,part:t.journalPart??T?.part},v),z={...t.removalStamps,...T?await this.runJournal?.stampsOf(T.journalId,T.part).catch(X=>(oe.warn(`Forge removal stamps not read: ${O(X)}`),{})):{}};u>0&&(b=await this.otherPartsOf(c,l,v));let H=bu(t.removalSpans,b?.spans);o&&(S=await this.sweepOfRemoval({conn:v,entry:o,includeChanged:a,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,removalSpans:H,signal:w.signal,guard:p,orgTier:h,operationId:R,muted:()=>u===0?C:void 0}));let Y=S;await Y?.ask();let U=Y?.takes??[],M=n.muteAutomation===!0&&(u>0||U.length>0)?await this.removalMute(l,wu(r),U,b?.parts.flatMap(X=>X.objects)??[],t.runUserId!==void 0&&u>0):void 0,L;C=M?.muted;let ee=async()=>{let X=M?.prepared;!X||w.signal.aborted||(L=await X.acquire(R),C=L.outcome)},q=await(u===0?(async()=>(await ee(),await Y?.first(),await Y?.afterRemoval(),$w))():xw(sr(v,"forge:undo"),r,{...D?{runStartedAt:new Date(D.first),runEndedAt:new Date(D.last)}:{runDurationMs:t.duration,runRecordedAt:new Date(t.timestamp)},...Object.keys(z).length>0?{removalStamps:z}:{},...H.length>0?{removalSpans:H}:{},...b&&b.laterParts.length>0?{laterParts:b.laterParts}:{},...Y?{sweep:X=>Y.first(X),afterRemoval:X=>Y.afterRemoval(X),automationMade:Y.automationMade}:{},...t.runUserId?{runUserId:t.runUserId}:{},...b&&b.parts.length>0?{otherParts:b.parts.map(X=>X.alongside)}:{},includeChanged:a,onUndeletable:zr(this.deps,l,"forge:undo"),beforeFirstWrite:ee,signal:w.signal,onProgress:(X,F,de)=>{let J=Math.min(100,Math.round(X/Math.max(F,1)*100));Le(this.deps,R,J,X,F,de),w.signal.aborted||this.deps.infraServices?.backgroundRegistry?.updateProgress(R,J),this.liveTracker?.updateProgress(R,J,X,F,de)}})).finally(async()=>{L&&(C=await L.release())});b&&await this.keepOtherPartStamps(b.parts,q.otherPartStamps??[]);let V=await S?.settle(),we=d?void 0:t.undo?.removedAt,ie=t.unreachable,re=b?g0(q.objects,b.parts):[],Ae=(b?.parts??[]).flatMap(X=>X.undo&&X.records>0?[{forgeId:X.forgeId,records:X.records}]:[]),me={forgeId:c,status:Dw(q.objects,q.cancelled),includeChanged:a,objects:q.objects,finishedAt:new Date().toISOString(),...we?{leftBy:we}:{},...ie>0?{mayHaveBeenWritten:ie}:{},...t.notLookedFor?{notLookedFor:t.notLookedFor}:{},...C?{mutedAutomation:C}:{},...re.length>0?{heldByOtherParts:re}:{},...Ae.length>0?{otherPartsLeft:Ae}:{}};u>0&&Z(this.deps,{action:"cleanup_delete",module:"forge",operationId:R,orgId:l,outcome:Po(me),guard:y,objects:Sn(me.objects),...we?{leftBy:we}:{},...C?{muted:ct(C)}:{}});let Je={...me,status:Eo(me.status,V),...V?{sweep:V}:{},...n.wholeOrgNotSwept?{wholeOrgNotSwept:!0}:{}};n.wholeOrgNotSwept&&oe.info("Forge removal: a clone of the whole org removed without its sweep; what the target\u2019s automation created during the run stays");let Ne=Nw(Je,u,t.undo,d),Fe=V&&GR(V,new Date().toISOString(),o?.sweep),W=Object.keys(q.stamps).length>0,se=q.span,te,ue;if(T)(q.objects.some(F=>F.deleted+F.alreadyGone>0)||d&&Ne!==void 0)&&(ue=await this.runJournal?.keepLeftPages(T.journalId,T.part,q.left()).catch(F=>{oe.warn(`Forge removal left not kept: ${O(F)}`)})),W&&await this.runJournal?.keepStamps(T.journalId,T.part,q.stamps).catch(F=>{oe.warn(`Forge removal stamps not kept: ${O(F)}`)});else if((q.gone.length>0||d&&Ne)&&!Cw(r)){let X=new Set(q.gone);te=r.flatMap(({ids:F})=>F.filter(de=>!X.has(de)))}if(Ne||W||se||te||ue||Fe){let X=F=>({...F,...Ne?{undo:Ne}:{},...Fe?{sweep:Fe}:{},...W&&!T?{removalStamps:{...F.removalStamps,...q.stamps}}:{},...se?{removalSpans:[...F.removalSpans??[],se]}:{},...te?{removalLeft:te}:{}});this.saveHistory(this.loadHistory().map(F=>F.forgeId===c?{...X(F),...ue?{removalLeftByObject:ue}:{}}:F)),await this.removalPlans?.update(c,F=>{let de={...X(F),...F.inJournal&&ue?{inJournal:{...F.inJournal,left:ue}}:{}};return Br(de).length>0?de:void 0}).catch(F=>{oe.warn(`Forge removal plan not updated: ${O(F)}`)})}let x=A(this.deps,e,"forge:undo:response",{result:Je,operationId:R});this.deps.broker.postToWebview(x);let N=Je.status==="failure"?"No record this run created could be removed.":u===0&&V&&V.status!=="success"?V.refusal??"The sweep left records in the org.":void 0;Je.status==="cancelled"||V?.status==="cancelled"?(pe(this.deps,R,{aborted:!0}),this.liveTracker?.cancel(R)):(pe(this.deps,R,{status:N&&u===0?"failure":Je.status}),N?(P=new Error(N),this.liveTracker?.fail(R,N)):Je.status==="partial"?this.liveTracker?.partial(R):this.liveTracker?.complete(R))}catch(v){P=v,await S?.settle().catch(D=>{oe.warn(`Forge sweep not recorded: ${O(D)}`)});let T=xt(v)?v:void 0;Z(this.deps,{action:"cleanup_delete",module:"forge",operationId:R,orgId:l,outcome:T?"stopped":"failure",guard:y,...T?{code:T.code}:{}}),E(this.deps,"forge:undo","forge:undo:error",e,v,{code:T?.code??"UNDO_ERROR",retryable:!0}),pe(this.deps,R,{status:"failure"}),this.liveTracker?.fail(R,O(v))}finally{b?.close(),I(P)}}async otherPartsOf(e,t,r){let n=[],o=[],i=this.loadHistory(),a=new Set(i.map(u=>u.forgeId)),d=(await this.keptRemovalPlans()).filter(u=>!a.has(u.forgeId)),c=u=>f0(u,i,d,t),l=[];for(let u of await this.runLineOf(e,i,d)){let f=i.find(h=>h.forgeId===u),p=f?void 0:d.find(h=>h.forgeId===u);(f??p)?.targetOrgId===t&&l.push((f??p)?.removalSpans??[]);let g=f?await this.otherPartFromEntry(f,t,r,c(u)):await this.otherPartFromPlan(p,t,r,c(u));g&&(g.close&&n.push(g.close),o.push(g.part))}return{parts:o,spans:bu(...l),laterParts:c(e),close:()=>n.forEach(u=>u())}}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(u=>u.forgeId===a),c=d?void 0:o.find(u=>u.forgeId===a);if((d??c)?.targetOrgId!==t)continue;let l=d?gn(d):c?Br(c):[];for(let{objectApiName:u}of l)i.add(u)}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(l=>!i.has(l)):[];if(!o||c.length===0)return[...a].filter(l=>l!==e);for(let l of c)i.set(l,await o.partsOf(l).catch(u=>(oe.warn(`Forge run journal parts not read: ${O(u)}`),[])))}}async keptRemovalPlans(){try{return await this.removalPlans?.list()??[]}catch(e){return oe.warn(`Forge removal plans could not be read: ${O(e)}`),[]}}async otherPartFromEntry(e,t,r,n){if(e.targetOrgId!==t||!e.idRemapCreated||this.removing.has(e.forgeId)||gn(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=ws(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:gn(e).map(c=>c.objectApiName),records:gn(e).reduce((c,l)=>c+l.count,0)},...a?{close:a}:{}}}async otherPartFromPlan(e,t,r,n){if(!e||e.targetOrgId!==t||this.removing.has(e.forgeId)||Br(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=Jl(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:Br(e).map(c=>c.objectApiName),records:Br(e).reduce((c,l)=>c+l.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:WA(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=>{oe.warn(`Forge removal stamps of another part not kept: ${O(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=>{oe.warn(`Forge removal plan not updated: ${O(a)}`)})}}sweepOfRemoval(e){let{conn:t,entry:r}=e,n=r.targetOrgId??"";return qo({input:async()=>{let o=await this.sweepInputOf(r,t,e.signal);return"gone"in o?{refused:o.gone}:o},org:Zr(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();Z(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:Wo(i)}:{},objects:Uo(o),details:Ho(o,r.forgeId),...a?{muted:ct(a)}:{}})},keepMade:async(o,i,a)=>{await this.removalPlans?.keepMade(r.forgeId,o,i,a).catch(d=>{oe.warn(`Forge sweep finds not kept: ${O(d)}`)})}})}async sweepInputOf(e,t,r){let n=await this.withIdsOf(e);if("gone"in n)return n;let o=n.entry,i=Hr(o),a=await this.sweepPartsBeside(e),d=new Set(Object.values(o.idRemapTable??{}).map(f=>f.slice(0,15))),c=this.targetAutomation,l=e.targetOrgId??"",u;if(!c)u={error:"Target automation reader not configured"};else try{u=await new fe(Si).withTimeout("forge:undo-sweep automation",()=>c.read(l,i.map(f=>f.objectApiName)))}catch(f){u={error:O(f)}}return Bo({writtenBetween:e.writtenBetween,created:i,remap:d,automation:zR(u),...e.runUserId?{runUserId:e.runUserId}:{},ties:await this.tiesOf(e),...a.length>0?{otherParts:a}:{},...r?{signal:r}:{}},sr(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(u=>u.forgeId===a),c=d?void 0:n.find(u=>u.forgeId===a);if((d??c)?.targetOrgId!==e.targetOrgId)continue;let l;if(d){let u=await this.withIdsOf(d);"gone"in u||(l=Hr(u.entry))}else if(c?.inJournal){let u=await this.planRecordsOf({...c,inJournal:c.inJournal},!0);"gone"in u||(l=u.records)}else c&&(l=c.objects);l&&o.push({part:d?.journalPart??c?.inJournal?.part??i,created:l})}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=uv(e.removalSpans),i=await this.removalPlans?.madeOf(e.forgeId).catch(()=>[]),a=await this.removalPlans?.lateOf(e.forgeId).catch(()=>[]);return{otherRuns:dv(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(!cv(t,d))return{ids:[],...d};let l=await c();return l?{ids:l.flatMap(({ids:u})=>u),...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=NA(d);i.push(d.remapInJournal?await a(c,async()=>{let l=await this.withIdsOf(d);return"gone"in l?void 0:Hr(l.entry)}):{ids:Hr(d).flatMap(({ids:l})=>l),...c})}for(let d of n??[]){if(o.has(d.forgeId)||d.forgeId===r||d.targetOrgId!==e)continue;let c=NA(d),l=d.inJournal;i.push(l?await a(c,async()=>{let u=await this.planRecordsOf({...d,inJournal:l},!0);return"gone"in u?void 0:u.records}):{ids:d.objects.flatMap(({ids:u})=>u),...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 ${Cf(n.pathOf(e))}, could not be read (${O(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`${vi(Ha(o))}. ${r} ${vi(Ba(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:he(this.deps.orgManager.getOrg(t),t)}:{},removes:!0})}catch(o){oe.warn(`Forge removal: the lock of the run's journal could not be taken (${O(o)})`);return}return"busy"in n?{busy:`${vi(Ha(n.busy))}. Removing its records now would delete under it what it goes on writing; remove them once it has ended. ${vi(Ba(n.busy))}. Nothing was read or written.`}:n}async handleUndoSweep(e){let t=ot(Pj,e,"forge:undo-sweep:error",this.deps);if(!t)return;let r=(a,d)=>E(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(jA,as);return}let o=n.journalId?this.journalBusy(n.journalId,"remove"):void 0;if(o){r(o,Ri);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. "+_c,"NOT_RECORDED");return}try{let a=await new fe(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:_o(Zr(d,"forge:undo-sweep"),c,n.removalSpans??[])});if("gone"in a){r(a.gone,is);return}this.deps.broker.postToWebview(A(this.deps,e,"forge:undo-sweep:response",{forgeId:t.forgeId,listing:a}))}catch(a){let d=a instanceof wr;E(this.deps,"forge:undo-sweep","forge:undo-sweep:error",e,a,{code:d?"TIMEOUT":"SWEEP_ERROR",retryable:!0})}}async handlePlanRequest(e){if(!this.planGenerator){E(this.deps,"forge:plan","forge:plan:error",e,new Error("Plan generator not configured"),{code:"NOT_INITIALIZED"});return}let t=ot(jj,e,"forge:plan:error",this.deps);if(!t)return;let{graph:r,config:n}=t,o=`forge-plan-${this.deps.nextId()}`;ze(this.deps,o,"forge","Generating execution plan");try{oe.info("Forge plan generation started");let i=await this.readPersonalFields(r,n),a=await new fe(DA).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),pe(this.deps,o,{waveCount:a.waves?.length??0})}catch(i){let a=i instanceof wr;E(this.deps,"forge:plan","forge:plan:error",e,i,{code:a?"TIMEOUT":"PLAN_ERROR",retryable:a}),pe(this.deps,o,{status:"failure"})}}async readPersonalFields(e,t){let r=this.orchestrator;if(!r)return e;try{return await new fe(DA).withTimeout("forge:plan:personal-fields",n=>r.readPersonalFields(e,t,n))}catch(n){return oe.warn(`Forge personal fields not read: ${O(n)}`),e}}async handleComplianceRequest(e){if(!this.complianceService){E(this.deps,"forge:compliance","forge:compliance:error",e,new Error("Compliance service not configured"),{code:"NOT_INITIALIZED"});return}let t=ot(Mj,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()}`;ze(this.deps,a,"forge","Generating compliance report");try{oe.info("Forge compliance report generation started");let d=await new fe(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),pe(this.deps,a,{framework:r})}catch(d){let c=d instanceof wr;E(this.deps,"forge:compliance","forge:compliance:error",e,d,{code:c?"TIMEOUT":"COMPLIANCE_ERROR",retryable:c}),pe(this.deps,a,{status:"failure"})}}async handleMetadataDiffRequest(e){if(!this.metadataDiff){E(this.deps,"forge:metadata-diff","forge:metadata-diff:error",e,new Error("Metadata diff service not configured"),{code:"NOT_INITIALIZED"});return}let t=ot(Lj,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()}`;ze(this.deps,i,"forge","Comparing metadata schemas");try{oe.info("Forge metadata diff started");let a=await new fe(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),oe.info("Forge metadata diff finished",{objects:o.length,differences:a.length,objectsMissing:a.filter(c=>c.issue==="object_missing").length}),pe(this.deps,i,{objectCount:o.length})}catch(a){let d=a instanceof wr;E(this.deps,"forge:metadata-diff","forge:metadata-diff:error",e,a,{code:d?"TIMEOUT":"METADATA_DIFF_ERROR",retryable:d}),pe(this.deps,i,{status:"failure"})}}async handleRehearseRequest(e){let t=this.rehearser,r=(b,S,C=!1)=>E(this.deps,"forge:rehearse","forge:rehearse:error",e,b,{code:S,retryable:C});if(!t){r(new Error("Forge rehearsal is not initialized"),"NOT_INITIALIZED");return}let n=ot(Fj,e,"forge:rehearse:error",this.deps);if(!n)return;let{graph:o,config:i,anonymizationRules:a}=n;if(i.inputMode==="org"){r(new Error(mj),hj);return}let d=(b,S,C={})=>Z(this.deps,{action:"forge_rehearse",module:"forge",operationId:b,orgId:i.targetOrgId,outcome:S,...C}),c=(b,S,C=!1)=>{d(e.id,"stopped",{code:S}),r(b,S,C)},l=this.deps.infraServices?.productionGuard;if(!l){c(new Error(be.message),be.code);return}let u=this.deps.orgManager.getOrg(i.targetOrgId),f=Ee(u),p=he(u,i.targetOrgId);if(f==="production"){c(new Error(`${p} 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."),Nf,!0);return}let g=`forge-rehearse-${this.deps.nextId()}`,h="Rehearsing a forge run";this.rehearseOperationId=g,ze(this.deps,g,"forge",h);let m=new AbortController,y=this.trackRun(g,h,m);this.liveTracker?.register(g,"forge",h);let R,k=!1,w=b=>this.deps.broker.postToWebview(A(this.deps,e,"forge:rehearse:progress",{...b})),I=b=>{if(b.phase!=="rehearsing"||!b.call||!b.calls)return;let S=Math.min(100,Math.round((b.call-1)/b.calls*100));m.signal.aborted||this.deps.infraServices?.backgroundRegistry?.updateProgress(g,S),this.liveTracker?.updateProgress(g,S,b.call-1,b.calls,`call ${b.call} of ${b.calls}`)},P=Fc(w,100);try{let b=await this.automationBeforeTheRun(i.targetOrgId,o),S="automation"in b?b.automation:void 0,C=await this.loadRecordTypeMappings(i,new AbortController().signal,{requests:0}),v=await t.rehearse(o,i,{recordTypeMappings:C,anonymizationRules:a,signal:m.signal,onProgress:T=>{if(T.phase==="reading"){P(T);return}P.flush(),w(T),I(T)},confirm:async T=>{let D=await l.confirmRun({stage:"rehearsal",org:p,orgTier:f,rows:T.rows,sampled:T.sampled,updates:T.updates.reduce((z,H)=>z+H.updates,0),calls:T.calls,maxCalls:T.maxCalls,fired:S?Pu(S):[],firedOnUpdate:S?Cu(S,T.updates.map(z=>z.objectApiName)):[],unread:S?xu(S):[{part:"automation",reason:"unread"in b?b.unread:""}]});if(D==="confirmed"){k=!0;return}throw new Uc(D==="declined"?"REHEARSAL_DECLINED":"CONFIRMATION_UNAVAILABLE",D==="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:v})),this.trials.note("rehearsal",Hu(o,i)),oe.info("Forge rehearsal",{rows:v.rows,sampled:v.sampled,judged:v.judged,passed:v.passed,notJudged:v.notJudged,calls:v.calls,plannedCalls:v.plannedCalls,codes:[...new Set(v.gaps.flatMap(T=>typeof T.detail?.statusCode=="string"?[T.detail.statusCode]:[]))]}),d(g,"success",{guard:k?"confirmed":"allowed",details:T0(v)}),pe(this.deps,g,{status:"success"}),this.liveTracker?.complete(g)}catch(b){let S=b instanceof Uc?b:void 0,C=b instanceof ZR?b:void 0,v=b instanceof QR?b:void 0,T=O(b);if(r(b instanceof Error?b:new Error(T),S?.code??(C?"REHEARSAL_CANCELLED":"REHEARSAL_ERROR"),!0),S||C){let D=S?.code==="REHEARSAL_DECLINED"?"declined":k?"confirmed":void 0;d(g,"stopped",{code:S?.code??"REHEARSAL_CANCELLED",...D?{guard:D}:{},...C?{details:{calls:C.calls}}:{}}),pe(this.deps,g,{aborted:!0}),this.liveTracker?.cancel(g)}else R=b,d(g,"failure",{...k?{guard:"confirmed"}:{},...v?{code:"REHEARSAL_NOT_ROLLED_BACK",details:{recordsLeft:v.ids.length},objects:v.objects.map(({objectApiName:D,created:z})=>({objectApiName:D,created:z,updated:0,deleted:0,failed:0}))}:{}}),De(this.deps,g,T,!0),this.liveTracker?.fail(g,T)}finally{P.flush(),y(R),this.rehearseOperationId===g&&(this.rehearseOperationId=null)}}async handleAutomationRequest(e){if(!this.targetAutomation){E(this.deps,"forge:automation","forge:automation:error",e,new Error("Target automation reader not configured"),{code:"NOT_INITIALIZED"});return}let t=ot(_j,e,"forge:automation:error",this.deps);if(!t)return;let{targetOrgId:r,graph:n}=t,o=`forge-automation-${this.deps.nextId()}`;ze(this.deps,o,"forge","Reading the target org's automation");try{let i=new fe(Si).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})),oe.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}),pe(this.deps,o,{objectCount:a.objectsRead.length})}catch(i){let a=i instanceof wr;E(this.deps,"forge:automation","forge:automation:error",e,i,{code:a?"TIMEOUT":"AUTOMATION_ERROR",retryable:a}),pe(this.deps,o,{status:"failure"})}}async readDeliverability(e,t){let r=()=>{},n=new Promise((o,i)=>{r=()=>i(new Error(Mn)),t?.addEventListener("abort",r,{once:!0})});try{return await Promise.race([new fe(ab).withTimeout("forge:deliverability",async()=>Wt(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=$u(t,{leftOut:new Set(t.nodes.filter(Bi).map(d=>d.objectApiName))}),i=new Set(o.map(d=>d.objectApiName)),{ofRun:a}=await ar({read:r,writes:(d,c)=>c==="insert"||c==="update"&&i.has(d),readDeliverability:()=>Ee(n)==="production"?Promise.resolve(qt):this.readDeliverability(e),accepted:!1,target:he(n,e),run:"clone"});return a.read?{...r,deliverability:a.read.reading,requests:r.requests+a.read.requests}:r}async handleUndoAutomation(e){let t=ot(Ej,e,"forge:undo-automation:error",this.deps);if(!t)return;let r=(c,l)=>E(this.deps,"forge:undo-automation","forge:undo-automation:error",e,c,{code:l}),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."),as);return}let i=o.journalId?this.journalBusy(o.journalId,"remove"):void 0;if(i){r(new Error(i),Ri);return}let a=(t.again===!0?Dg(o):gn(o)).map(c=>c.objectApiName),d=o.targetOrgId;try{let c=await this.otherPartObjectsOf(t.forgeId,d),l=[...new Set([...vn(a,c,{userKept:o.runUserId!==void 0}),...t.sweptObjects??[]])],u=await new fe(Si).withTimeout("forge:undo-automation",()=>n.read(d,l));this.deps.broker.postToWebview(A(this.deps,e,"forge:undo-automation:response",{forgeId:t.forgeId,automation:u,drafted:or(a)}))}catch(c){let l=c instanceof wr;E(this.deps,"forge:undo-automation","forge:undo-automation:error",e,c,{code:l?"TIMEOUT":"AUTOMATION_ERROR",retryable:l})}}async handleGapsRequest(e){if(!this.targetGaps){E(this.deps,"forge:gaps","forge:gaps:error",e,new Error("Target gap reader not configured"),{code:"NOT_INITIALIZED"});return}let t=ot(Uj,e,"forge:gaps:error",this.deps);if(!t)return;let{graph:r,config:n}=t,o=this.targetGaps,i=`forge-gaps-${this.deps.nextId()}`;ze(this.deps,i,"forge","Reading what the target org holds against the rows");try{let a=await new fe(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})),oe.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}),pe(this.deps,i,{objectCount:r.nodes.length})}catch(a){let d=a instanceof wr;E(this.deps,"forge:gaps","forge:gaps:error",e,a,{code:d?"TIMEOUT":"GAPS_ERROR",retryable:d}),pe(this.deps,i,{status:"failure"})}}async handleUsersRequest(e){let t=ot(Hj,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(vA);$e(r.limitInfo,"forge:users query");let{users:o,truncated:i}=SA(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){E(this.deps,"forge:users","forge:users:error",e,r,{code:"USERS_ERROR"})}}async handleTargetRecordsRequest(e){let t=ot(Bj,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 fe(ds).withTimeout("forge:target-records",()=>r.request(`/services/data/v${r.version}/limits/recordCount`)),o=Ab(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){E(this.deps,"forge:target-records","forge:target-records:error",e,r,{code:"TARGET_RECORDS_ERROR"})}}async handleSampleBudgetRequest(e){let t=ot(qj,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=WR({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){E(this.deps,"forge:sample-budget","forge:sample-budget:error",e,o,{code:"SAMPLE_BUDGET_ERROR"})}}async handlePreviewRoots(e){let t=ot(Wj,e,"forge:previewRoots:error",this.deps);if(!t)return;let{sourceOrgId:r,soqlQuery:n}=t,o=t.maxRoots??this.maxRoots(),i=wb(n);if("issue"in i){let c=Sb(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),l=d.limit!==void 0&&d.limit<=o?d.limit:o+1,{records:u,pages:f}=await new fe(n0).withTimeout("forge:previewRoots",()=>rr({query:async p=>c.query(p),queryMore:async p=>c.queryMore(p)},bb(a,d,void 0,o),l));$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(u.length,o),more:u.length>o,...d.limit!==void 0?{limit:d.limit}:{},...d.orderBy!==void 0?{orderBy:d.orderBy}:{},requests:f}))}catch(c){E(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",Nl);return yb(typeof e=="number"?e:void 0,Nl)}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(!jl(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:u,ids:f,sha256:p,readAt:g,query:h}=e.retried;return{...o,plan:{version:1,sourceOrgId:t.sourceOrgId,fingerprint:"",objectApiName:u,...h?{query:h}:{},from:"query",readAt:g,ids:f,sha256:p},planOfTheRunRetried:!0}}let i=this.runJournal?.storagePath;if(i===void 0||e.resumes)return o;await NR(i,new Date).catch(u=>{oe.warn(`Forge roots: the roots of past simulations were not swept (${O(u)})`)});let d=this.setupFingerprintOf(e.graph,t,e.anonymizationRules,e.readCeiling),c;try{c=xR(i,d)}catch(u){if(u instanceof _u)return o;throw u}if(e.dryRun)return{...o,keepAt:c,fingerprint:d};let l;try{l=await DR(c)}catch(u){if(!(u instanceof _u))throw u;u.fault==="changed"&&oe.warn(`Forge roots: the simulation's roots no longer read whole (${u.message})`)}return{...o,fingerprint:d,...l?{plan:l}:{}}}};import{randomUUID as E0}from"node:crypto";import*as JA from"node:os";import*as Dr from"node:path";var zA=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(!Dr.isAbsolute(s))throw new Error(`Invalid import path: "${s}" is not absolute. Pick a file inside the workspace or your home directory.`);let r=Dr.resolve(s),n=Dr.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=Dr.resolve(i);if(process.platform==="win32"){let d=r.toLowerCase(),c=a.toLowerCase();return d===c||d.startsWith(c+Dr.sep)}return r===a||r.startsWith(a+Dr.sep)}))throw new Error("Invalid import path: the file must be inside an open workspace folder or your home directory.");return r}async function GA(s,e){let t=await s.statSize(e);if(t>zA){let r=(t/1048576).toFixed(1),n=zA/(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 Bc=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=$(Ey,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 It(this.deps.configStore);if(Kg(o.list(),n)){r({success:!1,code:"DUPLICATE_NAME"});return}let a=(Array.isArray(t.config.objects)?t.config.objects:[]).map(u=>typeof u=="object"&&u!==null?u.objectApiName:void 0).filter(u=>typeof u=="string").filter(u=>na(u));if(a.length>0){r({success:!1,code:"SYNC_CANNOT_COPY",objects:a});return}let d=new Date().toISOString(),c=Xh.safeParse({...t.config,id:E0(),name:n,description:C0,createdAt:d,updatedAt:d});if(!c.success){let[u]=c.error.issues;r({success:!1,code:"INVALID_CONFIG",reason:u?`${u.path.join(".")}: ${u.message}`:c.error.message});return}let l=c.data;o.save(l),this.deps.log(`[TX] migration:save-sync-config:response saved ${l.id}`),r({success:!0,id:l.id,name:l.name})}catch(n){E(this.deps,"migration:save-sync-config","migration:error",e,n)}}getAllowedBaseDirs(){return[...this.deps.services?.getWorkspaceFolders?.()??[],JA.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){E(this.deps,"migration:pick-file","migration:error",e,t)}}async handleImportSfdmu(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Ty,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 GA(n,o);let{SfdmuImporter:i,SfdmuRefusal:a}=await import("./chunk-LNXBCE7E.mjs"),d=new i({readFile:async c=>(c!==o&&await GA(n,c),n.readFile(c))});try{let{config:c,notes:l}=await d.import(o),u=A(this.deps,e,"migration:import-sfdmu:response",{success:!0,config:c,notes:l});this.deps.broker.postToWebview(u)}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: ${O(n)}`);let o=A(this.deps,e,"migration:import-sfdmu:response",{success:!1,error:O(n)});this.deps.broker.postToWebview(o)}}};import*as cs from"node:fs/promises";var YA="settings",VA=G({version:j(),exportedAt:j(),exportedBy:j().optional(),categories:ve(_e(["syncMappings","forgePlans","pipelines","anonymizationTemplates",YA])),data:xi(j(),pn())});function XA(s){return s!==YA}var Mf={syncMappings:"sync:config:",forgePlans:"forge:templates",pipelines:"pipeline:saved:",anonymizationTemplates:"anonymization:"},KA={syncMappings:"syncConfigs",forgePlans:"forge",pipelines:"pipelines",anonymizationTemplates:"anonymizationTemplates"},ki="forge:templates";function D0(s){return typeof s.name=="string"&&s.name.length>0?s.name:s.id}var qc=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 l=await this.heldTemplates();r[i]=l.length>0?{[ki]:l}:{},n+=l.length;continue}let a=Mf[i],d=this.configStore.getKeysByPrefix(a),c={};for(let l of d){let u=this.configStore.get(l);u!==void 0&&(c[l]=u,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=VA.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(XA),d=0;for(let c of a){let l=i.data[c];if(!l||typeof l!="object"){r.push(`Category "${c}" has no data, skipped.`);continue}if(c==="forgePlans"){d+=await this.importTemplates(l,t,r);continue}let u=Mf[c];for(let[f,p]of Object.entries(l)){if(!f.startsWith(u)){r.push(`Key "${f}" does not match expected prefix "${u}" for category "${c}", skipped.`);continue}if(!t&&this.configStore.has(f)){r.push(`Key "${f}" already exists, skipped.`);continue}if(this.configStore.set(f,p,KA[c]),d++,c==="pipelines"){let g=sS(this.configStore,f.slice(u.length));g.length>0&&r.push(`Pipeline "${f}" 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=VA.safeParse(t);return r.success?{valid:!0,categories:r.data.categories.filter(XA)}:{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(Mf)){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(ki);return Array.isArray(r)?r.filter(ln):[]}let e=await this.workspace.readTemplates(),t=Lc(this.configStore,this.workspace.folder);return t?bi(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,l]of Object.entries(e)){if(c!==ki){r.push(`Key "${c}" does not match expected prefix "${ki}" for category "forgePlans", skipped.`);continue}if(!Array.isArray(l)){r.push(`Key "${c}" holds no list of templates, skipped.`);continue}for(let u of l){if(!ln(u)){r.push(`An entry of "${c}" has no id, skipped.`);continue}if(!i.has(u.id)){if(i.add(u.id),o.has(u.id)){if(!t){r.push(`Forge template "${D0(u)}" already exists, skipped.`);continue}d.push(u.id)}a.push(u)}}}return this.workspace?wA(this.configStore,this.workspace.folder,a,d):a.length>0&&this.configStore.set(ki,bi(n,a,new Set(d)),KA.forgePlans),a.length}};import*as Lf from"node:path";var Wc=class{deps;filePath;constructor(e){this.deps=e,this.filePath=Lf.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=bi(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=Lf.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 Wc({workspacePath:e,readFile:r=>cs.readFile(r,"utf-8"),writeFile:(r,n)=>cs.writeFile(r,n,"utf-8"),mkdir:r=>cs.mkdir(r,{recursive:!0}).then(()=>{})});return{folder:e,readTemplates:()=>t.list()}}var zc=class{constructor(e){this.deps=e;this.profileManager=new qc(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=$(jy,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){E(this.deps,"config:export","config:error",e,n)}}async handleImport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(My,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){E(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){E(this.deps,"config:categories","config:error",e,t)}}handleValidate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Ly,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){E(this.deps,"config:validate","config:error",e,n)}}};var M0=G({metric:j(),operator:_e(["gt","gte","lt","lte","eq","neq"]),threshold:Te(),warningThreshold:Te().optional()}),L0=G({id:j(),name:j(),description:j(),category:_e(["security","performance","compliance","custom"]),condition:M0,remediation:j(),enabled:Ge()}),Oi=G({id:j(),name:j(),description:j(),rules:ve(L0),createdAt:j(),updatedAt:j()});function QA(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 Gc=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";QA(a,n,o)?d="fail":i!==void 0&&QA(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 Jc="governance:policy:",F0="governance",Ii=class{constructor(e){this.configStore=e}configStore;getAll(){let e=this.configStore.getKeysByPrefix(Jc),t=[];for(let r of e){let n=this.configStore.get(r);if(n){let o=Oi.safeParse(n);o.success&&t.push(o.data)}}return t}getById(e){let t=this.configStore.get(`${Jc}${e}`);if(!t)return;let r=Oi.safeParse(t);return r.success?r.data:void 0}save(e){this.configStore.set(`${Jc}${e.id}`,e,F0)}delete(e){return this.configStore.delete(`${Jc}${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"]),Vc=class{constructor(e,t){this.deps=e;this.store=new Ii(e.configStore),this.engine=new Gc,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){E(this.deps,"governance:policies:list","governance:error",e,t)}}handlePolicySave(e){let t=$($y,e,"governance:error",this.deps);if(t)try{let r=Oi.safeParse(t.policy);if(!r.success){E(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){E(this.deps,"governance:policy:save","governance:error",e,r)}}handlePolicyDelete(e){let t=$(Cy,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){E(this.deps,"governance:policy:delete","governance:error",e,r)}}async handleEvaluate(e){let t=$(xy,e,"governance:error",this.deps);if(!t)return;let r=t;try{let n=this.store.getById(r.policyId);if(!n){E(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/${wo}/limits`),a={};for(let[l,{Max:u,Remaining:f}]of Object.entries(i))a[l]=u>0?Math.round((u-f)/u*100):0;for(let[l,u]of Object.entries(_0))u in a&&(a[l]=a[u]);let d=this.engine.evaluatePolicy(n,a);if(this.alertEngine)for(let l of d.ruleResults)l.status==="fail"&&l.actualValue!==null&&this.alertEngine.evaluate(`governance:${l.ruleId}`,l.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){E(this.deps,"governance:evaluate","governance:error",e,n)}}handleTemplates(e){try{let t=Ii.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){E(this.deps,"governance:templates","governance:error",e,t)}}};var Xc=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"]),Kc=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)||vh(c))continue;let l=this.inferRelationshipType(d.name);a.push({childObject:e,parentObject:c,lookupField:d.name,relationshipType:l,suggestedInsertOrder:0})}return a}inferRelationshipType(e){return H0.has(e)?"masterDetail":"lookup"}};var Yc=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,l)=>c+l.recordCount,0),a=o.reduce((c,l)=>c+l.estimatedApiCalls,0),d=a*2;return{objects:o,totalRecords:i,totalApiCalls:a,estimatedDurationSec:d}}};var Qc=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 Gp(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"]),Ai={direction:"source_to_target",mode:"full",conflictStrategy:"source_wins",operation:"insert",batchSize:200},Zc=class{constructor(e){this.deps=e}deps;suggester=new Xc;relationshipDetector=new Kc;previewEstimator=new Yc;autoFieldMapper=new Qc;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=$(gy,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,l)=>c.localeCompare(l))});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(n){E(this.deps,"quicksync:suggest-objects","quicksync:error",e,n)}}async handleDetectRelationships(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(hy,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(l=>({name:l.name,type:l.type,referenceTo:l.referenceTo??[],relationshipName:l.relationshipName??null})),a=r.availableObjects??(await n.describeGlobal()).sobjects.filter(l=>l.createable&&l.queryable).map(l=>l.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){E(this.deps,"quicksync:detect-relationships","quicksync:error",e,n)}}async handlePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(my,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=Za(this.deps.services?.getSandforgeSetting?.("sync.maxRecordsPerObject",void 0));for(let u of o){let p=(await n.query(`SELECT COUNT() FROM ${u}`)).totalSize??0;i.push({objectApiName:u,count:Math.min(p,a),...p>a?{heldInSource:p}:{}})}let d=new Set(r.parentObjects??[]),c={...this.previewEstimator.estimate(i,d),readCap:a},l=A(this.deps,e,"quicksync:preview:response",{preview:c});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`)}catch(n){E(this.deps,"quicksync:preview","quicksync:error",e,n)}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(yy,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let n=gg.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 u=0;u<a.length;u++){let f=a[u],p=n.parentObjects.includes(f),[g,h]=await Promise.all([Yt(n.sourceOrgId,f,()=>o.describe(f)),Yt(n.targetOrgId,f,()=>i.describe(f))]),m=g.fields.filter(w=>w.createable).map(w=>({apiName:w.name,label:w.label,type:w.type})),y=h.fields.filter(w=>w.createable).map(w=>({apiName:w.name,label:w.label,type:w.type})),R=this.autoFieldMapper.suggest(m,y),k=this.autoFieldMapper.toMappings(R);d.push({objectApiName:f,operation:Ai.operation,fieldMappings:k,transformRules:[],excludedFields:[],batchSize:Ai.batchSize,insertOrder:p?0:u+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:Ai.direction,mode:Ai.mode,objects:d,conflictStrategy:Ai.conflictStrategy,enableRollback:!1};Ie(this.deps,"info","Quick Sync",`Starting sync of ${a.length} object(s)`);let l=A(this.deps,e,"quicksync:execute:response",{syncConfig:c,objectCount:a.length});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`)}catch(n){E(this.deps,"quicksync:execute","quicksync:error",e,n)}}};var ZA=6e4,q0=2880*6e4,W0=60*6e4,el=class{deps;schedules=new Map;checkInterval;lastTickTime=0;claims;lastPrune=0;running=new Set;constructor(e){this.deps=e,this.claims=e.claims??ns()}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()},ZA),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+Yv)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*ZA&&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(l=>l.errors)[0],d=ed(i),c=[a,d].filter(l=>l!==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=sd(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 Ff="schedule:sync:",eT="syncSchedules",tl=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${Ff}${e.id}`,e,eT)}load(e){return this.configStore.get(`${Ff}${e}`)}list(){let e=this.configStore.getByCategory(eT);return Object.values(e).sort((r,n)=>n.createdAt.localeCompare(r.createdAt))}delete(e){return this.configStore.delete(`${Ff}${e}`)}loadAll(){return this.list()}};var z0=new Set(["sync:schedule:list","sync:schedule:upsert","sync:schedule:toggle","sync:schedule:delete"]),rl=class{constructor(e){this.deps=e}deps;executor;executeBridge;inFlight=0;claims=ns();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 el({scheduleStore:new tl(this.deps.configStore),configStore:new It(this.deps.configStore),onExecute:t=>this.executeDue(t),notificationCenter:{notify:(t,r,n)=>{this.deps.log(`[SyncSchedule] ${t}: ${r} \u2014 ${n}`),Ie(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){E(this.deps,"sync:schedule:list","sync:schedule:error",e,t)}}handleUpsert(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(hm,e,"sync:schedule:error",this.deps);if(!t)return;let r=t.schedule.configId;if(!new It(this.deps.configStore).load(r)){E(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=sd(n,o,Date.now());if(typeof i!="number"){E(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){E(this.deps,"sync:schedule:upsert","sync:schedule:error",e,a)}}handleToggle(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(mm,e,"sync:schedule:error",this.deps);if(t)try{let r=this.getExecutor().toggle(t.scheduleId,t.enabled);if(!r){E(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){E(this.deps,"sync:schedule:toggle","sync:schedule:error",e,r)}}handleDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ym,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){E(this.deps,"sync:schedule:delete","sync:schedule:error",e,r)}}};var G0=new Set(["direct","rename"]);function tT(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(f=>f.objectApiName===s.objectApiName);if(!a)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" does not carry it.`);let d=Ro([a]);if(d.length>0)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" cannot be applied. ${vo(d)}`);let c=$g([a]);if(c.length>0)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" cannot be applied. ${xg(c)}`);let l=a.externalIdField?.trim()||"Id",u=a.fieldMappings.find(f=>f.targetField===l&&G0.has(f.type));return{...n,keyField:l,keySource:l==="Id"?"Id":u?.sourceField??l,fieldMappings:a.fieldMappings,...a.excludedFields?.length?{excludedFields:a.excludedFields}:{},addOnFields:a.addOnFields,transformRules:a.transformRules,...i.keepContactPoints===!0?{keepContactPoints:!0}:{}}}}}var J0=G({entityName:j().min(1),changeType:j().min(1),recordIds:ve(j()),commitTimestamp:Te(),commitUser:j().optional(),transactionKey:j().optional(),changeOrigin:j().optional(),changedFields:ve(j()).optional(),nulledFields:ve(j()).optional()}).loose(),V0=G({event:G({replayId:Te()}).loose(),payload:G({ChangeEventHeader:J0}).loose()}).loose(),nl="ChangeEvent";function nT(s){return`/data/${s.endsWith("__c")?s.slice(0,-1):s}${nl}`}function oT(s){if(!s.endsWith(nl)||s===nl)return null;let e=s.slice(0,-nl.length);return e.endsWith("__")?`${e}c`:e}function sT(s,e){return s.endsWith("__c")?`${s.slice(0,-3)}__${e}__s`:s.endsWith("Address")?`${s.slice(0,-7)}${e}`:e}function rT(s){let e=s.indexOf(".");return e<0?s:sT(s.slice(0,e),s.slice(e+1))}function X0(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function iT(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[sT(i,d)]=c;else o[i]=a;for(let i of r.nulledFields??[])o[rT(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(rT),values:o}}var _f="SandForgeRealtime";function aT(s){return s.changeOrigin.split(";").some(e=>e.trim()===`client=${_f}`)}var ls=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 dT(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 l of r)l(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((l,u)=>{i.subscribe(a,c).then(()=>l(),f=>{e.delete(a),u(new ls(a,t.get(a)??K0(f)))})})},onDown(a){r.push(a)},disconnect(){n=!0,i.disconnect()}}}var cT="SELECT EventChannel, SelectedEntity FROM PlatformEventChannelMember";function lT(s){let e=new Map;for(let t of s){let r=typeof t.SelectedEntity=="string"?t.SelectedEntity:"",n=oT(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 uT(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(u=>u.externalId===!0).map(u=>u.name).sort()}catch(l){d=!1,n(`[realtime] ${i} could not be described in the target: ${O(l)}`)}return{objectApiName:i,channel:a,inTarget:d,externalIdFields:c,syncConfigs:o.filter(l=>l.objects.some(u=>u.objectApiName===i)).map(l=>({id:l.id,name:l.name}))}}))}var sl=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}},Fn=200,pT=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 fT(s){return s==="CREATE"||s==="UNDELETE"}function ol(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 gT(s){return Object.fromEntries(Object.entries(s).filter(([e])=>e!=="attributes"))}function hT(s){return s==null||s===""}function Uf(s){return String(s).toLowerCase()}var il=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:Fn,insertOrder:0}}plan;deps;mapping=new Bh;transforms=new Hh;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 l of i.recordIds){let u=c.changes.get(l);u?(u.eventIndexes.push(a),u.values={...u.values,...i.values},u.full=u.full||fT(i.changeType),u.needsRead=u.needsRead||i.changeType.startsWith("GAP_"),u.commitTimestamp=Math.min(u.commitTimestamp,i.commitTimestamp),u.replayId=Math.max(u.replayId,i.replayId)):c.changes.set(l,{recordId:l,eventIndexes:[a],changeType:i.changeType,full:fT(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,l)=>{for(let u of c.eventIndexes)t[u].push(l)};try{i.kind==="upsert"?await this.applyUpserts(a,d,r):await this.applyDeletes(a,d,r)}catch(c){let l=O(c);for(let u of a)d(u,{outcome:"failed",error:l})}}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:O(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"&&pT.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(p=>[p.name,p]));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(p=>p.needsRead),t);let i=e.filter(p=>!p.needsRead||p.full),a=await this.keysOf(i,t,!1);i=i.filter(p=>a.has(p.recordId));let d=await this.readTarget([...new Set([...a.values()])],o,this.writtenFieldsOf(i,a)),c=[],l=[];for(let p of i){let g=a.get(p.recordId),h=d.get(Uf(g))??[];if(h.length>1){t(p,{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(p,{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."}):p.full?c.push({change:p,record:this.recordFor(p,g,o,!1)}):l.push(p);continue}let y=String(m.Id),R=this.recordFor(p,g,o,!0),k=ol(m.LastModifiedDate);if(!(k!==null&&k>p.commitTimestamp&&!this.deps.ownWrites.wrote(y,k))){c.push({change:p,record:R,targetId:y});continue}switch(this.deps.conflictStrategy){case"source_wins":c.push({change:p,record:R,targetId:y});break;case"merge":{let I=Object.fromEntries(Object.entries(R).filter(([P,b])=>b!==null||P===this.plan.keyField));Object.keys(I).length>1?c.push({change:p,record:I,targetId:y}):t(p,{outcome:"kept-target"});break}case"manual":r.push(this.held(p,"upsert",R,m)),t(p,{outcome:"held"});break;case"target_wins":case"newest_wins":t(p,{outcome:"kept-target"});break}}if(l.length>0){for(let p of l)p.needsRead=!0;await this.readWhole(l,t);for(let p of l.filter(g=>g.full))c.push({change:p,record:this.recordFor(p,a.get(p.recordId),o,!1)})}if(c.length===0)return;let{outcomes:u}=await this.deps.write(this.objectConfig,c.map(p=>p.record),this.contactPoints),f=[];c.forEach((p,g)=>{let h=u[g];if(h?.success){t(p.change,{outcome:"applied"});let m=h.id??p.targetId;m&&f.push(m)}else t(p.change,{outcome:"failed",error:h?.errors[0]??"The target answered nothing for this record."})}),await this.rememberWrites(f)}async applyDeletes(e,t,r){let n=this.plan.objectApiName,o=new Map((await this.deps.target.describe(n)).fields.map(u=>[u.name,u])),i=await this.keysOf(e,t,!0),a=e.filter(u=>i.has(u.recordId)),d=await this.readTarget([...new Set([...i.values()])],o,[]),c=[];for(let u of a){let f=i.get(u.recordId),p=d.get(Uf(f))??[];if(p.length>1){t(u,{outcome:"failed",error:`${p.length} records of ${n} in the target have ${this.plan.keyField} = ${String(f)}.`});continue}let g=p[0];if(!g){t(u,{outcome:"applied"});continue}let h=String(g.Id),m=ol(g.LastModifiedDate);!(m!==null&&m>u.commitTimestamp&&!this.deps.ownWrites.wrote(h,m))||this.deps.conflictStrategy==="source_wins"?c.push({change:u,targetId:h}):this.deps.conflictStrategy==="manual"?(r.push(this.held(u,"delete",{[this.plan.keyField]:f},g)),t(u,{outcome:"held"})):t(u,{outcome:"kept-target"})}if(c.length===0)return;let{outcomes:l}=await this.deps.write({...this.objectConfig,operation:"delete"},c.map(u=>({Id:u.targetId})));c.forEach((u,f)=>{let p=l[f];t(u.change,p?.success?{outcome:"applied"}:{outcome:"failed",error:p?.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(ol(n.LastModifiedDate)??0).toISOString()}}async keysOf(e,t,r){let{keySource:n}=this.plan,o=e.filter(a=>n!=="Id"&&hT(a.values[n])&&!(n in a.values&&a.full));if(o.length>0){let a=await this.readSource(o.map(d=>d.recordId),`Id, ${qe(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(hT(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?[]:Qi(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 l=r.get(d);l&&((n?l.updateable!==!0:l.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={...gT(o),...n.values},n.full=!0}}async readSource(e,t,r){let n=bt(this.plan.objectApiName),o=new Map;for(let i=0;i<e.length;i+=Fn){let d=e.slice(i,i+Fn).map(u=>`'${er(u)}'`).join(", "),c=t==="FIELDS(ALL)"?` LIMIT ${Fn}`:"",l=await this.deps.source.query(`SELECT ${t} FROM ${n} WHERE Id IN (${d})${c}`,{includeDeleted:r});for(let u of l)o.set(String(u.Id),u)}return o}async readTarget(e,t,r){let n=bt(this.plan.objectApiName),o=qe(this.plan.keyField),i=pT.has(t.get(this.plan.keyField)?.type??""),a=r.filter(l=>l!=="Id"&&l!==this.plan.keyField&&l!=="LastModifiedDate"&&t.has(l)),d=["Id",...o==="Id"?[]:[o],"LastModifiedDate",...a],c=new Map;for(let l=0;l<e.length;l+=Fn){let f=e.slice(l,l+Fn).map(h=>i?String(Number(h)):`'${er(String(h))}'`).join(", "),p=`WHERE ${o} IN (${f})`,g;try{g=await this.deps.target.query(`SELECT ${d.map(qe).join(", ")} FROM ${n} ${p}`)}catch{g=await this.deps.target.query(`SELECT Id${o==="Id"?"":`, ${o}`}, LastModifiedDate FROM ${n} ${p}`)}for(let h of g){let m=Uf(h[this.plan.keyField]);c.set(m,[...c.get(m)??[],gT(h)])}}return c}async rememberWrites(e){if(e.length===0)return;let t=bt(this.plan.objectApiName);try{for(let r=0;r<e.length;r+=Fn){let n=e.slice(r,r+Fn).map(i=>`'${er(i)}'`).join(", "),o=await this.deps.target.query(`SELECT Id, LastModifiedDate FROM ${t} WHERE Id IN (${n})`);for(let i of o){let a=ol(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 al=class{constructor(e){this.deps=e}deps;async open(e){let t={subscribed:[],refused:[],notes:[]};for(let r of e){let n=nT(r),o=a=>{let d;try{d=iT(n,a)}catch(c){this.deps.onUnreadable(n,O(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 ls&&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:mT(d)})}else t.refused.push({objectApiName:r,reason:mT(a)})}}return t}close(){this.deps.transport.disconnect()}};function mT(s){return s instanceof ls?s.answer:O(s)}var rM=[2e3,1e4,3e4],nM=6e4,dl=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=O(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<nM);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 al({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 rM){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: ${O(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: ${O(t)}`)}}}async process(e){let t=e.map(()=>({outcome:"watched"})),r=new Map;e.forEach((i,a)=>{aT(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:l}=await d.apply(a.map(u=>e[u]));c.forEach((u,f)=>{t[a[f]]=u});for(let u of l)this.held.set(u.conflictId,{change:u,applier:d}),this.deps.sink.conflict(u)}catch(c){let l=O(c);for(let u of a)t[u]={outcome:"failed",error:l}}}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)=>oM(i,t[a]))),this.deps.replayStore.save(o)}};function oM(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 sM="realtime:replay:",iM="realtime",Ti=class{constructor(e,t){this.configStore=e;this.sourceOrgId=t}configStore;sourceOrgId;get key(){return`${sM}${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)},iM)}forget(){this.configStore.delete(this.key)}};function Hf(s){return s.eventsFailed===0?"success":s.eventsApplied>0?"partial":"failure"}function yT(s){return s.slice(0,15)}function wT(s){let e=s.store.recorder({runId:s.sessionId,configId:`realtime:${s.sessionId}`,configName:"",sourceOrgId:s.sourceOrgId,targetOrgId:s.targetOrgId,realtime:!0});s.identity&&kr(e,s.identity,`realtime ${s.sessionId}`);let t=s.backups?Ya({runId:s.sessionId,orgId:s.targetOrgId,files:s.backups,meta:s.meta}):void 0,r=d=>s.target.query(d),n=t?Qa({query:r,backup:t,recorder:e,describe:async d=>Or(await s.target.describe(d)),viewsEncrypted:yr(r)}):void 0,o=new Set,i=(d,c,l,u)=>{if(c==="insert"||c==="upsert"){for(let p of td(c,u))o.add(yT(p));return}if(c!=="delete")return;let f=l.flatMap((p,g)=>{let h=p.Id;return u[g]?.success===!0&&typeof h=="string"&&!o.has(yT(h))?[h]:[]});f.length>0&&e.deleted?.(d,f)},a;return{runId:s.sessionId,calls:rd(e,n),write:d=>{let c=Promise.resolve();return(l,u,f)=>{let p=c.then(async()=>{let g=await d(l,u,f);return i(l.objectApiName,l.operation,u,g.outcomes),g});return c=p.catch(()=>{}),p}},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 aM=new Set(["realtime:start","realtime:stop","realtime:status","realtime:metrics","realtime:objects","realtime:resolve-conflict"]);function dM(s){let e=r=>B(r,s.orgRegistry,s.orgManager),t=lt(s);return{async openTransport(r){let{streaming:n}=await e(r);return dT({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 rr({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 Yt(r,n,()=>o.describe(n))).fields}}}},writer(r,n){return async(o,i,a)=>{let d=await e(r),c=await ah(d,_f),l=new Cn({connection:c,bulkExecutor:new Rn(t.bulk.threshold),bulkManager:mr(s),retryConfig:t.retry,onProgress:()=>{},log:f=>s.log(f),...n?{calls:n}:{}});return new hv({upsert:(f,p,g,h)=>l.upsert(f,p,g,h),insert:(f,p,g)=>l.insert(f,p,g),update:(f,p,g)=>l.update(f,p,g),delete:(f,p,g)=>l.delete(f,p,g),describeTargetFields:async f=>Or(await Yt(r,f,()=>d.describe(f))),...a?{contactPoints:a}:{}}).write(o,i)}},async tooling(r,n){let o=await e(r),{records:i}=await rr({query:async a=>o.tooling.query(a),queryMore:async a=>o.tooling.queryMore(a)},n);return i}}}var cl=class{constructor(e,t){this.deps=e;this.syncConfigs=new It(e.configStore),this.access=t??dM(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(!aM.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 Ti(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&&Z(this.deps,{action:"realtime_sync",module:"sync",operationId:e.operationId,orgId:e.targetOrgId,outcome:Hf(this.lastMetrics),guard:e.guard,source:{origin:"org",orgId:e.sourceOrgId}}),t>0&&Ie(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=$(nm,e,"realtime:error",this.deps);if(t)try{let r=await this.access.tooling(t.sourceOrgId,cT),n=this.access.reader(t.targetOrgId),o=await uT(lT(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=Zg(O(r));E(this.deps,"realtime:objects","realtime:error",e,r,n?{code:n}:void 0)}}async handleStart(e){let t=$(tm,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(v=>tT(v,T=>this.syncConfigs.load(T),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 sl,d=this.access.reader(t.sourceOrgId),c=this.access.reader(t.targetOrgId),l=crypto.randomUUID(),u=o&&this.runCreations?wT({sessionId:l,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:v=>this.deps.log(v)}):void 0,f=u?u.write(this.access.writer(t.targetOrgId,u.calls)):this.access.writer(t.targetOrgId),p=new dR,g=Xn(yr(v=>d.query(v)),v=>d.describe(v)),h=new Map(n.map(v=>[v.objectApiName,new il(v,{source:d,target:c,write:f,conflictStrategy:t.conflictStrategy,ownWrites:a,contactPoints:p,maskedSourceFields:g})])),m,y=()=>{},R=new Promise((v,T)=>{y=D=>{D?m?.fail(D):i.signal.aborted?m?.cancel():m?.complete(),D?T(new Error(D)):v()}});R.catch(()=>{});let k=async()=>{if(!u)return;let v=await u.end({status:Hf(w.metrics()),cancelled:i.signal.aborted}).catch(T=>O(T));this.openRuns.delete(u.runId),v!==void 0&&Ie(this.deps,"warning","Real-time sync",`What the session wrote could not all be kept (${v}): removing it may leave some of it in the target.`)},w=new dl({sessionId:l,watchedObjects:t.watchedObjects,appliers:h,flushIntervalMs:t.flushIntervalMs,maxBatchSize:t.maxBatchSize},{openTransport:()=>this.access.openTransport(t.sourceOrgId),replayStore:new Ti(this.deps.configStore,t.sourceOrgId),sink:{events:v=>this.pushEvents(v),conflict:v=>this.pushConflict(v),status:v=>{if(v.status!=="error"){this.pushStatus(v);return}y(v.error),k().then(()=>this.pushStatus(v))}},log:v=>this.deps.log(v)}),I={session:w,abort:i,operationId:e.id,sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,guard:o,finish:v=>y(v),detach:()=>{},endRun:k};this.current=I,this.lastMetrics=null,u&&this.openRuns.add(u.runId);let P;try{P=await w.start()}catch(v){throw await k(),v}let b=w.snapshot();if(P.subscribed.length>0){let v=`Real-time sync of ${P.subscribed.length} object(s)`;this.registry?.register(w.sessionId,"sync",v,R,i),m=ir(this.liveTracker,w.sessionId,"realtime",v);let T=()=>{this.current?.session===w&&this.stopCurrent().then(D=>{D&&this.pushStopped(D,"cancelled")})};i.signal.addEventListener("abort",T,{once:!0}),I.detach=()=>i.signal.removeEventListener("abort",T)}else y(),await k();let S=new Set(P.subscribed),C=(await Promise.all(n.filter(v=>S.has(v.objectApiName)).map(async v=>({objectApiName:v.objectApiName,fields:[...await g(v.objectApiName)].sort()})))).filter(v=>v.fields.length>0);C.length>0&&(I.encryptedLeftOut=C),this.post(A(this.deps,e,"realtime:started",{success:P.subscribed.length>0,sessionId:w.sessionId,watchedObjects:P.subscribed,refused:P.refused,notes:P.notes,...C.length>0?{encryptedLeftOut:C}:{},...b.error?{error:b.error}:{}}))}catch(n){r(O(n))}}async passesProductionGuard(e,t,r){let n=this.deps.infraServices?.productionGuard;if(!n)throw Z(this.deps,{action:"realtime_sync",module:"sync",operationId:e.id,orgId:t,outcome:"stopped",code:be.code}),ea();let o={orgId:t,orgTier:Ee(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 Ze(n,o);if(i==="refused"||i==="declined"){Z(this.deps,{action:"realtime_sync",module:"sync",operationId:e.id,orgId:t,outcome:"stopped",guard:i});return}return i}async handleStop(e){let t=$(rm,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=$(om,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||Ie(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 cM=new Set(["file:save"]),ll=class{constructor(e,t){this.deps=e;this.saveDialog=t??new kn}deps;saveDialog;async handle(e){return cM.has(e.type)?(await this.handleSave(e),!0):!1}async handleSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Kh.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 lM=new Set(["reports:list","reports:audit","reports:lineage"]),uM="forge:history",pM="sync:history:all",bT=50;function fM(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 gM(s){let e=s.graph?.nodes??[];return e.filter(t=>!Mg(t)).length+Lg(s,e).length}var ul=class{constructor(e){this.deps=e}deps;async handle(e){if(!lM.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=$(Dy,e,"reports:error",this.deps);if(t===null)return;let r=new Io(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=$(Ny,e,"reports:error",this.deps);if(t===null)return;let r=new Eh(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?bT:Math.min(Math.floor(t),500)}build(e=bT){let t=this.deps.configStore.get(uM)??[],r=this.deps.configStore.get(pM)??[],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:mM(n)}}forgeReport(e){let t=gM(e),r=fM(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 hM(s){let e=s.sections[0]?.content?.status;return e==="failure"||e==="failed"||e==="partial"}function mM(s){let e=s.length;if(e===0)return{totalOperations:0,successRate:0,avgDuration:0,errorRate:0};let t=s.filter(hM).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 RT(s){return Object.values(s).every(e=>e<50)}var pl=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(Yf.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((l,u)=>l+u,0),i=RT(t),a=n!==void 0&&!RT(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 wM(s,e){return`smart-action:${s}:${e??""}`}var bM=300*1e3,RM=new Set(["smart-action:analyze"]),fl=class{constructor(e){this.deps=e;this.analyzer=new pl({getConnection:t=>B(t,e.orgRegistry,e.orgManager)})}deps;analyzer;cache=new Map;async handle(e){return RM.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=$(Xy,e,"smart-action:error",this.deps);if(t)try{let r=t.targetOrgId,n=t.sourceOrgId,o=wM(r,n),i=this.cache.get(o);if(i&&Date.now()-i.fetchedAt<bM){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){E(this.deps,"smart-action:analyze","smart-action:error",e,r)}}};var vM=new Set(["execution:abort"]),gl=class{constructor(e,t){this.deps=e;this.registry=t}deps;registry;async handle(e){return vM.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=$(Py,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){E(this.deps,"execution:abort","execution:error",e,t)}}};import{readFile as SM}from"node:fs/promises";import{join as kM}from"node:path";var Bf=new Map;function vT(s,e){let t=kM(s,`${e}.json`),r=Bf.get(t);if(r)return r;let n=SM(t,"utf-8").then(o=>JSON.parse(o));return Bf.set(t,n),n.catch(()=>Bf.delete(t)),n}var OM=new Set(["i18n:locale"]),hl=class{constructor(e,t){this.deps=e;this.localesDir=t}deps;localesDir;async handle(e){return OM.has(e.type)?(await this.handleLocaleRequest(e),!0):!1}async handleLocaleRequest(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Vy,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 vT(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}): ${O(n)}`);let o=A(this.deps,e,"i18n:locale:response",{lng:r,error:O(n)});this.deps.broker.replyToRequester(o)}}};import{AsyncLocalStorage as IM}from"node:async_hooks";function kT(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 ST=new IM;async function OT(s,e,t,r){let n=Symbol("pipeline sync"),o,i=s.registry?.onEvent((d,c,l)=>{c!=="started"||l.module!=="sync"||ST.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 ST.run(n,()=>Sa(t,()=>s.execute(e)));return o!==void 0?{...d,operationId:o}:d}finally{i?.(),r?.removeEventListener("abort",a)}}var AM=G({setting:j().regex(/^sandforge(?:\.[A-Za-z][A-Za-z0-9]*)+$/)}),ml=class{handlerDeps;executeCommand;showLog;panelRouteListener;panelReloadListener;idCounter=0;orgHandler;settingsHandler;monitorHandler;seedHandler;seedCloneHandler;seedCsvHandler;syncHandler;syncHistoryHandler;syncRemovalHandler;seedRemovalHandler;compareHandler;dataOpsHandler;complianceHandler;cleanupHandler;emptyHandler;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 wd({configStore:e.configStore,orgManager:e.orgManager,log:e.log}),this.recoveryProgressSource=Vv({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:Fl,bulkManager:new Th(Fl.bulk.maxConcurrentJobs),nextId:()=>this.nextId(),sandboxRefreshes:this.refreshDetector,recoveryProgress:this.recoveryProgressSource},this.orgHandler=new Sd(this.handlerDeps),this.recoveryHandler=new bd(this.handlerDeps),this.settingsHandler=new kd(this.handlerDeps),this.monitorHandler=new Md(this.handlerDeps),this.seedHandler=new Ud(this.handlerDeps),this.seedCloneHandler=new Wd(this.handlerDeps),this.seedCsvHandler=new Vd(this.handlerDeps),this.seedRemovalHandler=new tc(this.handlerDeps,void 0,r=>this.seedHandler.isRunning(r)||this.seedCsvHandler.isRunning(r)||this.seedCloneHandler.isRunning(r)),this.syncHandler=new Yd(this.handlerDeps),this.syncHistoryStore=new nc(e.configStore),this.syncHandler.setHistoryLogger(new oc(this.syncHistoryStore)),this.syncHistoryHandler=new Qd(this.handlerDeps,this.syncHistoryStore,this.syncHandler),this.syncRemovalHandler=new Zd(this.handlerDeps,this.syncHistoryStore,r=>this.syncHandler.isRunning(r)||this.realtimeHandler.isRunning(r)),this.compareHandler=new sc(this.handlerDeps),this.dataOpsHandler=new Eb(this.handlerDeps),this.complianceHandler=new cc(this.handlerDeps),this.cleanupHandler=new lc(this.handlerDeps),this.emptyHandler=new Ic(this.handlerDeps),this.automationHandler=new Ec(this.handlerDeps),this.aiHandler=new Dc(this.handlerDeps),this.autopilotHandler=new jc(this.handlerDeps),this.forgeHandler=new Hc(this.handlerDeps),this.frozenHandler=new tS(this.handlerDeps),this.frozenHandler.setSaltKeeper(eS(e.secretVault));let t=()=>[this.forgeHandler,this.frozenHandler,this.dataOpsHandler,this.complianceHandler,this.emptyHandler,this.autopilotHandler,this.realtimeHandler];this.checkpointHandler=new gd(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 Bc(this.handlerDeps),this.configHandler=new zc(this.handlerDeps),this.governanceHandler=new Vc(this.handlerDeps,this.monitorHandler.getAlertEngine()),this.quickSyncHandler=new Zc(this.handlerDeps),this.syncScheduleHandler=new rl(this.handlerDeps),this.realtimeHandler=new cl(this.handlerDeps),this.fileHandler=new ll(this.handlerDeps),this.reportsHandler=new ul(this.handlerDeps),this.smartActionHandler=new fl(this.handlerDeps),this.i18nHandler=new hl(this.handlerDeps,e.localesDir),this.automationHandler.setStepRunners({orgName:r=>{let n=e.orgManager.getOrg(r);return n?he(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 It(e.configStore).load(r),listSyncConfigs:()=>new It(e.configStore).list(),syncGuard:r=>kT(this.handlerDeps.infraServices?.productionGuard,Kp(r,e.orgManager.getOrg(r.targetOrgId))),runSync:(r,n,o)=>OT({execute:i=>this.syncHandler.executeScheduled(i,"pipeline"),registry:this.backgroundRegistry},r,n,o),orgTier:r=>{let n=e.orgManager.getOrg(r);return n?Ee(n):void 0},organizationIdsOf:r=>[e.orgManager.getOrg(r)?.orgId,this.refreshDetector.organizationIdOf(r)].filter(n=>typeof n=="string"&&n!==""),savedSeedTemplate:r=>new sn(e.configStore).load(r),listSeedTemplates:()=>new sn(e.configStore).list(),seed:(r,n)=>this.seedHandler.seedForPipeline(r,n),maskingTemplates:()=>[...Ch.map(r=>({...r,builtIn:!0})),...new ba(e.configStore).list().map(r=>({...r,builtIn:!1}))],anonymize:(r,n)=>this.dataOpsHandler.anonymizeForPipeline(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(uk),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){ko().remove(e),fk(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(mb(this.handlerDeps.secretVault)),this.syncHandler.setBackupRecordStore(e),this.syncRemovalHandler.setBackupRecordStore(e),this.realtimeHandler.setBackupRecordStore(e)}otherModuleRuns(e,t){return async(r,n)=>{let o=e==="forge"?this.forgeHandler:e==="frozen"?this.frozenHandler:void 0,i=new Io(this.handlerDeps.configStore).list({orgId:r,limit:ig}).entries,a=[...e==="forge"?[]:await this.forgeHandler.localRunsOn(r,n),...e==="sync"?[]:await this.syncRemovalHandler.localRunsOn(r),...e==="seed"?[]:await this.seedRemovalHandler.localRunsOn(r),...lv(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-XAMMIPZ4.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 gl(this.handlerDeps,e)}async replayQueuedOperation(e){let t=yn("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)}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"],this.orgHandler),t(["settings:get","settings:update","telemetry:status","telemetry:toggle"],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: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: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(["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: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:manifest:get","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=AM.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 yl=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 TM=100,EM=1e3,PM=3,CM=1e3;function $M(s){return typeof s=="object"&&s!==null&&"protocolVersion"in s&&"payload"in s&&typeof s.payload=="object"}var IT=500;function xM(s){let e=s.map(t=>`${t.path.map(String).join(".")}: ${t.message}`).join("; ");return e.length<=IT?e:`${e.slice(0,IT)}\u2026(+${s.length} issues)`}var bl=class{handlers=new Map;panels=new Set;rateLimiter;telemetry;fixSuggestionNotifier;mismatchCount=0;webviewSeen=!1;firstWebviewCallbacks=[];senders=new Map;constructor(e){this.rateLimiter=new yl(e?.rateLimitMax??TM,e?.rateLimitWindowMs??EM),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=O(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(!$M(e)){this.logFn?.("[MessageBroker] Received malformed message: not an envelope");return}let r=ng.safeParse(e);if(!r.success){let o=xM(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;Qf(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>=PM&&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>CM){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 Rl=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 vl=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 Sl=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=O(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 kl=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){oe.warn("OrgManager listener threw",{error:O(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 us="org.",Ol="org-cred.",qf="orgs",AT=1e4;function DM(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 NM(e)}function NM(s){if(s.orgType===_i(s.orgType,s.metadata?.edition))return s;let{safetyTier:e,color:t}=Ur("Developer");return{...s,orgType:"Developer",safetyTier:e,appearance:{...s.appearance,color:s.appearance.color===Wl?t:s.appearance.color}}}var Il=class{constructor(e,t,r){this.configStore=e;this.secretVault=t;this.orgManager=r}configStore;secretVault;orgManager;loadAll(){let e=this.configStore.getByCategory(qf),t=new Map,r=[];for(let[n,o]of Object.entries(e)){if(!n.startsWith(us))continue;let i=DM(o),a=i.orgId??i.id,d=n.slice(us.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(us.length);this.secretVault.deleteSecret(`${Ol}${o}`).catch(()=>{}),this.orgManager.removeOrg(o),oe.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=`${us}${e.id}`,n=this.configStore.get(r),i=n!==void 0&&Ee(n)==="production"&&bo(e)&&n.appearance?.color===Wl?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,qf),this.orgManager.addOrg(a),t&&await this.secretVault.storeObject(`${Ol}${e.id}`,t)}async removeOrg(e){this.configStore.delete(`${us}${e}`),await this.secretVault.deleteSecret(`${Ol}${e}`),this.orgManager.removeOrg(e)}async getCredentials(e){let t=this.secretVault.getObject(`${Ol}${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 ${AT} ms for org "${e}" \u2014 the OS keyring may be locked or unavailable.`))},AT)})])}finally{r!==void 0&&clearTimeout(r)}}updateOrgMetadata(e){this.configStore.set(`${us}${e.id}`,e,qf),this.orgManager.addOrg(e)}};import{mkdtemp as jM,readFile as MM,rm as LM}from"node:fs/promises";import{tmpdir as FM}from"node:os";import{join as Wf}from"node:path";async function TT(s){let e=await jM(Wf(FM(),"sandforge-sf-"));try{let t={stdout:Wf(e,"stdout.json"),stderr:Wf(e,"stderr.txt")},r;try{await s(t)}catch(o){r=o}let n=o=>MM(o,"utf8").catch(()=>"");return{stdout:await n(t.stdout),stderr:await n(t.stderr),...r!==void 0?{failure:r}:{}}}finally{await LM(e,{recursive:!0,force:!0}).catch(()=>{})}}var $T=10*1024*1024,_M=3e4,Al=3e4,Vf=6e4,ET=12e4,PT=3e4,UM=4,HM=2e3,BM=/["%!\u0000-\u001f\u007f]/,CT=/^[A-Za-z0-9._-]+={0,2}$/;async function Xf(s,e){let{exec:t}=await import("child_process"),{promisify:r}=await import("util"),n=await r(t)(s,{maxBuffer:$T,windowsHide:!0,env:eu(),...e});return{stdout:String(n.stdout),stderr:String(n.stderr)}}function xT(s,e){if(BM.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 Tl(s,e){let{exec:t,execFile:r}=await import("child_process");return new Promise(n=>{let o={encoding:"utf8",maxBuffer:$T,windowsHide:!0,timeout:e.timeoutMs,env:eu()},i={},a=!1,d=u=>{a||(a=!0,clearTimeout(i.timer),n(u))},c=(u,f,p)=>{d({stdout:String(f),stderr:String(p),...u?{failure:{message:u.message,killed:u.killed}}:{}})},l=process.platform==="win32"?t(["sf",...s.map(u=>xT(u.value,u.role))].join(" "),o,c):r("sf",s.map(u=>u.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"&&l.pid!==void 0&&r("taskkill",["/pid",String(l.pid),"/T","/F"],{windowsHide:!0},()=>{})},e.timeoutMs+HM),l.stdin?.once("error",()=>{}),l.stdin?.end(e.input??"")})}var qM=G({status:Te().optional(),result:pn().optional(),message:j().optional(),name:j().optional()}).loose();function DT(s){try{let e=qM.safeParse(JSON.parse(jT(s.stdout)));return e.success?e.data:void 0}catch{return}}function NT(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 WM=G({id:j().min(1),username:j().min(1),instanceUrl:j().min(1),accessToken:j().nullish(),alias:j().nullish(),connectedStatus:j().nullish(),apiVersion:j().nullish(),devHubId:j().nullish(),status:j().nullish(),expirationDate:j().nullish(),edition:j().nullish()}).loose(),zM=G({username:j().min(1),orgId:j().min(1),instanceUrl:j().min(1)}).loose();function zf(s,e,t=Vf){let r=DT(s);if(s.failure||r?.status!==0)throw NT(s,r,e,t);let n=zM.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 Gf(s){let e=Gi(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 jT(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 GM(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 JM(s,e){let t=s;return t.killed===!0?`its ${e/1e3} s limit`:typeof t.code=="number"?`exit code ${t.code}`:tu(O(s))??"an error that says nothing"}async function VM(s,e){let t=Date.now(),r=o=>process.platform==="win32"?xT(o,"temporary folder path"):GM(o),n=!1;try{let o=await TT(async a=>{let d=`${s} > ${r(a.stdout)} 2> ${r(a.stderr)}`;n=!0,await Xf(d,{timeout:e})}),i=o.failure===void 0?void 0:n?JM(o.failure,e):O(o.failure);return{ran:n,stdout:o.stdout,stderr:o.stderr,ms:Date.now()-t,...i?{failure:Os(i)}:{}}}catch(o){return{ran:n,stdout:"",stderr:"",ms:Date.now()-t,failure:Os(O(o))}}}function MT(s){if(!s.ran)return`could not be made (${(s.failure??"").slice(0,200)})`;let e=Pl(s.stderr);return`ended with ${s.failure??"exit code 0"} after ${Kf(s.ms)} s, with ${s.stdout.length} chars in its stdout file and ${s.stderr.length} in its stderr file${e?` ("${e}")`:""}`}function Pl(s){let e=tu(s);return e===void 0?void 0:Os(e).slice(0,200)}function Kf(s){return(s/1e3).toFixed(1)}function LT(s,e){return s.ms>=e-500}function XM(s,e,t,r,n){let o=Pl(s.stderr),i=a=>a.length>0?a.join(" | "):"none";return[`first run: ${Kf(s.ms)} s of the ${n/1e3} s allowed`+(LT(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: ${MT(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: ${Os(process.cwd())}`,`variables ${th()}`].join("; ")}function KM(s,e,t,r,n){let o=Pl(s.stderr),i=process.platform==="win32"?"where.exe sf":"which -a sf",a=new Set(t.sf.map(l=>l.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 ${Kf(s.ms)} s${LT(s,n)?`, its ${n/1e3} s limit,`:""} and exited with code 0. Run again with its output sent to a file, it ${MT(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 Jf(s){return s.connectedStatus!==void 0?s.connectedStatus==="Connected":s.isScratch===!0&&s.status==="Active"&&s.isExpired!==!0}function YM(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 QM(s){let e=await nh({instanceUrl:s.instanceUrl,accessToken:s.accessToken,...s.apiVersion?{version:s.apiVersion}:{}});return Ji(e)}async function ZM(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 El=class{constructor(e=ih,t=QM){this.readToken=e;this.readKind=t}readToken;readKind;versionAnswer;async isCliAvailable(){try{let{stdout:e}=await Xf("sf --version",{timeout:_M});return this.versionAnswer=Pl(e)??"",!0}catch{return!1}}async listOrgs(e){let t=await this.readOrgEntries(),r=this.dedupeByOrgId(t.filter(a=>Jf(a))),n=new Set(r.map(a=>a.orgId));for(let a of this.dedupeByOrgId(t.filter(d=>!Jf(d))))n.has(a.orgId)||e?.({username:a.username,...a.alias?{alias:a.alias}:{},orgId:a.orgId,reason:YM(a),why:"notConnected"});let o=await ZM(r.map(a=>async()=>{try{return{entry:await this.withUsableToken(a)}}catch(d){return{entry:a,reason:O(d)}}}),UM),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||!Jf(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}: ${O(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 Tl([{value:"org",role:"command"},{value:"display",role:"command"},{value:"--target-org",role:"flag"},{value:e,role:"username"},{value:"--json",role:"flag"}],{timeoutMs:PT}),r=DT(t);if(r?.name==="NamedOrgNotFoundError")return;if(t.failure||r?.status!==0)throw NT(t,r,"sf org display",PT);let n=WM.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:Gf(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"}),zf(await Tl(t,{timeoutMs:Vf}),"sf org login jwt")}async loginWithRefreshToken(e){if(!CT.test(e.clientId))throw new Error("The consumer key holds characters the Salesforce CLI does not accept.");if(!CT.test(e.refreshToken))throw new Error("Salesforce issued a refresh token the Salesforce CLI cannot store (unexpected characters).");let t=new URL(Gf(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 zf(await Tl(r,{timeoutMs:Vf,input:n}),"sf org login sfdx-url")}async readOrgEntries(){let e="sf org list --json",t=Date.now(),r,n="";try{let a=await Xf(e,{timeout:Al});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=jT(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 VM(e,Al),n=await rh(),o=XM(t,r,n,this.versionAnswer,Al);if(r.stdout.trim()!=="")return oe.warn(`${e} printed nothing on its pipe; what it wrote to a file was read instead. ${o}`),r.stdout;throw oe.warn(`${e} printed nothing, on its pipe or to a file. ${o}`),new Error(KM(t,r,n,this.versionAnswer,Al))}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:Gf(t),role:"login URL"}];return e&&r.push({value:"--alias",role:"flag"},{value:e,role:"alias"}),r.push({value:"--json",role:"flag"}),zf(await Tl(r,{timeoutMs:ET}),"sf org login web",ET)}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(ru(e.accessToken))return e;let t=await this.readToken(e.username);if(!ru(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=Gn({isScratch:e.isScratch,isSandbox:e.isSandbox,edition:e.orgEdition}),{safetyTier:r,color:n}=Ur(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??yo.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 eL(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 Cl=class{deps;results=new Map;constructor(e){this.deps=e}async execute(e,t){let r=Date.now(),{items:n,managedLeftOut:o}=await eL(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 tL(){return globalThis.crypto.randomUUID()}function FT(s){return{stepId:s.id,stepName:s.name,stepType:s.type,status:"skipped"}}function rL(s,e){let t={};for(let r of s.variables)r.defaultValue!==void 0&&(t[r.name]=r.defaultValue);return{...t,...e}}function nL(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 _T(s){return`Validation failed: ${s.join(", ")}`}function oL(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 $l=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=_T(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 l=rL(e,t),{steps:u}=e,f=this.deps.conditionalRouter,p=!1,g=0;for(;g<u.length;){if(this.cancelledRuns.has(a.id)||d.signal.aborted){a.status="cancelled";break}let h=u[g],m=await this.runStep(h,a,l,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(l,nL(m)),l[Ug]=m.status==="completed"?"succeeded":"failed",d.signal.aborted||m.status==="stopped"){a.status="cancelled";break}if(m.status==="failed"&&(p=!0,!h.continueOnError)){a.status="failed",a.error=m.error;break}let y=g+1;if(f.endsRun(h,m))y=u.length;else{let R=f.getNextStep(h,m),k=R?u.findIndex((w,I)=>I>g&&w.id===R):-1;k!==-1&&(y=k)}for(let R of u.slice(g+1,y)){let k=FT(R);a.stepResults.push(k),this.emit("stepSkipped",{runId:a.id,stepResult:k})}g=y}return a.status==="running"&&(a.status=p?"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 ${O(i)}.`}}if(!o)return FT(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?[_T(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)??oL(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:tL(),pipelineId:e.id,pipelineName:e.name,status:"queued",triggeredBy:r,stepResults:[],variables:t,startTime:new Date().toISOString()}}};var xl=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 aL=3e4;function dL(s,e,t={}){let r=Gn({isSandbox:e.isSandbox,edition:e.orgType,...t.typeScratch===!0&&s.scratch===!0?{isScratch:!0}:{}}),{safetyTier:n,color:o}=Ur(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:yo.DEFAULT_API_VERSION,edition:e.orgType,features:[]},status:"connected",lastConnected:new Date().toISOString(),tags:[]}}function cL(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 lL(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 uL(s,e,t={}){return{compareOrchestrator:n=>new Cl(n),automationOrchestrator:n=>new $l(n),seedOrchestrator:n=>new kv(n),syncOrchestrator:n=>new Sv(n),getSandforgeSetting:(n,o)=>o,isAIEnabled:()=>!1,configStore:s,showNotification:n=>e(` notification: ${n}`),runsFrom:"commandLine",...t}}function aQ(s){let{log:e}=s,t=s.waitMs??5*6e4,r=Zl();sh("command line");let n=RR(iL(s.storeDir,"configStore.json")),o=new Map,i=new Sl({get:k=>Promise.resolve(o.get(k)),store:(k,w)=>(o.set(k,w),Promise.resolve()),delete:k=>(o.delete(k),Promise.resolve())}),a=new kl,d=new Il(n,i,a),c=new El,l=new Jv;l.setSfdxBridge(c);let u=new bl;u.setLogFunction(e);let f=new Rl(u),p=uL(n,e,s.services),g=new ml({log:e,broker:u,stateSync:new vl(u),orgManager:a,orgRegistry:d,configStore:n,secretVault:i,authProvider:l,sfdxBridge:c,services:p});g.setLiveOperationTracker(new xl),s.compose?.({handlers:g,configStore:n,orgRegistry:d,orgManager:a,services:p,log:e}),g.registerAll(f);let h=[],m=new Set,y,R={webview:{postMessage:k=>{h.push(k);let w=lL(k);w&&e(` ${w}`),s.onPost?.(k);for(let I of[...m])I(k);return Promise.resolve(!0)},onDidReceiveMessage:k=>(y=k,{dispose:()=>{y=void 0}})}};return u.registerPanel(R),{posted:h,async connect(k){let w=await ch(k),I=await l.validateConnection(w.accessToken,w.instanceUrl),P=dL(w,I,{typeScratch:s.typeScratchOrgs===!0});return await d.saveOrg(P,{loginUrl:w.instanceUrl,instanceUrl:w.instanceUrl,accessToken:w.accessToken,username:w.username}),P},connectingRequests:()=>Zl()-r,request(k){let w=y;if(!w)return Promise.reject(new Error("No panel is registered with the broker."));let I=k.responseType??`${k.type}:response`,P=k.timeoutMs??aL,b={id:k.id??`wv-${sL()}`,type:k.type,timestamp:Date.now(),...k.payload!==void 0?{payload:k.payload}:{}},S=Date.now();return new Promise(C=>{let v=z=>{m.delete(T),clearTimeout(D),C(z)},T=z=>{let H=cL(z,b.id,I);if(!H)return;let Y=Date.now()-S;v({outcome:H,message:z,elapsedMs:Y,late:Y>P})},D=setTimeout(()=>v({outcome:"unanswered",elapsedMs:Date.now()-S,late:!0}),Math.max(t,P));m.add(T),w({protocolVersion:1,payload:b})})}}}export{$n as a,UT as b,sn as c,ep as d,rp as e,dd as f,yS as g,ld as h,bS as i,$L as j,sp as k,vS as l,LL as m,AS as n,FL as o,$E as p,aQ as q};