sandforge 1.82.0 → 1.84.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (251) hide show
  1. package/README.md +1 -1
  2. package/lib/chunk-23SEDORH.mjs +11 -0
  3. package/lib/{chunk-7WSLT5VX.mjs → chunk-24RFOFYT.mjs} +1 -1
  4. package/lib/chunk-26POJDIT.mjs +7 -0
  5. package/lib/{chunk-SFGZFB4F.mjs → chunk-2AZQHBEF.mjs} +1 -1
  6. package/lib/{chunk-6VSZNZHH.mjs → chunk-2HVOZUM4.mjs} +1 -1
  7. package/lib/{chunk-XFU3HRUV.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-SZGGFST2.mjs → chunk-326AJTIU.mjs} +14 -14
  12. package/lib/{chunk-Q6SXNKV2.mjs → chunk-36JOHEJL.mjs} +1 -1
  13. package/lib/chunk-3PVRGTVK.mjs +7 -0
  14. package/lib/{chunk-VZVICK7Q.mjs → chunk-3Q353S2R.mjs} +1 -1
  15. package/lib/chunk-3TZSBHEY.mjs +7 -0
  16. package/lib/{chunk-UHFLKP26.mjs → chunk-43TOMFV4.mjs} +1 -1
  17. package/lib/{chunk-XK5W7BVE.mjs → chunk-4CVUUVGJ.mjs} +1 -1
  18. package/lib/{chunk-VYOYXTCU.mjs → chunk-4EOHEDFP.mjs} +1 -1
  19. package/lib/{chunk-EOFO3PHS.mjs → chunk-4JE4BYXK.mjs} +1 -1
  20. package/lib/{chunk-7EYQYZJP.mjs → chunk-54WZUS7J.mjs} +1 -1
  21. package/lib/chunk-5CRLRHOJ.mjs +7 -0
  22. package/lib/{chunk-FA4ZKDCU.mjs → chunk-5IZTFMJM.mjs} +1 -1
  23. package/lib/chunk-5M5FQ7RP.mjs +7 -0
  24. package/lib/{chunk-3HROD5RE.mjs → chunk-5SMWFNE7.mjs} +1 -1
  25. package/lib/{chunk-YAIIRFKJ.mjs → chunk-5XTUSN72.mjs} +1 -1
  26. package/lib/chunk-6I6TWNV5.mjs +7 -0
  27. package/lib/{chunk-PYRZFUVU.mjs → chunk-6JWWSDM6.mjs} +1 -1
  28. package/lib/chunk-6O222PW6.mjs +7 -0
  29. package/lib/{chunk-2UU42PTD.mjs → chunk-6PD6K7LP.mjs} +1 -1
  30. package/lib/{chunk-GGUOIDWP.mjs → chunk-6QE6R6RL.mjs} +1 -1
  31. package/lib/{chunk-DJCGURW7.mjs → chunk-6WX5ZU7Q.mjs} +1 -1
  32. package/lib/{chunk-DT3T7FRD.mjs → chunk-6YL7BNYD.mjs} +1 -1
  33. package/lib/chunk-6ZLKIT3H.mjs +7 -0
  34. package/lib/{chunk-CBL42DUU.mjs → chunk-7QYHEHMA.mjs} +1 -1
  35. package/lib/chunk-7SQSWVAU.mjs +9 -0
  36. package/lib/{chunk-ZUBBEP75.mjs → chunk-7UVKIWKV.mjs} +1 -1
  37. package/lib/{chunk-TWV4A5RK.mjs → chunk-7WATA4SB.mjs} +1 -1
  38. package/lib/chunk-7YNM6KFZ.mjs +7 -0
  39. package/lib/chunk-A3MYSOOC.mjs +7 -0
  40. package/lib/chunk-AL4C3GFT.mjs +7 -0
  41. package/lib/chunk-B3FBHVNN.mjs +21 -0
  42. package/lib/{chunk-27Z76O2O.mjs → chunk-B63POIPQ.mjs} +1 -1
  43. package/lib/{chunk-RTWYLOCA.mjs → chunk-BAWCOKRW.mjs} +1 -1
  44. package/lib/{chunk-NWOI25WY.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-CPQIZGG5.mjs +7 -0
  49. package/lib/chunk-CVHNXJH3.mjs +7 -0
  50. package/lib/{chunk-HFUDCNU5.mjs → chunk-D4GF4FAB.mjs} +1 -1
  51. package/lib/chunk-DGDRQRCW.mjs +7 -0
  52. package/lib/{chunk-YAJQS3OL.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-TMA34QMA.mjs → chunk-EAC5QCE3.mjs} +1 -1
  56. package/lib/{chunk-VQJMP3DC.mjs → chunk-EC72TIEG.mjs} +1 -1
  57. package/lib/chunk-EPFCERGL.mjs +7 -0
  58. package/lib/{chunk-3MGMNK3Q.mjs → chunk-ETDCBLGU.mjs} +1 -1
  59. package/lib/{chunk-LXDSRP2W.mjs → chunk-F3AQW6IU.mjs} +1 -1
  60. package/lib/{chunk-A65ADTCR.mjs → chunk-FITPY3L4.mjs} +1 -1
  61. package/lib/chunk-FNJ4SGWO.mjs +7 -0
  62. package/lib/{chunk-SAMWHL22.mjs → chunk-FP7CYB2F.mjs} +1 -1
  63. package/lib/{chunk-JLZRZL5E.mjs → chunk-GKY2JMHY.mjs} +1 -1
  64. package/lib/chunk-GMIGWR6U.mjs +7 -0
  65. package/lib/{chunk-AUS6NFLZ.mjs → chunk-GNRSF65U.mjs} +1 -1
  66. package/lib/chunk-GOOVPVWX.mjs +7 -0
  67. package/lib/{chunk-PPHVWUFY.mjs → chunk-GWZRR3MM.mjs} +1 -1
  68. package/lib/{chunk-JH27IKCO.mjs → chunk-H2BHESDA.mjs} +2 -2
  69. package/lib/chunk-H33DVU3D.mjs +7 -0
  70. package/lib/chunk-H4CGM6YO.mjs +7 -0
  71. package/lib/{chunk-WOOUISSO.mjs → chunk-HCGXK7G7.mjs} +1 -1
  72. package/lib/{chunk-VZT4E2OJ.mjs → chunk-HIDW7FNV.mjs} +1 -1
  73. package/lib/chunk-HSBXRQTI.mjs +7 -0
  74. package/lib/chunk-HUZPBE47.mjs +7 -0
  75. package/lib/chunk-HV7VPEXP.mjs +7 -0
  76. package/lib/chunk-I6E6T6YY.mjs +7 -0
  77. package/lib/chunk-IUM4NFKI.mjs +10 -0
  78. package/lib/chunk-IVFVNNGB.mjs +37 -0
  79. package/lib/{chunk-5K2I2DMP.mjs → chunk-IZGCEOYO.mjs} +1 -1
  80. package/lib/{chunk-ZHIZY3ZC.mjs → chunk-J3DND3BC.mjs} +1 -1
  81. package/lib/{chunk-VPDEJGPS.mjs → chunk-JAEDM4SI.mjs} +1 -1
  82. package/lib/chunk-JCFBFF4Y.mjs +7 -0
  83. package/lib/{chunk-GBGHJTPC.mjs → chunk-JE6SCT6R.mjs} +1 -1
  84. package/lib/chunk-JGZPD4IM.mjs +7 -0
  85. package/lib/{chunk-C3LNYAVJ.mjs → chunk-JKJ74BX5.mjs} +1 -1
  86. package/lib/{chunk-EEFUE2ES.mjs → chunk-JLSIWO4Z.mjs} +1 -1
  87. package/lib/{chunk-3CX7GPCR.mjs → chunk-JSAJS3MY.mjs} +1 -1
  88. package/lib/chunk-JTJK2D36.mjs +7 -0
  89. package/lib/{chunk-V3R45ZWT.mjs → chunk-KAZS5Z6W.mjs} +1 -1
  90. package/lib/chunk-KB4ZHM4Q.mjs +10 -0
  91. package/lib/{chunk-J24TIGSI.mjs → chunk-KGU4SVIT.mjs} +1 -1
  92. package/lib/chunk-KJWFYBMU.mjs +15 -0
  93. package/lib/{chunk-H4JUYUSL.mjs → chunk-KZTZDC7H.mjs} +1 -1
  94. package/lib/chunk-L2E5WBGD.mjs +8 -0
  95. package/lib/{chunk-XU25YA46.mjs → chunk-L53JWJ3S.mjs} +1 -1
  96. package/lib/{chunk-Y4TDVDP2.mjs → chunk-LA4KIATH.mjs} +6 -6
  97. package/lib/chunk-LC3NDW4N.mjs +7 -0
  98. package/lib/{chunk-GCGHHN4K.mjs → chunk-LKTNQEBS.mjs} +1 -1
  99. package/lib/chunk-M2ABR4JM.mjs +7 -0
  100. package/lib/{chunk-3C2ZZIFN.mjs → chunk-M4BLK6HJ.mjs} +1 -1
  101. package/lib/{chunk-L4INJ5TZ.mjs → chunk-M6K34KGF.mjs} +1 -1
  102. package/lib/chunk-MDMPJEV3.mjs +7 -0
  103. package/lib/{chunk-32EUNQT6.mjs → chunk-MJZU3U5O.mjs} +68 -63
  104. package/lib/{chunk-PBE44M2Y.mjs → chunk-MSIEU5MR.mjs} +1 -1
  105. package/lib/{chunk-NLB3RGIY.mjs → chunk-N4WPCWJO.mjs} +1 -1
  106. package/lib/{chunk-SNEOKYV7.mjs → chunk-NCZKWSC7.mjs} +1 -1
  107. package/lib/{chunk-6KP6WETK.mjs → chunk-NED4MBIM.mjs} +1 -1
  108. package/lib/chunk-NOBQTEQD.mjs +7 -0
  109. package/lib/{chunk-RCYEBY42.mjs → chunk-NSQWI7ZY.mjs} +1 -1
  110. package/lib/{chunk-DBBPDSFN.mjs → chunk-O677VOGO.mjs} +1 -1
  111. package/lib/chunk-OFTT7J2M.mjs +7 -0
  112. package/lib/{chunk-C2N2TNEU.mjs → chunk-OLCVHL7I.mjs} +1 -1
  113. package/lib/chunk-OM5NORJG.mjs +7 -0
  114. package/lib/chunk-OMNMLKDT.mjs +7 -0
  115. package/lib/{chunk-CELEBWEZ.mjs → chunk-OPMO6I45.mjs} +1 -1
  116. package/lib/{chunk-LHU6CPGE.mjs → chunk-OUZQPYT3.mjs} +1 -1
  117. package/lib/chunk-OVNMB6Q2.mjs +7 -0
  118. package/lib/{chunk-6GQUZ4IP.mjs → chunk-PAXNWTYK.mjs} +1 -1
  119. package/lib/{chunk-XSKPYGMT.mjs → chunk-PBY2O6OF.mjs} +1 -1
  120. package/lib/chunk-PEDQPM2P.mjs +926 -0
  121. package/lib/chunk-PH7SP4YK.mjs +21 -0
  122. package/lib/{chunk-3SKLBRPL.mjs → chunk-PMN4PAC3.mjs} +1 -1
  123. package/lib/chunk-PMWAFDUB.mjs +48 -0
  124. package/lib/chunk-PPLVFX6N.mjs +7 -0
  125. package/lib/{chunk-STRMWSIQ.mjs → chunk-PR3XCSPO.mjs} +1 -1
  126. package/lib/{chunk-GJ6SZVHT.mjs → chunk-PR42EZSR.mjs} +1 -1
  127. package/lib/{chunk-YMDFF657.mjs → chunk-PWRJRL5U.mjs} +1 -1
  128. package/lib/{chunk-Q3DY7TO2.mjs → chunk-Q7GIJBCD.mjs} +1 -1
  129. package/lib/chunk-Q7TLC3I2.mjs +7 -0
  130. package/lib/{chunk-ZXFL2MSN.mjs → chunk-QAFPQ3YB.mjs} +1 -1
  131. package/lib/{chunk-T7WREYA5.mjs → chunk-QKEKG2LD.mjs} +1 -1
  132. package/lib/chunk-QO53K5W2.mjs +9 -0
  133. package/lib/{chunk-MUEQRIK7.mjs → chunk-QTG6LUZT.mjs} +1 -1
  134. package/lib/{chunk-KP5G6FUC.mjs → chunk-RE7RYF3B.mjs} +1 -1
  135. package/lib/{chunk-FOIWWK7G.mjs → chunk-RGBGUCJA.mjs} +1 -1
  136. package/lib/{chunk-DWMRIWV5.mjs → chunk-RGUQOSBU.mjs} +1 -1
  137. package/lib/{chunk-7PY3VQP3.mjs → chunk-RHNTHGNU.mjs} +1 -1
  138. package/lib/chunk-RKTFFCNS.mjs +7 -0
  139. package/lib/chunk-RMFU4BAL.mjs +28 -0
  140. package/lib/{chunk-KKOA62S4.mjs → chunk-ROV3QXEF.mjs} +14 -13
  141. package/lib/chunk-RT47RKLY.mjs +7 -0
  142. package/lib/{chunk-ZUTUYBNW.mjs → chunk-S42RBRH2.mjs} +1 -1
  143. package/lib/{chunk-Z42PHCVZ.mjs → chunk-SI267LYR.mjs} +1 -1
  144. package/lib/chunk-T3G6VZNS.mjs +7 -0
  145. package/lib/chunk-TNT27RBG.mjs +7 -0
  146. package/lib/chunk-UBIKR5VO.mjs +7 -0
  147. package/lib/chunk-UI3JQVRU.mjs +8 -0
  148. package/lib/{chunk-YT22LMF7.mjs → chunk-UIOMAX56.mjs} +1 -1
  149. package/lib/chunk-UX3BVH2Y.mjs +7 -0
  150. package/lib/chunk-VCUXCK36.mjs +7 -0
  151. package/lib/chunk-VINGECAJ.mjs +10 -0
  152. package/lib/chunk-VOXJHJIE.mjs +7 -0
  153. package/lib/chunk-W6PN6TJG.mjs +7 -0
  154. package/lib/{chunk-FKK5YBGZ.mjs → chunk-WAPSSYMT.mjs} +1 -1
  155. package/lib/{chunk-PR74GYVI.mjs → chunk-WUUKFE2U.mjs} +1 -1
  156. package/lib/chunk-WWTCWWZI.mjs +7 -0
  157. package/lib/chunk-WXDLQT2O.mjs +10 -0
  158. package/lib/chunk-WY5V5PR3.mjs +7 -0
  159. package/lib/chunk-X4BXESMQ.mjs +7 -0
  160. package/lib/chunk-XBQGZGWR.mjs +7 -0
  161. package/lib/chunk-XGGOUNPP.mjs +7 -0
  162. package/lib/chunk-XKWW3GKF.mjs +7 -0
  163. package/lib/{chunk-JJITOWZK.mjs → chunk-Y2DRK37K.mjs} +1 -1
  164. package/lib/{chunk-XZISAZA6.mjs → chunk-YA6ATMTB.mjs} +1 -1
  165. package/lib/{chunk-54HYHHVL.mjs → chunk-YDXMTWAT.mjs} +1 -1
  166. package/lib/chunk-YHR4WQPR.mjs +7 -0
  167. package/lib/{chunk-KJYEQHYP.mjs → chunk-YTLUYSMF.mjs} +1 -1
  168. package/lib/chunk-YWEQQL3C.mjs +8 -0
  169. package/lib/{chunk-PWVDNN2C.mjs → chunk-Z4LKKOFY.mjs} +1 -1
  170. package/lib/chunk-ZBAWJUG2.mjs +7 -0
  171. package/lib/{chunk-XO5FBOQF.mjs → chunk-ZJW6YOMV.mjs} +1 -1
  172. package/lib/chunk-ZQQXSCVI.mjs +7 -0
  173. package/lib/{chunk-47UHTN3Q.mjs → chunk-ZQWIVYVM.mjs} +1 -1
  174. package/lib/chunk-ZV7ZFQQC.mjs +9 -0
  175. package/lib/sandforge-autopilot.mjs +25 -25
  176. package/lib/sandforge-backup.mjs +1 -1
  177. package/lib/sandforge-checkpoint.mjs +1 -1
  178. package/lib/sandforge-cleanup.mjs +1 -1
  179. package/lib/sandforge-clone.mjs +1 -1
  180. package/lib/sandforge-compare.mjs +52 -21
  181. package/lib/sandforge-dataops.mjs +1 -1
  182. package/lib/sandforge-empty.mjs +4 -4
  183. package/lib/sandforge-env.mjs +106 -107
  184. package/lib/sandforge-frozen.mjs +1 -1
  185. package/lib/sandforge-mcp.mjs +12 -12
  186. package/lib/sandforge-monitor.mjs +1 -1
  187. package/lib/sandforge-pipeline.mjs +1 -1
  188. package/lib/sandforge-seed.mjs +1 -1
  189. package/lib/sandforge-sync.mjs +1 -1
  190. package/lib/sandforge-users.mjs +21 -23
  191. package/lib/sandforge.mjs +1 -1
  192. package/lib/sf/sandforge/compare.mjs +2 -2
  193. package/lib/sfPlugin.mjs +1 -1
  194. package/oclif.manifest.json +1 -1
  195. package/package.json +1 -1
  196. package/lib/chunk-2JZGCCPG.mjs +0 -9
  197. package/lib/chunk-3HEMJTAP.mjs +0 -925
  198. package/lib/chunk-3XG25GTF.mjs +0 -7
  199. package/lib/chunk-42BFLWHR.mjs +0 -7
  200. package/lib/chunk-466F37VD.mjs +0 -7
  201. package/lib/chunk-4JKR4PTZ.mjs +0 -8
  202. package/lib/chunk-52EXDVPN.mjs +0 -7
  203. package/lib/chunk-7CVDVBEE.mjs +0 -7
  204. package/lib/chunk-7LKI7OAS.mjs +0 -7
  205. package/lib/chunk-7SDZR6SR.mjs +0 -7
  206. package/lib/chunk-A32ISQ6M.mjs +0 -28
  207. package/lib/chunk-A7JJWOLT.mjs +0 -7
  208. package/lib/chunk-BMTNTBBM.mjs +0 -7
  209. package/lib/chunk-BN33LVPQ.mjs +0 -7
  210. package/lib/chunk-BZ24IAP5.mjs +0 -7
  211. package/lib/chunk-CCEH7L53.mjs +0 -7
  212. package/lib/chunk-CV47FDQW.mjs +0 -7
  213. package/lib/chunk-CZLJZQCS.mjs +0 -7
  214. package/lib/chunk-DIL62SUN.mjs +0 -7
  215. package/lib/chunk-DIS254AN.mjs +0 -7
  216. package/lib/chunk-FZF23M6R.mjs +0 -7
  217. package/lib/chunk-G2JR3F63.mjs +0 -7
  218. package/lib/chunk-GGNUACTY.mjs +0 -7
  219. package/lib/chunk-GHPR5UVV.mjs +0 -7
  220. package/lib/chunk-HIHCYMSL.mjs +0 -7
  221. package/lib/chunk-HKUWHVI7.mjs +0 -9
  222. package/lib/chunk-HQQVANWQ.mjs +0 -20
  223. package/lib/chunk-IRZJU2PG.mjs +0 -22
  224. package/lib/chunk-ISSP2FZ5.mjs +0 -7
  225. package/lib/chunk-IVZJSDJD.mjs +0 -7
  226. package/lib/chunk-JESRFE2Z.mjs +0 -11
  227. package/lib/chunk-JFNLKHY6.mjs +0 -8
  228. package/lib/chunk-JKT5YAQ2.mjs +0 -7
  229. package/lib/chunk-JQZTMFO7.mjs +0 -7
  230. package/lib/chunk-KIMQQ6JQ.mjs +0 -7
  231. package/lib/chunk-LAUOSXMN.mjs +0 -341
  232. package/lib/chunk-MKTXJCXN.mjs +0 -10
  233. package/lib/chunk-O2PUGRNW.mjs +0 -10
  234. package/lib/chunk-O4BROUGM.mjs +0 -7
  235. package/lib/chunk-P55MKIZX.mjs +0 -37
  236. package/lib/chunk-P63WJMXQ.mjs +0 -7
  237. package/lib/chunk-PE435FVH.mjs +0 -15
  238. package/lib/chunk-PPGDAUEQ.mjs +0 -7
  239. package/lib/chunk-QAPVKPEC.mjs +0 -7
  240. package/lib/chunk-RLWB7F26.mjs +0 -7
  241. package/lib/chunk-RYRMUPMY.mjs +0 -7
  242. package/lib/chunk-SCKUIE3R.mjs +0 -7
  243. package/lib/chunk-SU65Z2BA.mjs +0 -7
  244. package/lib/chunk-TCBAE65A.mjs +0 -7
  245. package/lib/chunk-WEMLDUQA.mjs +0 -7
  246. package/lib/chunk-WSUKC2U3.mjs +0 -7
  247. package/lib/chunk-WT3SCUHS.mjs +0 -7
  248. package/lib/chunk-YGJF55VJ.mjs +0 -7
  249. package/lib/chunk-YH4DYI6D.mjs +0 -7
  250. package/lib/chunk-ZQO5PDX5.mjs +0 -48
  251. package/lib/chunk-ZUOPC4W2.mjs +0 -7
@@ -0,0 +1,21 @@
1
+ import { createRequire as __sandforgeRequire } from 'node:module';
2
+ import { fileURLToPath as __sandforgePath } from 'node:url';
3
+ import { dirname as __sandforgeDirname } from 'node:path';
4
+ const require = __sandforgeRequire(import.meta.url);
5
+ const __filename = __sandforgePath(import.meta.url);
6
+ const __dirname = __sandforgeDirname(__filename);
7
+ import{a as dS,b as pd,c as cS,d as uS}from"./chunk-BXZ73A5M.mjs";import{b as sS}from"./chunk-CPQIZGG5.mjs";import{a as Bb}from"./chunk-O677VOGO.mjs";import{c as Ub,d as Hb}from"./chunk-JE6SCT6R.mjs";import{b as Mb}from"./chunk-ZRUDYB7O.mjs";import{d as lS,m as pS}from"./chunk-B3FBHVNN.mjs";import{a as iS,b as oo,c as Js,d as ep,e as tp,f as rp,g as aS,h as np}from"./chunk-GMIGWR6U.mjs";import{a as $l,b as Fb,c as _b,d as Fa,f as qs}from"./chunk-UIOMAX56.mjs";import{h as yR,k as OR,l as IR,m as zs,n as _o,o as Ul,p as Wa,q as AR,r as TR,s as ER,u as PR}from"./chunk-3PVRGTVK.mjs";import{a as hv,b as Yl,c as Kv,d as Xv,e as Yv,h as Qv,i as Zv,j as eS,k as tS,n as rS,o as nS,p as ud,q as Ql,r as ld,s as Zl}from"./chunk-JSAJS3MY.mjs";import{b as Jv,e as Vv}from"./chunk-BBRWFKS5.mjs";import{A as id,B as $v,C as xv,D as ad,E as dd,F as cd,G as Dn,H as Dv,I as Nv,L as jv,M as Mv,N as Lv,O as Fv,P as _v,R as Uv,S as Xl,T as Hv,U as Bv,V as qv,_ as Wv,a as Xa,aa as zv,ba as Gv,c as Ya,d as Qa,e as mv,f as yv,g as wv,h as It,j as Za,k as ed,l as rn,m as Wo,n as zo,o as Go,p as bv,q as Rv,r as vv,s as td,t as rd,u as nd,v as Sv,w as Tv,x as Ev,y as Pv,z as Cv}from"./chunk-6I6TWNV5.mjs";import{b as od,g as sd}from"./chunk-QAFPQ3YB.mjs";import{e as Er,g as kv,i as Ov,k as Iv,l as Jo,m as Av}from"./chunk-UX3BVH2Y.mjs";import{a as oS}from"./chunk-JLSIWO4Z.mjs";import{a as Fh,b as ia,e as Ia,g as An,h as ar,i as vb,l as Ib,p as Lb}from"./chunk-KJWFYBMU.mjs";import{a as Rt,b as Vw}from"./chunk-Z4LKKOFY.mjs";import{a as ab,b as db}from"./chunk-XCA5AONB.mjs";import{a as Aa,b as Kw,c as Xw,d as Yw,e as Us,f as Qw,g as Zw,h as eb,j as tb}from"./chunk-WB2RIVO3.mjs";import{$ as Am,$b as Vy,A as om,Ab as Sy,B as vn,Bb as ky,C as gl,Ca as _m,Cb as Oy,D as sm,Da as Um,Db as Iy,Dc as et,E as im,Ea as Hm,Eb as Ay,Ec as Zn,F as da,Fa as Bm,Fb as Ty,Fc as cb,G as am,Ga as qm,Gb as ua,Gc as ub,H as dm,Ha as Wm,Hb as Ey,I as cm,Ia as zm,Ib as Py,J as um,Ja as Gm,Jb as Cy,K as lm,Ka as Jm,Kb as $y,L as pm,La as Vm,Lb as xy,M as fl,Ma as Km,Mb as Dy,N as gm,Na as Xm,Nb as Ny,O as fm,Oa as Ym,Ob as jy,P as hm,Pa as Xr,Pb as My,Q as mm,Qa as Qm,Qb as Ly,R as ym,Ra as wl,Rb as Fy,S as wm,Sa as ca,Sb as _y,T as bm,Ta as Ds,Tb as Uy,U as Rm,Ua as Zm,Ub as Hy,V as vm,Va as ey,Vb as By,W as Sm,Wb as qy,X as km,Xb as Wy,Y as Om,Yb as zy,Z as Im,Zb as Gy,_ as Po,_b as Jy,a as Vr,aa as Tm,ac as Ky,b as Re,ba as Em,bc as Xy,c as oa,ca as Pm,cc as Yy,d as xt,da as hl,dc as Qy,e as bn,ea as Cm,ec as Zy,f as Eo,fa as $m,fb as ty,fc as ew,g as lt,ga as xm,gb as ry,gc as tw,h as br,ha as Dm,hb as ny,hc as rw,i as Rn,ia as Nm,ib as oy,ic as nw,j as A,ja as jm,jb as sy,jc as ow,k as Ie,ka as Mm,kb as iy,kc as sw,l as Je,la as Lm,lb as ay,lc as la,m as Fe,ma as Fm,mb as dy,mc as iw,n as ge,na as ml,nb as cy,nc as aw,o as T,oa as yl,ob as uy,oc as dw,p as sa,pa as xs,pb as ly,pc as cw,q as Ts,qb as py,qc as uw,r as Kr,rb as gy,rc as lw,s as je,sb as fy,sc as pw,t as Zh,tb as hy,tc as gw,u as em,ub as my,uc as fw,v as tm,vb as yy,vc as bl,w as rm,wb as wy,wc as $,x as aa,xb as by,yb as Ry,yc as Oa,z as nm,zb as vy}from"./chunk-XGGOUNPP.mjs";import{g as ka}from"./chunk-L53JWJ3S.mjs";import{a as Lt,b as Cs,c as Bh,d as qh}from"./chunk-CE6ZDGBB.mjs";import{a as lb,b as pb,c as gb,e as fb,f as hb,g as Pa,h as No,i as to,j as Zr,k as Tn,l as Ca}from"./chunk-OFTT7J2M.mjs";import{b as eo,c as Rb}from"./chunk-BOGNK4LV.mjs";import{$a as qo,A as $R,Aa as JR,Ba as VR,Ca as KR,E as xR,Ea as XR,Fa as YR,Ga as Jl,Ia as Uo,Ka as QR,La as Ja,Ma as ZR,T as DR,Va as ev,Xa as Ho,Za as tv,_a as Bo,a as Zi,b as wh,da as Bl,db as rv,ea as ql,eb as Tr,fb as Vl,ga as Wl,gb as sv,h as mR,hb as iv,i as _l,ib as av,jb as dv,ka as Ga,kb as Va,lb as Ka,ma as HR,n as CR,oa as zl,ob as cv,pb as uv,qa as BR,rb as Kl,sa as qR,sb as lv,tb as pv,ua as Gl,ub as gv,va as Gs,vb as fv,wa as WR,ya as zR,za as GR}from"./chunk-IVFVNNGB.mjs";import{a as Hw,b as Co,c as $o,d as In,e as Bw,f as qw,g as Il,j as rb,k as nb,l as Ea,m as ob,n as sb,q as Pl,r as Bs,s as ro,t as Ma}from"./chunk-VINGECAJ.mjs";import{A as Lw,B as sr,C as ba,D as Ra,E as va,G as Sa,J as Fw,K as kl,L as Ol,M as ir,N as _w,O as Uw,P as On,a as jh,b as mw,c as yw,d as ww,e as or,f as vl,g as Sl,h as bw,i as Rw,j as vw,k as Sw,l as Xn,n as Ms,o as Pw,p as Cw,r as $w,s as xw,t as Ls,v as Dw,w as Nw,x as jw,y as Mw}from"./chunk-H4CGM6YO.mjs";import{b as nv,c as ov}from"./chunk-IUM4NFKI.mjs";import{h as wR}from"./chunk-TEIBWMJM.mjs";import{a as bR,b as RR,f as vR,g as SR,h as kR}from"./chunk-BWWQXU2B.mjs";import{d as Ta}from"./chunk-T63U4OZJ.mjs";import{a as xb,b as La,c as Db,k as Nb,p as jb}from"./chunk-5XTUSN72.mjs";import{a as ib}from"./chunk-YYZL7UGV.mjs";import{a as ma,c as ya}from"./chunk-YDXMTWAT.mjs";import{b as Ww,f as zw,p as Ft,q as Fs,r as Al,s as Do,t as Tl,u as _s,x as Gw,y as Jw}from"./chunk-PMN4PAC3.mjs";import{b as NR,c as jR,d as za,e as Hl,g as MR,h as LR,i as FR,j as _R,m as UR}from"./chunk-H2BHESDA.mjs";import{c as Rr,d as Qn}from"./chunk-FP7CYB2F.mjs";import{b as Na,f as ja}from"./chunk-NED4MBIM.mjs";import{L as Ob,d as $a,h as xa,i as Sb,k as kb,z as Da}from"./chunk-KGU4SVIT.mjs";import{a as pa,b as Wt,c as Yr,d as Ns,e as ga,f as js,g as fa,h as Sn,i as hw,j as ha,k as Rl}from"./chunk-JAEDM4SI.mjs";import{a as xe}from"./chunk-5LFSFYFJ.mjs";import{b as yh}from"./chunk-OUZQPYT3.mjs";import{a as sl,c as Oo,d as il,e as ch,f as Is,g as al,h as uh,j as lh,k as ph,l as Io,m as gh,n as dl,o as fh,p as hh,q as mh,r as q}from"./chunk-MSIEU5MR.mjs";import{a as mb,b as zt,c as Gt,g as dr}from"./chunk-LC3NDW4N.mjs";import{$a as Gb,Ac as Ll,Bc as lR,Cc as pR,Dc as gR,Eb as Xb,Ec as Fl,Fb as Yb,G as Ab,Gb as Qb,Hb as Or,Hc as pt,I as Tb,Ib as Ir,Ic as qa,Jb as Ba,Jc as fR,K as Eb,Kb as Zb,Kc as hR,Mb as Nl,N as Pb,O as Cb,P as Cl,Qa as tn,Qb as eR,S as $b,Sa as xl,Ta as qb,Wa as Wb,Wb as tR,Xb as rR,Ya as no,Yb as nR,Za as Dl,Zb as Ar,_a as zb,b as _h,bb as Jb,c as rt,cb as Vb,d as Uh,db as Kb,dc as oR,e as ll,eb as cr,f as Hh,fc as sR,g as Es,gb as kr,gc as iR,h as pl,hb as ur,hc as aR,i as _t,ic as dR,j as Dt,jc as cR,lb as En,m as El,mb as Mo,mc as uR,n as Qr,nb as _a,o as bb,ob as Lo,oc as Cn,pb as Pn,pc as $n,q as Ot,qb as Fo,r as Hs,rb as Ua,s as Kt,tb as Ha,vc as xn,wc as Ws,yc as jl,zc as Ml}from"./chunk-KB4ZHM4Q.mjs";import{a as Mh,e as To,f as bt,g as Lh,i as Z,j as mt}from"./chunk-23SEDORH.mjs";import{a as Yi,f as Qi}from"./chunk-W6PN6TJG.mjs";import{q as Sr,r as en,s as jo}from"./chunk-3Q353S2R.mjs";import{a as vr,b as fe}from"./chunk-VV3B6IC3.mjs";import{a as oe}from"./chunk-4TLYUZD5.mjs";import{i as Ps}from"./chunk-INIT2UKJ.mjs";import{a as dh,b as Os,c as ol}from"./chunk-Q7TLC3I2.mjs";import{e as Iw,h as kn,k as Aw,l as Tw,m as Ew}from"./chunk-D4GF4FAB.mjs";import{b as wa}from"./chunk-CVHNXJH3.mjs";import{D as $s,F as Qh,p as Vh}from"./chunk-YA6ATMTB.mjs";import{b as Wh,e as zh,k as Gh,m as Jh}from"./chunk-HFSBDM7B.mjs";import{a as nr}from"./chunk-EADHKH3A.mjs";import{c as Ph,f as na,g as Ch,j as $h,l as xh,r as Dh,s as Nh}from"./chunk-M6K34KGF.mjs";import{$ as Eh,F as wr,G as As,N as Oh,P as Ih,Y as Ah,Z as Th,a as ea,b as rr,c as ta,f as Rh,j as vh,m as ra,n as ul,o as Sh,p as kh,q as Ao,r as yr}from"./chunk-TNT27RBG.mjs";import{a as tr,d as cl,f as bh,h as ze}from"./chunk-TZE3Y7IQ.mjs";import{a as ah,b as I}from"./chunk-CA5NAXSU.mjs";import{a as yb,b as wb}from"./chunk-PC247GKX.mjs";import{f as kw,j as Ow}from"./chunk-S42RBRH2.mjs";import{a as Xh,d as Yh}from"./chunk-WUUKFE2U.mjs";import{a as Kh}from"./chunk-EAC5QCE3.mjs";import{a as xo,d as Yn}from"./chunk-TUACWKIH.mjs";import{$b as xf,$c as Xu,A as ys,Aa as Br,Ad as yn,Ae as $t,Ba as Fi,Bd as Hf,Be as Ji,Ca as Rf,Cd as zr,Ce as Ss,Da as qu,Dd as Bf,De as ks,Ea as Wu,Ed as el,Ee as Vi,Fa as vf,Fd as qf,Fe as tl,Ga as zu,Gd as Wf,Ge as th,Hd as Gi,He as rl,I as hf,Id as zf,Je as rh,Lb as If,Le as nh,Ma as Sf,Mb as Vn,Me as nl,Na as kf,Nb as Ju,Ne as Ki,Ob as Vu,Oe as oh,Pb as Af,Pd as Gf,Pe as sh,Qb as Tf,Qe as ih,Re as Xi,Ub as Ef,Uc as wt,Wc as Kn,Wd as Rs,Xb as Pf,Xc as qi,Y as Li,Yb as Cf,Yd as Gr,Z as Uu,Zb as $f,Zc as Pe,_ as mf,_b as _i,_c as vo,ac as Df,ad as qr,ae as Jf,b as nf,bc as Ui,c as of,cd as Yu,d as uf,dc as Nf,dd as ye,ec as jf,ee as Jr,fc as Mf,fe as ut,ja as Hu,k as bo,kd as Wi,l as Ro,la as yf,lc as Lf,ld as So,mc as Ku,md as ko,me as Vf,nb as Of,ne as Kf,o as mn,ob as Gu,od as Ff,oe as vs,p as ms,pd as _f,q as lf,r as pf,s as gf,se as Xf,td as Qu,te as Yf,ud as Wr,ue as Qf,va as wf,vc as Hi,ve as Zf,wa as Bu,wd as Uf,we as eh,xa as bf,xc as Bi,xd as bs,yd as zi,z as ff,zc as ws,zd as Zu,ze as wn}from"./chunk-PMWAFDUB.mjs";import{a as sf,b as j,e as Te,f as Ke,i as hn,k as ve,l as J,o as af,p as ji,s as Mi,u as We,v as yt,x as df,y as cf,z as Jn}from"./chunk-WZQEK4WT.mjs";var gS="pipeline-rewind-grants",hS="pipeline:rewind-grant:",fS="pipeline:saved:",op=J({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:Jn.datetime(),grantedBy:j().max(80).optional(),takenBackAt:Jn.datetime().optional()}).strict();function Nn(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 sp(s,e){return`${hS}${s}:${e}`}var Vs=class{constructor(e){this.store=e}store;all(){return Object.values(this.store.getByCategory(gS)).flatMap(e=>{let t=op.safeParse(e);return t.success?[t.data]:[]})}get(e,t){let r=op.safeParse(this.store.get(sp(e,t)));return r.success?r.data:void 0}write(e){this.store.set(sp(e.pipelineId,e.stepId),op.parse(e),gS)}revoke(e,t){return this.store.delete(sp(e,t))}revokePipeline(e){let t=`${hS}${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&&Ks(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(`${fS}${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(`${fS}${e}`)?{refusal:"never"}:r.takenBackAt!==void 0||Ks(t.config)!==r.digest?{refusal:"changed"}:{grant:{organizationId:r.organizationId,checkpointId:r.checkpointId,digest:r.digest,grantedAt:r.grantedAt}}}};function Ks(s){let e=$t.safeParse(s??{});return e.success?ks(e.data):void 0}function mS(s,e){return new Vs(s).revokePipeline(e)}function jn(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 ZT="/lightning/setup/AsyncApexJobs/home";function yS(s){let e=jn(s);return e.ok?{ok:!0,url:new URL(ZT,e.url.origin).toString()}:e}import{randomBytes as eE}from"node:crypto";import{createReadStream as tE}from"node:fs";import{open as rE,readdir as nE,rm as oE,stat as sE}from"node:fs/promises";import{homedir as iE}from"node:os";import{join as lr,resolve as aE}from"node:path";import{createInterface as dE}from"node:readline";var ip="journal.ndjson",gd=2e3,SS=/^em-\d{8}-\d{6}-[a-z0-9]{4}$/,wS="abcdefghijklmnopqrstuvwxyz0123456789";function dp(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(eE(4),o=>wS[o%wS.length]).join("");return`em-${t}-${r}-${n}`}function ap(s){return SS.test(s)}function cp(s=process.env){let e=s.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?aE(e):lr(iE(),".sandforge");return lr(t,"empty")}var cE=j().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),nn=j().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Not an API name").max(80),Xs=Jn.datetime({offset:!0}),bS=ve(cE).max(gd),kS=We(["success","partial","failure","cancelled"]),OS=J({v:yt(1),kind:yt("head"),runId:j().regex(SS),organizationId:j().min(15).max(18),orgName:j(),startedAt:Xs,readAt:Xs,previewId:j(),mode:We(["objects","org"]),deleteMode:We(["recycle","hard"]),request:J({mode:We(["objects","org"]),objects:ve(j()).optional(),excluded:ve(j()).optional(),customSettings:Ke().optional(),files:Ke().optional(),managedPackages:Ke().optional(),unrestorable:Ke().optional()}).strict(),passes:ve(J({objectApiName:nn,records:Te().int().nonnegative().optional(),sent:Te().int().nonnegative().optional(),rows:j().max(200).optional()})),toDraftAlong:ve(J({objectApiName:nn,condition:j().optional()})),beforeParent:ve(J({objectApiName:nn,field:j(),parent:nn,reason:We(["restricted","customPrices"])})),undoLost:ve(J({objectApiName:nn,field:j().optional(),parent:nn.optional(),reason:We(["restricted","unordered","notRestorable"]),records:Te().int().nonnegative().optional(),atLeast:yt(!0).optional()})).optional()}),uE=J({kind:yt("attempt"),at:Xs,resumed:Ke()}),IS=J({kind:yt("spooled"),objectApiName:nn,place:Te().int().nonnegative(),count:Te().int().nonnegative(),sinceRead:Ke()}),lE=J({kind:yt("settled"),objectApiName:nn,deleted:bS,gone:bS}),pE=J({objectApiName:nn,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())}),AS=J({kind:yt("end"),at:Xs,status:kS,hardRefused:j().optional(),passes:ve(pE)}),gE=J({kind:yt("undo"),at:Xs,status:kS}),RS=ji("kind",[OS,uE,IS,lE,AS,gE]),Pr=class extends Error{constructor(e){super(e),this.name="EmptyJournalDamaged"}};function fE(s){return s==="success"||s==="partial"}var fd=class s{constructor(e,t){this.dir=e;this.head=t}dir;head;static async begin(e,t){let r=OS.parse({v:1,kind:"head",...t});await Da(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 vS(lr(e,ip))){r.kind==="head"&&(t=r);break}if(t===void 0)throw new Pr("The journal of this emptying names nothing it was to do.");return new s(e,t)}idsDirOf(e,t){return lr(this.dir,"ids",`${e}-${wt(t)}`)}async write(e,t="a"){let r=lr(this.dir,ip),n=await rE(r,t,$a);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(IS.parse({kind:"spooled",...e}))}async settled(e,t,r){for(let n=0;n<Math.max(t.length,r.length);n+=gd)await this.write({kind:"settled",objectApiName:e,deleted:t.slice(n,n+gd),gone:r.slice(n,n+gd)})}ended(e,t,r,n){return this.write(AS.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 vS(lr(this.dir,ip))}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":fE(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*vS(s){let e=tE(s,{encoding:"utf8"}),t=dE({input:e,crlfDelay:1/0}),r,n=0,o=(i,a)=>{try{return RS.parse(JSON.parse(i))}catch{throw new Pr(`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 Pr("The journal of this emptying is not on this machine."):i}finally{t.close(),e.destroy()}if(r)try{yield RS.parse(JSON.parse(r.raw))}catch{return}}var hd=class{constructor(e){this.root=e}root;orgDir(e){return lr(this.root,kb(e))}begin(e,t){return fd.begin(lr(this.orgDir(e),t.runId),{...t,organizationId:e})}async runsOf(e){let t=this.orgDir(e),r;try{r=await nE(t)}catch(n){if(n.code==="ENOENT")return[];throw n}return r.filter(ap).sort().map(n=>({runId:n,dir:lr(t,n)}))}async lastOf(e){return(await this.runsOf(e)).at(-1)}async open(e,t){if(!ap(t))throw new Pr(`Not an emptying's id: ${t}`);let r=lr(this.orgDir(e),t);try{await sE(r)}catch{throw new Pr(`No journal of the emptying ${t} is on this machine.`)}return fd.open(r)}async remove(e,t){ap(t)&&await oE(lr(this.orgDir(e),t),{recursive:!0,force:!0})}};import{createHash as hE}from"node:crypto";import{readFileSync as mE}from"node:fs";import{homedir as yE}from"node:os";import{join as md,resolve as wE}from"node:path";var TS=J({...yb,pipelineId:j().min(1).max(200),pipelineName:j().max(200).optional(),ranFrom:We(["editor","commandLine"]),triggeredBy:We(["manual","schedule","event","webhook","sandbox_refresh","deployment_complete"]),dryRun:Ke().optional()}),up=wb(s=>{let e=TS.safeParse(s);return e.success?e.data:void 0}),bE="run.lock",RE=/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;function ES(s=process.env){let e=s.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?wE(e):md(yE(),".sandforge");return md(t,"pipelines")}function Ys(s){return RE.test(s)&&!s.includes("..")?s:`p-${hE("sha256").update(s).digest("hex").slice(0,32)}`}function yd(s,e){return md(s,Ys(e))}function PS(s,e){return md(yd(s,e),bE)}function vE(s){try{let e=TS.safeParse(JSON.parse(mE(s,"utf8")));return e.success?e.data:void 0}catch{return}}function lp({version:s,token:e,...t}){return t}function CS(s,e,t,r={}){let n=PS(s,e),o=vE(n),i=o!==void 0&&up.holder(n,r)===void 0,a=up.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:lp(a.busy)}:{lock:{pipelineId:e,release:a.lock.release},...i&&o!==void 0?{tookOver:lp(o)}:{}}}function zL(s,e,t={}){let r=up.holder(PS(s,e),t);return r!==void 0?lp(r):void 0}function $S(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 pp(s,e){return`Pipeline "${e}" is already running on this machine: ${$S(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 xS(s){return`The run lock of pipeline "${s.pipelineName??s.pipelineId}" was left by ${$S(s)} started at ${s.acquiredAt} (process ${s.pid} on ${s.host}), whose process has ended: taken over.`}import{randomBytes as SE}from"node:crypto";import{mkdirSync as kE,readFileSync as jS,readdirSync as OE,renameSync as DS,statSync as IE,unlinkSync as AE,writeFileSync as TE}from"node:fs";import{join as fp}from"node:path";var hp=50,mp="history.json",yp=1,NS=4*1024*1024,EE=448,PE=384,CE=J({decision:We(["approved","rejected","timedOut","cancelled"]),via:We(["notification","page","terminal","commandLine"]).optional(),at:j().max(64),by:j().max(64).optional()}),$E=J({stepName:j().max(200),stepType:j().max(80),status:We(["pending","running","completed","failed","skipped","stopped"]),duration:Te().nonnegative().optional(),summary:j().max(8e3).optional(),error:j().max(8e3).optional(),approval:CE.optional()}),gp=J({runId:j().min(1).max(200),pipelineId:j().min(1).max(200),pipelineName:j().max(200),status:We(["idle","queued","running","completed","completed_with_warnings","failed","cancelled"]),triggeredBy:We(["manual","schedule","event","webhook","sandbox_refresh","deployment_complete"]),startTime:Jn.datetime({offset:!0}),duration:Te().nonnegative(),stepCount:Te().int().nonnegative(),errorCount:Te().int().nonnegative(),steps:ve($E).max(200).optional()}),xE=J({sandforgePipelineHistory:yt(yp),entries:ve(hn()).max(hp*4)});function YL(s,e){return fp(yd(s,e),mp)}function DE(s){let e=Date.parse(s.startTime);return{...s,ranFrom:"commandLine",timestamp:Number.isNaN(e)?0:e}}function MS(s){let e;try{e=JSON.parse(s)}catch{return{why:"it is not JSON"}}let t=xE.safeParse(e);if(!t.success){let o=e?.sandforgePipelineHistory;return{why:typeof o=="number"&&o>yp?`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=gp.safeParse(o);i.success?r.push(DE(i.data)):n+=1}return{entries:r,skipped:n}}function LS(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=OE(s,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name)}catch{return[]}let o=[];for(let i of n.sort()){let a=fp(s,i,mp),d,c;try{let l=IE(a);if(d=`${l.size}:${l.mtimeMs}`,l.size>NS){r(a,d,`[WARN] pipeline history ${a} is not listed: at ${l.size} bytes it is past the ${NS} a history of ${hp} runs takes.`);continue}c=jS(a,"utf8")}catch{continue}let u=MS(c);if("why"in u){r(a,d,`[WARN] pipeline history ${a} is not listed: ${u.why}. The runs it held are not shown in History; the next run from the command line starts it again.`);continue}u.skipped>0&&r(a,d,`[WARN] pipeline history ${a}: ${u.skipped} of its runs do not read and are not listed.`),o.push(...u.entries)}return o.sort((i,a)=>a.timestamp-i.timestamp)}}}function QL(s,e,t){let r=gp.safeParse(t);if(!r.success)throw new Error(`The run was not recorded: ${r.error.issues.slice(0,3).map(l=>`${l.path.join(".")||"(entry)"}: ${l.message}`).join("; ")}`);let n=yd(s,e);kE(n,{recursive:!0,mode:EE});let o=fp(n,mp),i=[],a,d;try{d=jS(o,"utf8")}catch{d=void 0}if(d!==void 0){let l=MS(d);"why"in l?(a=`${o}.unreadable-${Date.now()}`,DS(o,a)):i=l.entries.map(({ranFrom:g,timestamp:p,...f})=>gp.parse(f))}let c=[r.data,...i.filter(l=>l.runId!==r.data.runId)].sort((l,g)=>Date.parse(g.startTime)-Date.parse(l.startTime)).slice(0,hp),u=`${o}.${process.pid}-${SE(4).toString("hex")}.tmp`;TE(u,`${JSON.stringify({sandforgePipelineHistory:yp,entries:c},null,2)}
9
+ `,{encoding:"utf8",mode:PE,flag:"wx"});try{DS(u,o)}catch(l){try{AE(u)}catch{}throw l}return{kept:c.length,...a!==void 0?{setAside:a}:{}}}var Ht={major:20,minor:19},FS=5,NE=12,jE=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function gt(s){return s.replace(/\s*[\r\n\u2028\u2029]+\s*/g," ").trim()}function Ut(s){return`'${s.replace(/'/g,"'\\''")}'`}function Xt(s){return`'${s.replace(/['\u2018\u2019\u201a\u201b]/g,e=>e+e)}'`}function Vo(s){return JSON.stringify(s)}function wp(s){return s.endsWith(tl)?s.slice(0,-tl.length):s.replace(/\.json$/,"")}function ME(s){return`SFDX_AUTH_URL_${s.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")}`}function bp(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 _S(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 LE(s){return`npx -y sandforge@${s.sandforgeVersion} pipeline run --file ${s.fileName}`}function Rp(s,e){return[`SandForge pipeline "${gt(s.pipelineName)}", run from its file with VS Code closed.`,`Exported by SandForge ${s.sandforgeVersion} on ${s.exportedAt}.`,"",...e,"",`It runs: ${LE(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 vp(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} "${gt(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} "${gt(n.name)}" rewinds an org with no alias: confirm it with pipeline confirm.`)}return r}function Ko(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 FE({alias:s,...e}){return e}function Sp(s){if(!Ko(s.fileName))throw new Error("A pipeline file name is one line of text.");let e=[],t=s.orgs.flatMap(i=>Ko(i.key)?i.alias===void 0||Ko(i.alias)?[i]:(e.push(`The alias of org "${gt(i.label)}" holds a line break: it is asked below as an alias of this machine.`),[FE(i)]):(e.push(`Org "${gt(i.label)}" is named by a key no line can hold: run it from a terminal.`),[])),r=s.variables.filter(i=>Ko(i.name)?!0:(e.push(`Variable "${gt(i.name)}" holds a line break in its name, which no line gives: rename it.`),!1)),n=s.approvals.filter(i=>Ko(i.name)?!0:(e.push(`Approval step "${gt(i.name)}" holds a line break in its name: only a terminal answers it.`),!1)),o=s.rewinds.map(i=>i.alias===void 0||Ko(i.alias)?i:{name:i.name});return{input:{...s,orgs:t,variables:r,approvals:n,rewinds:o},leftOut:e}}function US(s){return s.orgs.filter(e=>e.alias===void 0).map((e,t)=>({...e,slot:`org_alias_${t+1}`}))}function _E(s){let{input:e,leftOut:t}=Sp(s),n=`${wp(e.fileName)}.sh`,o=Ys(e.pipelineId),i=e.schedule===null?void 0:bp(Ki(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.`]:[],..._S(i)]:["Its schedule cannot be written as a line of this machine's crontab:",gt(i.reason)],d=[`Keep it beside ${e.fileName}. It needs Node.js ${Ht.major}.${Ht.minor} or later`,"and the Salesforce CLI (sf), signed in to each org of the pipeline under its alias.","Each run is appended to runs.log, in the pipeline's folder below.","",...a,...t.length>0?["",...t]:[]],c=US(e),u=["#!/usr/bin/env bash",...Rp(e,d).map(l=>l===""?"#":`# ${l}`),"set -u","",'here="$(cd "$(dirname "$0")" && pwd)"',`file="$here/"${Ut(e.fileName)}`,`store="\${SANDFORGE_JOURNAL_DIR:-$HOME/.sandforge}/pipelines/"${Ut(o)}`,'mkdir -p "$store" && chmod 700 "$store"','log="$store/runs.log"',"","# cron starts a script with little more than /usr/bin and /bin on its PATH:","# the usual places of node and sf are added, then the default Node.js of nvm.",'PATH="$PATH:/usr/local/bin:$HOME/.local/bin"',"node_ok() {"," command -v node >/dev/null 2>&1 &&",` node -e 'const [a, b] = process.versions.node.split(".").map(Number); process.exit(a > ${Ht.major} || (a === ${Ht.major} && b >= ${Ht.minor}) ? 0 : 1)'`,"}","if ! node_ok || ! command -v sf >/dev/null 2>&1; then",' nvm_sh="${NVM_DIR:-$HOME/.nvm}/nvm.sh"',' if [ -s "$nvm_sh" ]; then',' . "$nvm_sh" >/dev/null 2>&1'," nvm use --silent default >/dev/null 2>&1 || true"," fi","fi",`say() { printf '%s %s\\n' "$(date -u +%Y-%m-%dT%H:%M:%SZ)" "$1" | tee -a "$log" >&2; }`,"if ! node_ok; then",` say "Node.js ${Ht.major}.${Ht.minor} or later is not found on this PATH ($PATH), nor through nvm: nothing ran. Install it, or add its folder to PATH at the top of this script."`," exit 127","fi","if ! command -v sf >/dev/null 2>&1; then",' say "The Salesforce CLI (sf) is not found on this PATH ($PATH): nothing ran. Install it (npm install -g @salesforce/cli), or add its folder to PATH at the top of this script."'," exit 127","fi",""];if(c.length>0||e.variables.length>0){u.push("# What the pipeline file does not hold, read from here or from the environment.",'# cron gives a script no environment of yours: set values in "$store/env",',"# one `export NAME='value'` a line, in a file only you can read (chmod 600).",'if [ -f "$store/env" ]; then . "$store/env"; fi');for(let l of c)u.push(`# The alias, on this machine, of org "${gt(l.label)}", which has none of its own`,"# (sf alias set <alias>=<its username>).",`${l.slot}="\${${l.slot.toUpperCase()}:-}"`);u.push("missing=()");for(let l of c)u.push(`[ -n "$${l.slot}" ] || missing+=(${Ut(`${l.slot} (the alias of org "${gt(l.label)}")`)})`);for(let l of e.variables)u.push(`[ -n "\${${l.env}:-}" ] || missing+=(${Ut(`${l.env} (variable "${gt(l.name)}"${l.secret?", a secret":""})`)})`);u.push('if [ "${#missing[@]}" -gt 0 ]; then',' say "Not set, so nothing ran: ${missing[*]}. Set each in this script or in $store/env."'," exit 2","fi","")}return u.push('args=(pipeline run --file "$file" --triggered-by schedule --fail-on-partial)',...c.map(l=>`args+=(--org ${Ut(`${l.key}=`)}"$${l.slot}")`),...e.variables.map(l=>`args+=(--var-env ${Ut(`${l.name}=${l.env}`)})`),...vp(e,"#",(l,g)=>`args+=(${l} ${Ut(g)})`),"",'say "start"',`npx -y ${Ut(`sandforge@${e.sandforgeVersion}`)} "\${args[@]}" >>"$log" 2>&1`,"code=$?",'say "exit $code"','exit "$code"',""),{runner:"cron",fileName:n,text:u.join(`
10
+ `),...i!==void 0?{schedule:i.kind==="line"?{...i,text:`${i.text} /bin/bash /path/to/${n}`}:i}:{}}}function UE(s){let e=nl(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>NE)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=>jE[n]).join(",");return t.map(n=>r===void 0?`New-ScheduledTaskTrigger -Daily -At ${Xt(n)}`:`New-ScheduledTaskTrigger -Weekly -DaysOfWeek ${r} -At ${Xt(n)}`)}function HE(s){let{input:e,leftOut:t}=Sp(s),r=wp(e.fileName),n=`${r}.ps1`,o=Ys(e.pipelineId),i;if(e.schedule!==null){let l=bp(Ki(e.schedule.cron,e.schedule.timezone,e.machineTimezone,e.now));if(l.kind!=="line")i=l;else{let g=UE(l.text);i=typeof g=="string"?{kind:"manual",reason:g}:{...l,text:[`# In PowerShell, from the folder that holds ${n}, once:`,`$action = New-ScheduledTaskAction -Execute 'pwsh' -Argument ('-NoProfile -File "{0}"' -f (Join-Path $PWD ${Xt(n)}))`,"$triggers = @(",...g.map(p=>` ${p}`),")",`Register-ScheduledTask -TaskName ${Xt(`SandForge ${r}`)} -Action $action -Trigger $triggers`].join(`
11
+ `)}}}let a=i===void 0?["This pipeline has no schedule: run this script by hand, or from a scheduler of your own."]:i.kind==="line"?[`Its schedule, as Task Scheduler reads it, in ${i.timezone}:`,...i.text.split(`
12
+ `).map(l=>` ${l}`),..._S(i)]:i.kind==="manual"?[`Its schedule, ${e.schedule?.cron} in ${e.schedule?.timezone}, as Task Scheduler reads it:`,gt(i.reason)]:["Its schedule cannot be written for this machine's clock:",gt(i.reason)],d=[`Keep it beside ${e.fileName}. It needs PowerShell 7 (pwsh), Node.js`,`${Ht.major}.${Ht.minor} or later and the Salesforce CLI (sf), signed in to each org of the`,"pipeline under its alias. Each run is appended to runs.log, in the pipeline's folder below.","",...a,...t.length>0?["",...t]:[]],c=US(e),u=[...Rp(e,d).map(l=>l===""?"#":`# ${l}`),"$ErrorActionPreference = 'Continue'","","$here = Split-Path -Parent $MyInvocation.MyCommand.Path",`$file = Join-Path $here ${Xt(e.fileName)}`,"$journal = if ($env:SANDFORGE_JOURNAL_DIR) { $env:SANDFORGE_JOURNAL_DIR } else { Join-Path $HOME '.sandforge' }",`$store = Join-Path (Join-Path $journal 'pipelines') ${Xt(o)}`,"New-Item -ItemType Directory -Force -Path $store | Out-Null","$log = Join-Path $store 'runs.log'","function Say([string] $line) {"," $stamped = '{0} {1}' -f ([DateTime]::UtcNow.ToString('yyyy-MM-ddTHH:mm:ssZ')), $line"," Add-Content -Path $log -Value $stamped"," [Console]::Error.WriteLine($stamped)","}","","if ($PSVersionTable.PSVersion.Major -lt 7) {",' Say ("PowerShell 7 (pwsh) runs this script, not PowerShell {0}: nothing ran. Start it with pwsh." -f $PSVersionTable.PSVersion)'," exit 127","}","$node = Get-Command node -ErrorAction SilentlyContinue","$nodeOk = $false","if ($node -and ((& node --version) -match '^v(\\d+)\\.(\\d+)')) {"," $major = [int] $Matches[1]",` $nodeOk = ($major -gt ${Ht.major}) -or ($major -eq ${Ht.major} -and [int] $Matches[2] -ge ${Ht.minor})`,"}","if (-not $nodeOk) {",` Say "Node.js ${Ht.major}.${Ht.minor} or later is not found on this PATH: nothing ran. Install it, or add its folder to PATH."`," exit 127","}","if (-not (Get-Command sf -ErrorAction SilentlyContinue)) {",' Say "The Salesforce CLI (sf) is not found on this PATH: nothing ran. Install it (npm install -g @salesforce/cli), or add its folder to PATH."'," exit 127","}",""];if(c.length>0||e.variables.length>0){u.push("# What the pipeline file does not hold, set here or in the environment.");for(let l of c)u.push(`# The alias, on this machine, of org "${gt(l.label)}", which has none of its own.`,`$${l.slot} = $env:${l.slot.toUpperCase()}`);u.push("$missing = @()");for(let l of c)u.push(`if (-not $${l.slot}) { $missing += ${Xt(`${l.slot} (the alias of org "${gt(l.label)}")`)} }`);for(let l of e.variables)u.push(`if (-not $env:${l.env}) { $missing += ${Xt(`${l.env} (variable "${gt(l.name)}"${l.secret?", a secret":""})`)} }`);u.push("if ($missing.Count -gt 0) {"," Say ('Not set, so nothing ran: {0}. Set each in this script or in the environment.' -f ($missing -join ', '))"," exit 2","}","")}return u.push("$runArgs = @('pipeline', 'run', '--file', $file, '--triggered-by', 'schedule', '--fail-on-partial')",...c.map(l=>`$runArgs += @('--org', (${Xt(`${l.key}={0}`)} -f $${l.slot}))`),...e.variables.map(l=>`$runArgs += @('--var-env', ${Xt(`${l.name}=${l.env}`)})`),...vp(e,"#",(l,g)=>`$runArgs += @('${l}', ${Xt(g)})`),"","Say 'start'",`& npx -y ${Xt(`sandforge@${e.sandforgeVersion}`)} @runArgs *>> $log`,"$code = $LASTEXITCODE",'Say "exit $code"',"exit $code",""),{runner:"taskScheduler",fileName:n,text:u.join(`
13
+ `),...i!==void 0?{schedule:i}:{}}}function BE(s){let e=nl(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]<FS)return!0;return!1}function qE(s){let{input:e,leftOut:t}=Sp(s),n=`${wp(e.fileName)}.yml`,o=Ys(e.pipelineId),i=e.schedule===null?void 0:bp(Ki(e.schedule.cron,e.schedule.timezone,e.schedule.timezone,e.now)),a=e.orgs.map((l,g)=>{let p=l.alias??`pipeline-org-${g+1}`;return{...l,ciAlias:p,secret:ME(p)}}),d=l=>l===""?"#":`# ${l}`,c=[...Rp(e,[`Save it as .github/workflows/${n} of a private repository, and commit`,`${e.fileName} at the repository's root. Each org signs in from a repository secret:`,...a.map(l=>` ${l.secret}: the sfdx auth URL of "${gt(l.label)}" (sf org auth show-sfdx-auth-url --target-org ${l.alias??"<its username>"} --json, its result.sfdxAuthUrl)`),...e.variables.map(l=>` ${l.env}: variable "${gt(l.name)}"${l.secret?" (a secret)":""}`),"","GitHub starts a schedule late when its runners are busy, the start of each hour most of","all, and may drop it under heavy load; it disables the schedules of a public repository",'after 60 days without activity (docs.github.com, "Events that trigger workflows").',...i?.kind==="refused"?["","The pipeline's schedule cannot be written for GitHub:",gt(i.reason)]:[],...i?.kind==="line"&&BE(i.text)?["",`GitHub starts a schedule every ${FS} minutes at most, whatever its line says.`]:[],...t.length>0?["",...t]:[]]).map(d),`name: ${Vo(`SandForge pipeline: ${gt(e.pipelineName)}`)}`,"","on:"];i?.kind==="line"&&c.push(" schedule:",` - cron: ${Vo(i.text)}`,` timezone: ${Vo(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: ${Vo(`sandforge-pipeline-${o}`)}`," cancel-in-progress: false","","permissions:"," contents: read","","jobs:"," run:"," runs-on: ubuntu-latest"," steps:"," - uses: actions/checkout@v4"," - uses: actions/setup-node@v4"," with:"," node-version: 22"," - name: Install the Salesforce CLI"," run: npm install -g @salesforce/cli"),a.length>0&&c.push(" - name: Sign in to the pipeline's orgs"," env:",...a.map(l=>` ${l.secret}: \${{ secrets.${l.secret} }}`)," # The URLs go to a private folder removed when this shell exits, a failed sign-in too."," run: |"," umask 077"," auth_dir=$(mktemp -d)",` trap 'rm -rf "$auth_dir"' EXIT`,...a.flatMap((l,g)=>[` printf '%s' "$${l.secret}" > "$auth_dir/org-${g+1}.txt"`,` sf org login sfdx-url --sfdx-url-file "$auth_dir/org-${g+1}.txt" --alias ${Ut(l.ciAlias)}`])),c.push(" # The Sync watermarks, the confirmations and the history of earlier runs."," - uses: actions/cache@v4"," with:"," path: .sandforge",` key: ${Vo(`sandforge-pipeline-${o}-\${{ github.run_id }}`)}`,` restore-keys: ${Vo(`sandforge-pipeline-${o}-`)}`),e.rewinds.length>0&&c.push(" # A Rewind step rewinds to a checkpoint kept on the machine of the run: import it"," # here first (sandforge checkpoint import), from a file you keep apart, with its key."," # - name: Import the checkpoint a Rewind step names",` # run: npx -y sandforge@${e.sandforgeVersion} checkpoint import --file <checkpoint file>`);let u=[`args=(pipeline run --file ${Ut(e.fileName)} --triggered-by "$TRIGGERED_BY" --fail-on-partial)`,...a.filter(l=>l.alias===void 0).map(l=>`args+=(--org ${Ut(`${l.key}=${l.ciAlias}`)})`),...e.variables.map(l=>`args+=(--var-env ${Ut(`${l.name}=${l.env}`)})`),...vp(e,"#",(l,g)=>`args+=(${l} ${Ut(g)})`),`npx -y ${Ut(`sandforge@${e.sandforgeVersion}`)} "\${args[@]}"`];return c.push(" - name: Run the pipeline"," env:"," SANDFORGE_JOURNAL_DIR: ${{ github.workspace }}/.sandforge"," TRIGGERED_BY: ${{ github.event_name == 'schedule' && 'schedule' || 'manual' }}",...e.variables.map(l=>` ${l.env}: \${{ secrets.${l.env} }}`)," run: |",...u.map(l=>` ${l}`),""),{runner:"githubActions",fileName:n,text:c.join(`
14
+ `),...i!==void 0?{schedule:i}:{}}}function HS(s){return{cron:_E(s),taskScheduler:HE(s),githubActions:qE(s)}}var WE={"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},zE=new Set(["seed","anonymize","rewind","restore","delete"]),GE={sandbox_refresh:"sandbox refresh",event:"event",webhook:"webhook",deployment_complete:"deployment"},JE="prebuilt-",VE="tpl-";function Zs(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)?s:void 0}function Cr(s){return typeof s=="string"&&s.trim()!==""?s:void 0}function bd(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function ei(s,e){return bd(s,e)?s[e]:void 0}function Qs(s){return JSON.parse(JSON.stringify(s))}function KE(s){switch(qi(s.orgType??"",s.metadata?.edition)){case"Sandbox":return"sandbox";case"Scratch":return"scratch";case"Developer":return"developer";default:return"production"}}function XE(s){let e=KE(s),t=Yu(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&&Yu(r,s.username)?{name:r}:{}}}function kp(s,e){return e.alias??e.name??s}function wd(s,e,t,r){return{exported:!1,pipelineId:s,code:e,message:t,...r?{issues:r}:{}}}function YE(s,e){let t=[];return s.forEach((r,n)=>{let o=Zs(r.config)??{};if(r.type==="sync"){let a=e.get(Cr(o.configId)??""),d=Cr(a?.sourceOrgId),c=Cr(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=bd(rl,r.type)?rl[r.type]??[]:[];for(let a of i){let d=Cr(o[a]);d!==void 0&&t.push({orgId:d,stepIndex:n,stepName:r.name,writes:zE.has(r.type)})}}),t}function QE({defaultValue:s,...e}){return e}function ZE(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 eP(s,e){let t=(s.triggers??[]).filter(n=>n.type==="schedule"&&(n.enabled||s.runsOutside!==void 0)&&Cr(n.config?.cron)!==void 0);if(t.length>1)return{many:t.length};let[r]=t;return r?{cron:(r.config.cron??"").trim(),timezone:Cr(r.config.timezone)?.trim()??e}:null}function tP(s){let e={};for(let t of Object.keys(th)){let r=WE[t],n=s.setting(t,r);n===r||n===void 0||n===null||(e[t]=n)}return e}function ti(s,e,t={}){return{code:s,text:e,...t}}function BS(s){let{pipeline:e}=s,t=e.id,r=Qs(e.steps??[]).map(p=>({...p,config:Zs(p.config)??{}})),n=eP(e,s.machineTimezone);if(n!==null&&"many"in n)return wd(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 f=p.config;if(p.type==="sync"){let m=Cr(f.configId);if(m===void 0||bd(o,m))continue;let y=Zs(s.syncConfig(m));if(!y)return wd(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]={...Qs(y),id:m}}let h=Cr(f.templateId);if(p.type==="seed"&&h&&!h.startsWith(JE)){let m=Zs(s.seedTemplate(h));m&&(i[h]={...Qs(m),id:h})}if(p.type==="anonymize"&&h&&!h.startsWith(VE)){let m=Zs(s.maskingTemplate(h));m&&(a[h]={...Qs(m),id:h})}}let d=YE(r,new Map(Object.entries(o))),c={},u=new Map;for(let p of d){if(bd(c,p.orgId))continue;let f=s.org(p.orgId);if(!f)return wd(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]=XE(f),u.set(p.orgId,f.authMethod!=="usernamePassword")}let l=ZE(e.variables??[]),g=Qs(e.variables??[]).map(p=>p.type==="secret"?QE(p):p);return{pipelineId:t,fileName:nh(e.name),schedule:n,orgs:c,cliHolds:u,uses:d,syncConfigs:o,seedTemplates:i,maskingTemplates:a,settings:tP(s),steps:r,variables:g,envs:l}}function qS(s,e,t){return s.checkedWhereItRuns!==!0&&e.type==="rewind"&&t!==void 0&&(t===Nn(e.name,"never")||t===Nn(e.name,"changed"))}function rP(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=(f,h)=>{a.push(f),t.push(ti(f,h,{step:o.name}))},c=s.stepRefusal?.(o,i),u=qS(s,o,c)?void 0:c,l=n(i).find(f=>ei(e.orgs,f)?.kind==="production"),g="runs",p;if(u!==void 0)g="refused",p=u,d("STEP_REFUSED",u);else if(l!==void 0){g="refused";let f=ei(e.orgs,l);p=`Step "${o.name}" writes to "${f?kp(l,f):l}", 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")g="asks",e.uses.some(h=>h.stepIndex>i&&h.writes&&ei(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"){g="asks";let f=Cr(o.config.orgId),h=f!==void 0?ei(e.orgs,f):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:g,notes:a,...p!==void 0?{refusal:p}:{}})}),{steps:r,notes:t}}function nP(s,e){let t=[];for(let[r,n]of Object.entries(e.orgs))if(n.alias===void 0&&t.push(ti("ORG_NO_ALIAS",`Org "${kp(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(ti("ORG_NOT_SIGNED_IN",`The Salesforce CLI of this machine does not hold org "${kp(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(ti("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=GE[r.type];!r.enabled||n===void 0||t.push(ti("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 oP(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 sP(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 WS(s,e,t){let{pipeline:r}=s;return rh({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 zS(s){let e=s.pipeline.id,t=BS(s);if("exported"in t)return t;let{steps:r,notes:n}=rP(s,t),o=[...n,...nP(s,t)],i=WS(s,t,o);if(!i.ok)return wd(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=oP(t),d=sP(t),c=a.map(g=>({key:g.key,...g.alias!==void 0?{alias:g.alias}:{},label:g.alias??g.name??g.key})),u=d.flatMap(g=>g.env!==void 0?[{name:g.name,env:g.env,secret:g.type==="secret"}]:[]),l={fileName:t.fileName,text:i.text,digest:i.file.digest,schedule:t.schedule,steps:r,orgs:a,variables:d,launchers:HS({pipelineId:e,pipelineName:s.pipeline.name,fileName:t.fileName,sandforgeVersion:s.sandforgeVersion,exportedAt:s.exportedAt,schedule:t.schedule,machineTimezone:s.machineTimezone,now:s.now,orgs:c,variables:u,approvals:r.filter(g=>g.type==="approval"&&g.fate==="asks").map(g=>({name:g.name,staging:g.notes.includes("STAGING_NEEDS_PERSON")})),rewinds:t.steps.filter(g=>g.type==="rewind").map(g=>{let p=Cr(g.config.orgId),f=p!==void 0?ei(t.orgs,p)?.alias:void 0;return{name:g.name,...f!==void 0?{alias:f}:{}}})}),notes:o,problems:(s.problems??[]).filter(g=>!t.steps.some(p=>qS(s,p,g)))};return{exported:!0,pipelineId:e,...l}}function GS(s){let e=BS(s);if("exported"in e)return;let t=WS(s,e,[]);return t.ok?t.file.digest:void 0}import{randomUUID as bL}from"node:crypto";import{join as RL}from"node:path";import{randomBytes as iP,randomUUID as Xo}from"node:crypto";import{lstat as aP,rename as dP,rm as cP,stat as uP}from"node:fs/promises";import{hostname as lP}from"node:os";import{basename as ni,dirname as XS,join as pP,sep as gP}from"node:path";var fP=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"]),$r="checkpoint",hP=8,mP=6e4,pr="CANCELLED",yP={success:"success",partial:"partial",unstable:"partial",failure:"failure",cancelled:"cancelled"},wP={preview:"previewed",rewind:"rewound to",undo:"used",export:"exported"};function Op(s){let{result:e,notes:t,deliverability:r}=s;return{done:!0,result:e,notes:t,...r!==void 0?{deliverability:r}:{}}}var bP=/\s*\b(?:No record was (?:read or )?written|Nothing was written)\./g;function Ip(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:YS([n,...o])},alsoRefused:o}:{done:!1,refusal:n,alsoRefused:o}}function YS(s){let e=!1;return s.map(({message:t})=>{let r=t.replace(bP,"").trim();return e?r:(e=r!==t.trim(),t)}).join(" ")}var RP=new Set(["RUN_WRITING","API_BUDGET","EMAILS"]),xr=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 JS(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 vP(){let[s,e,t,r,n,o,i,a,d,c,u,l,g]=await Promise.all([import("./chunk-4CVUUVGJ.mjs"),import("./chunk-BEA27DLS.mjs"),import("./chunk-JCFBFF4Y.mjs"),import("./chunk-PPLVFX6N.mjs"),import("./chunk-HSBXRQTI.mjs"),import("./chunk-WWTCWWZI.mjs"),import("./chunk-ZQWIVYVM.mjs"),import("./chunk-DUN2EPRC.mjs"),import("./chunk-JTJK2D36.mjs"),import("./chunk-N4WPCWJO.mjs"),import("./chunk-OVNMB6Q2.mjs"),import("./chunk-OPMO6I45.mjs"),import("./chunk-M4BLK6HJ.mjs")]);return{pageEmailsRefusal:u.pageEmailsRefusal,planSelection:a.planSelection,snapshotRowsOf:a.snapshotRowsOf,rewindWriters:a.rewindWriters,boundsRefusals:d.boundsRefusals,selectionDiff:d.selectionDiff,rewindStepsOf:d.rewindStepsOf,notConfirmedRefusal:d.notConfirmedRefusal,undeletableUnattendedRefusal:d.undeletableUnattendedRefusal,REWIND_STEP_WORDS:d.REWIND_STEP_WORDS,REWIND_MUTING_STEP_WORDS:d.REWIND_MUTING_STEP_WORDS,guardCheckpoint:o.guardCheckpoint,newArchiveKey:i.newArchiveKey,archiveKeyText:i.archiveKeyText,parseArchiveKey:i.parseArchiveKey,ARCHIVE_EXTENSION:i.ARCHIVE_EXTENSION,exportCheckpointArchive:i.exportCheckpointArchive,CheckpointExportError:i.CheckpointExportError,readArchiveHeader:i.readArchiveHeader,importCheckpointArchive:i.importCheckpointArchive,DEFAULT_KEEP_DAYS:s.DEFAULT_KEEP_DAYS,openCheckpointStore:s.openCheckpointStore,defaultCheckpointStoreRoot:s.defaultCheckpointStoreRoot,scratchOrgExpired:s.scratchOrgExpired,previewDirOf:s.previewDirOf,CheckpointStoreError:s.CheckpointStoreError,takeCheckpoint:e.takeCheckpoint,scopeCheckpoint:e.scopeCheckpoint,takeOrgOf:e.takeOrgOf,CheckpointTakeStopped:e.CheckpointTakeStopped,previewCheckpoint:t.previewCheckpoint,rewindOrg:r.rewindOrg,rewindOrgOf:r.rewindOrgOf,RewindStopped:r.RewindStopped,undoCheckpoint:n.undoCheckpoint,UndoStopped:n.UndoStopped,beforeRunScopeOf:c.beforeRunScopeOf,beforeRunAskedOf:c.beforeRunAskedOf,beforeRunKeepDaysOf:c.beforeRunKeepDaysOf,beforeRunDiskRefusal:c.beforeRunDiskRefusal,beforeRunOutcomeOf:c.beforeRunOutcomeOf,freeBytesOf:c.freeBytesOf,scopeBeforeRun:c.scopeBeforeRun,settleBeforeRun:c.settleBeforeRun,ReplayStore:l.ReplayStore,defaultReplayStoreRoot:l.defaultReplayStoreRoot,loadToRemove:g.loadToRemove,loadRecordsInfo:g.loadRecordsInfo}}var Oe=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 Rd(s){return s instanceof Rt?s:s instanceof Oe?s.code===pr?new Rt(s.message):new xr(s.code,s.alsoRefused.length>0?YS([s,...s.alsoRefused]):s.message,s.result,s.alsoRefused):s}async function VS(s){try{return(await uP(s)).isDirectory()}catch{return!1}}function Nt(s,e){return s!==void 0&&e!==void 0&&s.length>=15&&s.slice(0,15)===e.slice(0,15)}var KS=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function ri(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 Oe("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 ye(s)}function SP(s,e){let t=[...e].sort((n,o)=>o.length-n.length),r=s;for(let n of t)r=r.replaceAll(n,ni(n));for(let n of t){let o=XS(n);o===n||o.length<=1||(r=r.replaceAll(`${o}${gP}`,"").replaceAll(o,ni(o)))}return r}function kP(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 OP(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 Ap(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 vd=class{constructor(e,t={},r=xo){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(!fP.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"checkpoint:list":return await this.handleList(e),!0;case"checkpoint:scope":return await this.handleScope(e),!0;case"checkpoint:take":return await this.handleTake(e),!0;case"checkpoint:preview":return await this.handlePreview(e),!0;case"checkpoint:plan-selection":return await this.handlePlanSelection(e),!0;case"checkpoint:rewind":return await this.handleRewind(e),!0;case"checkpoint:undo":return await this.handleUndo(e),!0;case"checkpoint:delete":return await this.handleDelete(e),!0;case"checkpoint:keep":return await this.handleKeep(e),!0;case"checkpoint:rename":return await this.handleRename(e),!0;case"checkpoint:ignore-fields":return await this.handleIgnoreFields(e),!0;case"checkpoint:rewinds":return await this.handleRewinds(e),!0;case"checkpoint:export":return await this.handleExport(e),!0;case"checkpoint:import-read":return await this.handleImportRead(e),!0;case"checkpoint:import":return await this.handleImport(e),!0;default:return!1}}async sweep(){try{let t=await(await this.openedStore()).sweep();for(let r of t.checkpoints)this.deps.log(`[INFO] Removed checkpoint '${r.name}' of ${r.alias??r.organizationId}, taken ${r.takenAt}: kept until ${r.expiresAt}`+(r.undoUntil!==void 0?`; the undo of its last rewind, open until ${r.undoUntil}, went with it`:""));for(let r of t.journals)this.deps.log(`[INFO] Removed the journal of rewind ${r.rewindId} of checkpoint '${r.name}': it could be undone until ${r.undoUntil}`);for(let r of t.skipped)this.deps.log(`[INFO] Checkpoints of ${r} not swept: a take, a rewind or an undo runs`);t.checkpoints.length>0&&this.checkpointsChanged()}catch(e){this.deps.log(`[WARN] Expired checkpoints were not removed: ${I(e)}`)}}async keptBefore(e){let t=e.previousOrganizationId??this.deps.sandboxRefreshes?.organizationIdOf(e.orgId);return t===void 0||!KS.test(t)?0:(await(await this.openedStore()).list({organizationId:t})).length}async latestUsableOf(e){let t=this.deps.orgManager.getOrg(e);if(!t||!vo(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:${Xo()}`,o=this.registeredOrg(e.orgId),i=await this.modules(),a=await this.openedStore(),d=this.beforeRunRequestOf(i,e),c=i.beforeRunScopeOf(d),u=(f,h={})=>{let{taken:m}=h;Z(this.deps,{action:"checkpoint_take",module:$r,operationId:n,orgId:o.id,outcome:f,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 f=i.beforeRunDiskRefusal(r.planned.estimate.bytes,await(this.freeBytes??i.freeBytesOf)(a.root));if(f!==void 0)return u("stopped",{code:f.code}),{taken:!1,refusal:f}}let l=await this.connect(o);if(r.signal?.aborted)return u("cancelled"),{taken:!1,stopped:!0};let g;try{g=await this.take(n,i,a,l,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(f){if(f instanceof Oe&&f.code===pr)return u("cancelled"),{taken:!1,stopped:!0};if(f instanceof Oe&&f.refusal!==void 0)return u("stopped",{code:f.refusal.code}),{taken:!1,refusal:f.refusal};throw u("failure"),f}let p=await i.beforeRunOutcomeOf(a,c,g);return p.taken?u("success",{taken:p.checkpoint}):(this.checkpointsChanged(),u("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",ff.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:${Xo()}`;try{let n=wn.safeParse(e.config);if(!n.success)throw new Oe("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 Oe(pr,new a.CheckpointTakeStopped().message);let{checkpoint:u}=await this.take(r,a,d,c,i,{...o.name!==void 0?{nameWithDate:o.name}:{},mode:o.mode,...o.objects!==void 0?{objects:o.objects}:{},...o.excluded!==void 0?{excluded:o.excluded}:{},...o.maxTotal!==void 0?{maxTotal:o.maxTotal}:{},keepDays:o.keepDays,...o.ignoredFields!==void 0?{ignoredFields:o.ignoredFields}:{}},{description:`Pipeline '${e.origin.pipeline}': taking a checkpoint of ${ft(i)}`,...t?{signal:t}:{}});return{operationId:r,checkpointId:u.checkpointId,name:u.name,records:u.objects.reduce((l,g)=>l+g.records,0),objects:u.objects.length,bytes:u.bytes,movedWhileTaken:u.movedWhileTaken}}catch(n){throw Rd(n)}}async rewindForPipeline(e,t){let r=`checkpoint:pipeline:${Xo()}`,{grant:n,origin:o}=e;try{let i=await this.modules(),a=$t.safeParse(e.config);if(!a.success)throw new Oe("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!==ks(d)||n.checkpointId!==d.checkpointId)throw this.refusalOf(i.notConfirmedRefusal(o.step,!0));let c=await this.openedStore(),{folder:u,checkpoint:l}=await this.checkpointOf(c,d.checkpointId);if(!Nt(n.organizationId,l.org.organizationId))throw this.refusalOf(i.notConfirmedRefusal(o.step,!0));this.usable(i,l,"rewind");let g=this.registeredOrg(d.orgId);if(!Nt(g.orgId,l.org.organizationId)&&!Nt(this.deps.sandboxRefreshes?.organizationIdOf(g.id),l.org.organizationId))throw new Oe("OTHER_ORG",`The checkpoint '${l.name}' is not of ${ft(g)}, the org the Rewind step "${o.step}" names. No record was read or written.`);let p=ri(l,d.objects),f=await this.connect(g),h=ft(g),m={operationId:r,pipeline:{origin:o,grantedAt:n.grantedAt}},y=()=>(this.audit(m,"rewind",g,l,"stopped",{code:bt}),new Rt(new i.RewindStopped().message)),R=(x,V=[])=>(this.audit(m,"rewind",g,l,"stopped",{code:x.code}),this.refusalOf(x,V));if(t?.aborted)throw y();let S;try{S=await i.previewCheckpoint({org:i.takeOrgOf(f),store:c,readAutomation:x=>this.readAutomation(g.id,x),runWriting:this.runWriting(g.id,h,"rewind","No record would be read or written."),...t?{signal:t}:{}},{checkpoint:l,folder:u,orgName:h,registered:g,username:g.username,...p!==void 0?{objects:p}:{},reusesPreview:!0,...d.muteAutomation?{muteAutomation:!0}:{},acceptOutside:d.acceptOutside})}catch(x){throw t?.aborted?y():x}if(!S.previewed)throw R(S.refusal);let b=p!==void 0?i.selectionDiff(S.diff,await i.planSelection({checkpoint:l,previewDir:i.previewDirOf(u,S.diff.previewId),readAt:S.diff.readAt,objects:new Set(p),acceptOutside:d.acceptOutside,heldRows:i.snapshotRowsOf(l,u),...t?{signal:t}:{}})):S.diff,O=d.muteAutomation&&S.automation?El(S.automation,Gr(i.rewindStepsOf(b))).automation:S.automation,P=await i.boundsRefusals({orgName:h,preview:{diff:b,...O?{automation:O}:{},...S.emails?{emails:S.emails}:{},...S.emailsUncounted!==void 0?{emailsUncounted:S.emailsUncounted}:{},...S.deliverability?{deliverability:S.deliverability}:{}},bounds:{maxRecords:d.maxRecords,refuseWhenActive:d.refuseWhenActive},accepted:d,writers:async()=>i.rewindWriters(l.takenBy,await i.takeOrgOf(f).userId()),words:d.muteAutomation?i.REWIND_MUTING_STEP_WORDS:i.REWIND_STEP_WORDS,user:g.username}),[v,...w]=[...S.refusal!==void 0?[S.refusal]:[],...P.filter(x=>x.code!==S.refusal?.code)];if(v!==void 0)throw R(v,w);if(t?.aborted)throw y();let C=[],k=[],E=await this.writeAct(m,"rewind",g,l,`Pipeline '${o.pipeline}': rewinding ${h} to '${l.name}'`,async(x,V)=>{let H=await i.rewindOrg({org:i.rewindOrgOf(f),undelete:Y=>f.soap.undelete(Y),store:c,readAutomation:Y=>this.readAutomation(g.id,Y),runWriting:this.runWriting(g.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(B=>`${B.objectApiName} (${B.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:B})=>V(Y,B),signal:x,...d.muteAutomation?{mute:this.muteOf(f)}:{}},{checkpoint:l,folder:u,orgName:h,registered:g,username:g.username,previewId:S.diff.previewId,reusesPreview:S.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?(k=H.notes,Op(H)):Ip(H.refusal,H.alsoRefused,Y=>Y,!1)},x=>x instanceof i.RewindStopped,{...t?{signal:t}:{},acceptEmails:d.acceptEmails,refusalOf:x=>C.length>0?i.undeletableUnattendedRefusal(h,C,JS(x)):void 0});return{operationId:r,checkpointId:l.checkpointId,result:E,notes:k,estimate:S.estimate}}catch(i){throw Rd(i)}}async estimateTakeForPipeline(e,t){try{let r=wn.safeParse(e.config);if(!r.success)throw new Oe("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 Oe(pr,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((u,l)=>u+l.records,0),leftOut:c.leftOut.length,estimate:c.estimate}}catch(r){throw Rd(r)}}async previewRewindForPipeline(e,t){let{grant:r,origin:n}=e;try{let o=await this.modules(),i=$t.safeParse(e.config);if(!i.success)throw new Oe("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!==ks(a)||r.checkpointId!==a.checkpointId)throw this.refusalOf(o.notConfirmedRefusal(n.step,!0));let d=await this.openedStore(),{folder:c,checkpoint:u}=await this.checkpointOf(d,a.checkpointId);if(!Nt(r.organizationId,u.org.organizationId))throw this.refusalOf(o.notConfirmedRefusal(n.step,!0));this.usable(o,u,"rewind");let l=this.registeredOrg(a.orgId);if(!Nt(l.orgId,u.org.organizationId)&&!Nt(this.deps.sandboxRefreshes?.organizationIdOf(l.id),u.org.organizationId))throw new Oe("OTHER_ORG",`The checkpoint '${u.name}' is not of ${ft(l)}, the org the Rewind step "${n.step}" names. No record was read or written.`);let g=ri(u,a.objects),p=await this.connect(l),f=ft(l);if(t?.aborted)throw new Oe(pr,new o.RewindStopped().message);let h=await o.previewCheckpoint({org:o.takeOrgOf(p),store:d,readAutomation:P=>this.readAutomation(l.id,P),runWriting:this.runWriting(l.id,f,"rewind","No record would be read or written."),...t?{signal:t}:{}},{checkpoint:u,folder:c,orgName:f,registered:l,username:l.username,...g!==void 0?{objects:g}:{},reusesPreview:!0,...a.muteAutomation?{muteAutomation:!0}:{},acceptOutside:a.acceptOutside});if(!h.previewed)throw this.refusalOf(h.refusal);let m=g!==void 0?o.selectionDiff(h.diff,await o.planSelection({checkpoint:u,previewDir:o.previewDirOf(c,h.diff.previewId),readAt:h.diff.readAt,objects:new Set(g),acceptOutside:a.acceptOutside,heldRows:o.snapshotRowsOf(u,c),...t?{signal:t}:{}})):h.diff,y=a.muteAutomation&&h.automation?El(h.automation,Gr(o.rewindStepsOf(m))).automation:h.automation,R=await o.boundsRefusals({orgName:f,preview:{diff:m,...y?{automation:y}:{},...h.emails?{emails:h.emails}:{},...h.emailsUncounted!==void 0?{emailsUncounted:h.emailsUncounted}:{},...h.deliverability?{deliverability:h.deliverability}:{}},bounds:{maxRecords:a.maxRecords,refuseWhenActive:a.refuseWhenActive},accepted:a,writers:async()=>o.rewindWriters(u.takenBy,await o.takeOrgOf(p).userId()),words:a.muteAutomation?o.REWIND_MUTING_STEP_WORDS:o.REWIND_STEP_WORDS,user:l.username}),[S,...b]=[...h.refusal!==void 0?[h.refusal]:[],...R.filter(P=>P.code!==h.refusal?.code)];if(S!==void 0)throw this.refusalOf(S,b);let O=P=>m.objects.reduce((v,w)=>v+P(w),0);return{checkpointId:u.checkpointId,toDelete:O(({toDelete:P})=>P.createdSince+P.broughtBackSince+P.comesBackWithParent),toGiveBack:O(({toGiveBack:P})=>P.records),toBringBack:O(({toBringBack:P})=>P.inBin+P.withParent+P.deletedWhileTaken),toRecreate:O(({toRecreate:P})=>P??0),estimate:h.estimate}}catch(o){throw Rd(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:$r,operationId:Xo(),orgId:this.orgOfCheckpoint(o)?.id??o.org.organizationId,outcome:"success",details:{checkpointId:o.checkpointId,records:d.records,objects:d.objects,files:d.files,bytes:a.bytes}}),{exported:!0,checkpoint:o,header:d,bytes:a.bytes,sha256:a.sha256,...e.key===void 0?{key:t.archiveKeyText(i)}:{}}}catch(t){return{exported:!1,refusal:await this.transferRefusalOf(t,"EXPORT_ERROR")}}}async readImport(e){let t=await this.importChecked(e);return"refusal"in t?{allowed:!1,...t}:{allowed:!0,header:t.read.header}}async importCheckpoint(e){let t=await this.importChecked(e),r=(d,c,u,l={})=>{Z(this.deps,{action:"checkpoint_import",module:$r,operationId:Xo(),orgId:d,outcome:c,...l.code!==void 0?{code:l.code}:{},details:{...u?{checkpointId:u.checkpointId,records:u.records,objects:u.objects}:{},...l.alreadyKept?{alreadyKept:!0}:{}}})};if("refusal"in t)return t.orgId!==void 0&&r(t.orgId,"stopped",t.header,{code:t.refusal.code}),{imported:!1,refusal:t.refusal,...t.header?{header:t.header}:{}};let{m:n,store:o,org:i,read:a}=t;try{let d=await n.importCheckpointArchive({store:o,file:e.file,read:a,key:e.key,...i.alias?{alias:i.alias}:{},keepDays:e.keepDays??n.DEFAULT_KEEP_DAYS,takenOn:{host:lP(),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 u=c.refusal.code==="OTHER_ORG"?this.refreshedAt(t.organizationId):void 0;return{refusal:u!==void 0?{code:"OTHER_ORG",message:`The sandbox this file's checkpoint was taken of was refreshed on ${u.slice(0,10)}: ${ft(i)} is another org now, and the checkpoint can no longer be rewound to. ${ys} 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 Oe)return{code:e.code,message:e.message};let r=await this.modules().catch(()=>{});return r!==void 0&&e instanceof r.CheckpointExportError?{code:e.code,message:e.message}:{code:t,message:I(e)}}async handleExport(e){let t=$(ay,e,"checkpoint:error",this.deps);if(!t)return;let r=[];try{let n=this.fileDialogs("export"),o=await this.modules(),i=await this.openedStore();r.push(i.root);let{checkpoint:a}=await this.checkpointOf(i,t.checkpointId);this.usable(o,a,"export");let{checkpointId:d}=a,c=await n.pickExportFile(`${d}${o.ARCHIVE_EXTENSION}`);if(c===void 0){this.respond(e,"checkpoint:export:response",{status:"cancelled",checkpointId:d});return}r.push(c);let u=await aP(c).then(()=>!0,()=>!1),l=u?pP(XS(c),`.${ni(c)}.${iP(4).toString("hex")}.export`):c;r.push(l);let g=await this.exportCheckpoint({checkpointId:d,out:l,sandforgeVersion:n.sandforgeVersion});if(!g.exported)throw new Oe(g.refusal.code,g.refusal.message);if(u)try{await dP(l,c)}catch(p){throw await cP(l,{force:!0}),p}this.respond(e,"checkpoint:export:response",{status:"saved",checkpointId:d,fileName:ni(c),key:g.key,records:g.header.records,objects:g.header.objects,bytes:g.bytes})}catch(n){this.fail(e,this.pathless(n,r,"EXPORT_ERROR"),"EXPORT_ERROR")}}async handleImportRead(e){let t=[];try{let r=this.fileDialogs("import"),n=await this.modules(),o=await this.openedStore();t.push(o.root);let i=await r.pickImportFile();if(i===void 0){this.respond(e,"checkpoint:import-read:response",{status:"cancelled"});return}t.push(i);let a=await n.readArchiveHeader(i);if("refusal"in a)throw this.refusalOf(a.refusal);let{header:d}=a.read,c=[],u;for(let g of this.deps.orgManager.getAllOrgs()){if(!this.organizationIdsOf(g.id).some(h=>Nt(h,d.organizationId)))continue;let f=await this.readImport({orgId:g.id,file:i});f.allowed?c.push(g.id):u??=f.refusal}if(c.length===0&&u!==void 0)throw new Oe(u.code,u.message);let l=await o.read(d.checkpointId)!==void 0;this.respond(e,"checkpoint:import-read:response",{status:"read",token:this.keepImportFile(i),fileName:ni(i),summary:kP(d),orgIds:c,...l?{keptHere:!0}:{}})}catch(r){this.fail(e,this.pathless(r,t,"IMPORT_ERROR"),"IMPORT_ERROR")}}async handleImport(e){let t=$(dy,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 Oe("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 Oe("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 Oe(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 Oe(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 Oe("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=Xo();this.importFiles.set(t,e);for(let r of this.importFiles.keys()){if(this.importFiles.size<=hP)break;this.importFiles.delete(r)}return t}pathless(e,t,r){let n=e instanceof Oe?e:new Oe(r,I(e));return new Oe(n.code,SP(n.message,t),n.retryable)}checkpointsChanged(){for(let e of this.changeListeners)try{e()}catch(t){this.deps.log(`[WARN] A listener of the checkpoints failed: ${I(t)}`)}}modules(){return this.loaded??=vP(),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 Oe("STORE_REFUSED",OP(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 Oe){let o=t.refusal?.holdingLimit,i={...t.alsoRefused.length>0?{alsoRefused:[...t.alsoRefused]}:{},...o!==void 0?{holdingLimit:o}:{}};T(this.deps,e.type,"checkpoint:error",e,t,{code:t.code,retryable:t.retryable,...Object.keys(i).length>0?{extraPayload:i}:{}});return}T(this.deps,e.type,"checkpoint:error",e,t,{code:r,retryable:n})}refusalOf(e,t=[]){return new Oe(e.code,e.message,RP.has(e.code),void 0,e,t)}registeredOrg(e){let t=this.deps.orgManager.getOrg(e);if(!t)throw new Oe("ORG_NOT_FOUND","SandForge has no connected org of this id: connect it first.");return t}async connect(e){try{return await q(e.id,this.deps.orgRegistry,this.deps.orgManager)}catch(t){throw t instanceof Oo&&t.code==="SCRATCH_ORG_EXPIRED"?new Oe("SCRATCH_EXPIRED",`${ft(e)} is a scratch org that has expired: its checkpoints no longer rewind it. `+ys):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||Yn(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||Nt(e.targetOrganizationId,r)||Nt(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(Nt(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||!KS.test(o)||n.some(i=>Nt(i,o))||n.push(o);return n}async listOfOrg(e,t){let r=o=>this.refreshedAt(o);return(await Promise.all(this.organizationIdsOf(t).map(o=>e.list({organizationId:o,refreshedAt:r})))).flat().sort((o,i)=>o.checkpointId<i.checkpointId?1:o.checkpointId>i.checkpointId?-1:0)}async withReplays(e){if(e.length===0)return e;try{let t=await this.modules();this.replays??=new t.ReplayStore({root:t.defaultReplayStoreRoot()});let r=this.replays,n=this.deps.orgManager.getAllOrgs(),o=new Map;for(let a of e)o.has(a.organizationId)||o.set(a.organizationId,await r.list({sourceOrganizationId:a.organizationId}));let i=[];for(let a of e){let d=(o.get(a.organizationId)??[]).filter(u=>u.checkpointId===a.checkpointId),c=[];for(let u of d){let l=n.find(f=>Nt(f.orgId,u.target.organizationId)),g=await r.mappingStoreOf(r.folderOf(u.sourceOrganizationId,u.checkpointId),u.target.organizationId).recordedLoads(),p=t.loadToRemove(g);c.push({target:{organizationId:u.target.organizationId,...u.target.name!==void 0?{name:u.target.name}:{},...l?{orgId:l.id}:{}},...u.replayedAt!==void 0?{replayedAt:u.replayedAt}:{},inPlace:u.inPlace,...u.removed?{removed:!0}:{},...u.choices?{choices:u.choices}:{},...l&&p?{records:{...t.loadRecordsInfo(p),orgId:l.id}}:{}})}i.push(c.length>0?{...a,replays:c}:a)}return i}catch(t){return this.deps.log(`[WARN] The replays of the checkpoints could not be read: ${I(t)}`),e}}orgOfCheckpoint(e){let t=e.org.organizationId,r=this.deps.orgManager.getAllOrgs(),n=r.filter(a=>Nt(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=>Nt(i?.organizationIdOf(a.id),t))}async checkpointOf(e,t){let r=await e.read(t);if(r===void 0)throw new Oe("NOT_FOUND",`No checkpoint ${t} is kept on this machine.`,!1);if(r.checkpoint===void 0)throw new Oe("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=ye(t.org);if(t.status!=="ready")throw new Oe(t.status==="taking"?"TAKING":"FAILED",t.status==="taking"?`The checkpoint '${t.name}' is being taken, or its take never ended: it can be ${wP[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 Oe("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. `+ys);if(e.scratchOrgExpired(t.org,Date.now()))throw new Oe("SCRATCH_EXPIRED",`${n} is a scratch org that has expired: its checkpoints no longer rewind it. `+ys)}connectedOrgOf(e,t){let r=this.orgOfCheckpoint(e);if(!r){let n=ye(e.org);throw new Oe("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 Oe("UNDO_CLOSED",`This rewind can no longer be undone: ${a}. No record was read or written.`)}audit(e,t,r,n,o,i={}){let{result:a,code:d,deliverability:c}=i,u=a?.mutedAutomation??i.muted,l=a?.rewindId??i.rewindId,g=e.pipeline;Z(this.deps,{action:t==="rewind"?"checkpoint_rewind":"checkpoint_undo",module:$r,operationId:e.operationId,orgId:r.id,outcome:o,...a?{objects:ka(In(a.deleted),a.restored,a.undeleted)}:{},...d!==void 0?{code:d}:{},...u?{muted:ut(u)}:{},details:{checkpointId:n.checkpointId,...l!==void 0?{rewindId:l}:{},...a?{status:a.status,passes:a.passes}:{},...a?.scope?{limitedTo:a.scope.objects.join(", ")}:{},...c!==void 0?{deliverability:c}:{},...c!==void 0&&c!=="withheld"&&i.acceptEmails===!0?{confirmed:"emails"}:{},...g?{pipeline:g.origin.pipeline,step:g.origin.step,trigger:g.origin.trigger,grantedAt:g.grantedAt}:{}}})}async handleList(e){let t=$(ty,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=$(ry,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=$(ny,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 Oe(pr,new a.CheckpointTakeStopped().message,!0);await this.take(e.id,a,d,c,i,t,{kept:({checkpoint:u,requests:l,estimate:g})=>this.respond(e,"checkpoint:take:response",{checkpoint:u,operationId:e.id,...l?{requests:l}:{},estimate:g})})}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}`,u=this.deps.infraServices?.backgroundRegistry,l=new AbortController,g=()=>{},p=new Promise((y,R)=>{g=S=>S===void 0?y():R(S)});p.catch(()=>{}),Je(this.deps,e,$r,c),u?.register(e,$r,c,p,l);let f=ar(this.liveTracker,e,$r,c),h=y=>{let{percentage:R,processedObjects:S,totalObjects:b,step:O}=y;Fe(this.deps,e,R,S,b,O),l.signal.aborted||u?.updateProgress(e,R),f.progress(R,S,b,O),a.onProgress?.(y)},m=()=>{u?u.abort(e):l.abort()};a.signal?.addEventListener("abort",m,{once:!0}),a.signal?.aborted&&m();try{let y=await t.takeCheckpoint({org:t.takeOrgOf(n),store:r,handler:this.deps,signal:l.signal,onProgress:h,runWriting:a.runWriting??this.runWriting(o.id,d,"take the checkpoint","No record was read.")},{...this.takeRequestOf(o,i),...i.name!==void 0?{name:i.name}:{},...i.nameWithDate!==void 0?{nameWithDate:i.nameWithDate}:{},keepDays:i.keepDays,...i.ignoredFields?{ignoredFields:i.ignoredFields}:{},...i.unprovenLeftOut===!0?{unprovenLeftOut:!0}:{},...i.beforeRun!==void 0?{beforeRun:i.beforeRun}:{}});if(!y.taken)throw ge(this.deps,e,{status:"refused",code:y.refusal.code}),f.fail(y.refusal.message),g(new Error(y.refusal.message)),this.refusalOf(y.refusal);for(let{objectApiName:b,reason:O}of y.notChecked)this.deps.log(`[WARN] checkpoint:take ${e}: what moved in ${b} while it was read was not checked: ${O}`);let{checkpoint:R}=y,S={checkpoint:R,...y.requests?{requests:y.requests}:{},estimate:y.estimate};return a.kept?.(S),this.checkpointsChanged(),ge(this.deps,e,{status:"success",objects:R.objects.length,records:R.objects.reduce((b,O)=>b+O.records,0)}),f.complete(),g(),S}catch(y){throw y instanceof Oe?y:y instanceof t.CheckpointTakeStopped?(u?.abort(e),ge(this.deps,e,{aborted:!0}),f.cancel(),g(),new Oe(pr,y.message,!0)):(ge(this.deps,e,{status:"failure"}),f.fail(I(y)),g(y),y)}finally{a.signal?.removeEventListener("abort",m)}}async handlePreview(e){let t=$(oy,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=ri(i,t.objects),d=this.connectedOrgOf(i,`preview the checkpoint '${i.name}'`),c=await this.connect(d),u=await r.previewCheckpoint({org:r.takeOrgOf(c),store:n,readAutomation:l=>this.readAutomation(d.id,l),runWriting:this.runWriting(d.id,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(!u.previewed)throw this.refusalOf(u.refusal);this.previewsAnswered?.set(u.diff.previewId,u.diff),this.previewReads.set(u.diff.previewId,{checkpointId:i.checkpointId,readAt:u.diff.readAt}),this.respond(e,"checkpoint:preview:response",{diff:u.diff,...u.automation?{automation:u.automation}:{},...u.emails?{emails:u.emails}:{},...u.emailsKeepingOutside?{emailsKeepingOutside:u.emailsKeepingOutside}:{},...u.emailsUncounted!==void 0?{emailsUncounted:u.emailsUncounted}:{},...u.deliverability?{deliverability:u.deliverability}:{},estimate:u.estimate,...u.refusal?{refusal:u.refusal}:{}})}catch(r){this.fail(e,r,"PREVIEW_ERROR")}}async handlePlanSelection(e){let t=$(iy,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=ri(i,t.objects)??[],d=r.previewDirOf(o,t.previewId),c=this.previewReads.get(t.previewId);if(c?.checkpointId!==i.checkpointId||!await VS(d))throw new Oe("PREVIEW_GONE",`The preview to plan this selection from is no longer kept on this machine: preview the rewind to '${i.name}' again. No record was read or written.`);let u=await r.planSelection({checkpoint:i,previewDir:d,readAt:c.readAt,objects:new Set(a),acceptOutside:t.acceptOutside,heldRows:r.snapshotRowsOf(i,o)});this.respond(e,"checkpoint:plan-selection:response",{checkpointId:i.checkpointId,previewId:t.previewId,plan:u})}catch(r){this.fail(e,r,"PLAN_SELECTION_ERROR")}}async handleRewind(e){let t=$(sy,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=ri(d,t.objects);if(!await VS(o.previewDirOf(a,t.previewId)))throw new Oe("PREVIEW_GONE",`The preview this rewind was confirmed on is no longer kept on this machine: preview the rewind to '${d.name}' again, then rewind. No record was read or written.`);let u=this.connectedOrgOf(d,`rewind it to the checkpoint '${d.name}'`),l=await this.connect(u),g=this.pageAt(e);if(n?.signal.aborted)throw this.audit(g,"rewind",u,d,"stopped",{code:bt}),new Oe(pr,new o.RewindStopped().message,!0);let p=this.previewsAnswered?.get(t.previewId);this.previewsAnswered?.delete(t.previewId);let f=p?.checkpointId===d.checkpointId?p:void 0,h=ft(u);await this.writeAct(g,"rewind",u,d,`Rewinding ${h} to '${d.name}'`,async(m,y)=>{let R=await o.rewindOrg({org:o.rewindOrgOf(l),undelete:b=>l.soap.undelete(b),store:i,readAutomation:b=>this.readAutomation(u.id,b),runWriting:this.runWriting(u.id,h,"rewind","No record was read or written."),onUndeletable:Vr(this.deps,u.id,"checkpoint:rewind"),onProgress:({percentage:b,step:O})=>y(b,O),signal:m,...t.muteAutomation===!0?{mute:this.muteOf(l)}:{}},{checkpoint:d,folder:a,orgName:h,registered:u,username:u.username,previewId:t.previewId,...f?{reusesPreview:f}:{},...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 Op(R);let S=t.fromPage===!0;return Ip(R.refusal,R.alsoRefused,b=>S?o.pageEmailsRefusal(b,"rewind",h):b,S)},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=$(cy,e,"checkpoint:error",this.deps);if(!t)return;let n=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(e.id);try{let o=await this.modules(),i=await this.openedStore(),{folder:a,checkpoint:d}=await this.checkpointOf(i,t.checkpointId);this.usable(o,d,"undo"),await this.undoOffered(i,a,d,t.rewindId);let c=this.connectedOrgOf(d,`undo its rewind to '${d.name}'`),u=await this.connect(c),l=this.pageAt(e);if(n?.signal.aborted)throw this.audit(l,"undo",c,d,"stopped",{code:bt,rewindId:t.rewindId}),new Oe(pr,new o.UndoStopped().message,!0);let g=ft(c);await this.writeAct(l,"undo",c,d,`Undoing the rewind of ${g} to '${d.name}'`,async(p,f)=>{let h=await o.undoCheckpoint({org:o.rewindOrgOf(u),undelete:y=>u.soap.undelete(y),store:i,readAutomation:y=>this.readAutomation(c.id,y),runWriting:this.runWriting(c.id,g,"undo the rewind","No record was read or written."),onUndeletable:Vr(this.deps,c.id,"checkpoint:undo"),onProgress:({percentage:y,step:R})=>f(y,R),signal:p,...t.muteAutomation===!0?{mute:this.muteOf(u)}:{}},{checkpoint:d,folder:a,orgName:g,registered:c,username:c.username,rewindId:t.rewindId,acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails===!0,canMute:!0});if(h.undone)return Op(h);let m=t.fromPage===!0;return Ip(h.refusal,h.alsoRefused,y=>m?o.pageEmailsRefusal(y,"undo",g):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()=>_t(e),t,{...this.muteLeases,writes:r})}pageAt(e){return{operationId:e.id,respond:(t,r)=>this.respond(e,t,r)}}async writeAct(e,t,r,n,o,i,a,d={}){let{operationId:c}=e,{rewindId:u}=d,l=this.deps.infraServices?.backgroundRegistry,g=new AbortController,p=()=>{},f=new Promise((S,b)=>{p=O=>O===void 0?S():b(O)});f.catch(()=>{}),Je(this.deps,c,$r,o),l?.register(c,$r,o,f,g);let h=ar(this.liveTracker,c,$r,o),m=u!==void 0?{rewindId:u}:{},y=(S,b)=>{Fe(this.deps,c,S,0,0,b),g.signal.aborted||l?.updateProgress(c,S),h.progress(S,0,0,b)},R=()=>{l?l.abort(c):g.abort()};d.signal?.addEventListener("abort",R,{once:!0}),d.signal?.aborted&&R();try{let S=await i(g.signal,y);if(!S.done)throw this.audit(e,t,r,n,"stopped",{code:S.refusal.code,...m}),ge(this.deps,c,{status:"refused",code:S.refusal.code}),h.fail(S.refusal.message),p(new Error(S.refusal.message)),this.refusalOf(S.refusal,S.alsoRefused);let{result:b,notes:O,deliverability:P}=S,v={...P!==void 0?{deliverability:P}:{},...d.acceptEmails===!0?{acceptEmails:!0}:{}};for(let C of O)this.deps.log(`[WARN] checkpoint:${t} ${c}: ${C}`);for(let C of b.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 w=d.refusalOf?.(b);if(w!==void 0)throw this.audit(e,t,r,n,JS(b)?"partial":"stopped",{result:b,code:w.code,...v}),ge(this.deps,c,{status:"refused",code:w.code}),h.fail(w.message),p(new Error(w.message)),new Oe(w.code,w.message,!1,b);if(this.audit(e,t,r,n,yP[b.status],{result:b,...v}),e.respond?.(`checkpoint:${t}:response`,{result:b,operationId:c}),b.status==="cancelled")l?.abort(c),ge(this.deps,c,{aborted:!0}),h.cancel(),p();else if(b.status==="failure"){let C=`Nothing the ${t} set out to write went through: its result says why.`;ge(this.deps,c,{status:b.status}),h.fail(C),p(new Error(C))}else ge(this.deps,c,{status:b.status}),b.status==="success"?h.complete():h.partial(),p();return b}catch(S){if(S instanceof Oe)throw S;if(a(S))throw l?.abort(c),ge(this.deps,c,{aborted:!0}),h.cancel(),p(),this.audit(e,t,r,n,"stopped",{code:pr,...m}),new Oe(pr,I(S),!0);let b=Hs(S);throw this.audit(e,t,r,n,"failure",{...m,...b?{muted:b}:{}}),this.unreleased(e,t,r,b),ge(this.deps,c,{status:"failure"}),h.fail(I(S)),p(S),S}finally{d.signal?.removeEventListener("abort",R)}}unreleased(e,t,r,n){n?.released===!1&&this.deps.log(`[WARN] checkpoint:${t} ${e.operationId}: `+Kt(n,ft(r)).map(o=>o.trim()).join("; "))}readAutomation(e,t){let r=this.targetAutomation;return new fe(mP).withTimeout("checkpoint:preview automation",()=>r.read(e,t,{undeletes:!0}))}ownReader(){return this.reader??=import("./chunk-GOOVPVWX.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async handleDelete(e){let t=$(uy,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 ${Ap(i)}`);if(n.length===0&&o.length>0)throw new Oe("RUN_WRITING",`The checkpoint was not deleted: ${Ap(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=$(ly,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=$(py,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=$(gy,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=$(fy,e,"checkpoint:error",this.deps);if(t!==null)try{let r=await this.openedStore(),{readRewindLedgers:n}=await import("./chunk-RGUQOSBU.mjs"),i=(t?.orgIds??this.deps.orgManager.getAllOrgs().map(c=>c.id)).map(c=>({orgId:c,ids:this.organizationIdsOf(c)})),a=await n(r.root,i.flatMap(({ids:c})=>c)),d=[];for(let[c,u]of a){for(let l of u.unreadable)this.deps.log(`[WARN] Line ${l} of the rewind ledger of ${c} does not parse: left out`);for(let l of u.records){let g=i.filter(({ids:p})=>p.some(f=>Nt(f,l.organizationId)));d.push({...l,orgIds:g.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 Oe("RUN_WRITING",`The checkpoint was not changed: ${Ap(d)}. Change it once that has ended.`,!0);let c;try{c=await n(i)}catch(u){throw u instanceof o.CheckpointStoreError?new Oe(u.code==="notFound"?"NOT_FOUND":u.code==="damaged"?"DAMAGED":"INVALID",u.message):u}this.respond(e,`checkpoint:${r}:response`,{checkpoint:c}),this.checkpointsChanged()}catch(o){this.fail(e,o,"CHANGE_ERROR")}}};var vt={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 gr(s,e){return Object.assign(new Error(e),{code:s})}function QS(s,e,t){let r=Vi(s);if(r==="refused")return gr(vt.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 gr(vt.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 Tp(s){return s.objects.flatMap(e=>e.fieldRules.filter(t=>t.ruleType==="ai_generate").map(t=>`${e.objectApiName}.${t.fieldApiName}`))}function Yo(s,e,t){let r=t(e)??Ui.find(d=>d.id===e);if(r==null)return{refusal:gr(vt.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=Po.safeParse(r);if(!i.success){let d=i.error.issues[0];return{refusal:gr(vt.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=Tp(i.data);return a.length>0?{refusal:gr(vt.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 ok={apiLimits:"apiLimits",storage:"storage",recentErrors:"recentErrors",failedJobs:"activeJobs"},Ep=Object.keys(ok),ZS={apiLimits:{variable:vs.apiLimits,read:s=>s.percent},storage:{variable:vs.storage,read:s=>s.percent},recentErrors:{variable:vs.recentErrors,read:s=>s.count},failedJobs:{variable:vs.failedJobs,read:s=>s.count}},sk=500,ik=J({orgId:Zh,checks:ve(We(["apiLimits","storage","recentErrors","failedJobs"])).min(1).refine(s=>new Set(s).size===s.length)}),ak=J({message:j().trim().min(1).max(sk)});function At(s,e){return`${s} ${e}${s===1?"":"s"}`}function Nr(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 Dr(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 xp(s){return Array.isArray(s)&&s.length>0?s:void 0}function IP(s){return e=>{let t=`Backup step "${e.name}"`,r=e.config??{},n=Dr(s,t,r.orgId,"the org it backs up");if(n)return n;let o=xp(r.objects);if(!o)return`${t} names no object: list the API names of the objects it backs up.`;let i=o.filter(a=>!em.safeParse(a).success);if(i.length>0)return`${t} names what is not an object API name: ${i.map(String).join(", ")}.`;if(!xs.safeParse({orgId:r.orgId,objects:o}).success)return`${t} backs up more objects than one backup takes: at most 100.`}}function AP(s){return e=>{let t=`Compare step "${e.name}"`,r=e.config??{},n=Dr(s,t,r.sourceOrgId,"the org it compares from")??Dr(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=xp(r.types);if(!o)return`${t} names no component type: choose what it compares.`;if(!Ds.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 TP(s){return e=>{let t=`Pre-check step "${e.name}"`,r=e.config??{},n=Dr(s,t,r.orgId,"the org it checks");if(n)return n;let o=xp(r.checks);if(!o)return`${t} names no check: choose what it checks (${Ep.join(", ")}).`;let i=o.filter(a=>typeof a!="string"||!Ep.includes(a));if(i.length>0)return`${t} names checks SandForge does not have: ${i.map(String).join(", ")}. It can check ${Ep.join(", ")}.`;if(!ik.safeParse({orgId:r.orgId,checks:o}).success)return`${t} names the same check twice.`}}function EP(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(!ak.safeParse({message:r}).success)return`${t} has a message longer than ${sk} characters.`}}function PP(s){return async(e,t)=>{let r=new Date().toISOString(),{orgId:n,objects:o}=xs.parse({orgId:e.config.orgId,objects:e.config.objects}),i=await s.backup({operationId:s.newId(),orgId:n,objects:o},t.signal),a=s.orgName(n)??n,d=i.objects.filter(u=>u.truncated).map(u=>u.objectApiName),c=`Backed up ${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 Nr(e,r,{operationId:i.operationId,orgId:n,objects:i.objects,totalRecords:i.totalRecords,partial:i.partial},c)}}function CP(s){return async(e,t)=>{let r=new Date().toISOString(),{sourceOrgId:n,targetOrgId:o,types:i}=Ds.parse({sourceOrgId:e.config.sourceOrgId,targetOrgId:e.config.targetOrgId,types:e.config.types}),a=await s.compare({sourceOrgId:n,targetOrgId:o,types:i},t.signal),{added:d,removed:c,modified:u,unchanged:l,notCompared:g}=a.summary,p=s.orgName(n)??n,f=s.orgName(o)??o;return Nr(e,r,{sourceOrgId:n,targetOrgId:o,types:i,summary:a.summary,content:a.content,variables:{[Kf]:String(d+c+u)}},`Compared ${At(i.length,"component type")} of ${p} with ${f}: ${c} only in ${p}, ${d} only in ${f}, ${u} modified, ${l} unchanged, ${g} not compared.`)}}function ek(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 $P(s){return async e=>{let t=new Date().toISOString(),{orgId:r,checks:n}=ik.parse({orgId:e.config.orgId,checks:e.config.checks}),o=s.orgName(r)??r,i=await s.readOrgHealth(r,n.map(l=>ok[l])),a=n.map((l,g)=>({check:l,signal:i[g]})),d={};for(let{check:l,signal:g}of a){let p=g?ZS[l].read(g):void 0;p!==void 0&&g.status!=="unknown"&&(d[ZS[l].variable]=String(p))}let c={orgId:r,checks:a.map(({check:l,signal:g})=>({check:l,status:g?.status??"unknown",message:g?.message??"Not read"})),variables:d},u=a.filter(({signal:l})=>!l||l.status==="critical"||l.status==="unknown");return u.length>0?Tt(e,t,c,`Pre-check "${e.name}" failed on ${o}: ${u.map(({check:l,signal:g})=>g?ek(g):`${l} was not read`).join("; ")}.`):Nr(e,t,c,`${a.length===1?"The check":`${a.length} checks`} passed on ${o}: ${a.map(({signal:l})=>ek(l)).join("; ")}.`)}}function xP(s){return async(e,t)=>{let r=new Date().toISOString(),{message:n}=ak.parse({message:e.config.message});return s.notify?(s.notify(t.pipelineName?`${t.pipelineName}: ${n}`:n),Nr(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 dk(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=DP(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 DP(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=oi(s,t);r="problem"in n?void 0:n.config.targetOrgId}else(t.type==="seed"||t.type==="anonymize")&&(r=on((t.config??{}).orgId));if(r!==void 0&&s.orgTier?.(r)==="staging")return s.orgName(r)??r}}function NP(s){return(e,t)=>{let r=`Approval step "${e.name}"`;if(!s.askApproval)return dk(s,e,t);switch(eh(e.config)){case"timeout":return`${r} waits for a time it cannot keep: set a whole number of minutes from 1 to ${Yf} (a day).`;case"message":return`${r} has a message that is not text, or is longer than ${Qf} characters.`;default:return}}}function tk(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 jP(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Approval step "${e.name}"`;if(!s.askApproval)return Tt(e,r,{},dk(s,e,void 0));let o=Zf(e.config)??Xf,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{...Nr(e,r,c,`Approved${tk(d)} at ${d.at}.`),approval:d};case"rejected":return{...Tt(e,r,c,`${n} was rejected${tk(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 oi(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=vn.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 ck(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(!vn.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 uk(s){return s===void 0||s.steps.slice(0,s.index).some(e=>e.type==="approval")}function MP(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=oi(s,e);if("problem"in n)return n.problem;let{config:o}=n,i=Dr(s,r,o.sourceOrgId,"the source org of its configuration")??Dr(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"&&!uk(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 Dp(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 Np(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 rk=3;function LP(s){let e=s.filter(r=>r.failed>0).flatMap(r=>Qu(r.errors).map(n=>`${r.objectApiName}, ${n.count} \xD7 ${n.example}`));if(e.length===0)return"";let t=e.length-rk;return`; refused: ${e.slice(0,rk).join("; ")}`+(t>0?`; and ${At(t,"other reason")}`:"")}function FP(s){return async(e,t)=>{let r=new Date().toISOString(),n=oi(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,Dp(t),t.signal);if(a.cancelled)throw new Rt(`Sync step "${e.name}" was cancelled: ${a.error??"the run stopped before it synced every object."}`);let d=s.orgName(o.targetOrgId)??o.targetOrgId,c=a.summary,u={configId:o.id,configName:i,operationId:a.operationId,status:a.status,totalProcessed:a.totalProcessed,totalSuccess:a.totalSuccess,totalFailed:a.totalFailed,totalSkipped:a.totalSkipped,objects:a.objectResults.map(p=>{let f=p.failed>0?Qu(p.errors):[];return{objectApiName:p.objectApiName,operation:p.operation,processed:p.processed,success:p.success,failed:p.failed,skipped:p.skipped,...f.length>0?{refusals:f}:{},...p.delta?{delta:p.delta}:{}}}),...typeof c=="object"&&c!==null?{summary:c}:{}},l=Np(a.objectResults,!0).map(p=>`; ${p}`).join(""),g=`${At(a.totalSuccess,"record")} written, ${a.totalFailed} failed and ${a.totalSkipped} skipped of ${a.totalProcessed} read${l}`;if(a.status!=="success"){let p=[a.error,ad(a)].filter(f=>f!==void 0&&f!=="");return Tt(e,r,u,`Sync step "${e.name}" ran "${i}" into ${d} and did not complete: ${g}`+LP(a.objectResults)+(p.length>0?`; ${p.join("; ")}`:"."))}return Nr(e,r,u,`Synced "${i}" into ${d}: ${g}.`)}}function on(s){return typeof s=="string"&&s.trim()!==""?s.trim():void 0}function jp(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 _P(s,e){return s!==void 0&&e!==void 0&&s.length>=15&&s.slice(0,15)===e.slice(0,15)}function Sd(s){return s.pipelineName??s.pipelineId}function lk(s,e,t,r,n){let o=s.orgName(t)??t,i=Vi(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"&&!uk(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 pk(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 gk(s){if(s instanceof Rt)return;let e=s?.code;return typeof e=="string"?e:void 0}function UP(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=Dr(s,r,n.orgId,"the org it seeds");if(o)return o;let i=on(n.templateId);if(i===void 0)return`${r} names no Seed template: choose the one it seeds with.`;let a=String(n.orgId),d=Yo(a,i,c=>s.savedSeedTemplate?.(c));return"refusal"in d?`${r}: ${d.refusal.message}`:pk(e,r,"a second try would write a second set of records")??lk(s,r,a,"seeds",t)}}function HP(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}=Ji.parse({orgId:e.config.orgId,templateId:on(e.config.templateId)}),a=s.orgName(o)??o,d;try{d=await s.seed({orgId:o,templateId:i,pipeline:{name:Sd(t)},answer:Dp(t)},t.signal)}catch(p){let f=gk(p);if(f===void 0)throw p;return Tt(e,r,{orgId:o,templateId:i,code:f},`${n}: ${p.message}`)}let{result:c}=d,u={orgId:o,templateId:i,operationId:d.operationId,runId:d.runId,status:c.status,totalRecordsCreated:c.totalRecordsCreated,totalRecordsFailed:c.totalRecordsFailed,objects:c.objectResults.map(p=>({objectApiName:p.objectApiName,recordsCreated:p.recordsCreated,recordsFailed:p.recordsFailed})),...d.automation.length>0?{automation:d.automation}:{}},l=At(c.totalRecordsCreated,"record"),g="take them back from Seed's History";if(c.cancelled)throw new Rt(`${n} was cancelled: it had created ${l} in ${a}, which stay there; ${g}.`);return c.status!=="success"?Tt(e,r,u,`${n} seeded ${a} and did not complete: ${l} created, ${c.totalRecordsFailed} refused; ${g}.`):Nr(e,r,u,`Seeded ${l} into ${a}: ${g}.`)}}function fk(s){let e=(s.listSeedTemplates?.()??[]).map(n=>({raw:n,builtIn:!1})),t=Ui.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=Po.safeParse(n);return[{id:i,name:d,builtIn:o,valid:c.success,usesAi:c.success&&Tp(c.data).length>0}]})}function BP(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 hk(s){return(s.maskingTemplates?.()??[]).map(e=>({id:e.id,name:e.name,builtIn:e.builtIn,objects:BP(e)}))}function qP(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=Dr(s,r,n.orgId,"the org it masks");if(o)return o;let i=on(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=on(n.object),u=on(n.where),l=vb({orgId:a,templateId:i,...c!==void 0?{object:c}:{},...u!==void 0?{where:u}:{},...e.retries!==void 0?{retries:e.retries}:{}},p=>d.some(f=>f.id===p));if("refusal"in l)return`${r}: ${l.refusal.message}`;let g=Ss.safeParse({orgId:a,templateId:i,...kd(n)});return g.success?lk(s,r,a,"masks",t):`${r} does not read (${jp(g.error)}).`}}function kd(s){return Object.fromEntries(["acceptAutomation","acceptEmails","muteAutomation"].flatMap(e=>s[e]===void 0?[]:[[e,s[e]]]))}var nk=3;function WP(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-nk;return`, refused by the org: ${e.slice(0,nk).join("; ")}`+(t>0?`; and ${At(t,"other reason")}`:"")}function zP(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=on(e.config.object),i=on(e.config.where),{orgId:a,templateId:d,acceptAutomation:c,acceptEmails:u,muteAutomation:l}=Ss.parse({orgId:e.config.orgId,templateId:on(e.config.templateId),...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...kd(e.config)}),g=s.orgName(a)??a,p=O=>O?` ${Kt(O,g).map(P=>P.trim()).join("; ")}.`:"",f;try{f=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:u,muteAutomation:l},pipeline:{name:Sd(t)},answer:Dp(t)},t.signal)}catch(O){let P=gk(O);if(P===void 0)throw O;let v=O.snapshot,w=Hs(O);return Tt(e,r,{orgId:a,templateId:d,code:P,...v!==void 0?{snapshot:v}:{},...w?{mutedAutomation:w}:{}},`${n}: ${O.message}`+(typeof v?.operationId=="string"?` The snapshot ${v.operationId} it took keeps the values it wrote over, in clear, until it is deleted on the DataOps page.`:"")+p(w))}let{result:h}=f,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:f.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 Rt(`${n} was cancelled: it masked ${At(h.recordsProcessed,"record")} in ${g} before the stop, and ${h.recordsNotMasked} still hold their values; ${m}.`+R);let S=h.objects.filter(O=>O.notMasked>0);if(h.recordsNotMasked>0){let O=`${S.map(P=>`${P.notMasked} of ${P.objectApiName}`).join(", ")} still hold their values${WP(h)}`;return Tt(e,r,y,`${n} masked ${g} and did not complete: ${O}; ${m}.${R}`)}let b=o!==void 0?i!==void 0?`the ${o} rows where ${i}`:`every ${o} row`:`every row of ${h.objects.map(O=>O.objectApiName).join(", ")}`;return Nr(e,r,y,`Masked ${At(h.recordsProcessed,"record")} in ${g}, ${b}; ${m}.${R}`)}}function GP(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=Dr(s,t,r.orgId,"the org it takes");if(n)return n;let o=String(r.orgId);if((s.orgTier?.(o)??"production")==="production")return`${t} names ${s.orgName(o)??o}, a production org or one SandForge cannot tell is not: SandForge takes no checkpoint of one.`;let i=wn.safeParse(r);if(!i.success)return`${t} does not read (${jp(i.error)}).`}}function JP(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 VP(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Checkpoint step "${e.name}"`;if(!s.takeCheckpoint)throw new Error(`${n} cannot run here: Checkpoints are not available in this window.`);let o=wn.parse(e.config),i=s.orgName(o.orgId)??o.orgId,a;try{a=await s.takeCheckpoint({config:o,origin:{pipeline:Sd(t),step:e.name,trigger:s.trigger??"manual"}},t.signal)}catch(u){if(!(u instanceof xr))throw u;return Tt(e,r,{orgId:o.orgId,code:u.code},u.message)}let d=a.movedWhileTaken,c=d.changed+d.deleted+d.created;return Nr(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")}, ${JP(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 KP={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 mk(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}, ${KP[a]}.`}}let i=s.organizationIdsOf?.(t)??[];if(n.organizationId!==void 0&&!i.some(a=>_P(a,n.organizationId)))return{why:"otherOrg",problem:`${e} rewinds ${s.orgName(t)??t} to the checkpoint ${o}, which was taken of another org.`}}function XP(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=Dr(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=$t.safeParse(r);if(!i.success)return`${t} does not read (${jp(i.error)}).`;let a=pk(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?Nn(e.name,d.refusal):mk(s,t,o,i.data.checkpointId)?.problem}}function $p(s){return{deleted:s.deleted.reduce((e,t)=>e+t.deleted,0),gaveBack:s.restored.reduce((e,t)=>e+t.restored+(t.restoredWithout??0),0),broughtBack:s.undeleted.reduce((e,t)=>e+t.undeleted,0),madeAgain:(s.recreated??[]).reduce((e,t)=>e+t.created,0)}}function Pp(s){let e=$p(s);return`${e.deleted} deleted, ${e.gaveBack} given their values back, ${e.broughtBack} brought back from the recycle bin`+(e.madeAgain>0?`, ${e.madeAgain} made again with new Ids`:"")}function Cp(s){return s.undo?`Undo on the Checkpoints page takes it back until ${s.undo.until}`:"it wrote nothing Undo would take back"}function YP(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=$t.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"},Nn(e.name,i.refusal));let a=s.orgName(o.orgId)??o.orgId,d=f=>f?` ${Kt(f,a).map(h=>h.trim()).join("; ")}.`:"",c;try{c=await s.rewind({config:o,grant:i.grant,origin:{pipeline:Sd(t),step:e.name,trigger:s.trigger??"manual"}},t.signal)}catch(f){let h=(f instanceof xr?f.result?.mutedAutomation:void 0)??Hs(f);if(!(f instanceof xr)){if(!h||f instanceof Rt)throw f;return Tt(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,mutedAutomation:h},`${I(f)}${d(h)}`)}return Tt(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:f.code,...f.alsoRefused.length>0?{alsoRefused:[...f.alsoRefused]}:{},...f.result?{status:f.result.status,...$p(f.result)}:{},...h?{mutedAutomation:h}:{}},`${f.message}${d(h)}`)}let{result:u}=c,l=u.residual.reduce((f,h)=>f+h.count,0),g={orgId:o.orgId,checkpointId:c.checkpointId,operationId:c.operationId,rewindId:u.rewindId,status:u.status,...$p(u),residual:l,...u.undo?{undoUntil:u.undo.until}:{},apiRequests:u.apiRequests.used,...u.mutedAutomation?{mutedAutomation:u.mutedAutomation}:{}},p=d(u.mutedAutomation);if(u.status==="cancelled")throw new Rt(`${n} was stopped part way in ${a}: ${Pp(u)}; ${Cp(u)}.${p}`);return u.status!=="success"?Tt(e,r,g,`${n} rewound ${a} and did not complete (${u.status}): ${Pp(u)}; ${At(l,"record")} still ${l===1?"differs":"differ"} from the checkpoint`+(u.unread&&u.unread.length>0?`, and ${u.unread.map(f=>f.objectApiName).join(", ")} could not be read`:"")+`; ${Cp(u)}.${p}`):Nr(e,r,g,`Rewound ${a} to the checkpoint ${c.checkpointId}: ${Pp(u)}, with ${At(u.apiRequests.used,"API request")}; ${Cp(u)}.${p}`)}}function yk(s,e,t,r){let n=r?{granted:{at:r.grantedAt,digestMatches:r.matches}}:{},o=$t.safeParse(e.config??{});if(!o.success)return{stepId:e.id,valid:!1,why:"config",...n};let{orgId:i,checkpointId:a}=o.data,d=mk({...s,checkpointKept:()=>t},"The step",i,a);return{stepId:e.id,checkpointId:a,valid:d===void 0,...d?{why:d.why}:{},...n}}function wk(s,e){s.registerHandler("backup",PP(e),IP(e)),s.registerHandler("compare",CP(e),AP(e)),s.registerHandler("precheck",$P(e),TP(e)),s.registerHandler("notification",xP(e),EP(e)),s.registerHandler("approval",jP(e),NP(e)),s.registerHandler("sync",FP(e),MP(e)),s.registerHandler("seed",HP(e),UP(e)),s.registerHandler("anonymize",zP(e),qP(e)),s.registerHandler("checkpoint",VP(e),GP(e)),s.registerHandler("rewind",YP(e),XP(e))}function dn(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 sn(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 an(s,e){return`${s} ${e}${s===1?"":"s"}`}function si(s){return typeof s=="string"&&s.trim()!==""?s.trim():void 0}function Od(s){return s.pipelineName??s.pipelineId}function Mp(s){if(s instanceof Rt)return;let e=s?.code;return typeof e=="string"?e:void 0}function Qo(s){return new Error(`${s} cannot be simulated here: nothing can read what it would do. Nothing was written.`)}function QP(s){return s<6e4?`${s/1e3} s`:s<36e5?`${Math.round(s/6e4)} min`:`${(s/36e5).toFixed(1)} h`}function vk(s){return`about ${an(s.apiRequests,"API request")} of the ${s.apiRequestsLeft} the org has left today, about ${s.seconds} s`}function ZP(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 bk(s){let e=Np(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 Rk=3;function eC(s){let e=s.flatMap(r=>(r.refusedFor??[]).map(({note:n})=>`${r.objectApiName}, ${n.replace(/\.$/,"")}`));if(e.length===0)return"";let t=e.length-Rk;return`; refused: ${e.slice(0,Rk).join("; ")}`+(t>0?`; and ${an(t,"other reason")}`:"")}function tC(s){let e=new Date().toISOString(),t=Vw(s.config)??0;return Promise.resolve(dn(s,e,{wouldWait:t},`Would wait ${QP(t)}: a simulation does not wait.`))}function rC(s){let e=new Date().toISOString();return Promise.resolve(dn(s,e,{asked:!1},"Not asked in a simulation: the route goes on as if it were approved."))}function nC(s){return e=>{let t=new Date().toISOString(),r=si(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(dn(e,t,{message:r},`${n}: "${r}"`))}}function oC(s){return e=>{let t=new Date().toISOString(),{orgId:r,objects:n}=xs.parse({orgId:e.config.orgId,objects:e.config.objects}),o=s.orgName(r)??r;return Promise.resolve(dn(e,t,{orgId:r,objects:n},`Would take a snapshot of ${an(n.length,"object")} of ${o} (${n.join(", ")}): a simulation takes none.`))}}function sC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Sync step "${e.name}"`,o=oi(s,e);if("problem"in o)throw new Error(o.problem);if(!s.simulateSync)throw Qo(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 f=Mp(p);if(f===void 0)throw p;return sn(e,r,{configId:i.id,code:f},`${n} would be refused: ${p.message}`)}if(c.cancelled)throw new Rt(`${n} was stopped before its simulation read every object. Nothing was written.`);let u={configId:i.id,configName:a,operationId:c.operationId,objects:c.objects.map(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}:{}},l=ZP(c.objects);return c.error?sn(e,r,u,`${n} would stop on ${c.failedObject??"an object"}: ${c.error}`):c.objects.reduce((p,f)=>p+f.refused,0)>0?sn(e,r,u,`${n} would run "${a}" into ${d} and not complete: ${l}${bk(c)}${eC(c.objects)}. Nothing was written.`):dn(e,r,u,`Would sync "${a}" into ${d}: ${l}${bk(c)}. Nothing was written.`)}}function iC(s){let e=s.previousResults.filter(t=>t.stepType==="approval");return{approved:e[e.length-1]?.status==="completed"}}function aC(s,e){return Uv(s,e)}function dC(s,e){let t=`about ${an(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 cC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Seed step "${e.name}"`,{orgId:o,templateId:i}=Ji.parse({orgId:e.config.orgId,templateId:si(e.config.templateId)}),a=s.orgName(o)??o,d=Yo(o,i,l=>s.savedSeedTemplate?.(l));if("refusal"in d)return sn(e,r,{orgId:o,templateId:i,code:d.refusal.code},`${n} would be refused: ${d.refusal.message}`);if(!s.previewSeed)throw Qo(n);let{template:c}=d.asked,u;try{u=await s.previewSeed({orgId:o,templateId:i,pipeline:{name:Od(t)},answer:iC(t)},t.signal)}catch(l){let g=Mp(l);if(g===void 0)throw l;return sn(e,r,{orgId:o,templateId:i,code:g},`${n} would be refused: ${l.message}`)}return dn(e,r,{orgId:o,templateId:i,records:u.records,objects:u.objects,storage:u.storage,apiRequests:u.apiRequests,...u.automation.length>0?{automation:u.automation}:{}},`Would seed "${c.name}" into ${a}: ${an(u.records,"record")} of ${an(u.objects,"object")}, as its template asks; ${aC(u.storage,a)}; ${dC(u.apiRequests,a)}. Nothing was written.`)}}function uC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Anonymize step "${e.name}"`;if(!s.previewMasking)throw Qo(n);let o=si(e.config.object),i=si(e.config.where),{orgId:a,templateId:d,acceptAutomation:c,acceptEmails:u,muteAutomation:l}=Ss.parse({orgId:e.config.orgId,templateId:si(e.config.templateId),...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...kd(e.config)}),g=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:u,muteAutomation:l},pipeline:{name:Od(t)},answer:{approved:!0}},t.signal),f=p.objects.filter(h=>h.records>0).map(h=>`${h.records} of ${h.objectApiName} (${h.fields.join(", ")})`);return dn(e,r,{orgId:a,templateId:d,records:p.records,objects:p.objects},p.records===0?`Would mask nothing in ${g}: no row of ${p.objects.map(h=>h.objectApiName).join(", ")} holds anything to mask. Nothing was written.`:`Would mask ${an(p.records,"record")} in ${g}: ${f.join("; ")}, after a snapshot of them. Nothing was written.`)}catch(p){let f=Mp(p);if(f===void 0)throw p;return sn(e,r,{orgId:a,templateId:d,code:f},`${n} would be refused: ${p.message}`)}}}function lC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Checkpoint step "${e.name}"`;if(!s.estimateTake)throw Qo(n);let o=wn.parse(e.config),i=s.orgName(o.orgId)??o.orgId;try{let a=await s.estimateTake({config:o,origin:{pipeline:Od(t),step:e.name,trigger:s.trigger??"manual"}},t.signal);return dn(e,r,{orgId:o.orgId,objects:a.objects,records:a.records,leftOut:a.leftOut,estimate:a.estimate},`Would take a checkpoint of ${i}: ${an(a.records,"record")} of ${an(a.objects,"object")} now, ${vk(a.estimate)}. Nothing was taken.`)}catch(a){if(!(a instanceof xr))throw a;return sn(e,r,{orgId:o.orgId,code:a.code},`${n} would be refused: ${a.message}`)}}}function pC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Rewind step "${e.name}"`;if(!s.rewindGrant||!s.previewRewind)throw Qo(n);let o=$t.parse(e.config),i=s.rewindGrant(t.pipelineId,e);if("refusal"in i)return sn(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:"NOT_CONFIRMED"},Nn(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:Od(t),step:e.name,trigger:s.trigger??"manual"}},t.signal);return dn(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`:"")+`, ${vk(d.estimate)}. Nothing was written.`)}catch(d){if(!(d instanceof xr))throw d;return sn(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 Sk(s,e){s.wrapHandler("delay",()=>tC),s.wrapHandler("approval",()=>rC),s.wrapHandler("notification",()=>nC(e)),s.wrapHandler("backup",()=>oC(e)),s.wrapHandler("sync",()=>sC(e)),s.wrapHandler("seed",()=>cC(e)),s.wrapHandler("anonymize",()=>uC(e)),s.wrapHandler("checkpoint",()=>lC(e)),s.wrapHandler("rewind",()=>pC(e))}var Zo=new Map,kk=(s,e)=>`${s}::${e}`;async function Yt(s,e,t,r=Date.now){let n=kk(s,e),o=Zo.get(n);if(o&&r()-o.at<3e5)return o.value;let i=t();Zo.set(n,{at:r(),value:i});try{return await i}catch(a){throw Zo.get(n)?.value===i&&Zo.delete(n),a}}function Ok(s){let e=kk(s,"");for(let t of Zo.keys())t.startsWith(e)&&Zo.delete(t)}var gC=J({orgId:j(),detectedAt:j(),evidence:We(["connection","monitor","production"]),previousOrganizationId:j().optional(),organizationId:j().optional(),previousInstanceName:j().optional(),instanceName:j().optional(),sandboxName:j().optional(),reportedBy:j().optional()}),fC=J({organizationId:j(),instanceName:j().optional(),formerOrganizationIds:ve(j()),refreshes:ve(gC)}),Ik="sandbox-refresh:",hC="sandbox-refresh",Ak=10,mC=20,yC=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function Lp(s){return s!==void 0&&yC.test(s)?s.slice(0,15):void 0}function Tk(s){try{return new URL(s).hostname.toLowerCase()}catch{return}}function wC(s){let e=Tk(s.instanceUrl),t=".my.salesforce.com";return e?.endsWith(t)?e.slice(0,-t.length):void 0}function bC(s,e,t){let r=t.toLowerCase(),n=wC(s);return n&&Tk(e.instanceUrl)?.startsWith(`${n}--${r}.`)?!0:e.username.toLowerCase()===`${s.username.toLowerCase()}.${r}`}var Id=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=Lp(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 g=t.instanceName!==void 0&&t.instanceName!==a.instanceName;(!i||g)&&this.write(e,{...a,instanceName:t.instanceName??a.instanceName});return}if(a.formerOrganizationIds.includes(o))return;let[d,...c]=a.refreshes,u=d?.evidence==="production"&&d.organizationId===void 0?d:void 0,l={...u??{orgId:e,detectedAt:this.now().toISOString(),evidence:r},previousOrganizationId:a.organizationId,organizationId:o,previousInstanceName:a.instanceName,instanceName:t.instanceName};return this.write(e,{organizationId:o,instanceName:t.instanceName,formerOrganizationIds:[a.organizationId,...a.formerOrganizationIds].slice(0,mC),refreshes:(u?[l,...c]:[l,...a.refreshes]).slice(0,Ak)}),this.deps.log?.(`[sandbox-refresh] ${n.alias}: org ${a.organizationId} is now ${o} (${r})`),u||this.emit(l),l}noteCompletedRefresh(e){let t=this.deps.orgManager.getOrg(e.orgId);if(!t)return[];let r=[];for(let n of this.deps.orgManager.getAllOrgs()){if(n.orgType!=="Sandbox"||n.id===t.id||!bC(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,Ak)}),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=Lp(t);return r!==void 0&&this.refreshesOf(e).some(n=>n.organizationId===r)}baselineOf(e){let t=Lp(e.orgId);return t===void 0?void 0:{organizationId:t,formerOrganizationIds:[],refreshes:[]}}read(e){let t=this.deps.configStore.get(`${Ik}${e}`);if(t===void 0)return;let r=fC.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(`${Ik}${e}`,t,hC)}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 RC,writeFile as vC}from"node:fs/promises";import{homedir as SC}from"node:os";import{basename as Fp}from"node:path";async function kC(){let[s,e,t,r,n,o,i,a,d,c,u]=await Promise.all([import("./chunk-E3A3LOCY.mjs"),import("./chunk-HV7VPEXP.mjs"),import("./chunk-5M5FQ7RP.mjs"),import("./chunk-M2ABR4JM.mjs"),import("./chunk-FNJ4SGWO.mjs"),import("./chunk-5CRLRHOJ.mjs"),import("./chunk-NOBQTEQD.mjs"),import("./chunk-6ZLKIT3H.mjs"),import("./chunk-ZBAWJUG2.mjs"),import("./chunk-4CVUUVGJ.mjs"),import("./chunk-OPMO6I45.mjs")]);return{recoveryFactsOf:s.recoveryFactsOf,recoveryAckKeyOf:s.recoveryAckKeyOf,readAcks:s.readAcks,frozenDatasetDirOf:s.frozenDatasetDirOf,recoveryStatusOf:e.recoveryStatusOf,awaitingAddressesOf:t.awaitingAddressesOf,recoveryUsersOf:t.recoveryUsersOf,recoveryTestersKey:t.recoveryTestersKey,readSavedTesters:t.readSavedTesters,saveTesters:t.saveTesters,replacedRunOf:t.replacedRunOf,choicesKeyOf:t.choicesKeyOf,planSignatureOf:t.planSignatureOf,changingUsersOf:t.changingUsersOf,usersDoneOf:t.usersDoneOf,usersAuditObjectsOf:t.usersAuditObjectsOf,ObservedUsersRunStore:t.ObservedUsersRunStore,journalDirOf:r.journalDirOf,newestHandoffOf:r.newestHandoffOf,recoveryHandoffNoteOf:r.recoveryHandoffNoteOf,recoveryHandoffPathOf:r.recoveryHandoffPathOf,writeRecoveryHandoff:r.writeRecoveryHandoff,guardUsersOrg:n.guardUsersOrg,usersToRestoreOf:n.usersToRestoreOf,planUsersGated:n.planUsersGated,gatedPlanAnswerOf:n.gatedPlanAnswerOf,applyUsers:o.applyUsers,UsersRunStore:i.UsersRunStore,defaultUsersStoreRoot:i.defaultUsersStoreRoot,readAudits:a.readAudits,myDomainHostOf:d.myDomainHostOf,openCheckpointStore:c.openCheckpointStore,defaultCheckpointStoreRoot:c.defaultCheckpointStoreRoot,ReplayStore:u.ReplayStore,defaultReplayStoreRoot:u.defaultReplayStoreRoot}}var OC=new Set(["recovery:status","recovery:users:list","recovery:users:plan","recovery:users:apply","recovery:users:cancel","recovery:users:config:save","recovery:users:config:export","recovery:users:config:import","recovery:audit","recovery:handoff","recovery:handoff:open","recovery:ack"]),tt=class extends Error{constructor(t,r,n=!1,o){super(r);this.code=t;this.retryable=n;this.step=o;this.name="Refused"}code;retryable;step},Ek="SandForge writes and reads a users.json on the disk of the machine it runs on: pick a folder there.",IC={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(SC()),s),filters:{JSON:["json"]}});if(t!==void 0){if(t.scheme!=="file")throw new tt("INVALID_PAYLOAD",Ek);return t.fsPath}},async pickUsersImport(){let s=await import("vscode"),t=(await s.window.showOpenDialog({title:s.l10n.t("Import the testers list from a users.json"),openLabel:s.l10n.t("Import"),canSelectFiles:!0,canSelectFolders:!1,canSelectMany:!1,filters:{JSON:["json"]}}))?.[0];if(t!==void 0){if(t.scheme!=="file")throw new tt("INVALID_PAYLOAD",Ek);return t.fsPath}}},AC=async s=>{let e=await import("vscode");await e.window.showTextDocument(e.Uri.file(s),{preview:!1})};function TC(s,e,t){return{org:s,users:[],emailsToPeople:0,apiRequests:t,refusals:[e]}}function EC(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 _p(s,e){return s.length>=15&&s.slice(0,15)===e.slice(0,15)}var PC=4e3,Ad=class{constructor(e,t={}){this.deps=e;this.options=t;this.dialogs=t.dialogs??IC,this.openInEditor=t.openInEditor??AC,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(!OC.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=$(Vn,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=$(Tf,e,"recovery:error",this.deps);if(t)try{let r=this.registered(t.orgId),n=await this.modules(),o=this.deps.sandboxRefreshes,i=r.orgType==="Sandbox"?o?.refreshesOf(t.orgId)[0]:void 0,a=n.recoveryAckKeyOf(t.orgId,i,u=>o?.organizationIdOf(u)),d=n.readAcks(this.deps.configStore,a);t.what==="finish"?d.finishedAt=this.now().toISOString():t.what==="resume"?delete d.finishedAt:t.mark==="cleared"?delete d.steps[t.step]:d.steps[t.step]=t.mark,this.deps.configStore.set(a,If.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=$(Vn,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=$(Ju,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=$(Ju,e,"recovery:error",this.deps);if(!t)return;let{orgId:r}=t;if(this.running.has(r)){this.fail(e,new tt("FAILED","A run of the users of this org is under way from this window: wait for it to end. Nothing was read or written.",!0,"users"));return}let n=new AbortController;this.running.set(r,n);try{let o=await this.modules(),i=this.simulated.get(r);if(i===void 0||i.choices!==o.choicesKeyOf(t))throw new tt("ORG_CHANGED","No simulation of these choices was answered on this page: simulate them, then apply. Nothing was read or written.",!1,"users");let a=await this.reach(o,r,"users"),{answer:d,gated:c}=await this.planOf(o,a,t);if(o.planSignatureOf(d)!==i.signature)throw new tt("ORG_CHANGED",`${a.orgName} changed since the simulation: a run now would not do what it showed. Simulate again. Nothing was written.`,!1,"users");let u=d.refusals??[];if(c===void 0||u.length>0)throw new tt("FAILED",`${u.map(y=>y.message).join(" ")} Nothing was written.`.trim(),!1,"users");let l=await this.consultGuard(e,a,d);if(n.signal.aborted)throw this.recordUsersRun(e,r,"stopped",l),new tt("CANCELLED","Stopped before the first write: nothing was written.");let g=o.changingUsersOf(d),p=y=>{this.deps.broker.postToWebview(A(this.deps,e,"recovery:users:progress",{orgId:r,done:y,total:g}))};p(0);let f=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:Gu(t.config),store:f,signal:n.signal,...c.options})}catch(y){throw this.recordUsersRun(e,r,"failure",l),y}if(h.kind==="refused")throw this.recordUsersRun(e,r,"stopped",l),new tt("ORG_CHANGED",`${a.orgName} changed since the plan read it: ${(h.plan.refusals??[]).map(y=>y.message).join(" ")} Nothing was written.`,!1,"users");let m={...h.answer,apiRequests:a.typingRequests+a.org.requests()+c.outsideRequests};this.recordUsersRun(e,r,m.status,l,m,o),this.respond(e,"recovery:users:apply:response",{orgId:r,applied:m})}catch(o){this.fail(e,o,"users")}finally{this.running.delete(r),this.simulated.delete(r),this.changed(r)}}handleUsersCancel(e){let t=$(Vn,e,"recovery:error",this.deps);t&&this.running.get(t.orgId)?.abort()}async planOf(e,t,r){let{org:n,organization:o}=t,i=u=>t.typingRequests+n.requests()+u,a;if(r.replaces!==void 0){let u=await e.replacedRunOf(this.users(e),o.organizationId,r.replaces);if("refusal"in u)return{answer:TC(o,u.refusal,i(0))};a=u.record}let d=await e.planUsersGated({conn:t.conn,org:n,orgName:t.orgName,users:Gu(r.config),...a!==void 0?{previous:a}:{},acceptUserEmails:r.acceptUserEmails,acceptEmails:r.acceptEmails,acceptAutomation:r.acceptAutomation,voice:"page",now:this.now()});return{answer:e.gatedPlanAnswerOf(d,o,i(d.outsideRequests)),gated:d}}async consultGuard(e,t,r){let n=this.deps.infraServices?.productionGuard;if(!n)throw new tt("FAILED",Re.message,!1,"users");let o=Pe(t.registered),{updated:i,added:a,removed:d}=EC(r),c=[{operation:"delete",objectName:"PermissionSetAssignment, GroupMember",recordCount:d},{operation:"update",objectName:"User, UserLogin",recordCount:i},{operation:"insert",objectName:"PermissionSetAssignment, GroupMember",recordCount:a}].filter(l=>l.recordCount>0),u="allowed";for(let l of c){let g=await et(n,{orgId:t.registered.id,orgTier:o,module:"recovery",...l});if(u=Zn(u,g.decision),g.decision==="refused")throw this.recordUsersRun(e,t.registered.id,"stopped",u),new tt("FAILED",`Operation blocked by Production Guard: ${g.check.blockedReason??g.check.impactSummary} Nothing was written.`,!1,"users");if(g.decision==="declined")throw this.recordUsersRun(e,t.registered.id,"stopped",u),new tt("CANCELLED",`Production Guard asked before this run (${g.check.impactSummary}), and the answer was no. Nothing was written.`,!1,"users")}return u}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=$(Vu,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=$(Vu,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 vC(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:Fp(r)})}catch(n){this.fail(e,this.pathless(n,r),"users")}}async handleConfigImport(e){let t=$(Vn,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=Fp(r),i;try{i=JSON.parse(await RC(r,"utf8"))}catch(c){throw new tt("INVALID_PAYLOAD",`${o} does not read as JSON (${I(c)}). Nothing was kept.`,!1,"users")}let a=Of.safeParse(i);if(!a.success){let c=a.error.issues.map(u=>{let l=u.path.map(String).join(".");return l===""?u.message:`${l}: ${u.message}`});throw new tt("INVALID_PAYLOAD",`${o} is not a users.json of sandforge users --config: ${c.join("; ")}. Nothing was kept.`,!1,"users")}let d=await this.modules();d.saveTesters(this.deps.configStore,d.recoveryTestersKey(d.myDomainHostOf(n.instanceUrl),t.orgId),a.data,this.now()),this.respond(e,"recovery:users:config:import:response",{status:"read",orgId:t.orgId,fileName:o,config:a.data}),this.changed(t.orgId)}catch(n){this.fail(e,this.pathless(n,r),"users")}}async handleAudit(e){let t=$(Af,e,"recovery:error",this.deps);if(t)try{let r=await this.modules(),n=await this.reach(r,t.orgId),{conn:o,organization:i}=n,a=r.myDomainHostOf(o.instanceUrl)??r.myDomainHostOf(n.registered.instanceUrl),d=await r.readAudits({transport:{request:l=>o.request(l)},journalDir:this.journalDir(r),now:this.now},{org:{organizationId:i.organizationId,kind:i.kind,alias:n.orgName,...a!==void 0?{host:a}:{}},asked:t.asked,save:t.save});for(let l of d.notes)this.deps.log(`[INFO] recovery:audit: ${l}`);let c=this.audited.get(t.orgId),u=c!==void 0&&_p(c.organizationId,i.organizationId)?c.audit:{};this.audited.set(t.orgId,{organizationId:i.organizationId,audit:{...u,...d.result.deliverability!==void 0?{deliverability:d.result.deliverability}:{},...d.result.schedules!==void 0?{schedules:d.result.schedules}:{},...d.result.endpoints!==void 0?{endpoints:d.result.endpoints}:{}}}),this.respond(e,"recovery:audit:response",{orgId:t.orgId,audit:d.result}),this.changed(t.orgId)}catch(r){this.fail(e,r)}}async handleHandoff(e){let t=$(Vn,e,"recovery:error",this.deps);if(t)try{let r=this.registered(t.orgId),n=await this.modules(),o=await this.statusOf(t.orgId),i=o.organizationId;if(i===void 0)throw new tt("NOT_CONNECTED",`The org ${o.alias} is now is not known yet: only its production's history reported its refresh. Connect to it once, then write the note. Nothing was written.`,!0,"handoff");let a=this.now().toISOString(),d=this.audited.get(t.orgId),c=n.recoveryHandoffNoteOf({status:o,org:{organizationId:i,kind:r.orgType==="Sandbox"?"sandbox":r.orgType==="Scratch"?"scratch":"developer",alias:o.alias,...o.myDomainHost!==void 0?{host:o.myDomainHost}:{}},...d!==void 0&&_p(d.organizationId,i)?{audits:d.audit}:{},at:a,...this.options.sandforgeVersion!==void 0?{sandforgeVersion:this.options.sandforgeVersion}:{}}),u=n.recoveryHandoffPathOf(this.journalDir(n),{organizationId:i,at:a});await n.writeRecoveryHandoff(u,c);try{await this.openInEditor(u)}catch(l){this.deps.log(`[WARN] recovery:handoff: the note was not opened: ${I(l)}`)}this.respond(e,"recovery:handoff:response",{orgId:t.orgId,path:u}),this.changed(t.orgId)}catch(r){this.fail(e,r,"handoff")}}async handleHandoffOpen(e){let t=$(Vn,e,"recovery:error",this.deps);if(t)try{let r=await this.modules(),n=await this.statusOf(t.orgId),o=n.organizationId!==void 0?await r.newestHandoffOf(this.journalDir(r),n.organizationId):void 0;if(o===void 0)throw new tt("NOTE_NOT_FOUND",`No handoff note of ${n.alias} as it is now is kept on this machine: write one. Nothing was written.`,!1,"handoff");try{await this.openInEditor(o.path)}catch(i){throw new tt("FAILED",`The handoff note could not be opened in the editor: ${I(i)}`,!0,"handoff")}this.respond(e,"recovery:handoff:open:response",{orgId:t.orgId,path:o.path})}catch(r){this.fail(e,r,"handoff")}}modules(){return this.loaded??=kC(),this.loaded}async openedCheckpoints(e){this.checkpoints??=Promise.resolve().then(()=>{let t=e.openCheckpointStore({root:e.defaultCheckpointStoreRoot()});if("store"in t)return t.store;throw new tt("FAILED",`The checkpoints cannot be read in ${t.refusal.path}: ${t.refusal.reason}.`)});try{return await this.checkpoints}catch(t){throw this.checkpoints=void 0,t}}users(e){return this.usersStore??=new e.UsersRunStore({root:e.defaultUsersStoreRoot()}),this.usersStore}replays(e){return this.replayStore??=new e.ReplayStore({root:e.defaultReplayStoreRoot()}),this.replayStore}journalDir(e){return this.options.journalDir??e.journalDirOf()}factsDeps(e){let t=this.deps.sandboxRefreshes;return{configStore:this.deps.configStore,orgOf:r=>this.deps.orgManager.getOrg(r),refreshesOf:r=>t?.refreshesOf(r)??[],organizationIdOf:r=>t?.organizationIdOf(r),checkpoints:()=>this.openedCheckpoints(e),replays:()=>this.replays(e),users:()=>this.users(e),journalDir:this.journalDir(e),frozenDatasetDir:()=>e.frozenDatasetDirOf(this.deps.configStore),usersListed:(r,n)=>{let o=this.listed.get(r);return o!==void 0&&_p(o.organizationId,n)?o.total:void 0}}}async statusOf(e){let t=await this.modules(),r=await t.recoveryFactsOf(this.factsDeps(t),e);if("refused"in r)throw this.registered(e),new tt(r.refused,`${e} is not an org SandForge brings back into service.`);return t.recoveryStatusOf(r.facts)}registered(e,t){let r=this.deps.orgManager.getOrg(e);if(r===void 0)throw new tt("ORG_NOT_FOUND",`No org is registered in SandForge as ${e}: connect it on the Organizations page.`,!1,t);if(!vo(r))throw new tt("NOT_A_DEVELOPMENT_ORG",`${ye(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=ye(n,n.username),i;try{i=await q(t,this.deps.orgRegistry,this.deps.orgManager)}catch(d){throw new tt("NOT_CONNECTED",`${o} could not be reached (${I(d)}): reconnect it on the Organizations page. Nothing was read or written.`,!0,r)}let a=await e.guardUsersOrg(i,{orgName:o,registered:n});if(!a.allowed){let{refusal:d}=a;throw new tt(d.code==="PRODUCTION"?"NOT_A_DEVELOPMENT_ORG":"NOT_CONNECTED",d.message,d.code==="ORG_UNTYPED",r)}return{registered:n,orgName:o,conn:i,org:a.org,organization:a.organization,typingRequests:a.typingRequests}}changed(e){for(let t of[...this.statusListeners])try{t(e)}catch(r){this.deps.log(`[WARN] recovery: a listener of the steps failed: ${I(r)}`)}}respond(e,t,r){let n=A(this.deps,e,t,r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}pathless(e,t){return e instanceof tt||t===void 0?e:new Error(I(e).replaceAll(t,Fp(t)))}fail(e,t,r){let n=t instanceof tt?t:new tt("FAILED",I(t),!0,r),o=n.message.trim()===""?n.code:n.message,i=n.step??r;T(this.deps,e.type,"recovery:error",e,new Error(o.slice(0,PC)),{code:n.code,retryable:n.retryable,...i!==void 0?{extraPayload:{step:i}}:{}})}};var CC=5,$C=5e3,xC=3e4,DC=J({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()}),NC=J({access_token:j().min(1),refresh_token:j().min(1).optional(),instance_url:j().min(1).max(2048)}),Pk=J({error:j().min(1),error_description:j().optional()}),so=class extends Error{constructor(){super("Sign-in cancelled."),this.name="DeviceLoginCancelledError"}},Td=class extends Error{constructor(e){super(e),this.name="RefusedByHostError"}};function jC(s,e){return new Promise((t,r)=>{if(e?.aborted){r(new so);return}let n=()=>{clearTimeout(o),r(new so)},o=setTimeout(()=>{e?.removeEventListener("abort",n),t()},s);e?.addEventListener("abort",n,{once:!0})})}function $k(s){let e=jn(s);if(!(!e.ok||e.url.username!==""||e.url.password!=="")&&!(e.url.port!==""||!ih(e.url.hostname)))return e.url}function Ck(s){return`Salesforce refused the device sign-in: ${s.error_description?`${s.error_description} (${s.error})`:s.error}`}var Ed=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??jC}async authorize(e,t,r){let n=await this.post(e,{response_type:"device_code",client_id:t},r),o=Pk.safeParse(n);if(o.success)throw new Error(Ck(o.data));let i=DC.safeParse(n);if(!i.success)throw new Error("Salesforce answered the device sign-in without a usable code.");let a=$k(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,pf);return{deviceCode:i.data.device_code,userCode:i.data.user_code,verificationUri:a.href,intervalMs:(i.data.interval??CC)*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 so;if(c instanceof Td)throw c;continue}let d=Pk.safeParse(a);if(d.success){if(d.data.error==="authorization_pending")continue;if(d.data.error==="slow_down"){o+=$C;continue}throw new Error(Ck(d.data))}return MC(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 so;let n=AbortSignal.timeout(xC),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 so:a}let i=await o.text();try{return JSON.parse(i)}catch{throw new Td(`Salesforce answered HTTP ${o.status} with a page instead of JSON. Check the login URL.`)}}};function MC(s){let e=NC.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=$k(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 jr=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 LC,readdir as FC}from"node:fs/promises";import{join as xk}from"node:path";var _C=/^[^.][^@/\\]*@[^/\\]+\.json$/;async function Dk(s,e=Date.now()){let t=xk(s,".sfdx"),r;try{r=await FC(t)}catch{return 0}let n=new Set;return await Promise.all(r.filter(o=>_C.test(o)&&!o.endsWith(".partial.json")).map(async o=>{let i=await UC(xk(t,o),e);i&&n.add(i)})),n.size}async function UC(s,e){try{let t=JSON.parse(await LC(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 HC}from"node:os";var BC=new Set(["org:list","org:connect","org:connect:cancel","org:disconnect","org:select","org:update","org:open-in-browser","org:cli-status"]),Nk=15e3,jk="The Salesforce CLI holds no connected org yet. Use Log in with your browser on the Organizations page: it opens the Salesforce login page.",Pd=class{constructor(e,t={}){this.deps=e;this.browser=t.browser??new jr,this.deviceLogin=t.deviceLogin??new Ed,this.countCliOrgs=t.countCliOrgs??(()=>Dk(HC())),this.connectTo=t.connectTo??(r=>mh(r))}deps;browser;deviceLogin;countCliOrgs;connectTo;pendingSignIns=new Map;async handle(e){if(!BC.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=$(Gy,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){T(this.deps,"org:connect","org:error",e,new Error(t),{code:r,retryable:!1})}notifyCliMissing(e){Ie(this.deps,"error","Salesforce CLI",`${ms} ${e}`,{actions:[{label:"Install the CLI",command:"sf-cli-install",url:lf}]})}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,ms,"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",jk,{autoDismissMs:null,code:"NO_CLI_ORGS"}),this.failConnect(e,jk,"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=I(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=>`${ye(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 ph(this.connectTo({instanceUrl:o,accessToken:n,version:t.metadata.apiVersion}).then(u=>Yi(u)),Nk,`the org did not answer within ${Nk/1e3} s`),a=Kn({isSandbox:i.sandbox,edition:i.edition}),{safetyTier:d,color:c}=qr(a);return a!==t.orgType&&this.deps.log(`[INFO] org:import: ${t.alias} says it is ${i.edition??(i.sandbox?"a sandbox":"no edition")}; typed ${a}`),{credentials:r,org:{...t,orgType:a,safetyTier:d,appearance:{...t.appearance,color:c},metadata:{...t.metadata,edition:i.edition??""}}}}catch(i){return this.deps.log(`[WARN] org:import: ${t.alias} gave no edition and could not be asked what it is (${I(i)}): typed Production until it is reconnected`),e}}refreshedEntryFor(e){let t=this.deps.sandboxRefreshes;if(!t||this.deps.orgManager.getOrg(e.id))return;let r=e.username.toLowerCase();return this.deps.orgManager.getAllOrgs().find(n=>n.username.toLowerCase()===r&&t.wasRefreshedTo(n.id,e.orgId))}async handleUsernamePassword(e,t){if(!t.username||!t.password){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=Kn({isSandbox:o.isSandbox,edition:o.orgType}),{safetyTier:a,color:d}=qr(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:bo.DEFAULT_API_VERSION,edition:o.orgType,features:[]},status:"connected",lastConnected:new Date().toISOString(),tags:[]},u=this.deps.authProvider.buildConnectionConfig({method:"usernamePassword",loginUrl:r,username:t.username,password:t.password,securityToken:t.securityToken},n);await this.deps.orgRegistry.saveOrg(c,u);let l=A(this.deps,e,"org:statusChanged",{orgId:c.id,status:"connected"});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`),Ie(this.deps,"success","Connected",`${ye(c)} connected.`)}catch(o){let i=I(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=Xi(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,ms,"SF_CLI_NOT_FOUND");return}let o=t.alias??"",i=await this.deps.sfdxBridge.loginWeb(o,r);await this.importSignedInOrg(e,i,"OAuth")}catch(n){let o=I(n);this.deps.log(`[ERR] org:oauth-web: ${o}`),Ie(this.deps,"error","OAuth Failed",o),this.failConnect(e,o,"OAUTH_WEB_FAILED")}}async handleJwt(e){let t=$(Jy,e,"org:error",this.deps);if(!t)return;let r=this.resolveLoginUrl(e,t);if(r)try{if(!await this.requireCli(e,"JWT sign-in runs through it."))return;let n=await this.deps.sfdxBridge.loginJwt({username:t.username,clientId:t.clientId,keyFile:t.jwtKeyFile,loginUrl:r,alias:t.alias||void 0});await this.importSignedInOrg(e,n,"JWT")}catch(n){let o=I(n);this.deps.log(`[ERR] org:jwt: ${o}`),Ie(this.deps,"error","JWT Sign-in Failed",o),this.failConnect(e,o,"JWT_LOGIN_FAILED")}}async handleOAuthDevice(e){let t=$(Vy,e,"org:error",this.deps);if(!t)return;let r=this.resolveLoginUrl(e,t);if(!r)return;let n=new AbortController;this.pendingSignIns.set(e.id,n);try{if(!await this.requireCli(e,"The device sign-in hands its session to it."))return;let o=await this.deviceLogin.authorize(r,t.clientId,n.signal),i=A(this.deps,e,"org:device-code",{userCode:o.userCode,verificationUri:o.verificationUri,expiresAt:o.expiresAt});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`);let a=await this.browser.open(o.verificationUri);a.status==="error"&&this.deps.log(`[WARN] org:oauth-device: verification page not opened: ${a.message}`);let d=await this.deviceLogin.awaitApproval(r,t.clientId,o,n.signal);if(n.signal.aborted)throw new Error("Sign-in cancelled.");let c=await this.deps.sfdxBridge.loginWithRefreshToken({clientId:t.clientId,refreshToken:d.refreshToken,instanceUrl:d.instanceUrl,alias:t.alias||void 0});await this.importSignedInOrg(e,c,"Device Sign-in")}catch(o){if(n.signal.aborted){this.deps.log(`[INFO] org:oauth-device cancelled id=${e.id}`),this.failConnect(e,"Sign-in cancelled.","CANCELLED");return}let i=I(o);this.deps.log(`[ERR] org:oauth-device: ${i}`),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=$(Ky,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,ms,"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,`${ye(n.org)} connected.`),this.ackConnect(e,o??n.org.id)}async handleOrgDisconnect(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Xy,e,"org:error",this.deps);if(!t)return;let r=t;Io().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=$(Yy,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){T(this.deps,"org:update","org:error",e,new Error(`Unknown org: ${t.orgId}`),{code:"ORG_NOT_FOUND",retryable:!1});return}try{this.deps.orgRegistry.updateOrgMetadata({...r,alias:t.alias,appearance:{...r.appearance,color:t.color},tags:t.tags,...t.staging!==void 0?{staging:t.staging}:{}})}catch(o){T(this.deps,"org:update","org:error",e,o,{code:"ORG_UPDATE_FAILED",retryable:!0});return}let n=A(this.deps,e,"org:list:response",{orgs:this.deps.orgManager.getAllOrgs()});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`),this.syncOrgState()}async handleOpenInBrowser(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Qy,e,"org:error",this.deps);if(!t)return;let r=this.deps.orgManager.getOrg(t.orgId);if(!r){T(this.deps,"org:open-in-browser","org:error",e,new Error(`No registered org has the id "${t.orgId}".`),{code:"ORG_NOT_FOUND",retryable:!1});return}let n=jn(r.instanceUrl);if(!n.ok){let a=n.reason==="not-https"?`its instance URL must use HTTPS, got "${n.protocol}"`:"its instance URL is not a valid URL";T(this.deps,"org:open-in-browser","org:error",e,new Error(`Cannot open "${ye(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 qC(s){let e=yf.safeParse(s.services?.getSandforgeSetting?.("forge.graphView","auto"));return e.success?e.data:"auto"}var WC=new Set(["settings:get","settings:update","telemetry:status","telemetry:toggle"]),Cd=class{constructor(e){this.deps=e}deps;async handle(e){if(!WC.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:qC(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=$(ew,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=$(tw,e,"settings:error",this.deps);if(!t)return;let{enabled:r}=t;if(!this.deps.services?.setSandforgeSetting){let n=A(this.deps,e,"telemetry:toggle:response",{success:!1,enabled:this.deps.services?.getSandforgeSetting?.("telemetry",!1)??!1,error:"Settings backend not available \u2014 telemetry preference was not persisted."});this.deps.broker.postToWebview(n);return}try{await this.deps.services.setSandforgeSetting("telemetry",r);let n=this.deps.services.getSandforgeSetting?.("telemetry",r)??r,o=A(this.deps,e,"telemetry:toggle:response",{success:!0,enabled:n});this.deps.broker.postToWebview(o)}catch(n){this.deps.log(`[ERR] telemetry:toggle: ${I(n)}`);let o=A(this.deps,e,"telemetry:toggle:response",{success:!1,enabled:this.deps.services.getSandforgeSetting?.("telemetry",!1)??!1,error:I(n)});this.deps.broker.postToWebview(o)}}};var Up={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"}},Hp=1,Mk=.15,zC=.55;function Lk(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 GC(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 Bp(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 Fk(s){switch(s){case"up":return"degrading";case"down":return"improving";case"stable":return"stable"}}function _k(s){return s.direction!=="up"?0:Math.min(15,Math.max(0,Math.abs(s.changePercent)*.5))}function ii(s){return s>=70?"healthy":s>=40?"warning":"critical"}function Uk(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 Hk(s){let e=s.max-s.remaining;return`${s.usedPercent}% used (${e.toLocaleString()} / ${s.max.toLocaleString()})`}var $d=class{calculate(e){let t=[],r=this.countOptionalDimensions(e),n=this.computeLimitsWeightMultiplier(r);this.addCoreLimitFactors(e,t,n),this.addRemainingLimitFactors(e,t,n);let o=this.computeOptionalDimensionWeight(r);this.addMetadataDimension(e,t,o),this.addCoverageDimension(e,t,o),this.addSecurityDimension(e,t,o);let{weightedSum:i,totalWeight:a}=t.reduce((p,f)=>({weightedSum:p.weightedSum+f.score*f.weight,totalWeight:p.totalWeight+f.weight}),{weightedSum:0,totalWeight:0}),d=a>0?Math.round(i/a):100,c=this.scoreToOverallStatus(d),l=[...t].sort((p,f)=>p.score-f.score).filter(p=>p.status!=="healthy").slice(0,3),g=this.buildSummary(c,l);return{overallScore:d,overallStatus:c,factors:t,summary:g,topRisks:l}}countOptionalDimensions(e){let t=0;return(e.metadataCounts!==void 0||e.orgInfo!==void 0)&&t++,e.codeCoverage!==void 0&&t++,e.securitySettings!==void 0&&t++,t}computeLimitsWeightMultiplier(e){if(e===0)return Hp;let t=e*Mk;return Math.max(zC,Hp-t)}computeOptionalDimensionWeight(e){return e===0?0:Mk}addCoreLimitFactors(e,t,r){for(let[n,o]of Object.entries(Up)){let i=e.limits.find(g=>g.name===n);if(!i)continue;let a=Lk(i.usedPercent),d=this.fetchTrendData(e,n),c=d?Fk(d.direction):"stable",u=d?_k(d):0,l=Math.max(0,Math.round(a-u));t.push({name:i.name,category:o.category,score:l,weight:o.weight*r,status:ii(l),detail:Hk(i),recommendation:Uk(i.name,i.usedPercent),trend:c})}}addRemainingLimitFactors(e,t,r){let n=new Set(Object.keys(Up)),o=e.limits.filter(c=>!n.has(c.name)&&c.usedPercent>0);if(o.length===0)return;let i=Object.values(Up).reduce((c,u)=>c+u.weight,0),d=Math.max(0,(Hp-i)*r)/o.length;for(let c of o){let u=Lk(c.usedPercent),l=this.fetchTrendData(e,c.name),g=l?Fk(l.direction):"stable",p=l?_k(l):0,f=Math.max(0,Math.round(u-p));t.push({name:c.name,category:"limits",score:f,weight:d,status:ii(f),detail:Hk(c),recommendation:Uk(c.name,c.usedPercent),trend:g})}}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(Bp(n,50,500)*.4+Bp(o,200,2e3)*.3+Bp(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:ii(a),detail:d,recommendation:c,trend:"stable"})}addCoverageDimension(e,t,r){if(e.codeCoverage===void 0)return;let n=GC(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:ii(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:ii(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 JC=ve(J({version:j()}));function Bk(s){let e=JC.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 VC(s){if(!s)return;let e=new Date(s);return Number.isNaN(e.getTime())?void 0:e.toISOString()}var xd=class{cache=new Map;cacheTtlMs;constructor(e=300*1e3){this.cacheTtlMs=e}async fetch(e,t){let r=this.cache.get(e);if(r&&Date.now()-r.fetchedAt<this.cacheTtlMs)return r.data;let[n,o,i,a,d,c]=await Promise.all([t.latestApiVersion(),t.queryOrg(),t.queryCount("SELECT COUNT() FROM User WHERE IsActive = true"),t.queryCount("SELECT COUNT() FROM EntityDefinition WHERE DeploymentStatus != null AND QualifiedApiName LIKE '%__c'"),t.queryCount("SELECT COUNT() FROM ApexClass"),t.queryCount("SELECT COUNT() FROM FlowDefinitionView WHERE IsActive = true")]),u=o.namespacePrefix||void 0,l=VC(o.createdDate),g={name:o.name,orgId:o.orgId,type:o.type,edition:o.edition,instanceName:o.instanceName,apiVersion:n,userCount:i,customObjectCount:a,apexClassCount:d,flowCount:c,...u!==void 0?{namespacePrefix:u}:{},...l!==void 0?{createdDate:l}:{}};return this.cache.set(e,{data:g,fetchedAt:Date.now()}),g}clearCache(e){e?this.cache.delete(e):this.cache.clear()}};function qk(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 qp=1440*60*1e3,Wk=7*qp,KC=500*1024,XC=900*1e3,YC=2,QC="trends",ZC=new Set(_i),e$=qp,Nd=class{configStore;lastSaveTimestamps=new Map;constructor(e){this.configStore=e}trendKey(e){return`trend:${e}`}record(e,t){let r=Date.now();this.isRateLimited(e,r)||this.append(e,this.read(e),t,r)}recordAndGetTrends(e,t,r){let n=Date.now(),o=this.read(e),a=(this.isRateLimited(e,n)?o:this.append(e,o,t,n)).filter(u=>u.timestamp>=Dd(n-Wk)),d=a.filter(u=>u.timestamp>=Dd(n-e$)),c={};for(let u of r)c[u]=this.computeTrend(u,a,d);return c}getHistory(e,t=qp){let r=Dd(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)<XC}append(e,t,r,n){let o=Dd(n-Wk),i=[...t,r].filter(d=>d.timestamp>=o).map(d=>({...d,limits:d.limits.filter(c=>ZC.has(c.name))})),a=this.trimToSizeLimit(i);return this.configStore.set(this.trendKey(e),a,QC),this.lastSaveTimestamps.set(e,n),a}computeTrend(e,t,r){let{values:n,timestamps:o}=zk(e,t),{values:i}=zk(e,r);if(i.length<2)return{limitName:e,direction:"stable",changePercent:0,sparklineData:n,timestamps:o};let a=i[0],d=i[i.length-1],c=d-a,u;Math.abs(c)<=YC?u="stable":c>0?u="up":u="down";let l;if(u==="up"&&d<100){let g=this.getTimeSpanMs(r);if(g>0){let p=c/g;if(p>0){let h=(100-d)/p;l=Math.round(h/(3600*1e3)*10)/10}}}return{limitName:e,direction:u,changePercent:Math.round(c*10)/10,predictedTimeToLimit:l,sparklineData:n,timestamps:o}}getTimeSpanMs(e){if(e.length<2)return 0;let t=new Date(e[0].timestamp).getTime();return new Date(e[e.length-1].timestamp).getTime()-t}trimToSizeLimit(e){let t=[...e];for(;t.length>0&&!(new TextEncoder().encode(JSON.stringify(t)).length<=KC);)t.shift();return t}};function Dd(s){return new Date(s).toISOString()}function zk(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 jd=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||!t$(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 t$(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 es="alert:state:",Wp="alerts";var Md=class{constructor(e){this.configStore=e}configStore;saveAlerts(e){this.configStore.set(`${es}active`,e,Wp)}loadAlerts(){let e=this.configStore.get(`${es}active`);return Array.isArray(e)?e:[]}saveDefinitions(e){this.configStore.set(`${es}definitions`,e,Wp)}loadDefinitions(){let e=this.configStore.get(`${es}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(`${es}history`,i,Wp)}loadHistory(){let e=this.configStore.get(`${es}history`);return Array.isArray(e)?e:[]}};var zp=[{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 Ld=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 Fd=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 _d=class{fetchLogs;analyses=new Map;truncatedCache=new Map;constructor(e){this.fetchLogs=e}analyze(e){let t=r$(e),r=n$(e),n=o$(e),o=e.durationMs,i=s$(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 r$(s){return Math.min(Math.floor(s.logSize/500),100)}function n$(s){return Math.min(Math.floor(s.logSize/1e3),150)}function o$(s){return Math.min(s.logSize*10,6e6)}function s$(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 i$=new Set(xf);function Jk(s){return typeof s=="string"&&i$.has(s)?s:"Unknown"}function a$(){let s=new Map;return{load:e=>s.get(e),save:(e,t)=>{s.set(e,t)}}}function Gk(s){return`${s.sandboxName}:${s.refreshDate}`}var Ud=class{querySandboxes;onRefreshDetected;seen;refreshCache=new Map;supportedCache=new Map;truncatedCache=new Map;constructor(e,t,r=a$()){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(Gk(c))||this.onRefreshDetected?.(c)}let a=o.map(Gk);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=>Df(r.status))}};var Hd=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 Vk=new Set(["Queued","Processing"]),Bd=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=>Vk.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=>Vk.has(r.status)).length,completed:t.filter(r=>r.status==="Completed").length,failed:t.filter(r=>r.status==="Failed").length}}};var d$=3e4,c$=1440*60*1e3,Kk=100,Xk=50,Yk=20,Qk="sandbox-process-seen:";function u$(s){return{load:e=>{let t=s.get(`${Qk}${e}`);return Array.isArray(t)?t.filter(r=>typeof r=="string"):void 0},save:(e,t)=>{s.set(`${Qk}${e}`,t,"sandbox-refresh")}}}function l$(s){return s instanceof Oo?s.code==="ORG_AUTH_EXPIRED":dh(s)||ol(s)!==void 0}function ai(s){let e=ol(s);return e!==void 0&&!(s instanceof Oo)?`the org could not be reached (${e})`:I(s)}function Zk(s){let e=new Nd(s.configStore),t=async(v,w,C)=>{try{return await C(await s.getConnection(v))}catch(k){if(!l$(k))throw k;s.log(`[WARN] monitor:${w} ${v}: ${ai(k)}; read again on a new connection`);try{return await C(await s.getConnection(v,{again:!0}))}catch(E){throw E instanceof Oo&&E.code==="ORG_TEMPORARILY_UNREACHABLE"?k:E}}},r=new Md(s.configStore),n=new jd(v=>{s.log(`[ALERT] ${v.severity}: ${v.message}`);let w=v.severity==="critical"?"error":"warning";s.notify(w,v.message),r.saveAlerts(n.getActiveAlerts())}),o=r.loadDefinitions(),i=o.length>0?o:zp;for(let v of i)n.addDefinition(v);o.length===0&&r.saveDefinitions(zp);let a=r.loadAlerts();n.restoreAlerts(a);let d=new Ld(async(v,w)=>{let C=await s.getConnection(v),{records:k,truncated:E}=await Cs(C,`SELECT Id, Operation, Status, DurationMilliseconds, LogLength, StartTime, LogUser.Username FROM ApexLog WHERE Status != 'Success' AND StartTime > ${w} ORDER BY StartTime DESC LIMIT ${Xk}`,Xk);return xe(C.limitInfo,"monitor:error-logs apexLog"),{records:k.map(x=>({id:x.Id,errorType:x.Status,message:`${x.Operation} - ${x.Status}`,timestamp:x.StartTime,user:x.LogUser?.Username??void 0,context:x.Operation})),truncated:E}}),c=async(v,w)=>{let C=await v.query(`SELECT COUNT() FROM ApexLog WHERE Status != 'Success' AND StartTime > ${w}`);return xe(v.limitInfo,"monitor:refresh apexLogCount"),C.totalSize},u=new Fd(async v=>{let w=await s.getConnection(v),{records:C,truncated:k}=await Cs(w,`SELECT Id, UsersId, Users.Username, LoginType, SessionType, CreatedDate, SourceIp FROM AuthSession ORDER BY CreatedDate DESC LIMIT ${Kk}`,Kk);return xe(w.limitInfo,"monitor:sessions authSession"),{records:C.map(E=>({sessionId:E.Id,userId:E.UsersId,username:E.Users?.Username??E.UsersId,sessionType:E.SessionType??E.LoginType??"Unknown",loginTime:E.CreatedDate,sourceIp:E.SourceIp??""})),truncated:k}}),l=new _d(async(v,w)=>{let C=await s.getConnection(v),{records:k,truncated:E}=await Cs(C,`SELECT Id, Operation, Status, DurationMilliseconds, LogLength, StartTime, LogUser.Username FROM ApexLog ORDER BY StartTime DESC LIMIT ${w}`,w);return xe(C.limitInfo,"monitor:apex-insights apexLog"),{records:k.map(x=>({id:x.Id,operation:x.Operation??"Unknown",status:x.Status,durationMs:x.DurationMilliseconds??0,logSize:x.LogLength??0,startTime:x.StartTime,user:x.LogUser?.Username??"Unknown"})),truncated:E}}),g=new Set,p=new Ud(async v=>{if(g.has(v))return{supported:!1,events:[],truncated:!1};let w=await s.getConnection(v),C;try{C=await Cs(w,`SELECT Id, SandboxName, Status, CreatedDate, Description FROM SandboxProcess ORDER BY CreatedDate DESC LIMIT ${Yk}`,Yk)}catch(k){let E=k instanceof Error?k.message:String(k);if(E.includes("SandboxProcess")&&E.includes("not supported"))return g.add(v),{supported:!1,events:[],truncated:!1};throw k}return xe(w.limitInfo,"monitor:sandbox-refresh sandboxProcess"),{supported:!0,events:C.records.map(k=>({orgId:v,sandboxName:k.SandboxName??"Unknown",refreshDate:k.CreatedDate,status:Jk(k.Status),sourceOrg:k.Description??void 0})),truncated:C.truncated}},v=>s.onSandboxRefreshCompleted?.(v),u$(s.configStore)),f=new Map,h=async(v,w)=>{let C=f.get(v);if(C&&Date.now()-C.fetchedAt<d$)return C.data;let k=await w.request(`/services/data/${Ro}/limits`);return f.set(v,{data:k,fetchedAt:Date.now()}),k},m=async v=>{try{let C=(await t(v,"apiLimits",x=>h(v,x))).DailyApiRequests;if(!C||!C.Max)return{name:"apiLimits",status:"unknown",score:0,message:"No API limit reported"};let k=Math.round((C.Max-C.Remaining)/C.Max*100);return{name:"apiLimits",status:k>80?"critical":k>60?"warning":"ok",score:100-k,message:`API usage at ${k}%`,percent:k}}catch(w){return{name:"apiLimits",status:"unknown",score:0,message:`Unable to fetch limits: ${ai(w)}`}}},y=async v=>{try{let C=(await t(v,"storage",x=>h(v,x))).DataStorageMB;if(!C||!C.Max)return{name:"storage",status:"unknown",score:0,message:"No storage limit reported"};let k=Math.round((C.Max-C.Remaining)/C.Max*100);return{name:"storage",status:k>85?"critical":k>70?"warning":"ok",score:100-k,message:`Storage usage at ${k}%`,percent:k}}catch(w){return{name:"storage",status:"unknown",score:0,message:`Unable to fetch storage: ${ai(w)}`}}},R=async v=>{let w;try{let E=new Date(Date.now()-c$).toISOString();w=await t(v,"recentErrors",x=>c(x,E))}catch(E){return{name:"recentErrors",status:"unknown",score:0,message:`Unable to fetch error logs: ${ai(E)}`}}let C=Math.max(0,100-w*5);return{name:"recentErrors",status:w>10?"critical":w>3?"warning":"ok",score:C,count:w,message:`${w} recent errors`}},S=async v=>{let w=await Lt(v,`SELECT Id, JobType, Status, NumberOfErrors, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${mn.monitorJobs}`);return xe(v.limitInfo,"monitor:refresh asyncJobs"),w.map(C=>({id:C.Id,jobType:C.JobType??"Batch",status:C.Status,createdBy:C.CreatedById,createdDate:C.CreatedDate,failedRecords:C.NumberOfErrors}))},b=new Bd(v=>t(v,"activeJobs",S)),O=async v=>{try{await b.fetch(v);let w=b.getJobStats(v),C=Math.max(0,100-w.failed*10);return{name:"activeJobs",status:w.failed>5?"critical":w.failed>0?"warning":"ok",score:C,count:w.failed,outOf:w.total,message:`${w.active} active, ${w.failed} failed of ${w.total} recent jobs`}}catch(w){return{name:"activeJobs",status:"unknown",score:0,message:`Unable to fetch jobs: ${ai(w)}`}}},P=new Hd([m,y,R,O]);return{trendStorage:e,alertStateStore:r,alertEngine:n,errorLogMonitor:d,userSessionMonitor:u,apexLogAnalyzer:l,sandboxRefreshTracker:p,healthCheck:P,healthSignals:{apiLimits:m,storage:y,recentErrors:R,activeJobs:O},getOrFetchLimits:h,forgetOrg:v=>{f.delete(v)}}}var eO=25e3,tO=20,p$=20,g$=20,f$=500,oO=`SELECT Id, JobType, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${mn.monitorJobs}`,h$=`SELECT Id, JobType, Status, NumberOfErrors, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${mn.monitorJobs}`,m$=new Set([oO,h$]),y$=new Set(["Queued","Preparing","Processing"]),w$=new Set(["BatchApex","Queueable","Future"]),di=3600*1e3,rO=di,nO=3;function Gp(s){let e=Math.floor(s/60),t=s%60;return e>0?`${e}h${String(t).padStart(2,"0")}m`:`${t}m`}function b$(s,e){return s.status===e.status&&s.batchesProcessed===e.batchesProcessed&&s.totalBatches===e.totalBatches}function R$(s,e,t){let r=new Map;for(let n of e){let o=s?.get(n.id);if(o!==void 0&&b$(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 v$(s,e,t){let r=[],n=[],o=[];for(let a of s){if(!y$.has(a.status)||!w$.has(a.jobType))continue;let d=e.get(a.id),c=d===void 0?null:t-d.unchangedSinceMs,u=a.batchesProcessed,l=a.totalBatches;if(a.status==="Processing"&&u!==null&&l!==null&&u<l&&c!==null&&c>=di){n.push({job:a,stillMs:c,done:u,total:l});continue}if(d?.movedWhileWatched===!0&&c!==null&&c<di)continue;let g=t-Date.parse(a.createdDate);g>=rO&&o.push({job:a,ageMs:g,stillMs:c})}n.sort((a,d)=>d.stillMs-a.stillMs);for(let{job:a,stillMs:d,done:c,total:u}of n){let l=Gp(Math.floor(d/6e4));r.push({type:"stuck",severity:"critical",title:`${a.jobType} ${a.id}: no batch completed in ${l}`,detail:`${c} of ${u} batches processed, unchanged across ${l} of observation by this dashboard while ${a.status} (stall bound ${di/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<nO)continue;let c=d.reduce((u,l)=>u+(l.failedRecords||0),0);r.push({type:"frequent_failures",severity:"critical",title:`${d.length} ${a} jobs failed`,detail:`${d.length} of the last ${s.length} jobs are ${a} failures (${c} failed batch execution(s) reported) \u2014 at or above the ${nO}-failure pattern threshold.`,affectedJobs:d.map(u=>u.id),recommendation:`Open the most recent ${a} failure and read its extended status: a repeat at this rate is a defect or a data problem, not contention.`})}if(o.length>0){o.sort((g,p)=>p.ageMs-g.ageMs);let a=o[0],d=Gp(Math.floor(a.ageMs/6e4)),{batchesProcessed:c,totalBatches:u}=a.job,l=c===null||u===null||u<=0?"it reports no batch counter, so its progress cannot be observed":a.stillMs===null||a.stillMs<6e4?`${c} of ${u} batches processed, first seen at these values on this refresh`:`${c} of ${u} batches processed, unchanged over the ${Gp(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 ${rO/6e4}m or more after submission`,detail:`${a.job.jobType} ${a.job.id} is ${a.job.status}, submitted ${d} ago; ${l}. Time since submission includes time spent queued: it is not evidence of a stall.`,affectedJobs:o.map(({job:g})=>g.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 ${di/6e4}m of watching; a job without batch counters never is.`})}return r}var S$=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"]),qd=class{constructor(e,t){this.deps=e;this.externalBrowser=t??new jr;let r=Zk({configStore:e.configStore,log:n=>e.log(n),notify:(n,o)=>Ie(e,n,"Alert",o),getConnection:async(n,o)=>(o?.again===!0&&Io().remove(n),this.withSharedJobQuery(n,await q(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 xd;healthCalculator=new $d;liveOperationTracker;getOrFetchLimits;forgetServicesOrg;errorLogMonitor;userSessionMonitor;apexLogAnalyzer;sandboxRefreshTracker;healthCheck;healthSignals;alertEngine;alertStateStore;inFlightJobRecords=new Map;jobProgress=new Map;externalBrowser;setLiveOperationTracker(e){this.liveOperationTracker=e,e.onChange(this.onLiveOperationsChange)}onLiveOperationsChange=()=>this.pushLiveOperationsSoon();livePush;dispose(){this.livePush!==void 0&&(clearTimeout(this.livePush),this.livePush=void 0),this.liveOperationTracker?.offChange(this.onLiveOperationsChange)}pushLiveOperationsSoon(){this.livePush===void 0&&(this.livePush=setTimeout(()=>{this.livePush=void 0;let e={id:this.deps.nextId(),type:"monitor:live-operations:changed",timestamp:Date.now(),payload:{operations:(this.liveOperationTracker?.getAll()??[]).map(t=>({...t}))}};this.deps.broker.postToWebview(e)},f$),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(!S$.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&&m$.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 ${eO}ms bound; skipping ${t}`),!0):!1}async handleRefresh(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Xr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{await new fe(eO).withTimeout("monitor:refresh",n=>this.executeRefresh(e,r,n))}catch(n){T(this.deps,"monitor:refresh","monitor:error",e,n)}}async executeRefresh(e,t,r){try{let n=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),[o,i]=await Promise.allSettled([this.getOrFetchLimits(t.orgId,n),Lt(n,oO)]);if(o.status==="rejected")throw o.reason;let a=qk(o.value);xe(n.limitInfo,"monitor:refresh limits");let d=[];for(let v of a){let w=this.alertEngine.evaluate(v.name,v.usedPercent,t.orgId);w&&d.push(w)}if(this.alertStateStore.saveAlerts(this.alertEngine.getActiveAlerts()),d.length>0&&this.alertStateStore.saveHistory(d),i.status==="rejected")throw i.reason;let c=i.value;if(xe(n.limitInfo,"monitor:refresh asyncJobs"),this.inFlightJobRecords.set(t.orgId,c),this.pastDeadline(r,"org info and health check"))return;let u=Date.now(),l=c.map(v=>({id:v.Id,jobType:v.JobType??"Unknown",status:v.Status,createdBy:v.CreatedById,createdDate:v.CreatedDate,failedRecords:v.NumberOfErrors,batchesProcessed:v.JobItemsProcessed??null,totalBatches:v.TotalJobItems??null})),g=c.length>=mn.monitorJobs,p=l.map(({id:v,jobType:w,status:C,createdBy:k,createdDate:E,failedRecords:x})=>({id:v,jobType:w,status:C,createdBy:k,createdDate:E,failedRecords:x})),f=R$(this.jobProgress.get(t.orgId),l,u);this.jobProgress.set(t.orgId,f);let h=v$(l,f,u),m={orgId:t.orgId,limits:a,timestamp:new Date().toISOString()},y=this.trendStorage.recordAndGetTrends(t.orgId,m,_i),[R,S]=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 b=this.healthCalculator.calculate({limits:a,orgId:t.orgId,trends:y,orgInfo:R}),O=b.overallScore;if(this.pastDeadline(r,"the monitor:data reply"))return;let P=A(this.deps,e,"monitor:data",{limits:a,jobs:p,jobsTruncated:g,healthScore:O,healthReport:b,trends:y,jobInsights:h,orgInfo:R,orgHealthStatus:S,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 "${I(n)}"`))return;T(this.deps,"monitor:refresh","monitor:error",e,n)}finally{this.inFlightJobRecords.delete(t.orgId)}}async computeOrgHealth(e){try{return await this.healthCheck.computeHealth(e)}catch(t){this.deps.log(`[WARN] HealthCheck failed: ${String(t)}`);return}}async fetchOrgInfo(e,t){try{let r={latestApiVersion:async()=>Bk(await t.request("/services/data")),queryOrg:async()=>{let n=this.deps.orgManager.getOrg(e),o=await Lt(t,"SELECT Name, Id, OrganizationType, InstanceName, NamespacePrefix, CreatedDate FROM Organization LIMIT 1");xe(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=$(Xr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await q(r.orgId,this.deps.orgRegistry,this.deps.orgManager),o=await n.request(`/services/data/${Ro}/limits/recordCount`);xe(n.limitInfo,"monitor:storage recordCount");let i=(o.sObjects??[]).filter(p=>p.count>0).sort((p,f)=>f.count-p.count),a=i.slice(0,g$),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 Lt(n,`SELECT QualifiedApiName, Label FROM EntityDefinition WHERE QualifiedApiName IN (${d.map(f=>`'${f}'`).join(", ")})`);xe(n.limitInfo,"monitor:storage entityDefinition");for(let f of p)f.Label&&c.set(f.QualifiedApiName,f.Label)}let u=a.map(p=>({objectName:p.name,label:c.get(p.name)??p.name,recordCount:p.count})),l=i.reduce((p,f)=>p+f.count,0),g=A(this.deps,e,"monitor:storage:response",{success:!0,objects:u,totalRecords:l,objectCount:i.length});this.deps.broker.postToWebview(g),this.deps.log(`[TX] ${g.type} id=${g.id}`)}catch(n){T(this.deps,"monitor:storage","monitor:error",e,n)}}async handleDeployments(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Xr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await q(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 ${tO}`)).records;xe(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>=tO});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(n){T(this.deps,"monitor:deployments","monitor:error",e,n)}}async handleApiUsage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Xr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await q(r.orgId,this.deps.orgRegistry,this.deps.orgManager),o=await this.getOrFetchLimits(r.orgId,n);xe(n.limitInfo,"monitor:api-usage limits");let i=["DailyApiRequests","DailyBulkApiBatches","DailyBulkV2QueryJobs","DailyBulkV2QueryFileStorageMB","DailyStreamingApiEvents","DailyGenericStreamingApiEvents","DailyDurableStreamingApiEvents","DailyAsyncApexExecutions","HourlyAsyncReportRuns","HourlyTimeBasedWorkflow","DailyWorkflowEmails","MassEmail","SingleEmail","HourlyPublishedPlatformEvents","DailyStandardVolumePlatformEvents"],a=[];for(let c of i){let u=o[c];if(u&&typeof u.Max=="number"){let l=u.Max-u.Remaining,g=u.Max>0?Math.round(l/u.Max*100):0;a.push({category:c,used:l,max:u.Max,usedPercent:g})}}a.sort((c,u)=>u.usedPercent-c.usedPercent);let d=A(this.deps,e,"monitor:api-usage:response",{success:!0,categories:a});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(n){T(this.deps,"monitor:api-usage","monitor:error",e,n)}}async handleOpenApexJobs(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Qm,e,"monitor:error",this.deps);if(!t)return;let r=this.deps.orgManager.getOrg(t.orgId);if(!r){T(this.deps,"monitor:open-apex-jobs","monitor:error",e,new Error(`No registered org has the id "${t.orgId}".`),{code:"ORG_NOT_FOUND"});return}let n=yS(r.instanceUrl);if(!n.ok){let o=n.reason==="not-https"?`its instance URL must use HTTPS, got "${n.protocol}"`:"its instance URL is not a valid URL";T(this.deps,"monitor:open-apex-jobs","monitor:error",e,new Error(`Cannot open Apex Jobs for "${ye(r)}": ${o}.`),{code:"INVALID_INSTANCE_URL"});return}try{let o=await this.externalBrowser.open(n.url),i=A(this.deps,e,"monitor:open-apex-jobs:response",o);this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} status=${o.status}`)}catch(o){T(this.deps,"monitor:open-apex-jobs","monitor:error",e,o)}}async handleErrorLogs(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Xr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await this.errorLogMonitor.fetch(r.orgId),i=[...this.errorLogMonitor.getErrorsByType(r.orgId).entries()].map(([d,c])=>({type:d,count:c})),a=A(this.deps,e,"monitor:error-logs:response",{success:!0,errors:n,errorsByType:i,totalCount:n.length,truncated:this.errorLogMonitor.isTruncated(r.orgId)});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id}`)}catch(n){T(this.deps,"monitor:error-logs","monitor:error",e,n)}}async handleSessions(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Xr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await this.userSessionMonitor.fetch(r.orgId),o=this.userSessionMonitor.getActiveUserCount(r.orgId),i=A(this.deps,e,"monitor:sessions:response",{success:!0,sessions:n,activeUserCount:o,truncated:this.userSessionMonitor.isTruncated(r.orgId)});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(n){T(this.deps,"monitor:sessions","monitor:error",e,n)}}async handleApexInsights(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Xr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await this.apexLogAnalyzer.fetchAndAnalyze(r.orgId,p$),o=this.apexLogAnalyzer.getTopIssues(r.orgId),i=A(this.deps,e,"monitor:apex-insights:response",{success:!0,analyses:n,topIssues:o,truncated:this.apexLogAnalyzer.isTruncated(r.orgId)});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(n){T(this.deps,"monitor:apex-insights","monitor:error",e,n)}}async checkSandboxIdentity(e){let t=this.deps.sandboxRefreshes;if(!(!t||this.deps.orgManager.getOrg(e)?.orgType!=="Sandbox"))try{let r=await q(e,this.deps.orgRegistry,this.deps.orgManager),[n]=await Lt(r,"SELECT Id, InstanceName FROM Organization");xe(r.limitInfo,"monitor:sandbox-refresh organization"),n&&t.observe(e,{organizationId:n.Id,instanceName:n.InstanceName??void 0},"monitor")}catch(r){this.deps.log(`[WARN] monitor:sandbox-refresh identity check: ${I(r)}`)}}async handleSandboxRefresh(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Xr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{await this.checkSandboxIdentity(r.orgId);let n=await this.sandboxRefreshTracker.fetch(r.orgId),o=this.sandboxRefreshTracker.isRefreshInProgress(r.orgId),i=A(this.deps,e,"monitor:sandbox-refresh:response",{success:!0,supported:this.sandboxRefreshTracker.isSupported(r.orgId),refreshes:n,inProgress:o,truncated:this.sandboxRefreshTracker.isTruncated(r.orgId),detected:this.deps.sandboxRefreshes?.refreshesOf(r.orgId)??[]});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(n){T(this.deps,"monitor:sandbox-refresh","monitor:error",e,n)}}handleAlerts(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.alertEngine.getActiveAlerts(),r=this.alertStateStore.loadHistory(),n=A(this.deps,e,"monitor:alerts:result",{alerts:t,history:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleAlertAcknowledge(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(wl,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=$(wl,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 Jp="seed:template:",sO="seedTemplates",cn=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${Jp}${e.id}`,e,sO)}load(e){return this.configStore.get(`${Jp}${e}`)}list(){let e=this.configStore.getByCategory(sO);return Object.values(e).sort((r,n)=>n.updatedAt.localeCompare(r.updatedAt))}delete(e){return this.configStore.delete(`${Jp}${e}`)}};var Wd=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 iO=[{id:"assureur-fr",name:"Assureur fran\xE7ais",description:"Compagnie d'assurance fran\xE7aise avec contrats, sinistres et assur\xE9s.",industry:"Insurance",locale:"fr-FR",dataPatterns:{Name:{fieldType:"string",generator:"faker",params:{method:"company.name",locale:"fr"},examples:["AXA Pr\xE9voyance","Mutuelle du Soleil","Groupe Assurancia"]},FirstName:{fieldType:"string",generator:"faker",params:{method:"person.firstName",locale:"fr"},examples:["Jean","Marie","Philippe"]},LastName:{fieldType:"string",generator:"faker",params:{method:"person.lastName",locale:"fr"},examples:["Dupont","Martin","Lefebvre"]},SIRET__c:{fieldType:"string",generator:"pattern",params:{pattern:"###########00##"},examples:["12345678900012","98765432100034","55566677800015"]},Contract_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Auto","Habitation","Sant\xE9","Vie","Responsabilit\xE9 Civile"]},examples:["Auto","Habitation","Sant\xE9"]},Premium__c:{fieldType:"currency",generator:"range",params:{min:200,max:5e3,currency:"EUR"},examples:["450.00","1200.50","3200.00"]}}},{id:"hospital-us",name:"H\xF4pital am\xE9ricain",description:"Hospital system with patients, procedures, and medical codes.",industry:"Healthcare",locale:"en-US",dataPatterns:{FirstName:{fieldType:"string",generator:"faker",params:{method:"person.firstName",locale:"en_US"},examples:["James","Sarah","Michael"]},LastName:{fieldType:"string",generator:"faker",params:{method:"person.lastName",locale:"en_US"},examples:["Johnson","Williams","Smith"]},MRN__c:{fieldType:"string",generator:"sequence",params:{prefix:"MRN-",padLength:8},examples:["MRN-00000001","MRN-00000002","MRN-00000003"]},ICD10_Code__c:{fieldType:"string",generator:"random_pick",params:{values:["J06.9","I10","E11.9","M54.5","J18.9","K21.0","N39.0"]},examples:["J06.9","I10","E11.9"]},CPT_Code__c:{fieldType:"string",generator:"random_pick",params:{values:["99213","99214","99215","99203","99204","36415","71046"]},examples:["99213","99214","36415"]},Insurance_Provider__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Blue Cross","Aetna","UnitedHealth","Cigna","Medicare","Medicaid"]},examples:["Blue Cross","Aetna","Medicare"]}}},{id:"ecommerce-b2c",name:"E-commerce B2C",description:"Online retail with products, orders, customers, and reviews.",industry:"Retail",locale:"en-US",dataPatterns:{Product_Name__c:{fieldType:"string",generator:"faker",params:{method:"commerce.productName"},examples:["Ergonomic Steel Chair","Wireless Bluetooth Headphones","Organic Cotton T-Shirt"]},SKU__c:{fieldType:"string",generator:"sequence",params:{prefix:"SKU-",padLength:6},examples:["SKU-000001","SKU-000002","SKU-000003"]},Price__c:{fieldType:"currency",generator:"range",params:{min:9.99,max:999.99,currency:"USD"},examples:["29.99","149.50","499.00"]},Order_Status__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Pending","Processing","Shipped","Delivered","Returned","Cancelled"]},examples:["Pending","Shipped","Delivered"]},Rating__c:{fieldType:"number",generator:"range",params:{min:1,max:5},examples:["4","5","3"]},Review_Text__c:{fieldType:"textarea",generator:"ai_generate",params:{prompt:"Product review, 1-3 sentences, realistic tone"},examples:["Great product, fast shipping!","Good quality but runs small.","Exactly as described."]}}},{id:"banque-eu",name:"Banque europ\xE9enne",description:"European bank with accounts, transactions, IBAN/BIC codes.",industry:"Banking",locale:"fr-FR",dataPatterns:{IBAN__c:{fieldType:"string",generator:"faker",params:{method:"finance.iban",locale:"fr"},examples:["FR7630006000011234567890189","DE89370400440532013000","ES9121000418450200051332"]},BIC__c:{fieldType:"string",generator:"faker",params:{method:"finance.bic"},examples:["BNPAFRPPXXX","DEUTDEFFXXX","BBVAESMMXXX"]},Transaction_Amount__c:{fieldType:"currency",generator:"range",params:{min:-1e4,max:5e4,currency:"EUR"},examples:["1250.00","-450.75","15000.00"]},Transaction_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Virement","Pr\xE9l\xE8vement","Carte","Ch\xE8que","Esp\xE8ces"]},examples:["Virement","Carte","Pr\xE9l\xE8vement"]},Account_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Courant","\xC9pargne","PEL","Titre","Professionnel"]},examples:["Courant","\xC9pargne","PEL"]},Risk_Score__c:{fieldType:"number",generator:"range",params:{min:0,max:100},examples:["15","42","78"]}}},{id:"startup-saas",name:"Startup SaaS",description:"SaaS company with subscriptions, MRR metrics, churn tracking.",industry:"Technology",locale:"en-US",dataPatterns:{Company_Name__c:{fieldType:"string",generator:"faker",params:{method:"company.name"},examples:["Acme Cloud","DataSync Pro","NeuralFlow AI"]},Plan__c:{fieldType:"picklist",generator:"weighted_pick",params:{values:{Free:.4,Starter:.25,Pro:.2,Enterprise:.15}},examples:["Free","Pro","Enterprise"]},MRR__c:{fieldType:"currency",generator:"range",params:{min:0,max:25e3,currency:"USD"},examples:["0.00","499.00","12500.00"]},Churn_Risk__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Low","Medium","High","Critical"]},examples:["Low","Medium","High"]},Active_Users__c:{fieldType:"number",generator:"range",params:{min:1,max:500},examples:["12","85","250"]},NPS_Score__c:{fieldType:"number",generator:"range",params:{min:-100,max:100},examples:["72","-15","45"]}}},{id:"immobilier",name:"Immobilier",description:"Agence immobili\xE8re avec biens, mandats et visites.",industry:"Real Estate",locale:"fr-FR",dataPatterns:{Property_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Appartement","Maison","Studio","Loft","Terrain","Local commercial"]},examples:["Appartement","Maison","Studio"]},Surface__c:{fieldType:"number",generator:"range",params:{min:15,max:300,unit:"m\xB2"},examples:["45","120","85"]},Price__c:{fieldType:"currency",generator:"range",params:{min:5e4,max:2e6,currency:"EUR"},examples:["185000","450000","1200000"]},City__c:{fieldType:"string",generator:"random_pick",params:{values:["Paris","Lyon","Marseille","Bordeaux","Toulouse","Nantes","Lille"]},examples:["Paris","Lyon","Bordeaux"]},Mandate_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Exclusif","Simple","Semi-exclusif"]},examples:["Exclusif","Simple","Semi-exclusif"]},DPE__c:{fieldType:"picklist",generator:"weighted_pick",params:{values:{A:.05,B:.1,C:.2,D:.3,E:.2,F:.1,G:.05}},examples:["C","D","B"]}}},{id:"education",name:"\xC9ducation",description:"Educational institution with students, courses, and grades.",industry:"Education",locale:"fr-FR",dataPatterns:{Student_ID__c:{fieldType:"string",generator:"sequence",params:{prefix:"STU-",padLength:6},examples:["STU-000001","STU-000002","STU-000003"]},FirstName:{fieldType:"string",generator:"faker",params:{method:"person.firstName",locale:"fr"},examples:["L\xE9a","Hugo","Emma"]},LastName:{fieldType:"string",generator:"faker",params:{method:"person.lastName",locale:"fr"},examples:["Bernard","Petit","Robert"]},Course_Name__c:{fieldType:"string",generator:"random_pick",params:{values:["Math\xE9matiques","Physique","Histoire","Anglais","Informatique","Philosophie"]},examples:["Math\xE9matiques","Physique","Informatique"]},Grade__c:{fieldType:"number",generator:"range",params:{min:0,max:20,precision:1},examples:["14.5","8.0","17.5"]},Semester__c:{fieldType:"picklist",generator:"random_pick",params:{values:["S1","S2","S3","S4","S5","S6"]},examples:["S1","S2","S3"]}}},{id:"logistique",name:"Logistique",description:"Logistics company with parcels, warehouses, and shipment tracking.",industry:"Logistics",locale:"fr-FR",dataPatterns:{Tracking_Number__c:{fieldType:"string",generator:"sequence",params:{prefix:"TRK-",padLength:10},examples:["TRK-0000000001","TRK-0000000002","TRK-0000000003"]},Status__c:{fieldType:"picklist",generator:"random_pick",params:{values:["En pr\xE9paration","Exp\xE9di\xE9","En transit","En livraison","Livr\xE9","Retourn\xE9"]},examples:["Exp\xE9di\xE9","En transit","Livr\xE9"]},Weight__c:{fieldType:"number",generator:"range",params:{min:.1,max:500,unit:"kg"},examples:["2.5","15.0","125.0"]},Warehouse__c:{fieldType:"string",generator:"random_pick",params:{values:["Paris-Nord","Lyon-Est","Marseille-Port","Bordeaux-Sud","Lille-Centre"]},examples:["Paris-Nord","Lyon-Est","Marseille-Port"]},Carrier__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Colissimo","Chronopost","DHL","FedEx","UPS","GLS"]},examples:["Colissimo","Chronopost","DHL"]},Delivery_Date__c:{fieldType:"date",generator:"relative_date",params:{minDaysFromNow:1,maxDaysFromNow:14},examples:["2026-03-01","2026-03-05","2026-03-12"]}}},{id:"rh",name:"Ressources humaines",description:"HR department with employees, leaves, payroll, and performance.",industry:"Human Resources",locale:"fr-FR",dataPatterns:{Employee_ID__c:{fieldType:"string",generator:"sequence",params:{prefix:"EMP-",padLength:5},examples:["EMP-00001","EMP-00002","EMP-00003"]},Department__c:{fieldType:"picklist",generator:"random_pick",params:{values:["R&D","Marketing","Ventes","RH","Finance","Support","Direction"]},examples:["R&D","Marketing","Finance"]},Contract_Type__c:{fieldType:"picklist",generator:"weighted_pick",params:{values:{CDI:.6,CDD:.2,Stage:.1,Alternance:.1}},examples:["CDI","CDD","Stage"]},Salary__c:{fieldType:"currency",generator:"range",params:{min:25e3,max:12e4,currency:"EUR"},examples:["35000","55000","85000"]},Leave_Type__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Cong\xE9s pay\xE9s","RTT","Maladie","Sans solde","Maternit\xE9","Formation"]},examples:["Cong\xE9s pay\xE9s","RTT","Maladie"]},Leave_Days__c:{fieldType:"number",generator:"range",params:{min:.5,max:25},examples:["1","5","12"]}}},{id:"ong",name:"ONG/Association",description:"Non-profit organization with donors, campaigns, and volunteers.",industry:"Non-Profit",locale:"fr-FR",dataPatterns:{Donor_Type__c:{fieldType:"picklist",generator:"weighted_pick",params:{values:{Particulier:.7,Entreprise:.2,Fondation:.1}},examples:["Particulier","Entreprise","Fondation"]},Donation_Amount__c:{fieldType:"currency",generator:"range",params:{min:5,max:5e4,currency:"EUR"},examples:["25.00","150.00","5000.00"]},Campaign_Name__c:{fieldType:"string",generator:"ai_generate",params:{prompt:"Charity campaign name, inspiring and concise"},examples:["Solidarit\xE9 Hiver 2026","Course pour la Vie","Un Toit Pour Tous"]},Volunteer_Status__c:{fieldType:"picklist",generator:"random_pick",params:{values:["Actif","Inactif","En formation","Suspendu"]},examples:["Actif","En formation","Inactif"]},Hours_Volunteered__c:{fieldType:"number",generator:"range",params:{min:1,max:200},examples:["8","40","120"]},Tax_Receipt__c:{fieldType:"boolean",generator:"weighted_pick",params:{values:{true:.8,false:.2}},examples:["true","false","true"]}}}],zd=class{customPersonas=new Map;customCounter=0;getBuiltInPersonas(){return[...iO]}getPersona(e){let t=iO.find(r=>r.id===e);return t||this.customPersonas.get(e)}async createCustomPersona(e,t){let r=O$(e),n=await t(r),o=A$(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())}},aO=df(s=>typeof s=="string"&&s.trim().length>0?Number(s):s,Te().finite()),io=aO.optional().catch(void 0),Vp=j().min(1).optional().catch(void 0),Kp={faker:J({method:j().transform((s,e)=>{let t=jf(s);return t||(e.addIssue({code:cf.custom,message:`unknown faker method ${s}`}),sf)}),locale:Vp}),random_pick:J({values:ve(af([j(),Te(),Ke()]).transform(String)).min(1)}),weighted_pick:J({values:Mi(j(),aO).refine(s=>Object.keys(s).length>0)}),range:J({min:io,max:io,currency:Vp}),sequence:J({prefix:Vp,start:io,step:io,padLength:io}),pattern:J({pattern:j().min(1)}),ai_generate:J({prompt:j().min(1)}),relative_date:J({minDaysFromNow:io,maxDaysFromNow:io})},k$={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 O$(s){let e=Object.keys(Kp);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}: ${k$[r]}`),"",`Faker methods: ${Nf.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 I$(s){let e=s.generator;if(typeof e!="string"||!Object.hasOwn(Kp,e))return null;let r=Kp[e].safeParse(s.params??{});if(!r.success)return null;let n=typeof s.fieldType=="string"?s.fieldType:"string";return e==="ai_generate"&&!Ef(n)?null:{fieldType:n,generator:e,params:r.data,examples:Array.isArray(s.examples)?s.examples.filter(o=>typeof o=="string"):[]}}function A$(s){let e;try{e=Sf(kf,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=I$(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 ts="SEED_WRITE_DECLINED",dO=6e4;function un(s){let e=s?.read.gate.audit;return e===void 0?{}:{details:{deliverability:e,...s?.accepted===!0?{confirmed:"emails"}:{}}}}var gO="the checkpoints of this window are not open to the Seed page",Jt=class extends Error{constructor(t,r,n){super(r);this.code=t;this.refusal=n;this.name="SeedCheckpointStopped"}code;refusal};async function ci(s,e){try{if(!s)throw new Error(gO);return{ask:e,planned:await s.scope(e,{})}}catch(t){throw new Jt(Pn,Sr(t))}}async function ui(s,e,t,r,n){let o=await Ha(async()=>{if(!s)throw new Error(gO);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,jo(i))})});if("stop"in o)throw new Jt(o.stop.code,o.stop.message,o.stop.refusal);return o.checkpoint}async function Mn(s,e,t,r,n){if(!(!e||!s))try{return await s.settle(e,t)}catch(o){return r(`[WARN] ${n}: the checkpoint '${e.name}' taken before the run is kept: `+I(o)),e}}function li(s,e){let t=new Set(s);return(r,n)=>t.has(r)&&(n==="insert"||e&&n==="update")}function Vd(s,e){return typeof s.unread=="string"?{firing:[]}:Jr(s,void 0,e)}function cO(s,e,t){return t==="refuse"?{code:vt.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:uR,message:s.gate.stop?.message??"The seed was refused for its emails. Nothing was written."}}var T$={ask:(s,e)=>s.confirmRun(e),unanswered:"goOn"};function E$(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 uO(s,e){return`The seed needed an answer before it wrote \u2014 ${E$(s,e)} \u2014 and no Approval step before it approved the run: put one before it. Nothing was written.`}function lO(s,e,t){if(Os(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 Gd=1e3;function P$(s){return Array.isArray(s.objectResults)?{...s,objectResults:s.objectResults.map(e=>{let t=e.createdIds.length>Gd||e.errors.length>Gd;return t?{...e,createdIds:e.createdIds.slice(0,Gd),errors:e.errors.slice(0,Gd),truncated:t}:e})}:s}function pO(s){return{query:async e=>s.tooling.query(e),queryMore:async e=>s.tooling.queryMore(e)}}function C$(s){return s.objectResults.flatMap(t=>t.errors)[0]??"The seed wrote no records."}var $$=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"]),Jd=class{constructor(e){this.deps=e;this.seedTemplateStore=new cn(e.configStore),this.templateManager=new Wd(()=>crypto.randomUUID(),()=>new Date().toISOString(),this.seedTemplateStore),this.personaManager=new zd}deps;seedTemplateStore;templateManager;personaManager;registry;liveTracker;runCreations;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}setRunCreations(e){this.runCreations=e}runningRuns=new Set;isRunning(e){return this.runningRuns.has(e)}setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-GOOVPVWX.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}readAutomation(e,t,r,n,o,i,a){let d=this.targetAutomation;return ud({org:n,objects:r,writes:o,readAutomation:c=>i===void 0?new fe(dO).withTimeout("seed automation",()=>d.read(e,c)):typeof i.unread=="string"?Promise.reject(new Error(i.unread)):Promise.resolve(i),readLimits:()=>Ar(t),...a?{deliverability:a}:{},...i===void 0?{readDeliverability:()=>Pe(this.deps.orgManager.getOrg(e))==="production"?Promise.resolve(zt):Gt(t)}:{}})}setMuteLeases(e){this.muteLeases=e}muteLeases={};setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}beforeRunCheckpoints;checkpointProgress(e){return(t,r,n,o)=>{Fe(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=$(Em,e,"seed:automation:error",this.deps);if(t)try{let r=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),n=this.deps.orgManager.getOrg(t.orgId),o=await this.readAutomation(t.orgId,r,t.objects,ye(n,t.orgId),Zv(t.objects,t.publishes===!0));if("error"in o)throw new Error(o.error);let i=A(this.deps,e,"seed:automation:response",{orgId:t.orgId,objects:t.objects,preview:o.preview});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(r){T(this.deps,"seed:automation","seed:automation:error",e,r,{retryable:!0})}}async handle(e){if(!$$.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}`),!!$(xm,e,"seed:error",this.deps))try{let{listScenarioPacks:t,nodeScenarioPackFiles:r}=await import("./chunk-T3G6VZNS.mjs"),n=this.workspaceFolders(),o=await t(r(),n);this.answerScenario(e,"seed:scenario:packs:response",{packs:o,workspace:n.length>0})}catch(t){T(this.deps,"seed:scenario:packs","seed:error",e,t)}}async handleScenarioPrepare(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Dm,e,"seed:error",this.deps);if(t)try{let r=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),{prepareScenario:n,readScenarioCaseStatus:o,scenarioKnowledge:i}=await import("./chunk-GWZRR3MM.mjs"),{seedObjectAccess:a}=await import("./chunk-NCZKWSC7.mjs"),d=await o(async l=>(await r.query(l)).records),c=await i(a(r),l=>r.describe(l)),u=n(t.pack,{caseStatus:d,knowledge:c,...t.seed!==void 0?{seed:t.seed}:{},...t.articleBodyField!==void 0?{articleBodyField:t.articleBodyField}:{}});this.answerScenario(e,"seed:scenario:prepare:response",{...u})}catch(r){T(this.deps,"seed:scenario:prepare","seed:error",e,r,{retryable:!0})}}async handleScenarioExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Nm,e,"seed:error",this.deps);if(!t)return;let{compileScenario:r,ScenarioCompileError:n}=await import("./chunk-7WATA4SB.mjs"),o;try{o=r(t.pack,t.options)}catch(a){if(!(a instanceof n))throw a;T(this.deps,"seed:scenario:execute","seed:error",e,a,{code:"SCENARIO_INVALID",retryable:!1});return}let i=Po.safeParse(o.template);if(!i.success){T(this.deps,"seed:scenario:execute","seed:error",e,new Error(`The scenario compiled to a template the seed refuses: ${i.error.issues[0]?.message??"invalid"}`),{code:"SCENARIO_INVALID",retryable:!1});return}await this.runAsked(e,{orgId:t.orgId,template:i.data,...t.locale!==void 0?{locale:t.locale}:{},...t.muteAutomation!==void 0?{muteAutomation:t.muteAutomation}:{},...t.checkpointFirst?{checkpointFirst:t.checkpointFirst}:{}},{pack:t.pack,options:t.options,compiled:o})}async keepScenario(e,t,r){let{compiled:n,pack:o}=t,i=n.tests.filter(l=>l.openCase!==void 0),a=new Set(i.map(l=>l.openCase?.caseKey)),d=Object.keys(r).filter(l=>a.has(l)).length,c={packId:o.id,packName:o.name,tests:n.tests.length,openCasesWritten:d,openCases:a.size};if(d===0)return{...c,companion:{kind:"none"}};let u=this.runCreations;if(!u)return{...c,companion:{kind:"failed",message:"The runs are not kept in this window."}};try{let{nodeScenarioSidecarFiles:l,scenarioRunSidecar:g,writeScenarioRunSidecar:p}=await import("./chunk-UBIKR5VO.mjs");return await p(l(),u.storagePath,g({runId:e.operationId,pack:o,compiled:n,options:t.options,caseIds:r})),{...c,companion:{kind:"kept"}}}catch(l){let g=I(l);return this.deps.log(`[WARN] seed:scenario:execute ${e.operationId}: the companion file could not be written, so its test file cannot be: ${g}`),{...c,companion:{kind:"failed",message:g}}}}async handleScenarioAgents(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(jm,e,"seed:error",this.deps);if(t)try{let r=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),{readAgentCatalog:n}=await import("./chunk-JPEVIXNH.mjs"),{scenarioCasePicklists:o,toolingQueryAll:i}=await import("./chunk-GWZRR3MM.mjs"),{scenarioProjectOf:a}=await import("./chunk-RT47RKLY.mjs"),d=await n(i(pO(r))),c=await o(u=>r.describe(u));this.answerScenario(e,"seed:scenario:agents:response",{orgId:t.orgId,agents:d.kind==="agents"?{kind:"agents",agents:d.catalog.agents}:d,project:await a(this.workspaceFolders()),...c?{casePicklists:c}:{}})}catch(r){T(this.deps,"seed:scenario:agents","seed:error",e,r,{retryable:!0})}}async handleScenarioSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Mm,e,"seed:error",this.deps);if(t)try{let{nodeScenarioPackFiles:r,saveScenarioPack:n}=await import("./chunk-T3G6VZNS.mjs"),o=await n(r(),this.workspaceFolders(),t.pack,t.overwrite===!0);this.answerScenario(e,"seed:scenario:save:response",{outcome:o})}catch(r){T(this.deps,"seed:scenario:save","seed:error",e,r)}}async handleScenarioTestFile(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Lm,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 q(o.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),{readAgentCatalog:d}=await import("./chunk-JPEVIXNH.mjs"),{nodeAgentTestSpecFiles:c}=await import("./chunk-XBQGZGWR.mjs"),{toolingQueryAll:u}=await import("./chunk-GWZRR3MM.mjs"),{findScenarioPack:l,nodeScenarioPackFiles:g}=await import("./chunk-T3G6VZNS.mjs"),{nodeScenarioSidecarFiles:p}=await import("./chunk-UBIKR5VO.mjs"),{scenarioProjectOf:f,writeRunTestFile:h}=await import("./chunk-RT47RKLY.mjs"),m=this.workspaceFolders(),y=await h({sidecar:p(),spec:c()},{runId:t.runId,storagePath:n.storagePath,project:await f(m),alias:ye(i,o.targetOrgId),choice:t.choice,...t.overwrite!==void 0?{overwrite:t.overwrite}:{},readCatalog:()=>d(u(pO(a))),findPack:(R,S)=>l(g(),m,R,S)});r(y)}catch(n){T(this.deps,"seed:scenario:test-file","seed:error",e,n,{retryable:!0})}}async handleTemplateSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Cm,e,"seed:error",this.deps);if(t)try{let r=t.template;if(r.id&&this.templateManager.get(r.id)){let n=this.templateManager.update(r.id,r),o=A(this.deps,e,"seed:template:save:response",{success:!0,id:n.id});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}else{let n=this.templateManager.create(r),o=A(this.deps,e,"seed:template:save:response",{success:!0,id:n.id});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}}catch(r){T(this.deps,"seed:template:save","seed:error",e,r)}}async handleTemplateLoad(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(hl,e,"seed:error",this.deps);if(t)try{let r=this.seedTemplateStore.load(t.id),n=A(this.deps,e,"seed:template:load:response",{template:r??null});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){T(this.deps,"seed:template:load","seed:error",e,r)}}async handleTemplateList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let r=this.seedTemplateStore.list().map(o=>({id:o.id,name:o.name,description:o.description,tags:o.tags,updatedAt:o.updatedAt,objectCount:o.objects.length,totalRecords:o.objects.reduce((i,a)=>i+a.recordCount,0)})),n=A(this.deps,e,"seed:template:list:response",{templates:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(t){T(this.deps,"seed:template:list","seed:error",e,t)}}async handleTemplateDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(hl,e,"seed:error",this.deps);if(t)try{let r=this.seedTemplateStore.delete(t.id),n=A(this.deps,e,"seed:template:delete:response",{success:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){T(this.deps,"seed:template:delete","seed:error",e,r)}}async handleListPersonas(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.personaManager.getBuiltInPersonas(),r=this.personaManager.getCustomPersonas(),n=[...t,...r].map(i=>({id:i.id,name:i.name,description:i.description,industry:i.industry,locale:i.locale,dataPatterns:i.dataPatterns})),o=A(this.deps,e,"seed:list-personas:response",{personas:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(t){T(this.deps,"seed:list-personas","seed:error",e,t)}}async handleCreatePersona(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$($m,e,"seed:error",this.deps);if(t)try{let r=t;if(!r.description||r.description.trim().length===0){let c=A(this.deps,e,"seed:create-persona:response",{persona:{id:"",name:"",description:"",industry:"",locale:"",dataPatterns:{}},success:!1,error:"Description is required to create a custom persona"});this.deps.broker.postToWebview(c);return}let n=this.deps.services;if(!n?.isAIEnabled())throw new Error("AI is disabled. Enable sandforge.ai.enabled and add your Anthropic API key in SandForge Settings > AI > API key to create custom personas.");let o=async c=>(await n.aiClient().chat({messages:[{role:"user",content:c}]})).text,i=await this.personaManager.createCustomPersona(r.description,o),a={id:i.id,name:i.name,description:i.description,industry:i.industry,locale:i.locale,dataPatterns:i.dataPatterns},d=A(this.deps,e,"seed:create-persona:response",{persona:a,success:!0});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(r){T(this.deps,"seed:create-persona","seed:error",e,r)}}buildSeedCallAI(){let e=this.deps.services;return e?.isAIEnabled()?async t=>{try{return(await e.aiClient().chat({messages:[{role:"user",content:t}]})).text}catch(r){return this.deps.log(`[AI] seed data generation failed, falling back to faker: ${I(r)}`),"[]"}}:async()=>"[]"}async handleDescribeGlobal(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Tm,e,"seed:error",this.deps);if(!t)return;let r=t,n=lt(this.deps);try{let o=await q(r.orgId,this.deps.orgRegistry,this.deps.orgManager),d=(await new fe(n.timeouts.describeGlobal).withTimeout("describe-global",()=>o.describeGlobal())).sobjects.filter(u=>u.createable).filter(u=>!Bi(u.name)).map(u=>({apiName:u.name,label:u.label,recordCount:0,dependencies:[]})),c=A(this.deps,e,"seed:describe-global:response",{objects:d});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(o){T(this.deps,"seed:describe-global","seed:error",e,o)}}async handleDescribeObject(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Pm,e,"seed:error",this.deps);if(!t)return;let r=t,n=lt(this.deps);try{let o=await q(r.orgId,this.deps.orgRegistry,this.deps.orgManager),i=wt(r.objectApiName),d=await new fe(n.timeouts.describe).withTimeout("describe-object",()=>o.describe(i)),c=d.fields.filter(g=>g.createable).map(g=>({fieldApiName:g.name,label:g.label,type:g.type,required:!g.nillable&&!g.defaultedOnCreate,picklistValues:g.picklistValues?.map(p=>p.value)??[],referenceTo:g.referenceTo??[],length:g.length,integerDigits:Mf(g),objectApiName:r.objectApiName})),u=Kv(i,d.recordTypeInfos,i===Ao?await Yl(o):[]),l=A(this.deps,e,"seed:describe-object:response",{objectApiName:r.objectApiName,objectLabel:d.label,fields:c,recordTypes:u});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`)}catch(o){T(this.deps,"seed:describe-object","seed:error",e,o)}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Am,e,"seed:error",this.deps);if(!t)return;let r=t;if(r.dryRun===!0){T(this.deps,"seed:execute","seed:error",e,new Error('Seed has no dry run: remove "dryRun" from this request to run the seed.'),{code:"DRY_RUN_UNSUPPORTED",retryable:!1});return}await this.runAsked(e,r)}async runAsked(e,t,r){let n=e.id,o={module:"seed",operation:e.type};try{let i=await this.clearSeed(t,n,o,T$,r!==void 0);if("refusal"in i){let{refusal:u}=i;T(this.deps,"seed:execute","seed:error",e,new Error(u.message),{code:u.code,retryable:!1,...u.extraPayload?{extraPayload:u.extraPayload}:{}}),u.failed&&je(this.deps,n,u.message,!1,{context:o,...u.failed.authored?{authored:!0}:{}});return}let a=r?`Seed of the scenario ${r.pack.name}`:"Seed data generation",{abortController:d,execution:c}=this.beginSeed(e,i,n,o,a,void 0,r);this.registry?this.registry.register(n,"seed",a,c,d):await c}catch(i){this.deps.infraServices?.performanceTracker?.complete(n),this.liveTracker?.fail(n,I(i));let a=lO(i,n,this.deps.log);T(this.deps,"seed:execute","seed:error",e,i,{code:Eo(i),retryable:!0,extraPayload:a}),je(this.deps,n,I(i),!0,{extraPayload:a,context:o})}}async clearSeed(e,t,r,n,o=!1,i=!1){let a=z=>{i||Z(this.deps,z)},d=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200,c=e.template.objects.map(z=>({...z,batchSize:z.batchSize??d}));Object.assign(r,Kr(c));let u=await q(e.orgId,this.deps.orgRegistry,this.deps.orgManager),l={...e.template,objects:c},g=l.objects.some(z=>z.objectApiName===Ao)?Xv(l,await Yl(u)):{template:l,personObjects:[]};if("refusal"in g)return{refusal:{code:"RECORD_TYPES_MIXED",message:g.refusal}};let p={orgId:e.orgId,template:g.template,personObjects:g.personObjects,locale:await Yv(e.locale,u)},f=e.template.objects.reduce((z,se)=>z+se.recordCount,0),h=[],m=z=>{h.push(z),this.deps.log(`[WARN] seed:execute ${t}: ${z}`)},y=this.deps.orgManager.getOrg(p.orgId),R=ye(y,p.orgId),S=g.template.objects.map(z=>({objectApiName:z.objectApiName,recordCount:z.recordCount})),b=this.targetAutomation,O=await new fe(dO).withTimeout("seed automation",()=>b.read(p.orgId,S.map(z=>z.objectApiName))).catch(z=>({unread:I(z)})),P=Qv(g.template,o),v;if("muteAutomation"in e&&e.muteAutomation===!0)try{v=await Ot(async()=>_t(u),O,{...this.muteLeases,writes:P})}catch(z){if(!Dt(z))throw z;return a({action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",code:z.code}),{refusal:{code:z.code,message:z.message,extraPayload:{},failed:{authored:!0}}}}v&&(p.mute=v);let w=nS(e.fit,f);w&&(p.fit=w);let{describedFieldsOf:C,requiredForAccountKinds:k}=await import("./chunk-B63POIPQ.mjs"),E=0,x=C(async z=>(E++,u.describe(z))),V=eS(O,v?.plan,P,await tS(g.template,O,x.unset)),H=await dr({read:O,...v?.plan?{plan:v.plan}:{},writes:P,readDeliverability:()=>Pe(y)==="production"?Promise.resolve(zt):Gt(u),accepted:!1,target:R,run:"seed",keepsAddresses:!0}),Y={read:H,accepted:!1};p.emails=Y;let B=H.gate.verdict==="asks",N;if(e.checkpointFirst!==void 0){let z={module:"seed",orgId:p.orgId,operationId:t,written:S.filter(se=>se.recordCount>0).map(se=>se.objectApiName),running:V.running??{firing:[]},request:e.checkpointFirst};try{N=await ci(this.beforeRunCheckpoints,z)}catch(se){if(!(se instanceof Jt))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:Q}=await import("./chunk-NCZKWSC7.mjs"),K=await Q(g.template,L(u)),ae=Mv(Ts(this.deps.services),g.template),U=await jv(K,{describeCreateableFields:x.createable,describeRequiredFields:k(x,g.personObjects)},ae),re={duplicateRules:Uo(O),partition:ae,slices:U,slicesRead:E,bulkThreshold:lt(this.deps).bulk.threshold,automationRead:Cn(O)},ne=await Hv(cr(u,p.orgId),K,g.personObjects,ye(y,p.orgId),N?.planned,{...$n(H.ofRun),...bb(v?.plan)},re,V.room);if(ne.check.verdict==="unread"&&m(`the data storage the org has left could not be read (${ne.check.unread}): whether the records fit is not known`),ne.refusal){let z=ne.refusedFor==="checkpoint",se=z?Pn:ne.refusedFor==="apiRequests"?Mo:Xl,te=z?ne.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 he=ne.check,D=z?void 0:rS(Bv(ne),K,g.personObjects,V.room,re);return{refusal:{code:se,message:ne.refusal,extraPayload:{...he.verdict==="unread"||se!==Xl?{}:{estimateMB:Number(Ws(he.estimateMB)),remainingMB:he.remainingMB,...Ir(he),maxMB:he.maxMB,org:ye(y,p.orgId)},...te!==void 0?{checkpointRefusal:te}:{},...D?{fit:D}:{}},failed:{authored:!0}}}}let ue=await this.readAutomation(p.orgId,u,S.map(z=>z.objectApiName),R,P,v?.automation??O,H.gate.deliverability),ce=ld(ue,S,R);for(let z of ce.unknown??[])m(z);if(ce.refusal)return a({action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",code:Ql}),{refusal:{code:Ql,message:ce.refusal,extraPayload:{...ce.figures?{...ce.figures}:{},...o?{scenario:!0}:{}},failed:{authored:!0}}};if(i)return{preview:{records:K.objects.reduce((z,se)=>z+se.recordCount,0),objects:K.objects.length,storage:ne.check,apiRequests:ne.api,automation:Zl(ue,R),warnings:h},storage:ne,asks:ne.check.verdict==="unread"||ne.api.verdict==="near"||N!==void 0||B,emailsAsked:B,emails:H};let be=this.deps.infraServices?.productionGuard;if(!be)return Z(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",code:Re.code}),{refusal:{code:Re.code,message:Re.message,failed:{authored:!1}}};let Xe={orgId:p.orgId,orgTier:Pe(y),operation:"insert",objectName:"SeedData",recordCount:f,module:"seed"},{check:De,decision:_e}=await et(be,Xe);if((_e==="refused"||_e==="declined")&&Z(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",guard:_e}),_e==="refused")throw bn(De.blockedReason??De.impactSummary);if(_e==="declined")return{refusal:{code:xt.declined,message:"Operation cancelled by user (confirmation declined).",failed:{authored:!1}}};if(ne.check.verdict==="unread"||ne.api.verdict==="near"||N!==void 0||B){let z=await n.ask(be,{stage:"write",module:"seed",org:R,orgTier:Pe(y),objects:g.template.objects.map(se=>({objectApiName:se.objectApiName,rows:se.recordCount})).sort((se,te)=>te.rows-se.rows),total:f,storage:xn(ne.check),counted:!0,...Lo(ne.api),...N?{checkpoint:N.planned}:{},...H.gate.confirmation});if(z==="confirmed"&&B&&(Y.accepted=!0),z==="declined")return Z(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",guard:_e,code:ts,...un(Y)}),{refusal:{code:ts,message:"The seed was cancelled before it wrote anything. Nothing was written.",failed:{authored:!0}}};if(z==="unavailable"&&B){let se=cO(H,R,n.unanswered);return Z(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",guard:_e,code:se.code,...un(Y)}),{refusal:{...se,failed:{authored:!0}}}}if(z==="unavailable"&&N!==void 0)return Z(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",guard:_e,code:vt.unanswered}),{refusal:{code:vt.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(z==="unavailable"&&n.unanswered==="refuse")return Z(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:p.orgId,outcome:"stopped",guard:_e,code:vt.unanswered}),{refusal:{code:vt.unanswered,message:uO(ne,R),failed:{authored:!0}}};z==="unavailable"&&this.deps.log(`[WARN] seed:execute ${t}: nobody could be asked about the storage or the API requests the org has left; the seed goes on`)}return{conn:u,run:p,plannedRecords:f,guardDecision:_e,automation:ue,orgName:R,warnings:h,...N?{checkpoint:N}:{}}}beginSeed(e,t,r,n,o,i,a){this.deps.infraServices?.performanceTracker?.start(r,"seed"),Je(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 gr(vt.orgUnknown,`The org the seed writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was written.`);let r=QS(Pe(t),e.answer,ye(t,e.orgId));if(r)throw r;let n=Yo(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 gr(i.refusal.code,i.refusal.message);if(t?.aborted)throw new Rt("The simulation of the seed was stopped before it said what the seed would meet. Nothing was written.");if(i.asks&&!e.answer.approved){let a=ye(this.deps.orgManager.getOrg(e.orgId),e.orgId);if(i.emailsAsked){let d=cO(i.emails,a,o.unanswered);throw gr(d.code,d.message)}throw gr(vt.unanswered,uO(i.storage,a))}return i.preview}async seedForPipeline(e,t){let r=this.pipelineSeedOf(e),n=Rn("seed:pipeline",crypto.randomUUID(),"seed:execute"),o=n.id,i={module:"seed",operation:n.type},a={ask:()=>Promise.resolve(e.answer.approved?"confirmed":"unavailable"),unanswered:"refuse"};return Ea(e.answer,async()=>{let d=await this.clearSeed(r,o,i,a);if("refusal"in d)throw gr(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:bt}),new Rt("The seed was cancelled before it wrote anything. Nothing was written.");let c=Zl(d.automation,d.orgName);for(let m of c)this.deps.log(`[INFO] seed:execute ${o}: ${m}`);let u,l=`Pipeline seed of ${r.template.name}`,{abortController:g,execution:p}=this.beginSeed(n,d,o,i,l,{pipeline:e.pipeline,ended:m=>{u=m}});this.registry?.register(o,"seed",l,p,g);let f=()=>{this.registry?this.registry.abort(o):g.abort()};t?.addEventListener("abort",f,{once:!0});try{await p}finally{t?.removeEventListener("abort",f)}let h=u;if(h===void 0)throw new Error("The seed ended without a result.");if("error"in h)throw h.error instanceof Error?h.error:new Error(I(h.error));return{operationId:o,runId:h.result.operationId,result:h.result,automation:c,warnings:d.warnings}})}async executeSeed(e,t,r,n,o,i,a,d,c,u){let l=lt(this.deps),g=new Date().toISOString(),p,f=!1,h={},m=r.template.name,y={origin:"generator",...typeof m=="string"?{label:m}:{}};try{let R=br(this.deps),S=new Xa({retryConfig:l.retry,signal:o.signal,onRetry:(ie,Ee,Ne)=>{this.deps.log(`[RETRY] seed insert attempt=${ie} code=${Ee.originalError.statusCode} delay=${Ne}ms`)}}),b=this.deps,O=crypto.randomUUID(),P=d?this.deps.orgManager.getOrg(r.orgId)?.orgId:void 0,v=this.runCreations?.recorder({runId:O,targetOrgId:r.orgId,startedAt:g,...d?{pipeline:d.pipeline}:{},...P?{targetOrganizationId:P}:{}});Tr(v,()=>t.identity(),`seed:execute ${n}`);let w={base:0,total:0},C=(ie,Ee,Ne)=>{let st=w.base+ie,Be=Math.max(w.total,st,Ee,1),Ve=Math.round(st/Be*100);Fe(b,n,Ve,st,Be,Ne),this.liveTracker?.updateProgress(n,Ve,st,Be,Ne)},k=hv({conn:t,bulkThreshold:l.bulk.threshold,bulkManager:R,retry:S,signal:o.signal,label:`seed:execute ${n}`,log:ie=>this.deps.log(ie),onProgress:C,...v?{calls:{sending:(ie,Ee,Ne)=>v.sending(ie,Ee,Ne),answered:(ie,Ee)=>v.answered(ie,Ee)}}:{}}),E=async(ie,Ee,Ne,st)=>{Ne.length>0&&(f=!0);let Be=await k(ie,Ee,Ne,st);return v?.note(Ee,Be.successIds),Be},x=ie=>this.deps.log(`[WARN] seed:execute ${n}: what the run created could not all be kept, so removing it may leave some of it in the org: ${I(ie)}`),{SeedValidator:V}=await import("./chunk-6QE6R6RL.mjs"),{DataPlanBuilder:H}=await import("./chunk-5IZTFMJM.mjs"),{FieldMapper:Y}=await import("./chunk-J3DND3BC.mjs"),{ReferenceLinker:B}=await import("./chunk-43TOMFV4.mjs"),{AIDataGenerator:N}=await import("./chunk-YTLUYSMF.mjs"),{FakerFallback:L}=await import("./chunk-HCGXK7G7.mjs"),{readExistingParentIds:Q,readPresentParentIds:K}=await import("./chunk-GKY2JMHY.mjs"),{seedObjectAccess:ae}=await import("./chunk-NCZKWSC7.mjs"),{describedFieldsOf:U,requiredForAccountKinds:re}=await import("./chunk-B63POIPQ.mjs"),{seedTargetOf:ne}=await import("./chunk-2JDAOWUW.mjs"),ue=c?(await import("./chunk-ETDCBLGU.mjs")).seedKnowledge:void 0,ce=new N(this.buildSeedCallAI()),be=new L(r.locale),Xe=new Y({aiGenerator:ce,fakerFallback:be}),De=new B,_e=new V,z=new H,{SeedGrappeAdapter:se}=await import("./chunk-PTTHSSQO.mjs"),te=Ts(this.deps.services),he=U(ie=>t.describe(ie)),D={validator:_e,describeCreateableFields:he.createable,describeVisibleFields:he.visible,describeComputedFields:he.computed,describePicklistValues:he.picklistValues,describeFieldLengths:he.lengths,describeRequiredFields:re(he,r.personObjects),objectAccess:ae(t),readExistingParentIds:(ie,Ee,Ne)=>Q(t,ie,Ee,Ne),readPresentParentIds:(ie,Ee)=>K(t,ie,Ee),describeKeyPrefix:he.keyPrefix,...ne(t),planBuilder:z,fieldMapper:Xe,referenceLinker:De,insert:E,generateId:()=>crypto.randomUUID(),now:()=>new Date().toISOString(),services:this.deps.services,grappeAdapter:new se(()=>crypto.randomUUID(),te?.grappeSize),grappeConfig:te,onGrappeEvent:ie=>sa(this.deps,ie),onProgress:ie=>{w.base=ie.processedRecords,w.total=ie.totalRecords,C(0,ie.totalRecords,`Insert ${ie.objectApiName}`)},signal:o.signal,...c&&ue?{onRowIds:(ie,Ee)=>{ie==="Case"&&Object.assign(h,Ee)},knowledge:ue({org:t,plan:{publish:!0,links:c.compiled.closedCaseArticles},...v?{journal:v}:{},signal:o.signal})}:{}};if(!this.deps.services)throw new Error("SeedOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let W=this.deps.services.seedOrchestrator(D),X=r.template;Fe(this.deps,n,0,0,1,"Validating template and building plan");let F;this.runningRuns.add(O);let ee=r.mute,_=ee?.muted;try{u&&(p=await ui(this.beforeRunCheckpoints,u,O,o.signal,this.checkpointProgress(n)),v?.checkpoint?.(p));let ie=ee?.prepared?await ee.prepared.acquire(O):void 0;ie&&(_=ie.outcome);let Ee=ie&&r.emails?r.emails.read.afterLease(ie.outcome,r.emails.accepted):void 0;if(ie&&Ee)throw _=await ie.release(),new Jt(Ee.code,Ee.message);F=await W.execute(X,r.orgId,O).finally(async()=>{ie&&(_=await ie.release())}),_&&(F={...F,mutedAutomation:_});let Ne=await Mn(this.beforeRunCheckpoints,p,f,this.deps.log,`seed:execute ${n}`);p=void 0,Ne&&(F={...F,checkpoint:Ne})}catch(ie){throw await v?.end({status:"failure",finishedAt:new Date().toISOString(),objectResults:[]}).catch(x),this.runningRuns.delete(O),ie}await v?.end({finishedAt:new Date().toISOString(),status:F.status,...F.cancelled?{cancelled:!0}:{},objectResults:F.objectResults}).catch(x),c&&(F={...F,scenario:await this.keepScenario(F,c,h)}),this.runningRuns.delete(O),F.cancelled||Fe(this.deps,n,100,1,1,"Seed complete");let de=F.totalRecordsCreated;this.deps.infraServices?.performanceTracker?.update(n,de,1),this.deps.infraServices?.performanceTracker?.complete(n),F.cancelled?(this.registry?.abort(n),ge(this.deps,n,{aborted:!0,totalRecords:de}),this.liveTracker?.cancel(n)):(ge(this.deps,n,{status:F.status,totalRecords:de}),F.status==="failure"?this.liveTracker?.fail(n,C$(F)):F.status==="partial"?this.liveTracker?.partial(n):this.liveTracker?.complete(n));let Se=F.objectResults.some(ie=>ie.recordsCreated+ie.recordsFailed>0),Ue=F.cancelled===!0?Se?"cancelled":"stopped":F.status;Z(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:Ue,...Ue==="stopped"?{code:rt}:{},guard:a,objects:F.objectResults.map(ie=>({...mt(ie.objectApiName),created:ie.recordsCreated,failed:ie.recordsFailed})),source:y,...F.mutedAutomation?{muted:ut(F.mutedAutomation)}:{},...F.checkpoint?.state==="taken"?{checkpointId:F.checkpoint.checkpointId}:{},...r.fit?{fit:r.fit}:{},...un(r.emails)});let He=A(this.deps,e,"seed:execute:response",P$(F));if(this.deps.broker.postToWebview(He),this.deps.log(`[TX] ${He.type} id=${He.id}`),d?.ended({result:F}),F.status==="failure"&&!F.cancelled)return{status:"failure"}}catch(R){this.deps.infraServices?.performanceTracker?.complete(n);let S=await Mn(this.beforeRunCheckpoints,p,f,this.deps.log,`seed:execute ${n}`),b=S?.state==="deleted"?`${I(R)} ${en}`:void 0,O=b!==void 0?new Error(b):R;if(R instanceof Jt){if(R.code===rt)this.registry?.abort(n),ge(this.deps,n,{aborted:!0,totalRecords:0}),this.liveTracker?.cancel(n);else{let C=I(O);this.liveTracker?.fail(n,C),je(this.deps,n,C,!1,{context:i,authored:!0})}let w=R.refusal?.code;return Z(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:"stopped",guard:a,code:R.code,...w!==void 0||r.emails?.read.gate.audit!==void 0?{details:{...un(r.emails).details,...w!==void 0?{checkpointRefusal:w}:{}}}:{}}),T(this.deps,"seed:execute","seed:error",e,O,{code:R.code,retryable:!1,...w!==void 0?{extraPayload:{checkpointRefusal:w}}:{}}),d?.ended({error:R}),R.code===rt?void 0:{status:"failure"}}this.liveTracker?.fail(n,I(O));let P=Dt(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}:{},...S?.state==="taken"?{checkpointId:S.checkpointId}:{},...r.fit?{fit:r.fit}:{},...un(r.emails)});let v=lO(R,n,this.deps.log);return T(this.deps,"seed:execute","seed:error",e,R,{...P?{code:P.code}:{},retryable:!0,extraPayload:{...v,...S?{checkpoint:S}:{}}}),je(this.deps,n,I(O),!0,{extraPayload:v,context:i}),d?.ended({error:O}),{status:"failure"}}}};function x$(s){if(s.length>512)throw new Error(`SOQL WHERE clause too long (${s.length} > 512 chars)`);return bh(s)}var pi=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 Ps(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 ${ze(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 Ps(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 ${ze(t)}${this.whereOf(r,n)}`}whereOf(e,t){let r=e?x$(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 gi=class{resolveInsertOrder(e,t){if(e.length===0)return[];let r=new Set(e),n=t.filter(l=>l.from!==l.to&&r.has(l.from)&&r.has(l.to)),o=new Map(e.map(l=>[l,new Set])),i=new Map(e.map(l=>[l,new Set])),a=new Map(e.map(l=>[l,new Set]));for(let l of n)o.get(l.to)?.add(l.from),l.required&&(Xp(l)?a:i).get(l.to)?.add(l.from);let d=Zi(i).filter(l=>l.length>1);if(d.length>0)throw new Error(N$(d,n.filter(l=>!Xp(l))));let c=new Map(e.map(l=>[l,new Set([...i.get(l)??[],...a.get(l)??[]])])),u=Zi(c).some(l=>l.length>1)?i:c;return D$(Zi(o),o,e).flatMap(l=>l.length>1?wh(l,u):l)}lookupsOf(e,t){return t.filter(r=>r.to===e&&!Xp(r)).map(r=>({field:r.fieldApiName,referenceTo:r.from}))}lookupsFilledAfter(e,t){let r=new Map(e.map((n,o)=>[n,o]));return t.filter(n=>{let o=r.get(n.to),i=r.get(n.from);return!n.required&&o!==void 0&&i!==void 0&&i>=o})}detectSelfReferentialEdges(e){return e.filter(t=>t.from===t.to)}buildEdgesFromDescribe(e,t){let r=new Set(e),n=[];for(let o of e){let i=t.get(o);if(i){for(let a of i.fields)if(a.createable!==!1&&!(o===rr&&a.name==="ActivityId")&&a.type==="reference"&&a.referenceTo){let d=ws(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 ul(r))n.push({from:o.sourceObject,to:o.targetObject,fieldApiName:o.relationshipName,relationshipType:"lookup",required:!0});return n}};function D$(s,e,t){let r=new Map;t.forEach((c,u)=>{r.has(c)||r.set(c,u)});let n=new Map;s.forEach((c,u)=>c.forEach(l=>n.set(l,u)));let o=s.map(c=>Math.min(...c.map(u=>r.get(u)??1/0))),i=s.map((c,u)=>{let l=new Set;for(let g of c)for(let p of e.get(g)??[]){let f=n.get(p);f!==void 0&&f!==u&&l.add(f)}return l}),a=new Set,d=[];for(;d.length<s.length;){let c=-1;for(let u=0;u<s.length;u++)a.has(u)||[...i[u]].some(l=>!a.has(l))||(c===-1||o[u]<o[c])&&(c=u);if(c===-1)break;a.add(c),d.push(s[c])}return d}function Xp(s){return ul(new Set([s.from,s.to])).some(e=>e.sourceObject===s.from&&e.targetObject===s.to&&e.relationshipName===s.fieldApiName)}function N$(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(", ")}. ${j$(t)} must be set when the record is created, so no object of the cycle can be written first.`}function j$(s){return s.length<=1?s.join(""):`${s.slice(0,-1).join(", ")} and ${s[s.length-1]}`}function Yp(s){return s==="insert"||s==="upsert"}function Kd(s,e){return{sending:(t,r,n)=>{Yp(r)&&s.sending(t,n,r==="upsert"?{upsert:!0}:void 0)},opened:(t,r,n,o)=>{Yp(r)&&s.sending(t,n,{job:o,...r==="upsert"?{upsert:!0}:{}})},answered:(t,r,n)=>{if(!Yp(r))return;let o=dd(r,n);s.answered(t,o),e?.(o.length)}}}var M$=new Set(["seed:clone:describe-source","seed:clone:preview","seed:clone:execute"]),L$=5,F$=10,_$=-1,fO="Operation blocked by Production Guard: ",Mr={confirmationDeclined:"PRODUCTION_CONFIRMATION_DECLINED",guardBlocked:"PRODUCTION_GUARD_BLOCKED",failed:"CLONE_FAILED",emailsExceeded:"CLONE_EMAILS_EXCEEDED",apiBudgetExceeded:"API_BUDGET_EXCEEDED",storageExceeded:"CLONE_STORAGE_EXCEEDED"},U$=3;function H$(s,e){let t=s.filter(n=>n.recordCount>0).map(n=>({objectApiName:n.objectApiName,rows:n.recordCount,bytes:no(n.objectApiName,{rows:n.recordCount})})).sort((n,o)=>o.bytes-n.bytes),r=Or({storageBytes:t.reduce((n,o)=>n+o.bytes,0)},e);if(r.verdict==="exceeds")return{estimateMB:r.estimateMB,remainingMB:r.remainingMB,maxMB:r.maxMB,...Ir(r),heaviest:t.slice(0,U$).map(({objectApiName:n,rows:o,bytes:i})=>({objectApiName:n,rows:o,mb:i/(1024*1024)}))}}function hO(s){let e=s<10?100:10;return String(s<=0?0:Math.ceil(s*e-1e-9)/e)}function SO(s,e){let t=s.heaviest.map(r=>`${r.objectApiName} (${r.rows} records, ${hO(r.mb)} MB)`).join(", ");return`its records take about ${hO(s.estimateMB)} MB of data storage, and ${e} has ${s.remainingMB} MB left of ${s.maxMB} MB${Ba(s,e)}. The heaviest: ${t}. Narrow their filter or leave them out, then preview again; or copy a sample of the source that fits with Forge (Depth ALL, Records per object: A sample that fits the target).`}function B$(s,e){return`The clone was refused before it wrote anything: ${SO(s,e)} Nothing was written.`}var q$=6e4,W$={neutralized:!1,fields:[],values:0},z$="PREVIEWED_FOR_OTHER_ORGS",G$="NOT_PREVIEWED",J$="PREVIEW_NOT_HELD",V$=50,Yd=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-GOOVPVWX.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(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 ud({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:()=>Ar(t),...i?{deliverability:i}:{}});return ld(d,a,n)}readTargetAutomation(e,t){let r=this.targetAutomation;return new fe(q$).withTimeout("clone automation",()=>r.read(e,t))}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}beforeRunCheckpoints;setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}runCreations;runningRuns=new Set;setRunCreations(e){this.runCreations=e}isRunning(e){return this.runningRuns.has(e)}async endKept(e,t,r){if(!e)return!1;try{return await e.end({finishedAt:new Date().toISOString(),status:r.status,...r.cancelled?{cancelled:!0}:{},objectResults:[]}),!0}catch(n){return this.deps.log(`[WARN] seed:clone:execute ${t}: what the clone created could not all be kept, so removing it may leave some of it in the org: ${I(n)}`),!1}finally{this.runningRuns.delete(t)}}stoppedForCheckpoint(e,t,r,n,o){let{operationId:i}=t;if(r.code===rt){Z(this.deps,{...t,outcome:"stopped",source:void 0,code:rt}),this.registry?.abort(i),ge(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}:{}}),je(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(!M$.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=$(Fm,e,"seed:clone:error",this.deps);if(t)try{let r=await q(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await r.describeGlobal();xe(r.limitInfo,"seed:clone:describe-source");let o=n.sobjects.filter(a=>a.createable&&a.queryable).filter(a=>!Bi(a.name)).map(a=>({apiName:a.name,label:a.label,recordCount:_$})),i=A(this.deps,e,"seed:clone:describe-source:response",{objects:o});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} count=${o.length}`)}catch(r){T(this.deps,"seed:clone:describe-source","seed:clone:error",e,r)}}async handlePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ml,e,"seed:clone:error",this.deps);if(t)try{let r=await q(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),o=new pi({log:this.deps.log}),i=new gi,a=t.objects.map(b=>b.objectApiName),d=new Map(t.objects.map(b=>[b.objectApiName,b.whereClause])),c=new Map,u=new Map,l=[];for(let b of t.objects){let[O,P]=await Promise.all([Xd("target",b.objectApiName,()=>n.describe(b.objectApiName)),Xd("source",b.objectApiName,()=>o.describe(r,b.objectApiName))]);xe(n.limitInfo,`seed:clone:preview describe ${b.objectApiName} in the target`),xe(r.limitInfo,`seed:clone:preview describe ${b.objectApiName}`),c.set(b.objectApiName,O),u.set(b.objectApiName,P);let v=vh(b.objectApiName,yO(b.objectApiName,c.get(b.objectApiName),u.get(b.objectApiName)),d),[w,C,k]=await Promise.all([o.countRecords(r,b.objectApiName,b.whereClause,v),o.fetchSample(r,b.objectApiName,L$,b.whereClause,v),v.length>0?o.countRecords(r,b.objectApiName,b.whereClause):void 0]),E=k===void 0?0:k-w;l.push({objectApiName:b.objectApiName,recordCount:w,...E>0?{leftToThePlatform:E}:{},sampleRecords:C.map(x=>ox(x,F$))})}let g=i.buildEdgesFromDescribe(a,wO(c,u)),p=i.resolveInsertOrder(a,g),f=l.map(b=>({...b,relationships:i.lookupsOf(b.objectApiName,g)})),h=Q$(i.lookupsFilledAfter(p,g),p),m=Z$(p,u,c),y=ex(p,c,u),R={objects:f,insertOrder:p,...h.length>0?{filledAfterInsert:h}:{},...m.length>0?{sourceOnlyLookups:m}:{},...y.length>0?{targetOnlyRequiredLookups:y}:{}},S=A(this.deps,e,"seed:clone:preview:response",R);this.deps.broker.postToWebview(S),this.deps.log(`[TX] ${S.type} id=${S.id}`),this.rememberPreview(e.id,t,new Map(l.map(b=>[b.objectApiName,b.recordCount])),new Set(i.lookupsFilledAfter(p,g).map(b=>b.to)))}catch(r){let n=r instanceof Qd?r:void 0;T(this.deps,"seed:clone:preview","seed:clone:error",e,r,{...n?{code:X$,retryable:!1,extraPayload:{objectApiName:n.objectApiName,org:ye(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<=V$)break;this.previewedOrgs.delete(o)}}refusedAgainstItsPreview(e){if(e.previewId===void 0)return{code:G$,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:J$,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:z$,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=$(ml,e,"seed:clone:error",this.deps);if(!t)return;let r=this.refusedAgainstItsPreview(t);if(r!==void 0){T(this.deps,e.type,"seed:clone:error",e,new Error(r.reason),{code:r.code});return}let n=e.id,o=Date.now(),i={module:"seed",operation:e.type,...Kr(t.objects.map(b=>({objectApiName:b.objectApiName})))},a=new AbortController,d=()=>{},c=new Promise((b,O)=>{d=P=>P===void 0?b():O(P)});c.catch(()=>{}),this.registry?.register(n,"clone",`Clone ${t.objects.length} object(s)`,c,a);let u={action:"seed_clone",module:"seed",operationId:n,orgId:t.targetOrgId,outcome:"failure",source:{origin:"org",orgId:t.sourceOrgId}},l=!1,g,p=0,f,h=!1,m=[],y=!!(t.upsert&&t.externalIdField),R=Ov(t.keepContactPoints===!0?{keepContactPoints:!0}:{}),S=()=>R?.report()??W$;try{let b=this.deps.infraServices?.productionGuard;if(!b){Z(this.deps,{...u,outcome:"stopped",source:void 0,code:Re.code}),je(this.deps,n,Re.message,!1,{context:i,extraPayload:{code:Re.code}}),d(new Error(Re.message));return}let O=this.deps.orgManager.getOrg(t.targetOrgId),P={orgId:t.targetOrgId,orgTier:Pe(O),operation:t.upsert?"upsert":"insert",objectName:t.objects.map(M=>M.objectApiName).join(", ")||"CloneData",recordCount:"unknown",module:"clone"},{check:v,decision:w}=await et(b,P);if(u.guard=w,(w==="refused"||w==="declined")&&Z(this.deps,{...u,outcome:"stopped",source:void 0}),w==="refused")throw new Error(`${fO}${v.blockedReason??v.impactSummary}`);if(w==="declined"){let M="Operation cancelled by user (confirmation declined).";je(this.deps,n,M,!1,{context:i,extraPayload:{code:Mr.confirmationDeclined}}),d(new Error(M));return}let C=await q(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),k=await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),E=ye(O,t.targetOrgId),x=this.previewedOrgs.get(t.previewId??""),V=x?.recordCounts,H=t.objects.map(M=>({objectApiName:M.objectApiName,recordCount:V?.get(M.objectApiName)??0})),Y=H.filter(M=>M.recordCount>0).map(M=>M.objectApiName),B=(M,G,pe)=>{let ke=pe!==void 0?{checkpointRefusal:pe}:{};Z(this.deps,{...u,outcome:"stopped",source:void 0,code:M,...pe!==void 0?{details:ke}:{}}),je(this.deps,n,G,!1,{context:i,authored:!0,extraPayload:{code:M,...ke}}),d(new Error(G))},N,L=Y.length>0?await this.readTargetAutomation(t.targetOrgId,Y).catch(M=>({unread:I(M)})):{unread:"the clone sends no record"},Q=Y.length>0?await dr({read:L,writes:li(Y,!0),readDeliverability:()=>Pe(O)==="production"?Promise.resolve(zt):Gt(k),accepted:!1,target:E,run:"clone",keepsAddresses:t.keepContactPoints===!0}):void 0,K=Q?.gate.verdict==="asks";if(t.checkpointFirst!==void 0){try{N=await ci(this.beforeRunCheckpoints,{module:"seed",orgId:t.targetOrgId,operationId:n,written:Y,running:Vd(L,li(Y,!0)),request:t.checkpointFirst})}catch(G){if(!(G instanceof Jt))throw G;B(G.code,G.message);return}let M=Ua(N.planned);if(M){B(M.code,M.message,M.refusal.code);return}}let ae=await this.emailGate(t.targetOrgId,k,H,E,L,Q?.gate.deliverability);for(let M of ae?.unknown??[])this.deps.log(`[WARN] seed:clone:execute ${n}: ${M}`);let U=await kr(cr(k,t.targetOrgId)).catch(M=>({unread:I(M)})),re=t.upsert?void 0:H$(H,U);if(ae?.refusal&&ae.figures){let M=K$(ae.figures,re?`It would be refused for its data storage too: ${SO(re,E)}`:void 0);Z(this.deps,{...u,outcome:"stopped",source:void 0,code:Mr.emailsExceeded}),je(this.deps,n,M,!1,{context:i,authored:!0,extraPayload:{code:Mr.emailsExceeded,...ae.figures,...re?{alsoRefused:[{code:Mr.storageExceeded,org:E,...re}]}:{}}}),d(new Error(M));return}let ne="unread"in U?await ur(k).catch(M=>({unread:I(M)})):U.dailyApiRequests;if(re){let M=B$(re,E);Z(this.deps,{...u,outcome:"stopped",source:void 0,code:Mr.storageExceeded}),je(this.deps,n,M,!1,{context:i,authored:!0,extraPayload:{code:Mr.storageExceeded,org:E,...re}}),d(new Error(M));return}let ue=En({run:_v(H.map(M=>({objectApiName:M.objectApiName,rows:M.recordCount})),{threshold:lt(this.deps).bulk.threshold,perCall:this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200),duplicateRules:Uo(L),...x?{secondPass:x.secondPass}:{},automationRead:Y.length>0?Cn(L):0}),...Fo(N?.planned),...$n(Q?.ofRun)},ne);ue.verdict==="unread"&&this.deps.log(`[WARN] seed:clone:execute ${n}: the daily API requests the target has left could not be read (${ue.unread})`);let ce=_a(ue,E,wa);if(ce){Z(this.deps,{...u,outcome:"stopped",source:void 0,code:Mr.apiBudgetExceeded}),je(this.deps,n,ce,!1,{context:i,authored:!0,extraPayload:{code:Mr.apiBudgetExceeded}}),d(new Error(ce));return}let be=!1;if(N||K){let M=H.filter(pe=>pe.recordCount>0).map(pe=>({objectApiName:pe.objectApiName,rows:pe.recordCount})).sort((pe,ke)=>ke.rows-pe.rows),G=await b.confirmRun({stage:"write",module:"seed",org:E,orgTier:Pe(O),objects:M,total:M.reduce((pe,ke)=>pe+ke.rows,0),storage:xn(Or({storageBytes:M.reduce((pe,ke)=>pe+no(ke.objectApiName,{rows:ke.rows}),0)},U)),counted:!0,...Lo(ue),...N?{checkpoint:N.planned}:{},...Q?.gate.confirmation});if(G!=="confirmed"){let pe=Q?.gate.stop;G!=="declined"&&!N&&pe?B(pe.code,pe.message):B(G==="declined"?ts:vt.unanswered,G==="declined"?"The clone was cancelled before it wrote anything. Nothing was written.":`The clone needed an answer before it wrote \u2014 the checkpoint it takes first reads whole tables of ${E} \u2014 and there was no one to ask. Nothing was written.`);return}be=K}if(u.details=un(Q?{read:Q,accepted:be}:void 0).details,Je(this.deps,n,"clone",`Clone ${t.objects.length} object(s)`),this.liveTracker?.register(n,"clone",`Clone ${t.objects.length} object(s)`),N)try{f=await ui(this.beforeRunCheckpoints,N,n,a.signal,(M,G,pe,ke)=>{Fe(this.deps,n,M,G,pe,ke),this.liveTracker?.updateProgress(n,M,G,pe,ke)})}catch(M){if(!(M instanceof Jt))throw M;this.stoppedForCheckpoint(e,u,M,i,Date.now()-o),d(M.code===rt?void 0:M);return}l=!0;let Xe=lt(this.deps),De=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200;i.batchSize=De;let _e=new Map,z={objects:0,records:0,of:1};g=this.runCreations?.recorder({runId:n,targetOrgId:t.targetOrgId,sourceOrgId:t.sourceOrgId,startedAt:new Date(o).toISOString(),origin:"clone"}),f&&g?.checkpoint?.(f),Tr(g,()=>k.identity(),`seed:clone:execute ${n}`),g&&this.runningRuns.add(n);let se=new Dn({...g?{calls:Kd(g,M=>{p+=M})}:{},keyPrefixOf:M=>_e.get(M)?.keyPrefix,connection:k,bulkExecutor:new kn(Xe.bulk.threshold),bulkManager:br(this.deps),retryConfig:Xe.retry,signal:a.signal,onProgress:(M,G,pe)=>{Fe(this.deps,n,G>0?Math.round(M/G*100):0,M,G,pe),this.liveTracker?.updateProgress(n,Math.round((z.objects+M/Math.max(G,1))/z.of*100),z.records+M,0,pe)},log:M=>this.deps.log(M)}),te=new pi({log:this.deps.log}),he=new gi,D=t.objects.map(M=>M.objectApiName),W=new Set(D),X=new Map,F=new Map,ee=new Map;for(let M of D){let[G,pe]=await Promise.all([Xd("target",M,()=>k.describe(M)),Xd("source",M,()=>te.describe(C,M))]);xe(k.limitInfo,`seed:clone:execute describe ${M}`),xe(C.limitInfo,`seed:clone:execute describe ${M} in the source`),X.set(M,G),F.set(M,pe),ee.set(M,Er(G).fields??[]),_e.set(M,{keyPrefix:G.keyPrefix??null,recordTypes:Wh(G.recordTypeInfos)})}let _=he.buildEdgesFromDescribe(D,wO(X,F)),de=he.resolveInsertOrder(D,_),Se=he.lookupsFilledAfter(de,_);z.of=Math.max(de.length,1);let Ue=new Map(t.objects.map(M=>[M.objectApiName,M])),He=new Map,ie=new Map,Ee=new Map,Ne=[],st=new Rh,Be=0,Ve=!1,fs=new Map,qn=[],Wn=W.has(ta),jt=M=>Lt(k,M),Pi=new Map,hr=new Map,Ci=Qn(Rr(M=>Lt(C,M)),async M=>F.get(M)??await te.describe(C,M)),mo=new Map,yo=async(M,G)=>{if(G.length===0)return;let pe=await Ci(M);for(let ke of pe){let we=!1;for(let Le of G)ke in Le&&(we||=Le[ke]!==null&&Le[ke]!==void 0,delete Le[ke]);we&&mo.set(M,(mo.get(M)??new Set).add(ke))}},zn=async(M,G)=>{let pe=(X.get(M)?.fields??[]).filter(Le=>Le.type==="reference"),ke=await $R({lookups:pe,rows:G,known:Pi,query:jt});if(ke.size===0)return;let we=hr.get(M)??new Map;for(let Le of G)for(let{name:me}of pe){let Ye=Le[me];typeof Ye!="string"||!ke.has(Ye)||(delete Le[me],we.set(me,(we.get(me)??0)+1))}we.size!==0&&(hr.set(M,we),this.deps.log(`[INFO] seed:clone ${M}: written without a user or a queue the target does not hold, which the platform fills (the owner with the user the clone writes as): `+[...we].map(([Le,me])=>`${Le} on ${me}`).join(", ")))},hs=async(M,G)=>{await yo(M,G),await zn(M,G),R&&Iv(R,M,ee.get(M)??[],G,y?t.externalIdField:void 0),G.length>0&&(h=!0);try{return{outcomes:t.upsert&&t.externalIdField?await se.upsert(M,t.externalIdField,G,De):await se.insert(M,G,De),stopped:!1}}catch(pe){if(!(pe instanceof Jo))throw pe;return{outcomes:pe.written,stopped:!0}}},mr=(M,G,pe,ke)=>{M.forEach((we,Le)=>{let me=typeof G[Le]?.Id=="string"?G[Le].Id:"";if(we.success){pe.insertedCount++,me&&we.id&&(He.set(me,we.id),pe.idMappings.push({sourceId:me,targetId:we.id}));let Ye=we.id;if(Ye)for(let{fieldName:Ce,sourceRefId:qt}of ke[Le]??[])Ne.push({objectApiName:pe.objectApiName,newId:Ye,sourceId:me||void 0,fieldName:Ce,sourceRefId:qt})}else we.existingId?(pe.linkedCount=(pe.linkedCount??0)+1,me&&(He.set(me,we.existingId),pe.idMappings.push({sourceId:me,targetId:we.existingId}))):(pe.failedCount++,pe.errors.push({sourceId:me,message:we.errors[0]??"Unknown insert error"}))})},$i=async M=>{let G=new Map((m.find(me=>me.objectApiName===rr)?.idMappings??[]).map(me=>[me.sourceId,me.targetId])),pe=new Map;for(let[me,Ye]of fs){let Ce=G.get(me);Ce&&pe.set(Ye,Ce)}let ke=M.map(me=>String(me.Id)).filter(me=>pe.has(me));if(ke.length===0)return new Map;let we;try{we=await kh(jt,[...new Set(ke.map(me=>pe.get(me)??""))])}catch(me){return this.deps.log(`[seed:clone] tasks written with the clone's emails not looked up, written as read: ${I(me)}`),new Map}let Le=new Map;for(let me of ke){let Ye=we.get(pe.get(me)??"");Ye&&Le.set(me,Ye)}return Le},_r=async(M,G,pe)=>{if(Ah[M]===void 0)return new Map;let ke;try{ke=await Th(jt,M,pe)}catch(Le){return this.deps.log(`[seed:clone] ${M}: the relations the target holds not looked up, written as read: ${I(Le)}`),new Map}let we=new Map;for(let[Le,me]of ke){let Ye=G[Le]?.Id;typeof Ye=="string"&&we.set(Ye,me)}return we},xi=async(M,G)=>{if(ie.size===0)return new Map;let pe=X.get(wr),ke=[...new Set(G.flatMap(Ce=>Object.keys(Ce)))].filter(Ce=>RO(pe,Ce)),we;try{we=await Ih(jt,G.map((Ce,qt)=>({OpportunityId:Ce.OpportunityId,[As]:Ce[As],IsPrimary:M[qt]?.IsPrimary})),Ce=>ie.get(Ce),ke)}catch(Ce){return this.deps.log(`[seed:clone] ${wr}: the roles the platform wrote with the clone's opportunities not looked up, written as read \u2014 an opportunity may hold the role of its contact twice: ${I(Ce)}`),new Map}let{found:Le,alike:me}=we;if(me.length>0){this.deps.log(`[seed:clone] ${wr}: ${Oh(me.length)}`);for(let Ce of me)ie.delete(String(G[Ce]?.OpportunityId))}let Ye=new Map;for(let[Ce,qt]of Le){let kt=M[Ce]?.Id;typeof kt=="string"&&(Ye.set(kt,String(qt.Id)),Ee.set(kt,qt),ie.delete(String(G[Ce]?.OpportunityId)))}return Ye},Et=async(M,G)=>{let pe=X.get(wr),ke=[];if(M.forEach(([me,Ye],Ce)=>{let qt=Ee.get(String(me.Id))??{},kt=Object.entries(G[Ce]??{}).filter(([le,Me])=>RO(pe,le)&&Me!==null&&Me!==void 0&&String(qt[le]??"")!==String(Me));kt.length>0&&ke.push({Id:Ye,...Object.fromEntries(kt)})}),ke.length===0||Ve||a.signal.aborted)return;let we;try{we=await se.update(wr,ke,De)}catch(me){if(!(me instanceof Jo))throw me;Ve=!0,we=me.written}let Le=ke.flatMap((me,Ye)=>we[Ye]?.success?[]:[`${me.Id}: ${we[Ye]?.errors[0]??"not updated"}`]);Le.length>0&&this.deps.log(`[seed:clone] ${wr}: linked, and left as the platform wrote them, without the fields of the source's roles: ${Le.slice(0,3).join(" | ")}`)},fn=async()=>{Wn=!1;let M=qn.splice(0,qn.length),G=m.find(me=>me.objectApiName===rr);if(M.length===0||!G||Ve)return;if(a.signal.aborted){Ve=!0;return}let pe=M.map(me=>vO(rr,me,X.get(rr),W,He)),ke=bO(rr,M,pe,Se,He),{outcomes:we,stopped:Le}=await hs(rr,pe);mr(we,M,G,ke),z.records+=M.length,Le&&(Ve=!0)};for(let M=0;M<de.length;M++){if(a.signal.aborted){Ve=!0;break}let G=de[M],pe=Ue.get(G);Fe(this.deps,n,Math.round(M/de.length*100),M,de.length,`Cloning ${G}`),z.objects=M,this.liveTracker?.updateProgress(n,Math.round(M/de.length*100),z.records,0,`Cloning ${G}`);let ke;try{ke=await te.fetchRecords(C,G,pe.whereClause)}catch(Ae){Be++,m.push({objectApiName:G,sourceCount:0,insertedCount:0,failedCount:0,idMappings:[],errors:[{sourceId:"",message:I(Ae)}]});continue}let we=st.keep(G,ke,yO(G,X.get(G),F.get(G)).map(({name:Ae})=>Ae)),Le=ke.length-we.length;if(G===rr)for(let Ae of we){let qe=Ae.ActivityId;typeof Ae.Id=="string"&&typeof qe=="string"&&qe!==""&&fs.set(Ae.Id,qe)}let me=we.map(Ae=>vO(G,Ae,X.get(G),W,He)),Ye=nx(we,X.get(G));Ye.length>0&&this.deps.log(`[INFO] seed:clone ${G}: ${Ye.length} field(s) the target does not have left out \u2014 ${Ye.join(", ")}`);let Ce=bO(G,we,me,Se,He),qt=zh(G,me,_e.get(G)?.recordTypes??[]);if(qt.length>0){Be++,m.push({objectApiName:G,sourceCount:ke.length,insertedCount:0,failedCount:we.length,...Le>0?{leftToThePlatform:Le}:{},idMappings:[],errors:qt.map(Ae=>{let qe=we.find((Ze,Ct)=>Gh(me[Ct],[Ae]));return{sourceId:typeof qe?.Id=="string"?qe.Id:Ae.recordTypeId,message:Jh(Ae)}})});continue}if(G===rr&&Wn){let Ae=we.map(qe=>Sh(qe));qn.push(...we.filter((qe,Ze)=>Ae[Ze])),we=we.filter((qe,Ze)=>!Ae[Ze]),me=me.filter((qe,Ze)=>!Ae[Ze]),Ce=Ce.filter((qe,Ze)=>!Ae[Ze])}let kt=G===ta?await $i(we):G===wr?await xi(we,me):await _r(G,we,me),le=[],Me=[];if(kt.size>0){let Ae=we.map(qe=>!kt.has(String(qe.Id)));we.forEach((qe,Ze)=>{Ae[Ze]||(le.push([qe,kt.get(String(qe.Id))??""]),Me.push(me[Ze]))}),we=we.filter((qe,Ze)=>Ae[Ze]),me=me.filter((qe,Ze)=>Ae[Ze]),Ce=Ce.filter((qe,Ze)=>Ae[Ze])}if(a.signal.aborted){Ve=!0;break}let{outcomes:ot,stopped:Hr}=await hs(G,me);if(Hr&&(Ve=!0,ot.length===0))break;if(G===sx&&ot.forEach((Ae,qe)=>{let Ze=me[qe]?.[As];Ae.success&&Ae.id&&Ae.created!==!1&&typeof Ze=="string"&&Ze!==""&&ie.set(Ae.id,Ze)}),G===wr&&le.length>0&&await Et(le,Me),le.length>0){let Ae=X.get(G),qe=await Eh(G,le,Ze=>Ae?.fields.find(Ct=>Ct.name===Ze)?.updateable!==!1,async Ze=>{try{return await se.update(G,Ze,De)}catch(Ct){if(!(Ct instanceof Jo))throw Ct;return Ve=!0,Ct.written}},()=>Ve||a.signal.aborted);qe&&this.deps.log(`[seed:clone] ${G}: ${qe}`)}let ht={objectApiName:G,sourceCount:ke.length,insertedCount:0,failedCount:0,linkedCount:kt.size,...G===wr&&kt.size>0?{writtenByThePlatform:kt.size}:{},...Le>0?{leftToThePlatform:Le}:{},...Ye.length>0?{fieldsNotInTarget:Ye}:{},idMappings:[],errors:[]};for(let[Ae,qe]of kt)He.set(Ae,qe),ht.idMappings.push({sourceId:Ae,targetId:qe});if(mr(ot,we,ht,Ce),m.push(ht),z.records+=we.length,Ve)break;G===ta&&await fn()}await fn();let Qt;if(Ne.length>0&&(a.signal.aborted&&(Ve=!0),Qt=Ve?rx(Ne):await tx({owed:Ne,idMap:He,targetConn:k,targetOrgId:t.targetOrgId,stopped:()=>a.signal.aborted,report:M=>{Fe(this.deps,n,100,z.records,z.records,M),this.liveTracker?.updateProgress(n,100,z.records,0,M)}}),a.signal.aborted&&(Ve=!0),g&&Qt.filled>0)){let M=new Map;for(let{objectApiName:G,newId:pe}of Ne)M.set(G,[...M.get(G)??[],pe]);for(let[G,pe]of M)g.wroteAgain(G,pe)}for(let M of m){let G=hr.get(M.objectApiName);G&&(M.lookupsNotCarried=[...G].map(([ke,we])=>({field:ke,records:we})));let pe=mo.get(M.objectApiName);pe&&(M.encryptedLeftOut=[...pe].sort())}let wo=m.reduce((M,G)=>M+G.sourceCount,0),Gn=m.reduce((M,G)=>M+G.insertedCount,0),Di=m.reduce((M,G)=>M+(G.linkedCount??0),0),Ni=m.reduce((M,G)=>M+(G.leftToThePlatform??0),0),$e=m.reduce((M,G)=>M+G.failedCount,0),Ge=$e===0&&Be===0?"success":Gn+Di>0?"partial":"failure",Qe=Qt!==void 0&&Qt.filled<Qt.owed,at=S(),St=(Ve||Qe)&&Ge==="success"?"partial":Ge,nt=await this.endKept(g,n,{status:St,cancelled:Ve});g=void 0;let ct=await Mn(this.beforeRunCheckpoints,f,h,this.deps.log,`seed:clone:execute ${n}`);f=void 0;let Mt={status:St,objectResults:m,totalSourceRecords:wo,totalInserted:Gn,totalLinked:Di,...Ni>0?{totalLeftToThePlatform:Ni}:{},totalFailed:$e,...Qt?{secondPass:Qt}:{},durationMs:Date.now()-o,...Ve?{cancelled:!0}:{},contactPoints:at,...nt&&p>0?{runId:n}:{}};l=!1;let Ur=Ve?Gn+$e>0?"cancelled":"stopped":Mt.status;Z(this.deps,{...mO(u,Ur,m,y,at),...Ur==="stopped"?{code:rt}:{},...ct?.state==="taken"?{checkpointId:ct.checkpointId}:{}});let Pt=!Ve&&Mt.status==="failure"?"No record could be cloned.":void 0;Ve?(this.registry?.abort(n),ge(this.deps,n,{aborted:!0,totalInserted:Gn,totalFailed:$e}),this.liveTracker?.cancel(n)):(ge(this.deps,n,{status:Mt.status,totalInserted:Gn,totalFailed:$e}),Pt!==void 0?this.liveTracker?.fail(n,Pt):Mt.status==="partial"?this.liveTracker?.partial(n):this.liveTracker?.complete(n));let Zt={...Mt,...ct?{checkpoint:ct}:{}},er=A(this.deps,e,"seed:clone:execute:response",Zt);this.deps.broker.postToWebview(er),this.deps.log(`[TX] ${er.type} id=${er.id} status=${Mt.status}`),d(Pt===void 0?void 0:new Error(Pt))}catch(b){let O=await Mn(this.beforeRunCheckpoints,f,h,this.deps.log,`seed:clone:execute ${n}`);l&&Z(this.deps,{...mO(u,"failure",m,y,S()),...O?.state==="taken"?{checkpointId:O.checkpointId}:{}}),await this.endKept(g,n,{status:"failure",cancelled:!1});let P=O?.state==="deleted"?`${I(b)} ${en}`:I(b);this.deps.log(`[ERR] seed:clone:execute: ${P}`),je(this.deps,n,I(b),!0,{context:i,extraPayload:{code:P.startsWith(fO)?Mr.guardBlocked:Mr.failed,...O?{checkpoint:O}:{}}}),this.liveTracker?.fail(n,P),d(b)}}};function K$(s,e){let t=[`narrow the filters of ${s.objects.join(", ")} or leave them out`,`turn off ${s.senders.map(r=>`"${r}"`).join(", ")}`,...s.bypasses.map(r=>"give the user the clone writes as "+(r.permissionSet?`the permission set ${r.permissionSet}, whose ${r.permission}`:`a permission set holding ${r.permission}, which`)+" keeps them quiet")];return`The clone was refused before it wrote anything: its records would make ${s.org} send about ${cR(s.emails,s.limit)}, ${s.remaining} of ${s.max} left today. Past what is left, a flow that sends in the save refuses its record (CANNOT_EXECUTE_FLOW_TRIGGER), and the org's own emails stop for the rest of the day. To clone them, ${t.join("; or ")}. ${e?`${e} `:""}Nothing was written.`}function mO(s,e,t,r,n){return{...s,details:{...s.details,...Es(n).details},outcome:e,objects:t.map(o=>({...mt(o.objectApiName),...r?{upserted:o.insertedCount}:{created:o.insertedCount},failed:o.failedCount})),carried:Object.fromEntries(t.map(o=>[o.objectApiName,o.idMappings.length]))}}function yO(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)&&ws(s,n.name,n.nillable)).map(n=>({name:n.name,referenceTo:n.referenceTo??[]}))}async function Xd(s,e,t){try{return await t()}catch(r){let n=I(r);throw s==="target"&&Y$(r,n)?new Qd(e,n):new Error(`${e} could not be described in the ${s} org: ${n}`)}}var X$="OBJECT_NOT_IN_TARGET",Qd=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 Y$(s,e){return s?.errorCode==="NOT_FOUND"||/\bNOT_FOUND\b|requested resource does not exist|INVALID_TYPE/.test(e)}function wO(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 Q$(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 Z$(s,e,t){let r=new Set(s);return s.flatMap(n=>{let o=Zd(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 ex(s,e,t){return s.flatMap(r=>{let n=Zd(t.get(r));return n?(e.get(r)?.fields??[]).filter(o=>o.type==="reference"&&!n.has(o.name)&&o.createable!==!1&&o.defaultedOnCreate!==!0&&ws(r,o.name,o.nillable)).flatMap(o=>(o.referenceTo??[]).map(i=>({objectApiName:r,field:o.name,referenceTo:i}))):[]})}function bO(s,e,t,r,n){let o=r.filter(c=>c.to===s),i=new Set(o.filter(c=>c.from!==s).map(c=>c.fieldApiName)),a=new Set(o.map(c=>c.fieldApiName)),d=new Set(e.map(c=>c.Id).filter(c=>typeof c=="string"));return t.map((c,u)=>{let l=[];for(let g of a){let p=e[u]?.[g];typeof p!="string"||p===""||n.has(p)||g in c&&(!i.has(g)&&!d.has(p)||(delete c[g],l.push({fieldName:g,sourceRefId:p})))}return l})}async function tx(s){let{owed:e,targetConn:t}=s,{patchCycleFkUpdates:r}=await import("./chunk-BRY3PLIZ.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:Hi()});return(Array.isArray(d)?d:[d]).map((c,u)=>{let l=a[u]?.Id;return{id:c.id??(typeof l=="string"?l:""),success:c.success,errors:(c.success?[]:c.errors).map(kw)}})},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 rx(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 Zd(s){let e=new Set((s?.fields??[]).map(t=>t.name));return e.size>0?e:null}function nx(s,e){let t=Zd(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 ox(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 sx="Opportunity";function RO(s,e){if(e==="OpportunityId"||e===As)return!1;let t=s?.fields.find(r=>r.name===e);return t!==void 0&&t.updateable!==!1}function vO(s,e,t,r,n){let o=new Set((t?.fields??[]).filter(d=>d.createable===!1).map(d=>d.name)),i=Zd(t),a={};for(let[d,c]of Object.entries(e))d==="Id"||o.has(d)||i&&!i.has(d)||(a[d]=c);if(t)for(let d of t.fields){if(d.type!=="reference"||!(d.referenceTo??[]).some(u=>r.has(u)))continue;let c=a[d.name];typeof c=="string"&&n.has(c)&&(a[d.name]=n.get(c))}for(let d of ra(s,a))delete a[d];return a}var ix=new Set(["double","currency","percent","int","integer"]),ec=class{validate(e,t,r,n){let o=[],i=new Map(r.map(a=>[a.name,a]));for(let a=0;a<e.length&&o.length<100;a++){let d=e[a];for(let c of t){if(o.length>=100)break;if(!c.sfFieldApiName)continue;let u=i.get(c.sfFieldApiName);if(!u)continue;let l=d[c.csvHeader]??"";if(l===""&&!u.nillable&&u.defaultValue===null){o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"missing_required",message:`Required field "${c.sfFieldApiName}" is empty`,value:l});continue}if(l!==""){if(ix.has(u.type.toLowerCase())){let g=parseFloat(l);isNaN(g)&&o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"type_mismatch",message:`Expected numeric value for field "${c.sfFieldApiName}", got "${l}"`,value:l})}u.length&&u.length>0&&l.length>u.length&&o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"length_exceeded",message:`Value exceeds max length ${u.length} for field "${c.sfFieldApiName}" (got ${l.length})`,value:l}),u.type.toLowerCase()==="picklist"&&u.picklistValues&&u.picklistValues.length>0&&(u.picklistValues.map(p=>p.value).includes(l)||o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"invalid_picklist",message:`Invalid picklist value "${l}" for field "${c.sfFieldApiName}"`,value:l}))}}}if(n&&o.length<100){let a=t.find(d=>d.sfFieldApiName===n);if(a){let d=new Map;for(let c=0;c<e.length&&o.length<100;c++){let u=e[c][a.csvHeader]??"";if(u==="")continue;let l=d.get(u);l!==void 0?o.push({row:c+1,column:a.csvHeader,field:n,errorType:"duplicate_external_id",message:`Duplicate external ID "${u}" (also in row ${l})`,value:u}):d.set(u,c+1)}}}return{valid:o.length===0,errors:o,warningCount:0}}};var ax=new Set(["seed:csv:validate","seed:csv:execute"]),dx=100,kO="IMPORT_CANCELLED",cx=6e4,Qp="CSV_STORAGE_EXCEEDED";function ux(s){let e=s<10?100:10;return String(s<=0?0:Math.ceil(s*e-1e-9)/e)}function lx(s,e,t){let r=e>0?no(s,{rows:e})/e:0,n=Wb(t);return r>0?Math.max(0,Math.floor(n*1024*1024/r)):0}var tc=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-GOOVPVWX.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async handle(e){if(!ax.has(e.type))return!1;switch(e.type){case"seed:csv:validate":return await this.handleValidate(e),!0;case"seed:csv:execute":return await this.handleExecute(e),!0;default:return!1}}async endKept(e,t,r){if(!e)return!1;try{return await e.end({finishedAt:new Date().toISOString(),status:r.status,...r.cancelled?{cancelled:!0}:{},objectResults:[]}),!0}catch(n){return this.deps.log(`[WARN] seed:csv:execute ${t}: what the import created could not all be kept, so removing it may leave some of it in the org: ${I(n)}`),!1}finally{this.runningRuns.delete(t)}}stoppedForCheckpoint(e,t,r,n){let{operationId:o}=t;if(r.code===rt){Z(this.deps,{...t,outcome:"stopped",source:void 0,code:kO}),this.registry?.abort(o),ge(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}:{}}),T(this.deps,"seed:csv:execute","seed:csv:error",e,r,{code:r.code,retryable:!1,...i!==void 0?{extraPayload:a}:{}}),je(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=$(yl,e,"seed:csv:error",this.deps);if(t)try{let r=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),n=await r.describe(t.objectApiName);xe(r.limitInfo,`seed:csv:validate describe ${t.objectApiName}`);let i=new ec().validate(t.records,t.columnMappings,n.fields,t.externalIdField),a=A(this.deps,e,"seed:csv:validate:response",i);this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id} valid=${i.valid}`)}catch(r){T(this.deps,"seed:csv:validate","seed:csv:error",e,r)}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(yl,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((f,h)=>{i=m=>m===void 0?f():h(m)});a.catch(()=>{}),this.registry?.register(r,"csv","CSV import",a,o);let d={action:"seed_csv_import",module:"seed",operationId:r,orgId:t.orgId,outcome:"failure",source:{origin:"csv"}},c=!1,u,l=0,g,p=!1;try{let f=this.deps.infraServices?.productionGuard;if(!f){Z(this.deps,{...d,outcome:"stopped",source:void 0,code:Re.code}),T(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(Re.message),{code:Re.code,retryable:!1}),je(this.deps,r,Re.message,!1,{context:n,extraPayload:{code:Re.code}}),i(new Error(Re.message));return}let h=this.deps.orgManager.getOrg(t.orgId),m={orgId:t.orgId,orgTier:Pe(h),operation:t.externalIdField?"upsert":"insert",objectName:t.objectApiName,recordCount:t.records.length,module:"seed"},{check:y,decision:R}=await et(f,m);if(d.guard=R,(R==="refused"||R==="declined")&&Z(this.deps,{...d,outcome:"stopped",source:void 0}),R==="refused")throw bn(y.blockedReason??y.impactSummary);if(R==="declined"){let te="Operation cancelled by user (confirmation declined).";T(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(te),{code:xt.declined}),je(this.deps,r,te,!1,{context:n}),i(new Error(te));return}let S=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),b=ye(h,t.orgId),O=(te,he,D)=>{let W=D!==void 0?{checkpointRefusal:D}:{};Z(this.deps,{...d,outcome:"stopped",source:void 0,code:te,...D!==void 0?{details:W}:{}}),T(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(he),{code:te,retryable:!1,...D!==void 0?{extraPayload:W}:{}}),je(this.deps,r,he,!1,{context:n,authored:!0,extraPayload:{code:te,...W}}),i(new Error(he))},P=this.targetAutomation,v=li([t.objectApiName],!!t.externalIdField),w=await new fe(cx).withTimeout("csv automation",()=>P.read(t.orgId,[t.objectApiName])).catch(te=>({unread:I(te)}));typeof w.unread=="string"&&this.deps.log(`[WARN] seed:csv:execute ${r}: what the org runs on ${t.objectApiName} could not be read (${w.unread}): it is asked about its emails, and a checkpoint holds the object alone`);let C=await dr({read:w,writes:v,readDeliverability:()=>Pe(h)==="production"?Promise.resolve(zt):Gt(S),accepted:!1,target:b,run:"seed",keepsAddresses:!0}),k=C.gate.verdict==="asks",E;if(t.checkpointFirst!==void 0){try{E=await ci(this.beforeRunCheckpoints,{module:"seed",orgId:t.orgId,operationId:r,written:[t.objectApiName],running:Vd(w,v),request:t.checkpointFirst})}catch(he){if(!(he instanceof Jt))throw he;O(he.code,he.message);return}let te=Ua(E.planned);if(te){O(te.code,te.message,te.refusal.code);return}}let x=await kr(cr(S,t.orgId)).catch(te=>({unread:I(te)})),V="unread"in x?await ur(S).catch(te=>({unread:I(te)})):x.dailyApiRequests,H=Or({storageBytes:no(t.objectApiName,{rows:t.records.length})},x);if(!t.externalIdField&&H.verdict==="exceeds"){let te=t.records.length,he=lx(t.objectApiName,te,H),D=Ir(H),W=`The import was refused before it wrote anything: its ${te} rows take about ${ux(H.estimateMB)} MB of data storage, and ${b} has ${H.remainingMB} MB left of ${H.maxMB} MB${Ba(D,b)}, room for about ${he} 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:Qp});let X={org:b,rows:te,fitting:he,estimateMB:H.estimateMB,remainingMB:H.remainingMB,maxMB:H.maxMB,...D};T(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(W),{code:Qp,retryable:!1,extraPayload:X}),je(this.deps,r,W,!1,{context:n,authored:!0,extraPayload:{code:Qp,...X}}),i(new Error(W));return}let Y=En({run:Lv([{objectApiName:t.objectApiName,rows:t.records.length}],{threshold:lt(this.deps).bulk.threshold,perCall:this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200),duplicateRules:Uo(w)})+Fv(0,Cn(w)),...Fo(E?.planned),...$n(C.ofRun)},V);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 B=_a(Y,ye(h,t.orgId),wa);if(B){Z(this.deps,{...d,outcome:"stopped",source:void 0,code:Mo}),T(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(B),{code:Mo,retryable:!1}),je(this.deps,r,B,!1,{context:n,authored:!0,extraPayload:{code:Mo}}),i(new Error(B));return}let N=!1;if(E||k){let te=t.records.length,he=await f.confirmRun({stage:"write",module:"seed",org:b,orgTier:Pe(h),objects:[{objectApiName:t.objectApiName,rows:te}],total:te,storage:xn(Or({storageBytes:no(t.objectApiName,{rows:te})},x)),...Lo(Y),...E?{checkpoint:E.planned}:{},...C.gate.confirmation});if(he!=="confirmed"){let D=C.gate.stop;he!=="declined"&&!E&&D?O(D.code,D.message):O(he==="declined"?ts:vt.unanswered,he==="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 ${b} \u2014 and there was no one to ask. Nothing was written.`);return}N=k}if(d.details=un({read:C,accepted:N}).details,Je(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),E)try{g=await ui(this.beforeRunCheckpoints,E,r,o.signal,(te,he,D,W)=>{Fe(this.deps,r,te,he,D,W),this.liveTracker?.updateProgress(r,te,he,D,W)})}catch(te){if(!(te instanceof Jt))throw te;this.stoppedForCheckpoint(e,d,te,n),i(te.code===rt?void 0:te);return}c=!0;let L=lt(this.deps),Q=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200;n.batchSize=Q,u=this.runCreations?.recorder({runId:r,targetOrgId:t.orgId,startedAt:new Date().toISOString(),origin:"csv"}),g&&u?.checkpoint?.(g),Tr(u,()=>S.identity(),`seed:csv:execute ${r}`),u&&this.runningRuns.add(r);let K=new Dn({connection:S,bulkExecutor:new kn(L.bulk.threshold),bulkManager:br(this.deps),retryConfig:L.retry,signal:o.signal,onProgress:(te,he,D)=>{let W=he>0?Math.round(te/he*100):0;Fe(this.deps,r,W,te,he,D),this.liveTracker?.updateProgress(r,W,te,he,D)},log:te=>this.deps.log(te),...u?{calls:Kd(u,te=>{l+=te})}:{}}),ae=t.records.map(te=>px(te,t.columnMappings)),U=o.signal.aborted,re=[];if(!U){ae.length>0&&(p=!0);try{re=t.externalIdField?await K.upsert(t.objectApiName,t.externalIdField,ae,Q):await K.insert(t.objectApiName,ae,Q)}catch(te){if(!(te instanceof Jo))throw te;U=!0,re=te.written}}let ne=[],ue=0;for(let te of re)te.success?ue++:ne.length<dx&&ne.push(te.errors[0]??"Unknown insert error");let ce=re.length-ue,be=ce===0?"success":ue>0?"partial":"failure",Xe=!U&&be==="failure"?ne[0]??"No row could be imported.":void 0;c=!1;let De=await Mn(this.beforeRunCheckpoints,g,p,this.deps.log,`seed:csv:execute ${r}`);g=void 0,U&&re.length===0?Z(this.deps,{...d,outcome:"stopped",source:void 0,code:kO}):Z(this.deps,{...d,outcome:U?"cancelled":be,objects:[{...mt(t.objectApiName),...t.externalIdField?{upserted:ue}:{created:ue},failed:ce}],...De?.state==="taken"?{checkpointId:De.checkpointId}:{}});let _e=await this.endKept(u,r,{status:U&&be==="success"?"partial":be,cancelled:U});u=void 0;let z={insertedCount:ue,failedCount:ce,errors:ne,...U?{cancelled:!0}:{},..._e&&l>0?{runId:r}:{},...De?{checkpoint:De}:{}};U?(this.registry?.abort(r),ge(this.deps,r,{aborted:!0,insertedCount:ue,failedCount:ce}),this.liveTracker?.cancel(r)):(ge(this.deps,r,{status:be,insertedCount:ue,failedCount:ce}),Xe!==void 0?this.liveTracker?.fail(r,Xe):be==="partial"?this.liveTracker?.partial(r):this.liveTracker?.complete(r));let se=A(this.deps,e,"seed:csv:execute:response",z);this.deps.broker.postToWebview(se),this.deps.log(`[TX] ${se.type} id=${se.id} inserted=${ue} failed=${ce}`),i(Xe===void 0?void 0:new Error(Xe))}catch(f){let h=await Mn(this.beforeRunCheckpoints,g,p,this.deps.log,`seed:csv:execute ${r}`);c&&Z(this.deps,{...d,...h?.state==="taken"?{checkpointId:h.checkpointId}:{}}),await this.endKept(u,r,{status:"failure",cancelled:!1});let m=h?.state==="deleted"?`${I(f)} ${en}`:I(f);T(this.deps,"seed:csv:execute","seed:csv:error",e,f,{code:Eo(f),retryable:!0,...h?{extraPayload:{checkpoint:h}}:{}}),je(this.deps,r,m,!0,{context:n}),this.liveTracker?.fail(r,m),i(f)}}};function px(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]=gx(n))}return t}function gx(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 fx={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"])},hx=[{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 Zp(s,e){let t=s.toLowerCase(),r=e.toLowerCase();if(t===r)return!0;let n=fx[t];return n?n.has(r):r==="string"}var rc=class{validateMapping(e,t,r){let n=[],o=[],i=new Map(e.map(d=>[d.apiName,d])),a=new Map(t.map(d=>[d.apiName,d]));for(let[d,c]of Object.entries(r)){let u=i.get(d),l=a.get(c);if(!u||!l)continue;let g=this.checkTypeCompatibility(d,u.type,c,l.type);g.compatible?g.reason&&o.push(g):n.push(g)}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&&OO(a)){r.push({recordIndex:n,field:i.apiName,message:`Required field '${i.apiName}' is missing or empty`});continue}if(OO(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=Zp(o,i),d=hx.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"||!mx(e))return`Expected valid ${r} string`;break}}};function OO(s){return s==null||s===""}function mx(s){let e=Date.parse(s);return!isNaN(e)}var nc=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 eg=3e4,IO=6e4,tg="Nothing was read or written.",AO="Nothing was read.",TO="the checkpoints of this window are not open to the Sync page",wx=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"]),EO={insert:0,update:1,upsert:2,delete:3};function ng(s,e){let t=s.objects??[],r="insert";for(let o of t)EO[o.operation]>EO[r]&&(r=o.operation);s.mode==="delta"&&s.propagateDeletes===!0&&(r="delete");let n=t.map(o=>o.objectApiName);return{orgId:s.targetOrgId,orgTier:Pe(e),operation:r,objectName:n.length>0?n.join(", "):"SyncData",recordCount:"unknown",module:"sync"}}function bx(s){return s.map(e=>{let t={...mt(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 Rx=new Set(["direct","rename"]),rg=20,vx=J({fields:ve(J({name:j(),type:j(),createable:Ke(),updateable:Ke()}).loose())});function PO(s,e,t){let r=vx.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 CO(s){if(s==="ask")return{emailsLiftedBy:"Untick Mute automation to be asked about them and sync all the same"};let e=nb();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 oc=class{constructor(e){this.deps=e;this.syncConfigStore=new It(e.configStore)}deps;activeOperationIds=new Set;dmlTracker=new ia;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-GOOVPVWX.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}confirmAboveRecords(){let e=this.deps.services?.getSandforgeSetting?.("safety.confirmAboveRecords",tn);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):tn}readCap(){return id(this.deps.services?.getSandforgeSetting?.("sync.maxRecordsPerObject",void 0))}writeGateFor(e,t,r,n,o,i){let{targetConn:a}=t,d=this.deps.orgManager.getOrg(e.targetOrgId),c=this.targetAutomation,u=this.deps.infraServices?.productionGuard,l=CO(r),g=this.readCap(),p=qv(e,async f=>{let{totalSize:h}=await a.query(f);return Math.min(h,g)});return Wv({readStorage:()=>new fe(eg).withTimeout("sync:limits",()=>kr(a)),readApiBudget:()=>new fe(eg).withTimeout("sync:limits",()=>ur(a)),readAutomation:n??(f=>new fe(IO).withTimeout("sync:automation",()=>c.read(e.targetOrgId,f))),readLimits:()=>new fe(eg).withTimeout("sync:limits",()=>Ar(a)),readDeliverability:()=>Pe(d)==="production"?Promise.resolve(zt):Gt(a),emails:{target:ye(d,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}:{},...p?{countTarget:p}:{},targetFields:async f=>((await t.describeTargetFields(f)).fields??[]).map(h=>h.name)},{policy:r,org:ye(d,e.targetOrgId),orgTier:Pe(d),...u?{confirm:f=>u.confirmRun(f)}:{},emailsLiftedBy:l.emailsLiftedBy})}setRegistry(e){this.registry=e}setMuteLeases(e){this.muteLeases=e}muteLeases={};setHistoryLogger(e){this.historyLogger=e}setLiveOperationTracker(e){this.liveTracker=e}setRunCreations(e){this.runCreations=e}setBackupRecordStore(e){this.backupRecords=e}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}beforeRunCheckpoints;runCheckpointOf(e,t,r,n){let o=this.beforeRunCheckpoints,i={runId:t},a,d,c,u;return{gate:{scope:async(l,g)=>{if(!o)throw new Error(TO);return a={module:"sync",orgId:e.targetOrgId,operationId:t,written:[...l],running:g,request:r},d=await o.scope(a,i),u=d.refusal,d},take:async l=>{if(!o||!a)throw new Error(TO);let g=await o.take(a,i,{planned:l,...n?{signal:n.signal,onProgress:p=>{let f=jo(p.percentage),h=Math.round(p.percentage),{processedObjects:m,totalObjects:y}=p;Fe(this.deps,t,h,m,y,f),this.liveTracker?.updateProgress(t,h,m,y,f)}}:{}});return g.taken?(c=g.checkpoint,n?.recorder?.checkpoint?.(g.checkpoint)):"refusal"in g&&(u=g.refusal),g}},planned:()=>d,taken:()=>c,refusal:()=>u}}async settleRunCheckpoint(e,t,r){let n=e?.taken();if(!(!n||!this.beforeRunCheckpoints))try{return await this.beforeRunCheckpoints.settle(n,t)}catch(o){return this.deps.log(`[WARN] sync ${r}: the checkpoint '${n.name}' taken before the run is kept: ${I(o)}`),n}}isRunning(e){return this.activeOperationIds.has(e)}async handle(e){if(!wx.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=So(t.objects);return i.length===0?!1:(T(this.deps,r,n,e,new Error(`${ko(i)} ${o}`),{code:Wi,extraPayload:{rules:i}}),!0)}async handleConfigSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(im,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(sh(this.syncConfigStore.list(),r.id,r.name)){let o=A(this.deps,e,"sync:config:save:response",{success:!1,id:r.id,code:"DUPLICATE_NAME"});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} DUPLICATE_NAME`);return}this.syncConfigStore.save(r);let n=A(this.deps,e,"sync:config:save:response",{success:!0,id:r.id});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){T(this.deps,"sync:config:save","sync:error",e,r)}}async handleConfigLoad(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(da,e,"sync:error",this.deps);if(t)try{let r=this.syncConfigStore.load(t.id),n=A(this.deps,e,"sync:config:load:response",{config:r??null});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){T(this.deps,"sync:config:load","sync:error",e,r)}}async handleConfigList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let r=this.syncConfigStore.list().map(o=>{let i=this.syncConfigStore.loadDelta(o.id);return{id:o.id,name:o.name,description:o.description,updatedAt:o.updatedAt,mode:o.mode,propagateDeletes:o.propagateDeletes===!0,watermarks:i.kind==="stored"?i.state.entries.length:0}}),n=A(this.deps,e,"sync:config:list:response",{configs:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(t){T(this.deps,"sync:config:list","sync:error",e,t)}}async handleConfigDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(da,e,"sync:error",this.deps);if(t)try{let r=this.syncConfigStore.delete(t.id);await this.runCreations?.idMap().delete(t.id).catch(o=>this.deps.log(`[WARN] sync:config:delete ${t.id}: ${I(o)}`));let n=A(this.deps,e,"sync:config:delete:response",{success:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){T(this.deps,"sync:config:delete","sync:error",e,r)}}async handleConfigResetDelta(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(da,e,"sync:error",this.deps);if(t)try{if(!this.syncConfigStore.load(t.id))throw new Error("This configuration is no longer saved: there is nothing to reset.");let r=this.syncConfigStore.clearDelta(t.id),n=A(this.deps,e,"sync:config:reset-delta:response",{success:!0,id:t.id,cleared:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} cleared=${r}`)}catch(r){T(this.deps,"sync:config:reset-delta","sync:error",e,r)}}deltaStoreFor(){return this.syncConfigStore.deltaStore()}fileStoreFor(){return this.syncConfigStore.fileStore()}idMapFor(){let e=this.runCreations;if(e)return Ww(e.idMap(),t=>this.syncConfigStore.isSaved(t))}recordRun(e,t,r,n,o,i){let a=bx(r.objectResults??[]),d=a.some(u=>u.created+u.updated+u.deleted+u.failed+(u.upserted??0)>0),c=r.cancelled===!0?d?"cancelled":"stopped":r.status;Z(this.deps,{action:"sync_execute",module:"sync",operationId:t,orgId:e.targetOrgId,outcome:c,...c==="stopped"?{code:rt}:{},guard:n,objects:a,source:{origin:"org",orgId:e.sourceOrgId},details:{triggeredBy:o,...eo(i)},...r.mutedAutomation?{muted:ut(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 ng(e,this.deps.orgManager.getOrg(e.targetOrgId))}async assertFieldTypesMatch(e,t,r,n){let o=new rc,i=[],a=u=>({apiName:u.name,type:u.type});for(let u of e.objects){if(u.operation==="delete")continue;let l=u.objectApiName,g=new fe(n),[p,f]=await Promise.all([g.withTimeout(`describe-source-${l}`,()=>Yt(e.sourceOrgId,l,()=>t.describe(l))),g.withTimeout(`describe-target-${l}`,()=>Yt(e.targetOrgId,l,()=>r.describe(l)))]),h=PO(p,l,"source").map(a),m=PO(f,l,"target").filter(b=>b.createable||b.updateable).map(a),y=kv(u,{creatable:new Set(m.map(b=>b.apiName))}),R=Yh(y.fieldMappings,y.excludedFields),S=[Object.fromEntries(h.filter(b=>!R.has(b.apiName.toLowerCase())).map(b=>[b.apiName,b.apiName])),...u.fieldMappings.filter(b=>Rx.has(b.type)).map(b=>({[b.sourceField]:b.targetField}))];for(let b of S)for(let O of o.validateMapping(h,m,b).errors)i.push(`${l}.${O.sourceField} (${O.sourceType}) -> ${l}.${O.targetField} (${O.targetType})`)}if(i.length===0)return;let d=i.slice(0,rg).join("; "),c=i.length>rg?` and ${i.length-rg} 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=$(am,e,"sync:error",this.deps);if(!t)return;let r=lt(this.deps);try{let n=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),o=new fe(r.timeouts.describeGlobal),i=await o.withTimeout("describe-global",()=>n.describeGlobal());xe(n.limitInfo,"sync:describe-global");let a=i.sobjects.filter(l=>l.queryable&&!aa(l.name)),d,c=[];if(t.targetOrgId===void 0)d=a.filter(l=>l.createable).map(l=>l.name);else{let l=await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),g=await o.withTimeout("describe-global",()=>l.describeGlobal());xe(l.limitInfo,"sync:describe-global target");let p=new Map(g.sobjects.map(f=>[f.name,{createable:f.createable,updateable:f.updateable}]));d=[];for(let f of a){let h=p.get(f.name);if(h&&(h.createable||h.updateable)){d.push(f.name);continue}f.createable&&c.push({objectApiName:f.name,why:h?"notCreateable":"notInTarget"})}}let u=A(this.deps,e,"sync:describe-global:response",{objects:d,...c.length>0?{unwritable:c}:{}});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`)}catch(n){T(this.deps,"sync:describe-global","sync:error",e,n)}}async handleDescribeFields(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(dm,e,"sync:error",this.deps);if(!t)return;let r=t,n=lt(this.deps);try{let o=await q(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),i=await q(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))]);xe(o.limitInfo,`sync:describe-fields source ${r.objectApiName}`),xe(i.limitInfo,`sync:describe-fields target ${r.objectApiName}`);let u=g=>g.filter(p=>p.createable).map(p=>({apiName:p.name,label:p.label,type:p.type})),l=A(this.deps,e,"sync:describe-fields:response",{objectApiName:r.objectApiName,sourceFields:u(d.fields),targetFields:u(c.fields)});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`)}catch(o){T(this.deps,"sync:describe-fields","sync:error",e,o)}}async handleWriteOrder(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(gl,e,"sync:error",this.deps);if(!t)return;let r=t.config;try{let n=await q(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),o=lt(this.deps).timeouts.describe,i=new Map;for(let u of r.objects){if(u.operation==="delete")continue;let l=u.objectApiName;try{let g=await new fe(o).withTimeout(`describe-target-${l}`,()=>Yt(r.targetOrgId,l,()=>n.describe(l)));i.set(l,Pv(u,Er(g)))}catch{}}let{order:a}=Cv(r.objects,i),d=await this.encryptedMaskedOf(r,o).catch(()=>[]),c=A(this.deps,e,"sync:write-order:response",{order:a,...d.length>0?{encrypted:d}:{},readCap:this.readCap()});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(n){T(this.deps,"sync:write-order","sync:error",e,n)}}async encryptedMaskedOf(e,t){let r=e.objects.filter(a=>a.operation!=="delete");if(r.length===0)return[];let n=await q(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=Qn(Rr(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=$(vn,e,"sync:error",this.deps);t&&(this.refusedFieldless(e,t.config,"sync:execute","sync:error",tg)||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=$(gl,e,"sync:error",this.deps);if(!t||this.refusedFieldless(e,t.config,"sync:simulate","sync:error",AO))return;let r=e.id,n=t.config,o=`Simulation of a sync of ${n.objects.length} object(s), writing nothing`,i=new AbortController;Je(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,...Kr(t.objects)};try{let c=await this.readersFor(t,n.signal),{DataSync:u}=await import("./chunk-I6E6T6YY.mjs"),{ConflictResolver:l}=await import("./chunk-CHCHAE4B.mjs"),{FieldMappingService:g}=await import("./chunk-PR3XCSPO.mjs"),{TransformPipeline:p}=await import("./chunk-36JOHEJL.mjs"),{toolingQueriesOver:f,toolingValidationRules:h}=await import("./chunk-6O222PW6.mjs"),{toolingRetrievesOver:m}=await import("./chunk-GOOVPVWX.mjs"),y=c.targetConn.tooling,R=async()=>{throw new Error("A simulation writes nothing: the write it reached was refused.")},S=new u({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 b=o?this.runCheckpointOf(t,r,o):void 0,O=this.deps.services.syncOrchestrator({dataSync:S,conflictResolver:new l,fieldMapping:new g,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,"ask",void 0,b?.gate),queryTargetRows:c.queryTargetRows,recordTypes:c.recordTypes,currencies:c.currencies,standardPricebooks:c.standardPricebooks,deltaStore:this.deltaStoreFor(),deltaReads:c.deltaReads,idMap:this.idMapFor(),files:c.files,readValidationRules:h(async E=>(await nr({query:async x=>y.query(x),queryMore:async x=>y.queryMore(x)},E)).records,f(c.targetConn),m(c.targetConn)),onSimulationProgress:(E,x,V)=>{let H=Math.round(E/x*100),Y=`Simulating ${V}`;Fe(this.deps,r,H,E,x,Y),this.liveTracker?.updateProgress(r,H,E,x,Y)}});await this.assertFieldTypesMatch(t,c.sourceConn,c.targetConn,a.timeouts.describe);let P=await O.simulate(t),v=b?.planned(),w=[...c.cutAtReadCap],C={...P,...v?{checkpoint:v}:{},readCap:c.readCap,...w.length>0?{cutAtReadCap:w}:{},operationId:r};C.cancelled?this.endCancelled(r):C.error?(this.liveTracker?.fail(r,C.error),je(this.deps,r,C.error,!0,{context:d})):(Fe(this.deps,r,100,1,1,"Simulation complete"),ge(this.deps,r,{status:"success",simulated:!0}),this.liveTracker?.complete(r)),this.deps.log(`[sync] simulation ${r} ${C.cancelled?"stopped":"finished"}: `+C.objects.map(E=>`${E.objectApiName} insert=${E.insert} update=${E.update} delete=${E.delete} skipped=${E.skipped} refused=${E.refused} conflicts=${E.conflicts}`).join("; "));let k=A(this.deps,e,"sync:simulate:response",C);return this.deps.broker.postToWebview(k),this.deps.log(`[TX] ${k.type} id=${k.id}`),C}catch(c){return this.liveTracker?.fail(r,I(c)),T(this.deps,"sync:simulate","sync:error",e,c),je(this.deps,r,I(c),!0,{context:d}),i?.(c),null}}async simulateForPipeline(e,t){let r=vn.safeParse({config:e});if(!r.success)throw new Error(`Pipeline sync config failed validation: ${r.error.issues.map(p=>p.message).join("; ")}`);let n=So(r.data.config.objects);if(n.length>0)throw Object.assign(new Error(`${ko(n)} ${AO}`),{code:Wi});let o=Rn("sync:pipeline",crypto.randomUUID(),"sync:simulate"),i=o.id,a=this.deps.services?.getSandforgeSetting?.("sync.defaultBatchSize",200)??200,d={...r.data.config,objects:r.data.config.objects.map(p=>({...p,batchSize:p.batchSize??a}))},c=`Pipeline simulation of a sync of ${d.objects.length} object(s), writing nothing`,u=new AbortController,l=()=>u.abort();t?.aborted&&u.abort(),t?.addEventListener("abort",l,{once:!0}),Je(this.deps,i,"sync",c),this.liveTracker?.register(i,"sync",c);let g;try{let p=this.simulateSync(o,d,i,u,void 0,h=>{g=h});this.registry?.register(i,"sync",c,p.then(h=>({status:h===null||h.error?"failure":"success"})),u);let f=await p;if(f===null)throw g instanceof Error?g:new Error(I(g));return f}finally{t?.removeEventListener("abort",l)}}async handleRunControl(e,t){this.deps.log(`[RX] ${e.type} id=${e.id}`);let r=$(sm,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 q(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await q(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=this.readCap(),a=new Set,d=new Xa({retryConfig:r.retry}),c=(k,E)=>async(x,V,H)=>{let Y=wt(V.objectApiName),B="",N=$s(V.where,H?.changedSince);N&&(B+=` WHERE ${N}`),V.orderBy&&(B+=` ORDER BY ${cl(V.orderBy)}`);let L=!1,Q=await d.execute(async()=>{L=!1;let ae=(await k.describe(Y)).fields.map(ne=>ne.name),U=ae.length>0?ae:["Id"],re={query:async ne=>k.query(ne),queryMore:async ne=>k.queryMore(ne)};return Ps(`SELECT ${U.join(", ")} FROM ${Y}${B}`,async ne=>{let ue=await nr(re,ne,i);return L||=ue.truncated,ue.records})});if(!Q.success)throw Q.error??new Error("Query failed after retries");xe(k.limitInfo,`sync:execute query ${Y}`);let K=Q.result??[];if(L){H?.onBoundReached?.();let ae=K.length>=i?`${i} records (sandforge.sync.maxRecordsPerObject)`:`${Math.max(500,Math.ceil(i/200))} pages`,U=E===e.sourceOrgId?"source":"target";U==="source"&&a.add(V.objectApiName);let re=U==="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} (${U}): read stopped at ${K.length} record(s) \u2014 bound: ${ae}. ${re}.`),Ie(this.deps,"warning","Sync",`${Y}: only ${K.length} record(s) were read from the ${U} (bound: ${ae}) \u2014 ${re}. `+xv(U,i,$v))}return K},u=async(k,E,x)=>{let H=`SELECT COUNT() FROM ${wt(E.objectApiName)}`,Y=$s(E.where,x?.changedSince);Y&&(H+=` WHERE ${Y}`);let{totalSize:B}=await n.query(H);return Math.min(B,i)},l=async(k,E)=>{let x=wt(k.objectApiName),V=$s(k.where,E?.changedSince),H=`SELECT COUNT() FROM ${x} WHERE IsPersonAccount = true`+(V?` AND (${V})`:"");try{return(await n.query(H)).totalSize}catch{return 0}},g=new Map,p=async k=>{let E=g.get(k);if(E)return E;let x=await o.describe(k),V=Er(x);return g.set(k,V),V},f=async k=>Er(await o.describe(k)),h=async k=>(await nr({query:async E=>o.query(E),queryMore:async E=>o.queryMore(E)},k)).records,m=Vh({query:async k=>o.query(k),queryMore:async k=>o.queryMore(k)},t),y=async(k,E,x,V)=>{let H=await m(k,E,x,V);return xe(o.limitInfo,`sync:simulate lookup ${E.objectApiName}`),H},R=Qh({query:async(k,E)=>n.query(k,E),queryMore:async k=>n.queryMore(k)},{query:async k=>o.query(k),queryMore:async k=>o.queryMore(k)},t),S=k=>({pages:{query:async E=>k.query(E),queryMore:async E=>k.queryMore(E)},transport:k,create:async(E,x)=>k.sobject(E).create(x,{headers:Hi()})}),b=async(k,E)=>{let V=`SELECT Id FROM ${wt(k.objectApiName)}`,H=$s(k.where,E);H&&(V+=` WHERE ${H}`),k.orderBy&&(V+=` ORDER BY ${cl(k.orderBy)}`);let{records:Y}=await nr(S(n).pages,V,i);return Y.flatMap(B=>typeof B.Id=="string"?[B.Id]:[])},O={copy:yv({[e.sourceOrgId]:S(n),[e.targetOrgId]:S(o)}),sourceIds:b,store:this.fileStoreFor(),...e.files!==void 0&&mv(this.deps.infraServices?.productionGuard,e.targetOrgId,this.deps.orgManager.getOrg(e.targetOrgId))?{deleteFromTarget:async(k,E)=>Ow(await o.sobject(k).destroy(E),k).map(x=>({id:x.id,success:x.success,errors:x.errors}))}:{}},P=async()=>{let{readSyncRecordTypes:k}=await import("./chunk-6WX5ZU7Q.mjs");return k(S(n).pages,S(o).pages)},v=async()=>{let{readRunCurrencies:k}=await import("./chunk-OETEC3P7.mjs");return k(async E=>(await n.query(E)).records,async E=>(await o.query(E)).records,{source:async E=>(await n.tooling.query(E)).records,target:async E=>(await o.tooling.query(E)).records})},w=async()=>{let{readStandardPricebooks:k}=await import("./chunk-4JE4BYXK.mjs");return k(async E=>(await n.query(E)).records,async E=>(await o.query(E)).records)},C=Qn(Rr(async k=>(await n.query(k)).records),k=>Yt(e.sourceOrgId,k,()=>n.describe(k)));return{sourceConn:n,targetConn:o,querySource:c(n,e.sourceOrgId),queryTarget:c(o,e.targetOrgId),maskedSourceFields:C,countSource:u,describeTargetFields:p,describeTargetFieldsAgain:f,queryTargetRows:h,recordTypes:P,currencies:v,standardPricebooks:w,findInTarget:y,readSourceIds:k=>b(k),countPersonAccounts:l,deltaReads:R,files:O,readCap:i,cutAtReadCap:a}}async rerunFromSnapshot(e,t){this.deps.log(`[RX] sync:history:rerun id=${e.id}`);let r=$(vn,{...e,payload:{config:t}},"sync:history:error",this.deps);r&&(this.refusedFieldless(e,r.config,"sync:history:rerun","sync:history:error",tg)||await this.startExecution(e,r.config,"rerun"))}async executeScheduled(e,t="schedule"){let r=vn.safeParse({config:e});if(!r.success)throw new Error(`Scheduled sync config failed validation: ${r.error.issues.map(m=>m.message).join("; ")}`);let n=So(r.data.config.objects);if(n.length>0)throw Object.assign(new Error(`${ko(n)} ${tg}`),{code:Wi});let o=t==="pipeline"?Rn("sync:pipeline",crypto.randomUUID(),"sync:execute"):Rn("sync:schedule",crypto.randomUUID(),"sync:execute"),i=o.id,a=this.deps.services?.getSandforgeSetting?.("sync.defaultBatchSize",200)??200,d={...r.data.config,objects:r.data.config.objects.map(m=>({...m,batchSize:m.batchSize??a}))},c=this.deps.infraServices?.productionGuard;if(!c)throw this.recordRefused(i,d.targetOrgId,Re.code),oa();let{check:u,decision:l}=await et(c,this.buildGuardRequest(d)),g=l;if((l==="refused"||l==="declined")&&this.recordStopped(i,d.targetOrgId,l),l==="refused")throw new Error(`Operation blocked by Production Guard: ${u.blockedReason??u.impactSummary}`);if(l==="declined")throw new Error(`${t==="pipeline"?"Pipeline":"Scheduled"} sync cancelled (confirmation declined).`);this.dmlTracker.register(i,"sync","upsert",d.objects?.length??0),this.activeOperationIds.add(i),this.deps.infraServices?.performanceTracker?.start(i,"sync");let p=`${t==="pipeline"?"Pipeline":"Scheduled"} sync of ${d.objects?.length??0} object(s)`;Je(this.deps,i,"sync",p),this.liveTracker?.register(i,"sync",p,0,{pausable:!0});let f=new AbortController,h=this.executeSync(o,d,i,f,t,g);return this.registry?.register(i,"sync",p,h,f),h}async startExecution(e,t,r,n=!1,o){let i=e.id,a={module:"sync",operation:e.type},d=this.registry?.holdUntilStart(i);try{let c=this.deps.services?.getSandforgeSetting?.("sync.defaultBatchSize",200)??200,u=t,l={...u,objects:u.objects.map(S=>({...S,batchSize:S.batchSize??c}))};Object.assign(a,Kr(l.objects));let g=this.deps.infraServices?.productionGuard;if(!g){this.recordRefused(i,l.targetOrgId,Re.code),T(this.deps,"sync:execute","sync:error",e,new Error(Re.message),{code:Re.code}),je(this.deps,i,Re.message,!1,{context:a});return}let{check:p,decision:f}=await et(g,this.buildGuardRequest(l)),h=f;if((f==="refused"||f==="declined")&&this.recordStopped(i,l.targetOrgId,f),f==="refused")throw bn(p.blockedReason??p.impactSummary);if(f==="declined"){let S="Operation cancelled by user (confirmation declined).";T(this.deps,"sync:execute","sync:error",e,new Error(S),{code:xt.declined}),je(this.deps,i,S,!1,{context:a});return}if(d?.signal.aborted){this.answerCancelledBeforeStart(e,l,f);return}if(this.dmlTracker.isDuplicate(i)){this.deps.log(`[WARN] Duplicate sync operation detected: ${i}`),T(this.deps,"sync:execute","sync:error",e,new Error(`Duplicate operation: ${i}`)),je(this.deps,i,`Duplicate operation: ${i}`,!1,{context:a});return}this.dmlTracker.register(i,"sync","upsert",l.objects?.length??0),this.activeOperationIds.add(i),this.deps.infraServices?.performanceTracker?.start(i,"sync");let m=`Sync ${l.objects?.length??0} object(s)`;Je(this.deps,i,"sync",m),this.liveTracker?.register(i,"sync",m,0,{pausable:!0});let y=new AbortController,R=this.executeSync(e,l,i,y,r,h,n,o);this.registry?this.registry.register(i,"sync",m,R,y):await R}catch(c){this.dmlTracker.markFailed(i),T(this.deps,"sync:execute","sync:error",e,c,{code:Eo(c)}),je(this.deps,i,I(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:bt});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),ge(this.deps,e,{aborted:!0}),this.liveTracker?.cancel(e)}async executeSync(e,t,r,n,o,i,a=!1,d){let c=t.id?t:{...t,id:r},u=lt(this.deps),l,g,p=!1,f,h=v=>({measure:w=>v.measure(w),hold:async w=>{let C=await v.hold(w);return f=C.answer.emails,C}}),m=new nc;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}:{}}),S=this.backupRecords,b=R&&S?od({runId:r,orgId:c.targetOrgId,files:S,meta:this.deps.configStore}):void 0,O=d?this.runCheckpointOf(c,r,d,{signal:n.signal,...R?{recorder:R}:{}}):void 0,P=()=>{try{b?.close()}catch(v){this.deps.log(`[WARN] sync ${r}: the backup of what it wrote over could not be listed whole: `+I(v))}};try{let v=await this.readersFor(c,n.signal),{sourceConn:w,targetConn:C}=v;Tr(R,()=>C.identity(),`sync ${r}`);let k=v.queryTargetRows,E=R&&b?sd({query:k,backup:b,recorder:R,describe:v.describeTargetFields,viewsEncrypted:Rr(k)}):void 0,x=new kn(u.bulk.threshold),V=br(this.deps),H=new Dn({connection:C,bulkExecutor:x,bulkManager:V,retryConfig:u.retry,signal:n.signal,pauseGate:m,onProgress:(z,se,te)=>{let he=Math.round(z/se*100);Fe(this.deps,r,he,z,se,te),this.liveTracker?.updateProgress(r,he,z,se,te)},log:z=>this.deps.log(z),...R?{calls:cd(R,E)}:{}}),{DataSync:Y}=await import("./chunk-I6E6T6YY.mjs"),{ConflictResolver:B}=await import("./chunk-CHCHAE4B.mjs"),{FieldMappingService:N}=await import("./chunk-PR3XCSPO.mjs"),{TransformPipeline:L}=await import("./chunk-36JOHEJL.mjs"),Q=z=>{z.length>0&&(p=!0)},K=new Y({upsert:(z,se,te,he)=>(Q(te),H.upsert(z,se,te,he)),insert:(z,se,te)=>(Q(se),H.insert(z,se,te)),update:(z,se,te)=>(Q(se),H.update(z,se,te)),delete:(z,se,te)=>(Q(se),H.delete(z,se,te)),describeTargetFields:v.describeTargetFields}),ae=new B,U=new N,re=new L,ne={dataSync:K,conflictResolver:ae,fieldMapping:U,transformPipeline:re,querySource:v.querySource,maskedSourceFields:v.maskedSourceFields,queryTarget:v.queryTarget,services:this.deps.services,grappeConfig:Ts(this.deps.services),onGrappeEvent:z=>sa(this.deps,z),countSource:v.countSource,countPersonAccounts:v.countPersonAccounts,describeTargetFields:v.describeTargetFields,describeTargetFieldsAgain:v.describeTargetFieldsAgain,leaseOfTheGate:()=>g?.lease(),queryTargetRows:k,readSourceIds:v.readSourceIds,findInTarget:v.findInTarget,writeGate:(()=>{let z=o==="schedule"||o==="pipeline"?"unattended":"ask";if(!a)return h(this.writeGateFor(c,v,z,void 0,O?.gate));let se=this.targetAutomation;return g=Gv((he,D)=>this.writeGateFor(c,v,z,he,O?.gate,D),he=>new fe(IO).withTimeout("sync:automation",()=>se.read(c.targetOrgId,he)),he=>Ot(async()=>_t(C),he,{...this.muteLeases,writes:zv}),r,{target:ye(this.deps.orgManager.getOrg(c.targetOrgId),c.targetOrgId),liftedBy:CO(z).emailsLiftedBy}),h(g.gate)})(),recordTypes:v.recordTypes,currencies:v.currencies,standardPricebooks:v.standardPricebooks,signal:n.signal,pauseGate:m,deltaStore:this.deltaStoreFor(),deltaReads:v.deltaReads,files:{...v.files,onProgress:(z,se)=>{Fe(this.deps,r,z,0,0,se),this.liveTracker?.updateProgress(r,z,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 ue=this.deps.services.syncOrchestrator(ne);await this.assertFieldTypesMatch(c,w,C,u.timeouts.describe),Fe(this.deps,r,10,0,1,"Initializing sync");let ce=await ue.execute(c).finally(async()=>{l=await g?.release()}),be=await this.settleRunCheckpoint(O,p,r),Xe=[...v.cutAtReadCap],De={...ce,...Xe.length>0?{status:ce.status==="success"?"partial":ce.status,readCap:v.readCap,cutAtReadCap:Xe}:{},...l?{mutedAutomation:l}:{},...be?{checkpoint:be}:{}};if(await R?.end({status:De.status,cancelled:De.cancelled===!0}),P(),De.cancelled?this.endCancelled(r):(Fe(this.deps,r,100,1,1,"Sync complete"),ge(this.deps,r,{status:De.status??"completed"}),De.status==="failure"?this.liveTracker?.fail(r,De.error??"No record could be synced."):De.status==="partial"?this.liveTracker?.partial(r):this.liveTracker?.complete(r)),this.dmlTracker.markCompleted(r),c.files){let z=De.objectResults.flatMap(se=>se.files?[se.files]:[]);this.deps.log(`[sync] ${r} files: ${wv(z)}`)}xe(w.limitInfo,"sync:execute completion (source)"),xe(C.limitInfo,"sync:execute completion (target)");try{this.historyLogger?.logExecution(c,De,o)}catch(z){this.deps.log(`[WARN] sync history logging failed: ${I(z)}`)}this.recordRun(c,r,De,i,o,f);let _e=A(this.deps,e,"sync:execute:response",De);return this.deps.broker.postToWebview(_e),this.deps.log(`[TX] ${_e.type} id=${_e.id}`),De}catch(v){await R?.end({status:"failure"}),P(),this.dmlTracker.markFailed(r);let w=await this.settleRunCheckpoint(O,p,r),C=w?.state==="deleted";if(this.liveTracker?.fail(r,I(v)),v instanceof Ev){let V=O?.refusal(),H=C?`${v.message} ${en}`:v.message,Y={...V?{checkpointRefusal:V.code}:{},...w?{checkpoint:w}:{}};return Z(this.deps,{action:"sync_execute",module:"sync",operationId:r,orgId:c.targetOrgId,outcome:"stopped",guard:i,code:v.code,details:{triggeredBy:o,...V?{checkpointRefusal:V.code}:{},...eo(f)}}),T(this.deps,"sync:execute","sync:error",e,v,{code:v.code,extraPayload:Y}),je(this.deps,r,H,!1,{context:{module:"sync",operation:e.type,...Kr(c.objects)}}),{...v.result,configId:c.id,operationId:r,status:"failure",timestamp:new Date().toISOString(),error:H,...w?{checkpoint:w}:{}}}Os(v)&&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}`):Os(v)&&o==="rerun"&&this.deps.log(`[OFFLINE] sync replay failed again \u2014 not re-queued (replay outcomes surface via operation:failed): ${r}`);let k=C?new Error(`${I(v)} ${en}`):v;T(this.deps,"sync:execute","sync:error",e,v,{...w?{extraPayload:{checkpoint:w}}:{}}),je(this.deps,r,I(k),!0,{context:{module:"sync",operation:e.type,...Kr(c.objects)}});let x={...(v instanceof Tv?v.result:void 0)??{objectResults:[],totalProcessed:0,totalSuccess:0,totalFailed:0,totalSkipped:0,duration:0},configId:c.id,operationId:r,status:"failure",timestamp:new Date().toISOString(),error:I(k),...w?{checkpoint:w}:{}};try{this.historyLogger?.logExecution(c,x,o)}catch(V){this.deps.log(`[WARN] sync history logging failed: ${I(V)}`)}return this.recordRun(c,r,x,i,o,f),x}finally{this.pauseGates.delete(r),this.activeOperationIds.has(r)&&(this.deps.infraServices?.performanceTracker?.complete(r),this.activeOperationIds.delete(r))}}};var Sx=new Set(["sync:history:list","sync:history:detail","sync:history:rerun","sync:history:export"]),sc=class{constructor(e,t,r){this.deps=e;this.historyStore=t;this.syncOps=r}deps;historyStore;syncOps;async handle(e){if(!Sx.has(e.type))return!1;switch(e.type){case"sync:history:list":return this.handleList(e),!0;case"sync:history:detail":return this.handleDetail(e),!0;case"sync:history:export":return this.handleExport(e),!0;case"sync:history:rerun":return await this.handleRerun(e),!0;default:return!1}}handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.historyStore.list(),r=A(this.deps,e,"sync:history:list:response",{entries:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} count=${t.length}`)}catch(t){T(this.deps,"sync:history:list","sync:history:error",e,t)}}handleDetail(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(fl,e,"sync:history:error",this.deps);if(t)try{let r=this.historyStore.load(t.entryId)??null,n=A(this.deps,e,"sync:history:detail:response",{entry:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){T(this.deps,"sync:history:detail","sync:history:error",e,r)}}handleExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Sm,e,"sync:history:error",this.deps);if(t)try{let r=t.format==="csv"?this.historyStore.exportAsCsv(t.entryIds):this.historyStore.exportAsJson(t.entryIds),n=A(this.deps,e,"sync:history:export:response",{data:r,format:t.format});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} format=${t.format}`)}catch(r){T(this.deps,"sync:history:export","sync:history:error",e,r)}}async handleRerun(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(fl,e,"sync:history:error",this.deps);if(!t)return;let r=this.historyStore.load(t.entryId);if(!r){T(this.deps,"sync:history:rerun","sync:history:error",e,new Error(`History entry not found: ${t.entryId}`),{code:"NOT_FOUND"});return}await this.syncOps.rerunFromSnapshot(e,r.configSnapshot)}};var kx=1e4;async function $O(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=>Ft(c).filter(u=>t.has(u.objectApiName)),n=(await e.runs()).find(c=>c.sourceOrgId===s.sourceOrgId&&c.targetOrgId===s.targetOrgId&&r(c).length>0);if(!n)return{leftAsIs:!1,objects:[]};let o=n.created.map(c=>c.objectApiName),i=r(n).sort((c,u)=>o.indexOf(c.objectApiName)-o.indexOf(u.objectApiName)),a,d=[];for(let{objectApiName:c,ids:u}of i){let l=u.slice(0,kx),g;try{g=await e.countInTarget(c,l)+(u.length-l.length)}catch(p){a??=p instanceof Error?p.message:String(p),g=u.length}g>0&&d.push({objectApiName:c,count:g})}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 Ox=new Set(["sync:removal:info","sync:removal:list","sync:remove","sync:remove:sweep","sync:remove:automation","sync:earlier-copies"]),Ix=6e4,Ax=12e4,xO=6e4,Tx=6e4,DO="The run is still writing in another window: remove it once it has ended there.",ic=class{constructor(e,t,r,n=xo){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)&&Yn(e,this.self)}stillWriting(e){return this.isRunning(e.runId)||Yn(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-GOOVPVWX.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async handle(e){if(!Ox.has(e.type))return!1;switch(e.type){case"sync:removal:info":return await this.handleInfo(e),!0;case"sync:removal:list":return await this.handleList(e),!0;case"sync:remove":return await this.handleRemove(e),!0;case"sync:remove:sweep":return await this.handleSweepList(e),!0;case"sync:remove:automation":return await this.handleRemovalAutomation(e),!0;case"sync:earlier-copies":return await this.handleEarlierCopies(e),!0;default:return!1}}tierOf(e){let t=this.deps.orgManager.getOrg(e);return Pe(t)}infoOf(e,t=[]){let r=Ft(e),n=Jw(e,t),o=r.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length})),i=Do(e),a=this.keptBack(i),d=Al(e),c=Tl(e),u=_s(e),l={runId:e.runId,configId:e.configId,configName:e.configName,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,startedAt:e.startedAt,...e.end?{endedAt:e.end.at}:{},...!e.end&&e.inFlight?{inFlight:{objectApiName:e.inFlight.objectApiName,rows:e.inFlight.rows}}:{},...this.elsewhere(e)?{runningElsewhere:!0}:{},...e.realtime?{realtime:!0}:{},created:Fs(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}`))}:{},...u.length>0?{bringBack:u.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length}))}:{},...e.removal?.undo?{removed:e.removal.undo}:{},...n.length>0?{writtenAgain:n}:{}},g=e.removal?.undo?Ft(e,!0):[],p=g.length>0?{...l,createdByObject:g.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length}))}:l,f=r.length>0||i.length>0||u.length>0?r:g;if(f.length===0&&i.length===0&&u.length===0)return p;let h=this.refusalOf(e,f,[...i,...u]);return h?{...p,refusal:h}:p}keptBack(e){return ub(e,t=>this.deps.configStore.get(`backup:${t}`),cb(this.deps.services))}removalStepsOf(e,t=!1){let r=o=>[...new Set(o.map(({objectApiName:i})=>i))],n=r(Ft(e,t));return{bringBack:r(_s(e)),giveBack:r(this.keptBack(Do(e)).kept),setToDraft:sr(n),delete:On(n,[],{userKept:e.runUserId!==void 0})}}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:DO};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:Re.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(Tx).withTimeout(r,async()=>{let o=await q(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=ir(o,r);return Ya(t,e,Xn(o),()=>i.serverTime())});for(let o of Qa(r,n))this.deps.log(o);return n.some(o=>o.answered)?await t.get(e.runId)??e:e}catch(n){return this.deps.log(`[WARN] ${r}: the job could not be read back: ${I(n)}`),e}}async runOf(e){let t=await this.creations?.get(e);return t?this.withJobAnswered(t):void 0}async handleInfo(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(gm,e,"sync:remove:error",this.deps);if(t)try{let r=await this.runOf(t.runId),o=r!==void 0&&(Ft(r).length>0||Do(r).length>0)?await this.creations?.list()??[]:[],i=A(this.deps,e,"sync:removal:info:response",{info:r?this.infoOf(r,o):null});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(r){T(this.deps,"sync:removal:info","sync:remove:error",e,r)}}async handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(fm,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)&&(Fs(d)>0||Al(d)>0||Tl(d)>0||!d.end&&d.inFlight!==void 0)),a=A(this.deps,e,"sync:removal:list:response",{runs:i.map(d=>this.infoOf(d,o))});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id} count=${i.length}`)}catch(n){T(this.deps,"sync:removal:list","sync:remove:error",e,n)}}async handleEarlierCopies(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(hm,e,"sync:remove:error",this.deps);if(t)try{let r=this.creations,n=await $O(t,{runs:async()=>await r?.list()??[],isSaved:i=>this.configs.isSaved(i),countInTarget:async(i,a)=>{let d=await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),c=wt(i),u=0;for(let l of Ns(a.filter(Yr)))u+=(await d.query(`SELECT COUNT() FROM ${c} WHERE Id IN (${l})`)).totalSize;return u}}),o=A(this.deps,e,"sync:earlier-copies:response",{copies:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(r){T(this.deps,"sync:earlier-copies","sync:remove:error",e,r)}}async sweepInputOf(e,t,r,n){let o=this.targetAutomation,i=[...new Set([...t.created,...t.overwritten??[]].map(u=>u.objectApiName).filter(u=>!zw.includes(u)))],a;try{a=await new fe(Ix).withTimeout(`${r} automation`,()=>o.read(t.targetOrgId,i))}catch(u){a={error:I(u)}}let d=ir(e,r),c=await ed(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 Wo({...c,ties:{...c.ties,...await rd(t,c.writtenBetween,await this.creations?.list().catch(()=>[])??[],this.otherModuleRuns)}},d)}async localRunsOn(e){return td(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=$(ym,e,"sync:remove:sweep:error",this.deps);if(!t)return;let r=(n,o)=>T(this.deps,"sync:remove:sweep","sync:remove:sweep:error",e,new Error(n),{code:o});try{let n=await this.runOf(t.runId);if(!n){r("Nothing this run created is kept: there is nothing to sweep after.","NOT_KEPT");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){r("The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}let o=await new fe(Ax).withTimeout("sync:remove:sweep",async()=>{let i=await q(n.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=await this.sweepInputOf(i,n,"sync:remove:sweep");return Ho(rn(i,"sync:remove:sweep"),a,n.removal?.removalSpans??[])});this.deps.broker.postToWebview(A(this.deps,e,"sync:remove:sweep:response",{runId:n.runId,listing:o}))}catch(n){T(this.deps,"sync:remove:sweep","sync:remove:sweep:error",e,n,{code:"SWEEP_ERROR",retryable:!0})}}async handleRemovalAutomation(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(wm,e,"sync:remove:automation:error",this.deps);if(!t)return;let r=(n,o)=>T(this.deps,"sync:remove:automation","sync:remove:automation:error",e,new Error(n),{code:o});try{let n=await this.runOf(t.runId);if(!n){r("Nothing this run created is kept: there is nothing to remove.","NOT_KEPT");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){r("The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}let o=Rs(this.removalStepsOf(n,t.again===!0),t.sweptObjects??[]),i=[...new Set(Object.values(o).flat())],a=this.targetAutomation,d=await new fe(xO).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 vr;T(this.deps,"sync:remove:automation","sync:remove:automation:error",e,n,{code:o?"TIMEOUT":"AUTOMATION_ERROR",retryable:!0})}}sweepOfRemoval(e){let{conn:t,run:r,input:n}=e;return zo({input:async()=>{if(n instanceof Error)throw n;return n},org:rn(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=qo(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:Go(i)}:{},objects:Bo(o),details:{...a,runId:r.runId}})},keepMade:async(o,i,a)=>{await this.creations?.updateRemoval(r.runId,d=>nd(d,o,i,a)).catch(d=>{this.deps.log(`[WARN] sync:remove ${e.operationId}: what the sweep found made for the run could not be kept: ${I(d)}`)})}})}refuse(e,t,r,n=!1){T(this.deps,"sync:remove","sync:remove:error",e,new Error(t),{code:r,...n?{retryable:n}:{}})}recordNotRemoved(e,t,r,n={}){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=$(mm,e,"sync:remove:error",this.deps);if(!t)return;let r=this.creations;if(!r){this.refuse(e,"What Sync runs created is not kept in this window yet.","NOT_INITIALIZED",!0);return}let n;try{n=await this.runOf(t.runId)}catch(a){T(this.deps,"sync:remove","sync:remove:error",e,a,{code:"REMOVE_ERROR",retryable:!0});return}if(!n){this.refuse(e,"Nothing this run created is kept: it created nothing, or ran before runs kept what they created, or the record of it was dropped to make room.","NOT_KEPT");return}if(this.isRunning(n.runId)){this.refuse(e,"The run is still writing: remove it once it has ended.","RUNNING");return}if(this.elsewhere(n)){this.refuse(e,DO,"RUNNING");return}let o=t.again===!0;if(Ft(n,o).length===0&&Do(n).length===0&&_s(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=Ft(r,a),c=[...Do(r),..._s(r)],u=d.reduce((v,w)=>v+w.ids.length,0),l=c.reduce((v,w)=>v+w.ids.length,0),g=r.targetOrgId,p=this.deps.infraServices?.productionGuard;if(!p){this.recordNotRemoved(e,r,"stopped",{code:Re.code}),this.refuse(e,Re.message,Re.code);return}let{check:f,decision:h}=await et(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: ${f.blockedReason??f.impactSummary}`,xt.blocked):this.refuse(e,"Operation cancelled by user (confirmation declined).",xt.declined,!0);return}if(o?.signal.aborted){this.recordNotRemoved(e,r,"stopped",{guard:h,code:bt});let v={runId:r.runId,status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(A(this.deps,e,"sync:remove:response",{result:v,operationId:e.id}));return}let m=e.id,y=l>0?`Removing ${u} record(s) and file(s) a Sync run created, and giving ${l} record(s) it wrote over or deleted their values back`:`Removing ${u} record(s) and file(s) a Sync run created`,R=new AbortController,S=()=>{},b=new Promise((v,w)=>{S=C=>C===void 0?v():w(C)});b.catch(()=>{}),Je(this.deps,m,"sync",y),this.registry?.register(m,"sync",y,b,R),this.liveTracker?.register(m,"sync",y,u+l);let O,P;try{let v=await q(g,this.deps.orgRegistry,this.deps.orgManager),w=n.sweep?await this.sweepInputOf(v,r,"sync:remove sweep",R.signal).catch(ne=>new Error(I(ne))):void 0;P=w?await this.sweepOfRemoval({conn:v,run:r,input:w,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 k;if(n.muteAutomation===!0){let ne=Rs(this.removalStepsOf(r,a),C?.takes??[]),ue=[...new Set(Object.values(ne).flat())],ce=this.targetAutomation,be=await new fe(xO).withTimeout("sync:remove:automation",()=>ce.read(r.targetOrgId,ue,{undeletes:!0})).catch(Xe=>({unread:I(Xe)}));k=await Ot(async()=>_t(v),be,{...this.muteLeases,writes:Gr(ne)})}let E,x=k?.muted,V=async()=>{let ne=k?.prepared;!ne||R.signal.aborted||(E=await ne.acquire(m),x=E.outcome)},H=ir(v,"sync:remove"),Y=await Za(H,r.created),{result:B,notes:N,earlierStamped:L,duplicateSets:Q}=await Oa({run:r,org:H,includeChanged:i,...a?{again:a}:{},store:t,configs:this.configs,links:t.idMap(),...this.backups?{backups:this.backups}:{},earlierRuns:Gw(r,await t.list().catch(()=>[])),undelete:ne=>v.soap.undelete(ne),...C?{sweep:ne=>C.first(ne),afterRemoval:ne=>C.afterRemoval(ne),automationMade:C.automationMade}:{},...r.runUserId?{runUserId:r.runUserId}:{},onUndeletable:Vr(this.deps,g,"sync:remove"),beforeFirstWrite:V,signal:R.signal,onProgress:(ne,ue,ce)=>{let be=Math.min(100,Math.round(ne/Math.max(ue,1)*100));Fe(this.deps,m,be,ne,ue,ce),R.signal.aborted||this.registry?.updateProgress(m,be),this.liveTracker?.updateProgress(m,be,ne,ue,ce)}}).finally(async()=>{E&&(x=await E.release())}),K=await P?.settle(),ae=B.status==="cancelled"?{}:await Y.take(Q);for(let ne of[...N,...ae.note?[ae.note]:[]])this.deps.log(`[WARN] sync:remove ${m}: ${ne}`);for(let{runId:ne,records:ue}of L??[])this.deps.log(`[INFO] sync:remove ${m}: ${ue} record(s) given back hold the values of the earlier run ${ne} again, stamped on it`);let U={...B,objects:ae.object?[...B.objects,ae.object]:B.objects,status:Co(B.status,K),...K?{sweep:K}:{},...x?{mutedAutomation:x}:{}};Z(this.deps,{action:"cleanup_delete",module:"sync",operationId:m,orgId:g,outcome:$o(B),guard:h,objects:ka(In(U.objects),U.restored??[],U.undeleted??[]),...U.leftBy?{leftBy:U.leftBy}:{},...x?{muted:ut(x)}:{},details:{runId:r.runId}});let re=A(this.deps,e,"sync:remove:response",{result:U,operationId:m});this.deps.broker.postToWebview(re),this.deps.log(`[TX] ${re.type} id=${re.id} status=${U.status}`),U.status==="cancelled"||U.sweep?.status==="cancelled"?(ge(this.deps,m,{aborted:!0}),this.liveTracker?.cancel(m)):(ge(this.deps,m,{status:U.status}),U.status==="failure"?(O=new Error("Nothing this run created could be removed."),this.liveTracker?.fail(m,"Nothing this run created could be removed.")):U.status==="partial"?this.liveTracker?.partial(m):this.liveTracker?.complete(m))}catch(v){O=v,await P?.settle().catch(()=>{});let w=Dt(v)?v:void 0;this.recordNotRemoved(e,r,w?"stopped":"failure",{guard:h,...w?{code:w.code}:{}}),T(this.deps,"sync:remove","sync:remove:error",e,v,{code:w?.code??"REMOVE_ERROR",retryable:!0}),ge(this.deps,m,{status:"failure"}),this.liveTracker?.fail(m,I(v))}finally{S(O)}}};var Ex=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Px=/^[A-Za-z][A-Za-z0-9_]*$/;function ac(s,e,t){if(!Ex.test(t)||!Px.test(e))return{ok:!1,reason:"not-a-record"};let r=jn(s);return r.ok?{ok:!0,url:new URL(`/lightning/r/${e}/${t}/view`,r.url.origin).toString()}:r}var Cx=new Set(["seed:removal:info","seed:removal:list","seed:remove","seed:remove:sweep","seed:open-record"]),NO=6e4,$x=12e4,xx=6e4,jO="The seed is still writing: remove it once it has ended.",MO="The seed is still writing in another window: remove it once it has ended there.",dc=class{constructor(e,t,r=()=>!1,n=xo){this.deps=e;this.isRunning=r;this.self=n;this.externalBrowser=t??new jr}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)&&Yn(e,this.self)}setRunCreations(e){this.creations=e}setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-GOOVPVWX.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}setRegistry(e){this.registry=e}setLiveOperationTracker(e){this.liveTracker=e}async handle(e){return Cx.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 Pe(t)}infoOf(e){let t=Ft(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:Fs(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?Ft(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-UBIKR5VO.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:jO};if(this.elsewhere(e))return{code:"RUNNING",message:MO};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:Re.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(xx).withTimeout(r,async()=>{let o=await q(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=ir(o,r);return Ya(t,e,Xn(o),()=>i.serverTime())});for(let o of Qa(r,n))this.deps.log(o);return n.some(o=>o.answered)?await t.get(e.runId)??e:e}catch(n){return this.deps.log(`[WARN] ${r}: the job could not be read back: ${I(n)}`),e}}async runOf(e){let t=await this.creations?.get(e);return t?this.withJobAnswered(t):void 0}cleanupLineOf(e){let t=this.deps.orgManager.getOrg(e.targetOrgId);return ov(e,"npx sandforge cleanup",t?.alias??"<alias>")}notKeptWords(e){let t="rewind the org to a checkpoint taken before it, or empty its objects (DataOps, Cleanup, Empty objects), which deletes all their records.";return e?`${nv(e,this.cleanupLineOf(e))} Or ${t}`:`Nothing this run created is kept: it created nothing, or was dropped to make room for newer seeds. To take its records back, ${t}`}async handleInfo(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(bm,e,"seed:remove:error",this.deps);if(t)try{let r=await this.runOf(t.runId),n=r?void 0:await this.creations?.dropped(t.runId),o=A(this.deps,e,"seed:removal:info:response",{info:r?await this.withScenario(this.infoOf(r)):null,...n?{dropped:n,cleanupLine:this.cleanupLineOf(n)}:{}});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(r){T(this.deps,"seed:removal:info","seed:remove:error",e,r)}}async handleOpenRecord(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(qm,e,"seed:open-record:error",this.deps);if(!t)return;let r=(n,o)=>{T(this.deps,"seed:open-record","seed:open-record:error",e,new Error(n),{code:o})};try{let n=await this.creations?.get(t.runId);if(!n){r("Nothing of this run is kept any more.","NOT_KEPT");return}let o=t.recordId.slice(0,15),i;for(let{objectApiName:l,ids:g}of n.created){let p=g.find(f=>f.slice(0,15)===o);if(p){i={objectApiName:l,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=ac(a.instanceUrl,i.objectApiName,i.id);if(!d.ok){let l=d.reason==="not-https"?`its instance URL must use HTTPS, got "${d.protocol}"`:d.reason==="invalid"?"its instance URL is not a valid URL":"the record is not one an address can be built for";r(`Cannot open the record in "${ye(a)}": ${l}.`,d.reason==="not-a-record"?"NOT_CREATED":"INVALID_INSTANCE_URL");return}let c=await this.externalBrowser.open(d.url),u=A(this.deps,e,"seed:open-record:response",c);this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id} status=${c.status}`)}catch(n){T(this.deps,"seed:open-record","seed:open-record:error",e,n)}}async handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=[];for(let o of await this.creations?.list()??[])t.push(await this.withJobAnswered(o));let r=[];for(let o of t)r.push(await this.withScenario(this.infoOf(o)));let n=A(this.deps,e,"seed:removal:list:response",{runs:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} runs=${t.length}`)}catch(t){T(this.deps,"seed:removal:list","seed:remove:error",e,t)}}async sweepInputOf(e,t,r,n){let o=this.targetAutomation,i;try{i=await new fe(NO).withTimeout(`${r} automation`,()=>o.read(t.targetOrgId,t.created.map(c=>c.objectApiName)))}catch(c){i={error:I(c)}}let a=ir(e,r),d=await ed(a,t.created,i,n,void 0,[],{...t.runUserId?{runUserId:t.runUserId}:{},ties:{}});return Wo({...d,ties:{...d.ties,...await rd(t,d.writtenBetween,await this.creations?.list().catch(()=>[])??[],this.otherModuleRuns)}},a)}async localRunsOn(e){return td(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=$(vm,e,"seed:remove:sweep:error",this.deps);if(!t)return;let r=(n,o)=>T(this.deps,"seed:remove:sweep","seed:remove:sweep:error",e,new Error(n),{code:o});try{let n=await this.runOf(t.runId);if(!n){r("Nothing this run created is kept: there is nothing to sweep after.","NOT_KEPT");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){r("The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}let o=await new fe($x).withTimeout("seed:remove:sweep",async()=>{let i=await q(n.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=await this.sweepInputOf(i,n,"seed:remove:sweep");return Ho(rn(i,"seed:remove:sweep"),a,n.removal?.removalSpans??[])});this.deps.broker.postToWebview(A(this.deps,e,"seed:remove:sweep:response",{runId:n.runId,listing:o}))}catch(n){T(this.deps,"seed:remove:sweep","seed:remove:sweep:error",e,n,{code:"SWEEP_ERROR",retryable:!0})}}sweepOfRemoval(e){let{conn:t,run:r}=e;return zo({input:()=>this.sweepInputOf(t,r,"seed:remove sweep",e.signal),org:rn(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=qo(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:Go(o)}:{},objects:Bo(n),details:{...i,runId:r.runId}})},keepMade:async(n,o,i)=>{await this.creations?.updateRemoval(r.runId,a=>nd(a,n,o,i)).catch(a=>{this.deps.log(`[WARN] seed:remove ${e.operationId}: what the sweep found made for the run could not be kept: ${I(a)}`)})}})}refuse(e,t,r,n=!1){T(this.deps,"seed:remove","seed:remove:error",e,new Error(t),{code:r,...n?{retryable:n}:{}})}recordNotRemoved(e,t,r,n={}){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=$(Rm,e,"seed:remove:error",this.deps);if(!t)return;let r=this.creations,n=await this.runOf(t.runId);if(!r||!n){this.refuse(e,this.notKeptWords(await r?.dropped(t.runId)),"NOT_KEPT");return}let o=t.again===!0;if(Ft(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,jO,"RUNNING");return}if(this.elsewhere(n)){this.refuse(e,MO,"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=Ft(r,a),c=d.reduce((O,P)=>O+P.ids.length,0),u=r.targetOrgId,l=this.deps.infraServices?.productionGuard;if(!l){this.recordNotRemoved(e,r,"stopped",{code:Re.code}),this.refuse(e,Re.message,Re.code);return}let{check:g,decision:p}=await et(l,{orgId:u,orgTier:this.tierOf(u),operation:"delete",objectName:d.map(O=>O.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: ${g.blockedReason??g.impactSummary}`,xt.blocked):this.refuse(e,"Operation cancelled by user (confirmation declined).",xt.declined,!0);return}if(o?.signal.aborted){this.recordNotRemoved(e,r,"stopped",{guard:p,code:bt});let O={runId:r.runId,status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(A(this.deps,e,"seed:remove:response",{result:O,operationId:e.id}));return}let f=e.id,h=`Removing ${c} record(s) a Seed run created`,m=new AbortController,y=()=>{},R=new Promise((O,P)=>{y=v=>v===void 0?O():P(v)});R.catch(()=>{}),Je(this.deps,f,"seed",h),this.registry?.register(f,"seed",h,R,m),this.liveTracker?.register(f,"seed",h,c);let S,b;try{let O=await q(u,this.deps.orgRegistry,this.deps.orgManager);b=n.sweep?await this.sweepOfRemoval({conn:O,run:r,includeChanged:i,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,signal:m.signal,guard:l,operationId:f}):void 0;let P=b;await P?.ask();let v;if(n.muteAutomation===!0){let K=[...new Set(d.map(ue=>ue.objectApiName))],ae=Rs({setToDraft:sr(K),delete:On(K,[],{userKept:r.runUserId!==void 0})},P?.takes??[]),U=ae.delete??[],re=this.targetAutomation,ne=await new fe(NO).withTimeout("seed:remove automation",()=>re.read(r.targetOrgId,U)).catch(ue=>({unread:I(ue)}));v=await Ot(async()=>_t(O),ne,{...this.muteLeases,writes:Gr(ae)})}let w,C=v?.muted,k=async()=>{let K=v?.prepared;!K||m.signal.aborted||(w=await K.acquire(f),C=w.outcome)},E=ir(O,"seed:remove"),x=await Za(E,r.created),{result:V,notes:H,duplicateSets:Y}=await Oa({run:r,org:E,includeChanged:i,...a?{again:a}:{},store:t,...P?{sweep:K=>P.first(K),afterRemoval:K=>P.afterRemoval(K),automationMade:P.automationMade}:{},...r.runUserId?{runUserId:r.runUserId}:{},onUndeletable:Vr(this.deps,u,"seed:remove"),beforeFirstWrite:k,signal:m.signal,onProgress:(K,ae,U)=>{let re=Math.min(100,Math.round(K/Math.max(ae,1)*100));Fe(this.deps,f,re,K,ae,U),m.signal.aborted||this.registry?.updateProgress(f,re),this.liveTracker?.updateProgress(f,re,K,ae,U)}}).finally(async()=>{w&&(C=await w.release())}),B=await b?.settle(),N=V.status==="cancelled"?{}:await x.take(Y);for(let K of[...H,...N.note?[N.note]:[]])this.deps.log(`[WARN] seed:remove ${f}: ${K}`);let L={runId:V.runId,status:Co(V.status,B),includeChanged:V.includeChanged,objects:N.object?[...V.objects,N.object]:V.objects,finishedAt:V.finishedAt,...V.leftBy?{leftBy:V.leftBy}:{},...B?{sweep:B}:{},...C?{mutedAutomation:C}:{}};Z(this.deps,{action:"cleanup_delete",module:"seed",operationId:f,orgId:u,outcome:$o(V),guard:p,objects:In(L.objects),...L.leftBy?{leftBy:L.leftBy}:{},...C?{muted:ut(C)}:{},details:{runId:r.runId}});let Q=A(this.deps,e,"seed:remove:response",{result:L,operationId:f});this.deps.broker.postToWebview(Q),this.deps.log(`[TX] ${Q.type} id=${Q.id} status=${L.status}`),L.status==="cancelled"||L.sweep?.status==="cancelled"?(ge(this.deps,f,{aborted:!0}),this.liveTracker?.cancel(f)):(ge(this.deps,f,{status:L.status}),L.status==="failure"?(S=new Error("Nothing this run created could be removed."),this.liveTracker?.fail(f,"Nothing this run created could be removed.")):L.status==="partial"?this.liveTracker?.partial(f):this.liveTracker?.complete(f))}catch(O){S=O,await b?.settle().catch(()=>{});let P=Dt(O)?O:void 0;this.recordNotRemoved(e,r,P?"stopped":"failure",{guard:p,...P?{code:P.code}:{}}),T(this.deps,"seed:remove","seed:remove:error",e,O,{code:P?.code??"REMOVE_ERROR",retryable:!0}),ge(this.deps,f,{status:"failure"}),this.liveTracker?.fail(f,I(O))}finally{y(S)}}};var cc="sync:history:all",LO="syncHistory";var uc=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(cc,n,LO)}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(cc,r,LO),!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(cc)}loadAll(){let e=this.configStore.get(cc);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 Dx=/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+:/;function Nx(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))Dx.test(r)||e.includes(r)?t++:e.push(r);return t===0?{...s,errors:e}:{...s,errors:e,refusalsDropped:(s.refusalsDropped??0)+t}}var lc=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(Nx)},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 jx={Report:"ReportFolder",Dashboard:"DashboardFolder",EmailTemplate:"EmailTemplateFolder"},Mx=new Set(["compare:execute","compare:permissions","compare:snapshots","compare:drift","compare:validate-deployment","compare:deploy"]),Lx=5;function Fx(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 pc=class{constructor(e,t={}){this.deps=e;this.options=t}deps;options;validations=new Map;async handle(e){if(!Mx.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 q(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=await import("./chunk-2AZQHBEF.mjs"),a=this.options.waiting??i.DEFAULT_WAITING,d=this.progressTo(e),c=await i.retrieveComponents(i.metadataApiOf(n),n.version,t.components,{waiting:a,onProgress:d});if(c.managed.length>0){T(this.deps,"compare:validate-deployment","compare:error",e,new Error("A managed package installed "+c.managed.map(g=>`${g.componentType} ${g.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(g=>({componentType:g.componentType,fullName:g.fullName}))}});return}let u=c.retrieved.length>0?await i.deployPackage(i.metadataApiOf(o),c.zipFile,i.deployOptions(!0,t.testLevel,r),{waiting:a,onProgress:d}):void 0,l=i.deploymentReport(u,c,{sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,checkOnly:!0,testLevel:t.testLevel,runTests:r});l.success&&l.deployId&&this.keepValidation(l.deployId,{sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,zipFile:c.zipFile,components:c.retrieved,testLevel:t.testLevel,runTests:r}),this.post(A(this.deps,e,"compare:validate-deployment:response",{report:l}),l)}catch(n){T(this.deps,"compare:validate-deployment","compare:error",e,n,{code:await this.deployErrorCode(n)})}}async handleDeploy(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ey,e,"compare:error",this.deps);if(!t)return;let r=this.validations.get(t.validationId);if(!r){T(this.deps,"compare:deploy","compare:error",e,new Error(`No successful validation ${t.validationId} is waiting in this window: validate the deployment, then deploy it. Nothing was deployed.`),{code:"NOT_VALIDATED"});return}if(r.targetOrgId!==t.targetOrgId){T(this.deps,"compare:deploy","compare:error",e,new Error(`Validation ${t.validationId} was run in another org than the one named. Nothing was deployed.`),{code:"TARGET_MISMATCH"});return}let n;try{if(n=await this.passGuard(e,r.targetOrgId,r.components,!1),!n)return;this.validations.delete(t.validationId);let o=await q(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=await import("./chunk-2AZQHBEF.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:Fx(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}),T(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 ob,i=this.deps.orgManager.getOrg(t),a={orgId:t,orgTier:Pe(i),operation:"deploy",objectName:[...new Set(r.map(u=>u.componentType))].join(", "),recordCount:r.length,module:"compare"};if(n){let u=o.check(a);if(u.allowed)return"allowed";this.refuse(e,u.blockedReason??u.impactSummary);return}let{check:d,decision:c}=await et(o,a);if((c==="refused"||c==="declined")&&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"){T(this.deps,e.type,"compare:error",e,new Error("Operation cancelled by user (deployment confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}return c}refuse(e,t){T(this.deps,e.type,"compare:error",e,new Error(`Operation blocked by Production Guard: ${t}`),{code:"GUARD_BLOCKED"})}keepValidation(e,t){for(this.validations.set(e,t);this.validations.size>Lx;){let r=this.validations.keys().next().value;if(r===void 0)break;this.validations.delete(r)}}progressTo(e){return t=>Fe(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-2AZQHBEF.mjs");return e instanceof t?"STILL_RUNNING":"DEPLOY_ERROR"}async handleCompareStart(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Ds,e,"compare:error",this.deps);if(!t)return;let r=t;try{let n=await this.compareOrgs(r),o=A(this.deps,e,"compare:execute:response",n);this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(n){T(this.deps,"compare:execute","compare:error",e,n)}}async compareOrgs(e,t){t?.throwIfAborted();let r=await q(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager);t?.throwIfAborted();let n=await q(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(f,h)=>{let m=f===e.sourceOrgId?r:n,y=new Map,R=async O=>{t?.throwIfAborted();let P=await m.metadata.list(O);return xe(m.limitInfo,`compare:metadata list ${String(h)}`),Array.isArray(P)?P:[]},S=jx[h],b=S?(await R([{type:S}])).map(O=>({type:h,folder:O.fullName})):[{type:h}];for(let O=0;O<b.length;O+=3)for(let P of await R(b.slice(O,O+3)))y.set(P.fullName,JSON.stringify(P));return y},u=a(f=>f===e.sourceOrgId?r:n,t),l=new i(c,d,u);if(!this.deps.services)throw new Error("CompareHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let g=this.deps.services.compareOrchestrator({metadataCompare:l,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 g.execute(p,t)}async handlePermissions(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ca,e,"compare:error",this.deps);if(!t)return;let r=t;try{let n=await q(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await q(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=async(h,m)=>{let y=await Lt(h,"SELECT Id, Name, Label, IsOwnedByProfile FROM PermissionSet WHERE IsOwnedByProfile = false");xe(h.limitInfo,`compare:permissions ${m}`);let R=await Lt(h,"SELECT Id, Name FROM Profile");return xe(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)),u=new Set(d.permSets.map(h=>h.Name)),l=new Set(a.profiles.map(h=>h.Name)),g=new Set(d.profiles.map(h=>h.Name)),p={permissionSets:{sourceOnly:a.permSets.filter(h=>!u.has(h.Name)).map(h=>({name:h.Name,label:h.Label})),targetOnly:d.permSets.filter(h=>!c.has(h.Name)).map(h=>({name:h.Name,label:h.Label})),shared:a.permSets.filter(h=>u.has(h.Name)).map(h=>({name:h.Name,label:h.Label}))},profiles:{sourceOnly:a.profiles.filter(h=>!g.has(h.Name)).map(h=>({name:h.Name})),targetOnly:d.profiles.filter(h=>!l.has(h.Name)).map(h=>({name:h.Name})),shared:a.profiles.filter(h=>g.has(h.Name)).map(h=>({name:h.Name}))}},f=A(this.deps,e,"compare:permissions:response",{permissions:p});this.deps.broker.postToWebview(f),this.deps.log(`[TX] ${f.type} id=${f.id}`)}catch(n){T(this.deps,"compare:permissions","compare:error",e,n)}}async handleSnapshots(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ca,e,"compare:error",this.deps);if(!t)return;let r=t;try{let n=await q(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await q(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=async(p,f)=>{let h=await p.describeGlobal();xe(p.limitInfo,`compare:snapshots describeGlobal ${f}`);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)),u=new Set(d.objects.map(p=>p.name)),l={source:{orgId:r.sourceOrgId,totalObjects:a.totalObjects,customObjects:a.customObjects,standardObjects:a.standardObjects,queryableObjects:a.queryableObjects},target:{orgId:r.targetOrgId,totalObjects:d.totalObjects,customObjects:d.customObjects,standardObjects:d.standardObjects,queryableObjects:d.queryableObjects},diff:{sourceOnly:a.objects.filter(p=>!u.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=>u.has(p.name)).length},capturedAt:new Date().toISOString()},g=A(this.deps,e,"compare:snapshots:response",{snapshot:l});this.deps.broker.postToWebview(g),this.deps.log(`[TX] ${g.type} id=${g.id}`)}catch(n){T(this.deps,"compare:snapshots","compare:error",e,n)}}async handleDrift(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ca,e,"compare:error",this.deps);if(!t)return;let r=t;try{let n=await q(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await q(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=async(p,f)=>{let h={},m=await Lt(p,"SELECT Name, LanguageLocaleKey, DefaultLocaleSidKey, TimeZoneSidKey, FiscalYearStartMonth FROM Organization LIMIT 1");if(xe(p.limitInfo,`compare:drift companyInfo ${f}`),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)]),u=[];for(let p of c){let f=a[p],h=d[p];f===void 0?u.push({setting:p,sourceValue:"",targetValue:h??"",status:"missing_source"}):h===void 0?u.push({setting:p,sourceValue:f,targetValue:"",status:"missing_target"}):f!==h?u.push({setting:p,sourceValue:f,targetValue:h,status:"drift"}):u.push({setting:p,sourceValue:f,targetValue:h,status:"match"})}let l={items:u,totalChecked:u.length,driftCount:u.filter(p=>p.status==="drift").length,matchCount:u.filter(p=>p.status==="match").length,missingCount:u.filter(p=>p.status==="missing_source"||p.status==="missing_target").length,detectedAt:new Date().toISOString()},g=A(this.deps,e,"compare:drift:response",{drift:l});this.deps.broker.postToWebview(g),this.deps.log(`[TX] ${g.type} id=${g.id}`)}catch(n){T(this.deps,"compare:drift","compare:error",e,n)}}};import{randomBytes as eD}from"node:crypto";function FO(s,e,t){return s==="delete"?{...mt(e),deleted:t.done,failed:t.failed}:{...mt(e),updated:t.done,failed:t.failed}}async function gc(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:Re.code}),{ran:!1,operationId:r,code:Re.code,message:Re.message};let o=s.orgManager.getOrg(e.orgId),{check:i,decision:a}=await et(n,{orgId:e.orgId,orgTier:Pe(o),operation:e.operation,objectName:e.objectNames.join(", "),recordCount:e.recordCount,module:"dataops"}),d=a;if(a==="refused"||a==="declined")return 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)."};Je(s,r,"dataops",e.description);let c=new AbortController,u=()=>{},l=new Promise((h,m)=>{u=y=>y===void 0?h():m(y)});l.catch(()=>{}),s.infraServices?.backgroundRegistry?.register(r,"dataops",e.description,l,c);let g=ar(t,r,"dataops",e.description,e.recordCount),p=[],f=0;try{let h=await e.run((R,S)=>{p.push({objectApiName:R,counts:S}),f+=S.done+S.failed;let b=Math.min(100,Math.round(f/Math.max(e.recordCount,1)*100)),O=`${R}: ${S.done} done, ${S.failed} refused`;Fe(s,r,b,f,e.recordCount,O),g.progress(b,f,e.recordCount,O)},c.signal);await e.beforeEnd?.();let m=Rl(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:rt}:{outcome:m.status},...d?{guard:d}:{},objects:h.map(R=>FO(e.operation,R.objectApiName,R.counts))}),y)return s.infraServices?.backgroundRegistry?.abort(r),ge(s,r,{aborted:!0,done:m.done,failed:m.failed}),g.cancel(),u(),{ran:!0,operationId:r,outcome:m,...d?{guard:d}:{},cancelled:!0,error:`Cancelled: ${m.done} record(s) ${e.operation==="delete"?"deleted":"overwritten"} before the cancel; the rest were left as they are.`};if(ge(s,r,{status:m.status,done:m.done,failed:m.failed}),m.status==="failure"){let R=`The org refused the ${m.failed} record(s)`;g.fail(R),u(new Error(R))}else m.status==="partial"?g.partial():g.complete(),u();return{ran:!0,operationId:r,outcome:m,...d?{guard:d}:{}}}catch(h){await e.beforeEnd?.();let m=I(h);return Z(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,outcome:"failure",...d?{guard:d}:{},objects:p.map(y=>FO(e.operation,y.objectApiName,y.counts))}),je(s,r,m,!0,{context:{module:"dataops",operation:e.origin,objectName:e.objectNames.join(", ")}}),g.fail(m),u(h),{ran:!0,operationId:r,outcome:{...Rl(p),status:"failure"},...d?{guard:d}:{},error:m}}}var _O=100;async function Ux(s,e,t){let r=new Map,n=[],o=t.map(a=>ze(a.name)).filter(a=>a!=="Id"),i=[];for(let a=0;a<o.length;a+=_O)i.push(o.slice(a,a+_O));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 u={...c};delete u.attributes;let l=typeof u.Id=="string"?u.Id:void 0;if(!l)continue;let g=r.get(l);g?Object.assign(g,u):(r.set(l,u),n.push(l))}}return n.map(a=>r.get(a))}async function Hx(s,e,t){let r,n;try{if(r=or.parse(await s.describe(ze(t))),n=ze(r.name),r.queryable===!1)throw new Error(`${n} cannot be queried.`)}catch(f){return{status:"failed",objectApiName:t,message:I(f)}}let o=Us(e,n,r.fields),i=new Set(o.map(f=>f.field.name)),a=r.fields.filter(f=>Xw(f)&&Yw(f)||i.has(f.name)),d=[],c;try{d=await Ux(s,n,a)}catch(f){c=I(f)}let u=c?o:Us(e,n,r.fields,d),l=e.getPatterns(),g=u.map(f=>{let h=Qw(f.field),m=d.map(R=>R[f.field.name]),y=f.detectedBy==="content"?l[f.pattern]:void 0;return{fieldApiName:f.field.name,label:f.field.label,classification:f.classification,detectedBy:f.detectedBy,pattern:f.pattern,filled:m.filter(Aa).length,...y?{matched:m.filter(R=>typeof R=="string"&&y.test(R)).length}:{},...h?{searchedFor:h}:{}}}).sort((f,h)=>h.filled-f.filled||f.label.localeCompare(h.label)),p=Zw(r);return{status:"scanned",objectApiName:t,label:r.label,sampled:d.length,fields:g,nameField:p?{fieldApiName:p.name,label:p.label}:null,...c!==void 0?{sampleError:c}:{}}}async function UO(s,e,t,r=()=>new Date){let n=r().toISOString(),o=[];for(let i of t.objects)o.push(await Hx(s,e,i));return{orgId:t.orgId,scannedAt:n,sampleSize:200,objects:o}}async function Bx(s,e,t,r){let n=t.fields.filter(Kw).map(d=>d.name),o=await Sn(s,t.name,n,r),i=Us(e,t.name,t.fields,o),a=tb(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 HO(s,e,t,r){let n=[],o;for(let i of r){let a=or.parse(await s.describe(ze(i.objectApiName))),d=u=>({objectApiName:a.name,plan:{objectApiName:a.name,label:a.label,records:0,refused:u}});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 Bx(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 ga(s);let c=await fa(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 fc(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 qx(s,e){return e.map(t=>({objectApiName:s,fieldApiName:t.field.name,method:t.method,config:{}}))}async function BO(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 ha(s,i.objectApiName,i.ids,n);else{let d=i.erased??[],c=i.records??[];if(d.length===0||c.length===0)continue;let u=e.anonymize(c,qx(i.objectApiName,d)),l=[],g=0;c.forEach((p,f)=>{let h={Id:p.Id};for(let m of d)Aa(p[m.field.name])&&(h[m.field.name]=u[f][m.field.name]??null);Object.keys(h).length>1?l.push(h):g++}),a=await hw(s,i.objectApiName,l,n),a.done+=g}o.push({objectApiName:i.objectApiName,counts:a}),r?.(i.objectApiName,a)}return o}var qO="dataops:subject-requests",Wx="audit",zx=J({objectApiName:j(),done:Te().int().nonnegative(),failed:Te().int().nonnegative()}),Gx=ji("kind",[J({kind:yt("searched"),at:j(),searchedBy:ve(We(["email","phone","name"])),objects:ve(J({objectApiName:j(),found:Te().int().nonnegative(),truncated:Ke()}))}),J({kind:yt("exported"),at:j(),records:Te().int().nonnegative()}),J({kind:yt("erased"),at:j(),mode:We(["anonymize","delete"]),outcome:We(["success","partial","failure","stopped"]),operationId:j(),objects:ve(zx)})]),Jx=J({requestId:j().min(1),orgId:j().min(1),openedAt:j(),events:ve(Gx)}),hc=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(qO);return Array.isArray(e)?e.flatMap(t=>{let r=Jx.safeParse(t);return r.success?[r.data]:[]}):[]}write(e){this.configStore.set(qO,e.slice(-this.limit),Wx)}};function Kx(s){return Ku(s).slice(-8)}function Xx(s){return`%${s.split("").join("%")}%`}function WO(s,e){return typeof s=="string"&&s.trim().toLowerCase()===e.trim().toLowerCase()}function Yx(s,e,t){let r=ze(s.name);if(e==="email"&&t.email){let n=t.email.trim();return{field:s,kind:e,soql:`${r} = '${tr(n)}'`,matches:o=>WO(o,n)}}if(e==="phone"&&t.phone){let n=Kx(t.phone);return{field:s,kind:e,soql:`${r} LIKE '${Xx(n)}'`,matches:o=>typeof o=="string"&&Ku(o).includes(n)}}if(e==="name"&&t.name){let n=t.name.trim();return{field:s,kind:e,soql:`${r} = '${tr(n)}'`,matches:o=>WO(o,n)}}}async function Qx(s,e,t){try{let r=or.parse(await s.describe(ze(e))),n=ze(r.name);if(r.queryable===!1)throw new Error(`${n} cannot be queried.`);let o=eb(r).flatMap(({field:p,kind:f})=>{let h=Yx(p,f,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),u=[...new Set(["Id",...c?[c.name]:[],...o.map(p=>p.field.name)])].map(ze),l=await s.query(`SELECT ${u.join(", ")} FROM ${n} WHERE ${a} ORDER BY Id LIMIT ${t.limit}`),g=[];for(let p of l.records){if(typeof p!="object"||p===null)continue;let f=p;if(!Yr(f.Id))continue;let h=[...new Set(o.filter(y=>y.matches(f[y.field.name])).map(y=>y.field.name))];if(h.length===0)continue;let m=c?f[c.name]:null;g.push({id:f.Id,name:typeof m=="string"?m:null,matchedBy:h})}return{status:"searched",objectApiName:e,label:r.label,counted:d,records:g,truncated:d>t.limit,searched:i}}catch(r){return{status:"failed",objectApiName:e,message:Zx(I(r),t.identifiers)}}}function Zx(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 zO(s,e){let t=[];for(let r of e.objects)t.push(await Qx(s,r,e));return t}var tD=6e4,rD=new Set(["dataops:pii-inventory","dataops:dsr:search","dataops:dsr:export","dataops:dsr:erase","dataops:dsr:log"]),nD=20;function oD(s){let e="payload"in s?s.payload:void 0;return typeof e=="object"&&e!==null&&"dryRun"in e?e.dryRun===!0:!1}function sD(s){return typeof s=="object"&&s!==null&&"success"in s&&s.success===!0}function iD(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)=>sD(i)?[r[a]?.Id]:[])),n}catch(n){throw ib(n)==="may-have-written"&&e.wrote(t,r.map(o=>o.Id)),n}}}}function aD(s){return["email","name","phone"].filter(e=>s[e]!==void 0)}var mc=class{constructor(e,t){this.deps=e;this.saveDialog=t??new An}deps;found=new Map;maskingKey=eD(32).toString("hex");saveDialog;writing=new ab;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=lb;setDuplicatesSettle(e){this.duplicatesSettleMs=e}ownReader(){return this.reader??=import("./chunk-GOOVPVWX.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}isWritingTo(e){return this.writing.has(e)}get requestLog(){return new hc(this.deps.configStore)}get detector(){return this.deps.infraServices?.piiDetector??new Ta}async session(e,t){let r=await q(e,this.deps.orgRegistry,this.deps.orgManager);return pa(r,t)}async handle(e){if(!rD.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(oD(e)?void 0:db(e,"orgId"),()=>this.handleErase(e)),!0;default:return this.handleLog(e),!0}}async handleInventory(e){let t=$(Um,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:pii-inventory"),n=await UO(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){T(this.deps,"dataops:pii-inventory","dataops:error",e,r)}}async handleSearch(e){let t=$(Hm,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 zO(i,{objects:n,identifiers:o,limit:200}),d=this.requestLog,c=t.requestId!==void 0&&d.has(t.requestId,r)?t.requestId:crypto.randomUUID(),u=new Date().toISOString(),l={orgId:r,objects:new Map};for(let h of a)h.status==="searched"&&l.objects.set(h.objectApiName,new Set(h.records.map(m=>m.id)));this.hold(c,l),d.record(c,r,{kind:"searched",at:u,searchedBy:aD(o),objects:a.flatMap(h=>h.status==="searched"?[{objectApiName:h.objectApiName,found:h.records.length,truncated:h.truncated}]:[])});let g={requestId:c,orgId:r,searchedAt:u,limit:200,objects:a},p=A(this.deps,e,"dataops:dsr:search:response",{...g});this.deps.broker.postToWebview(p);let f=[...l.objects.values()].reduce((h,m)=>h+m.size,0);this.deps.log(`[TX] ${p.type} id=${p.id} records=${f}`)}catch(i){T(this.deps,"dataops:dsr:search","dataops:error",e,i)}}hold(e,t){for(this.found.delete(e),this.found.set(e,t);this.found.size>nD;){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=$(Bm,e,"dataops:error",this.deps);if(t)try{let r=this.heldFor(t.requestId,t.orgId),n=await this.session(t.orgId,"dataops:dsr:export"),o={},i=0;for(let[l,g]of r.objects){if(g.size===0)continue;let p=or.parse(await n.describe(l)),f=await Sn(n,p.name,p.fields.map(h=>h.name),[...g]);o[l]=f,i+=f.length}let a=new Date().toISOString(),d={sandforgeSubjectRequestVersion:1,requestId:t.requestId,orgId:t.orgId,exportedAt:a,objects:o},c=await this.saveDialog.save(`sandforge-subject-request-${t.requestId.slice(0,8)}.json`,JSON.stringify(d,null,2),["json"]);c.status==="saved"&&this.requestLog.record(t.requestId,t.orgId,{kind:"exported",at:a,records:i});let u=A(this.deps,e,"dataops:dsr:export:response",{requestId:t.requestId,records:i,saved:c});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id} ${c.status} records=${i}`)}catch(r){T(this.deps,"dataops:dsr:export","dataops:error",e,r)}}async handleErase(e){let t=$(Wm,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,Q)=>{let K=a.objects.get(Q.objectApiName);return L+Q.ids.filter(ae=>!K?.has(ae)).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"),u=await HO(c,this.detector,o,t.records),l=u.map(L=>L.plan),g=fc(l);if(i){let L=A(this.deps,e,"dataops:dsr:erase:response",{requestId:n,mode:o,dryRun:i,plan:l,written:g});this.deps.broker.postToWebview(L),this.deps.log(`[TX] ${L.type} id=${L.id} plan objects=${l.length}`);return}let p=l.filter(L=>!L.refused&&L.records>0),f=p.reduce((L,Q)=>L+Q.records,0);if(f===0){let L=l.flatMap(Q=>Q.refused?[Q.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=ye(this.deps.orgManager.getOrg(r),r),m=await q(r,this.deps.orgRegistry,this.deps.orgManager),y=this.targetAutomation,R=await Zr({act:o==="delete"?"cleanup":"masking",target:h,objects:g,org:No(m,L=>new fe(tD).withTimeout("dataops automation",()=>y.read(r,L)),Pe(this.deps.orgManager.getOrg(r))==="production"),accord:t,mayMute:!0,muteLeases:this.muteLeases,voice:"erasure"}),S=Tn(R.answer),b=S?{refused:S}:await to(R,e.id,t.acceptEmails===!0,"erasure");if("refused"in b){let L=crypto.randomUUID();Z(this.deps,{action:"subject_erase",module:"dataops",operationId:L,orgId:r,outcome:"stopped",code:b.refused.code}),this.requestLog.record(n,r,{kind:"erased",at:new Date().toISOString(),mode:o,outcome:"stopped",operationId:L,objects:[]}),T(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(b.refused.message),{code:b.refused.code,...S?Ca(S):{}});return}let O=b.held,P={},v=async()=>{if(!(!O||P.back)){P.back=await O.release();for(let L of Kt(P.back,h))this.deps.log(`[INFO] ${L}`)}},w=o==="anonymize"?gb({query:async L=>m.query(L),serverTime:async()=>(await m.soap.getServerTimestamp()).timestamp},pb(R.answer.automation,g.map(L=>L.objectApiName)),{settleMs:this.duplicatesSettleMs}):void 0,C={},k=async()=>{await v(),!C.read&&(C.read=!0,C.duplicates=await w?.read())},E=()=>hb(C.duplicates,h,"erasure"),x=()=>O?{mutedAutomation:P.back??O.outcome}:{},V=new Mb(void 0,this.maskingKey),H=await gc(this.deps,{orgId:r,operation:o==="delete"?"delete":"update",objectNames:p.map(L=>L.objectApiName),recordCount:f,action:"subject_erase",description:`Erase ${f} record(s) of a subject request`,origin:"dataops:dsr:erase",run:(L,Q)=>BO(w?iD(c,w):c,V,u,L,Q),beforeEnd:k},this.liveTracker).finally(v),Y=new Date().toISOString();if(!H.ran){this.requestLog.record(n,r,{kind:"erased",at:Y,mode:o,outcome:"stopped",operationId:H.operationId,objects:[]}),T(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(H.message),{...H.code?{code:H.code}:{},extraPayload:x()});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:B}=C;if(H.error!==void 0){let L=E();T(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(L?`${H.error} ${L}`:H.error),{...H.cancelled?{code:rt}:{},extraPayload:{...x(),...B?{duplicates:B}:{}}});return}let N=A(this.deps,e,"dataops:dsr:erase:response",{requestId:n,mode:o,dryRun:i,plan:l,outcome:H.outcome,...x(),...B?{duplicates:B}:{}});this.deps.broker.postToWebview(N),this.deps.log(`[TX] ${N.type} id=${N.id} ${H.outcome.status} done=${H.outcome.done} failed=${H.outcome.failed}`),fb(B)&&Ie(this.deps,"warning","Erase",E())}catch(a){T(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){T(this.deps,"dataops:dsr:log","dataops:error",e,t)}}};var dD=new Set(["User","Group","RecordType","BusinessHours","Profile","UserRole"]);function XO(s){return s.type==="reference"&&vl(s)&&s.nillable===!0&&s.filterable===!0&&s.referenceTo?.length===1&&!dD.has(s.referenceTo[0])}function YO(s,e){return e>0&&s/e>=.9}async function cD(s,e,t){let r,n,o;try{if(r=or.parse(await s.describe(ze(e.objectApiName))),n=ze(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:I(p)}}let i=r.fields.filter(Sl).sort((p,f)=>p.label.localeCompare(f.label)),a=r.fields.filter(XO),d=[...a,...r.fields.filter(p=>vl(p)&&!a.includes(p))],[c,u,l]=await Promise.all([bw(s,n,d,o),Rw(s,n,i,e.duplicateKey,o),Sw(s,n,r.fields,t,o)]),g=c.fields.filter(p=>a.some(f=>f.name===p.fieldApiName)&&YO(p.filled,o)&&p.filled<o).map(p=>{let f=a.find(h=>h.name===p.fieldApiName);return{fieldApiName:p.fieldApiName,label:p.label,referenceTo:f?.referenceTo?.[0]??"",filled:p.filled,empty:o-p.filled}}).sort((p,f)=>f.empty-p.empty||p.label.localeCompare(f.label));return{status:"scanned",objectApiName:e.objectApiName,label:r.label,totalRecords:o,fields:c.fields,unmeasured:c.unmeasured,stale:l.stale,orphans:g,duplicates:u.duplicates,keyFields:i.map(p=>({fieldApiName:p.name,label:p.label})),errors:[...c.errors,...u.errors,...l.errors],deletable:r.deletable===!0}}async function QO(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 cD(s,o,e.staleDays));return{orgId:e.orgId,staleDays:e.staleDays,scannedAt:r,orphanThreshold:.9,bounds:{duplicateGroupLimit:mw,duplicateSample:yw,singleFieldQueries:ww},objects:n}}function uD(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 og(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 Yr(t)?[t]:[]})}function lD(s,e){switch(s){case"int":case"long":case"double":case"currency":case"percent":return typeof e=="number"&&Number.isFinite(e)?String(e):void 0;case"boolean":return typeof e=="boolean"?String(e):void 0;case"date":return typeof e=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(e)?e:void 0;case"datetime":case"time":return;default:return typeof e=="string"?`'${tr(e)}'`:void 0}}function pD(s,e){let t=String(e??"");return typeof e=="string"&&s!=="date"?t.toLowerCase():t}var VO=100,gD=2e3;async function fD(s,e,t,r){let n=ze(e.name),o=ze(t.name),i=await vw(s,n,t.name),a=i.rows.reduce((l,g)=>l+g.count-1,0),d=i.rows.map(l=>lD(t.type,l.value));if(d.some(l=>l===void 0))throw new Error(`Copies of ${e.label} records cannot be picked out by ${t.label}: its values are dates and times, which this cleanup does not compare.`);let c=e.fields.some(l=>l.name==="LastModifiedDate"),u=[];for(let l=0;l<d.length&&u.length<r;l+=VO){let g=d.slice(l,l+VO).join(", "),p=await s.query(`SELECT Id, ${o}${c?", LastModifiedDate":""} FROM ${n} WHERE ${o} IN (${g}) ORDER BY Id LIMIT ${gD}`),f=new Map;for(let h of p.records){if(typeof h!="object"||h===null)continue;let m=h;if(!Yr(m.Id))continue;let y=pD(t.type,m[t.name]),R=f.get(y)??[];R.push({id:m.Id,modified:typeof m.LastModifiedDate=="string"?m.LastModifiedDate:""}),f.set(y,R)}for(let h of f.values()){h.sort((m,y)=>y.modified.localeCompare(m.modified)||y.id.localeCompare(m.id));for(let m of h.slice(1)){if(u.length>=r)break;u.push(m.id)}}}return{total:a,ids:u}}async function sg(s,e,t,r,n){let o=or.parse(await s.describe(ze(e))),i=ze(o.name),a=p=>o.fields.find(f=>f.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}`,f=(await s.query(`SELECT COUNT() FROM ${i} WHERE ${p}`)).totalSize,h=n?.modified!==void 0?uD(n.modified):void 0,m=h!==void 0&&n?.id!==void 0&&Yr(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),S=y.records.at(-1),b=og(n,R.length,f,{id:R.at(-1),...typeof S?.LastModifiedDate=="string"?{modified:S.LastModifiedDate}:{}});return{object:o,total:f,ids:R,truncated:(n?.skip??0)+R.length<f,...b?{next:b}:{}}}if(t.kind==="orphans"){let p=a(t.fieldApiName);if(!p||!XO(p))throw new Error(`${t.fieldApiName} is not a lookup of ${o.label} that can leave a record without its parent.`);let f=ze(p.name),h=(await s.query(`SELECT COUNT() FROM ${i}`)).totalSize,m=(await s.query(`SELECT COUNT() FROM ${i} WHERE ${f} = null`)).totalSize;if(!YO(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&&Yr(n.id)?` AND Id > '${n.id}'`:"",R=await s.query(`SELECT Id FROM ${i} WHERE ${f} = null${y} ORDER BY Id LIMIT ${r}`),S=JO(R.records),b=og(n,S.length,m,{id:S.at(-1)});return{object:o,total:m,ids:S,truncated:(n?.skip??0)+S.length<m,...b?{next:b}:{}}}let d=a(t.keyField);if(!d||!Sl(d))throw new Error(`${t.keyField} is not a field ${o.label} records can be grouped by.`);let c=n?.skip??0,u=await fD(s,o,d,c+r),l=u.ids.slice(c),g=og(n,l.length,u.total,{});return{object:o,total:u.total,ids:l,truncated:c+l.length<u.total,...g?{next:g}:{}}}var hD=6e4,mD=new Set(["dataops:cleanup:scan","dataops:cleanup:export","dataops:cleanup:delete"]);function eI(s){switch(s.kind){case"stale":return`stale-${s.days}d`;case"orphans":return`orphans-${s.fieldApiName}`;default:return`duplicates-${s.keyField}`}}var yc=class{constructor(e,t){this.deps=e;this.saveDialog=t??new An}deps;saveDialog;liveTracker;setLiveOperationTracker(e){this.liveTracker=e}targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;muteLeases={};setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}ownReader(){return this.reader??=import("./chunk-GOOVPVWX.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async session(e,t){let r=await q(e,this.deps.orgRegistry,this.deps.orgManager);return pa(r,t)}async handle(e){if(!mD.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 QO(r,t),o=A(this.deps,e,"dataops:cleanup:scan:response",{...n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} objects=${n.objects.length}`)}catch(r){T(this.deps,"dataops:cleanup:scan","dataops:error",e,r)}}async handleExport(e){let t=$(zm,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:cleanup:export"),n=await sg(r,t.objectApiName,t.recommendation,1e3,t.after),o=await Sn(r,n.object.name,n.object.fields.map(u=>u.name),n.ids),i=new Date().toISOString(),a={sandforgeCleanupVersion:1,orgId:t.orgId,objectApiName:n.object.name,recommendation:t.recommendation,exportedAt:i,recommended:n.total,records:o},d=await this.saveDialog.save(`sandforge-cleanup-${n.object.name}-${eI(t.recommendation)}.json`,JSON.stringify(a,null,2),["json"]),c=A(this.deps,e,"dataops:cleanup:export:response",{objectApiName:t.objectApiName,records:o.length,truncated:n.truncated,saved:d,exported:(t.after?.skip??0)+o.length,recommended:n.total,...n.next?{next:n.next}:{}});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id} ${d.status} records=${o.length}`)}catch(r){T(this.deps,"dataops:cleanup:export","dataops:error",e,r)}}async handleDelete(e){let t=$(Gm,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 sg(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 v=await fa(i,d,c,await ga(i)),w={objectApiName:d.name,label:d.label,records:c.length,related:v.related,uncounted:v.uncounted},C=A(this.deps,e,"dataops:cleanup:delete:response",{objectApiName:t.objectApiName,dryRun:o,plan:w,truncated:a.truncated,written:fc([w])});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 u=await q(r,this.deps.orgRegistry,this.deps.orgManager),l=ye(this.deps.orgManager.getOrg(r),r),g=this.targetAutomation,p=Pa(t),f=await Zr({act:"cleanup",target:l,objects:[{objectApiName:d.name,records:c.length}],org:No(u,v=>new fe(hD).withTimeout("dataops automation",()=>g.read(r,v)),Pe(this.deps.orgManager.getOrg(r))==="production"),accord:t,mayMute:!0,muteLeases:this.muteLeases,...p?{voice:p}:{}}),h=Tn(f.answer);if(h){T(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(h.message),{code:h.code,...Ca(h)});return}let m=await to(f,e.id,t.acceptEmails===!0,p);if("refused"in m){T(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(m.refused.message),{code:m.refused.code});return}let y=m.held,R={},S=async()=>{if(!(!y||R.back)){R.back=await y.release();for(let v of Kt(R.back,l))this.deps.log(`[INFO] ${v}`)}},b={objectApiName:d.name,label:d.label,records:c.length},O=await gc(this.deps,{orgId:r,operation:"delete",objectNames:[d.name],recordCount:c.length,action:"cleanup_delete",description:`Delete ${c.length} ${d.name} record(s): ${eI(n)}`,origin:"dataops:cleanup:delete",run:async(v,w)=>{let C=await ha(i,d.name,c,w);return v(d.name,C),[{objectApiName:d.name,counts:C}]},beforeEnd:S},this.liveTracker).finally(S);if(!O.ran){T(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(O.message),O.code?{code:O.code}:void 0);return}if(O.error!==void 0){T(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(O.error),O.cancelled?{code:rt}:void 0);return}let P=A(this.deps,e,"dataops:cleanup:delete:response",{objectApiName:t.objectApiName,dryRun:o,plan:b,truncated:a.truncated,outcome:O.outcome,...y?{mutedAutomation:R.back??y.outcome}:{}});this.deps.broker.postToWebview(P),this.deps.log(`[TX] ${P.type} id=${P.id} ${O.outcome.status} deleted=${O.outcome.done} failed=${O.outcome.failed}`)}catch(i){T(this.deps,"dataops:cleanup:delete","dataops:error",e,i)}}};import{join as bN}from"node:path";async function tI(s){let{permissions:e,objects:t}=s;if(e.viewAllData&&e.modifyAllData)return{kind:"org"};let r={kind:"perObject",viewAllData:e.viewAllData,modifyAllData:e.modifyAllData},n=await s.grants();if("unread"in n)return{...r,unseen:t.map(l=>({objectApiName:l,reason:"permissionsUnread",detail:n.unread}))};let o=await s.describe(t),i={grants:n.grants,describes:o,...s.customSettings?{customSettings:s.customSettings}:{}},a=Ub(t,i),d=a.length>0?[...o,...await s.describe(a)]:o,c=Hb(t,{...i,describes:d}),u=[];for(let[l,g]of c)"access"in g||u.push({objectApiName:l,reason:g.reason,...g.detail!==void 0?{detail:g.detail}:{}});return{...r,unseen:u}}function rI(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 yD=1e4,oI={bulkDestroy:()=>Promise.reject(new Error("an estimate sends no job"))};function ig(s){return Ls(oI,s,1,"hard")}var sI=9,wD=25;function iI(s,e,t){let r=e>0&&Ls(oI,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/Wt),jobs:[],toTheBin:!0};let n=Math.ceil(e/Ms),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 Lr(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 aI(s){return Math.max(1,Math.ceil(s/Pl))}function dI(s){return s.notSent?{apiRequests:0,seconds:0}:fi([Lr(aI(s.records),ro),Lr(1,Bs),Lr(s.restCalls,Ma),...s.jobs.map(e=>({apiRequests:Aw({stateReads:Ew(e)}),seconds:Tw(e)}))])}function bD(s){return s<=0?{apiRequests:0,seconds:0}:fi([Lr(1,Bs),Lr(Math.ceil(s/Pl),ro),Lr(Math.ceil(s/Wt),Ma),Lr(Math.ceil(s/Wt),ro)])}function RD(s){if(s<=0)return{apiRequests:0,seconds:0};let e=Math.ceil(s/Wt);return fi([Lr(e,Ma),Lr(e,ro)])}var vD=.05,nI={check:2,connect:3};function wc(s,e,t,r=0){let n=t*nI.check+nI.connect,o=t*e+n+s.apiRequests+r,i=Math.ceil(o*vD);return{apiRequests:o+i,seconds:e*Bs+s.seconds,requests:{reads:e,readings:t,passes:s.apiRequests,margin:i,connecting:n,...r>0?{mute:r}:{}}}}function cI(s){let e=s.passes.map(({objectApiName:d,records:c})=>iI(d,Math.max(0,c),s.mode)),t=fi([bD(s.toDraft),Lr(s.draftReads??0,ro),...e.map(dI),...(s.refused??[]).map(RD)]),r=wc(t,Math.max(0,s.reads),s.readings??2),n=e.reduce((d,c)=>d+c.jobs.reduce((u,l)=>u+Math.ceil(l/yD),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*wD,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:En(r.apiRequests,s.apiBudget),...a?{batches:s.bulkBatches?En(n,s.bulkBatches):{verdict:"unread",estimate:n,unread:"the limits the org answered list no DailyBulkApiBatches"}}:{}}}function uI(s,e,t,r=0){let n=fi(e.map(o=>{let i=iI(o.objectApiName,Math.max(0,o.records),s),a=dI(i);if(!o.idsRead||i.notSent)return a;let d=aI(i.records);return{apiRequests:a.apiRequests-d,seconds:a.seconds-d*ro}}));return wc(n,Math.max(0,t),1,Math.max(0,r)).apiRequests}var ag=3;function lI(s,e,t=0){return wc({apiRequests:Math.max(0,s),seconds:0},Math.max(0,e),1,Math.max(0,t)).apiRequests}function pI(s,e,t,r=0){let n={apiRequests:s.requests.passes,seconds:s.seconds-s.requests.reads*Bs},o=wc(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:En(o.apiRequests,i)}}var SD=_b.extend({relationshipName:j().nullish(),polymorphicForeignKey:Ke().optional()}),gI=Fa.extend({deletable:Ke().optional(),fields:ve(SD)});function dg(s){return xb.has(s)}var fI={pricebook2:{field:"IsStandard",value:!0}};function hI(s){let e=fI[s.toLowerCase()];return e?`${e.field} = ${String(e.value)}`:void 0}function ao(s){let e=fI[s.toLowerCase()];return e?`${e.field} = ${String(!e.value)}`:void 0}var kD=new Set(["pricebook2","product2"]);function mI(s,e){return e!==void 0&&s.childSObject!==void 0&&s.field!==void 0&&Fb(s.childSObject,s.field,e)?"restricted":s.cascadeDelete===!0?"cascade":s.restrictedDelete===!0?"restricted":"lookup"}function cg(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)?bc(s,i,o.field):void 0;yI(a,r)||t.push({parent:r,child:e(o.childSObject),field:o.field,kind:mI(o,r)})}return t}var hi=5,OD=8;function yI(s,e){if(s?.polymorphicForeignKey===!0)return!1;let t=s?.referenceTo??[];return t.length>0&&!t.some(r=>r.toLowerCase()===e.toLowerCase())}function ID(s,e,t){let r=bc(s,e,t);return(r?.referenceTo?.length??0)>1||r?.polymorphicForeignKey===!0}function ug(s,e,t){let r=new Map;for(let f of[...e,...s,...t.keys()])r.set(f.toLowerCase(),f);let n=f=>r.get(f.toLowerCase())??f,o=f=>t.get(f)??t.get(n(f)),i=new Set(s.map(f=>f.toLowerCase())),a=new Set([...e,...s].map(f=>f.toLowerCase())),d=new Map,c=new Map,u=new Set,l=(f,h)=>{let m=c.get(f)??new Set;m.add(h),c.set(f,m)},g=s.map(f=>({top:f,from:f,above:[]}));for(;g.length>0;){let f=[];for(let{top:h,from:m,above:y}of g){let R=o(m);if(!R){u.add(m);continue}for(let S of R.childRelationships??[]){if(mI(S,m)!=="cascade")continue;let b=n(S.childSObject),P=o(b)?.fields.find(k=>k.name.toLowerCase()===S.field.toLowerCase());if(yI(P,m))continue;let v=b.toLowerCase();if(!a.has(v)||v===m.toLowerCase()||y.some(k=>k.object.toLowerCase()===v))continue;let w=[{object:b,field:S.field,parent:m},...y],C=d.get(b)??[];if(w.length>1&&C.length>=OD){l(b,m);continue}d.set(b,[...C,{object:b,steps:w,emptied:h}]),!(i.has(v)||w.length>=hi)&&f.push({top:h,from:b,above:w})}}g=f}for(let f=!0;f;){f=!1;for(let[h,m]of d)for(let y of m)for(let[R,S]of y.steps.entries())R===0||!c.has(S.object)||y.steps.slice(0,R).some(O=>ID(t,O.object,O.field))||c.get(h)?.has(S.object)||(l(h,S.object),f=!0)}let p=[...d.keys()].filter(f=>!i.has(f.toLowerCase())).sort();return{emptied:new Set(s),routes:d,along:p,routesCut:new Map([...c].map(([f,h])=>[f,[...h].sort()])),undescribed:[...u].filter(f=>!i.has(f.toLowerCase())).sort()}}function rs(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 AD(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 bc(s,e,t){let r=t.toLowerCase();return s.get(e)?.fields.find(n=>n.name.toLowerCase()===r)}function Rc(s,e,t=ao,r=()=>{}){let n=[],o=(i,a,d,c)=>AD({soql:i,exact:a},d,r(c));for(let[i,a]of s.entries()){if(!e.has(a.object)){let f=[...n,a.field].join(".");return o(`${f} != null`,!1,f,a.parent)}let d=bc(e,a.object,a.field);if(!d){if(i===0)return;let f=s[i-1],h=[...n.slice(0,-1),f.field].join(".");return o(`${h} != null`,!1,h,f.parent)}let c=(d.referenceTo?.length??0)>1||d.polymorphicForeignKey===!0,u=d.relationshipName??void 0,l=i===s.length-1,g=u?[...n,u].join("."):void 0,p=[...n,d.name].join(".");if(c)return g?o(`${g}.Type = '${a.parent}'`,l,p,a.parent):o(`${p} != null`,!1,p,a.parent);if(l){let f=t(a.parent);if(f===void 0&&!kD.has(a.parent.toLowerCase()))return o(`${p} != null`,!0,p,a.parent);if(!g)return o(`${p} != null`,!1,p,a.parent);let h=f!==void 0?` AND ${g}.${f}`:"";return o(`${g}.Id != null${h}`,!0,p,a.parent)}if(!u||i+1>=hi)return o(`${p} != null`,!1,p,a.parent);n.push(u)}}function wI(s,e,t){let r=[];for(let[n,o]of s.entries()){let i=e.has(o.object)?bc(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>=hi)return;r.push(i.relationshipName)}}function mi(s,e,t=ao,r){let n=s.map(a=>Rc(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 bI(s,e,t,r,n,o=ao,i){let a={object:s,field:e,parent:t};if(r.emptied.has(t))return Rc([a],n,o,i);let d=(r.routes.get(t)??[]).map(c=>({object:s,steps:[a,...c.steps],emptied:c.emptied}));return mi(d,n,o,i)}var SI=4,RI=100,TD=/^[A-Za-z0-9]+$/;function vI(s,e){let t=ao(s);if(t!==void 0)return t;if(e&&s.toLowerCase()===yr.toLowerCase())return`${qs} = false`}var po="stopped before the org was asked";function kI(s,e,t="COUNT()"){let r=dg(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 ${ze(s)}${o}`,all:r}}var lo=class{statements=new Map;answers=new Map;ask(e,t){let r=kI(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 js([...this.statements].map(([n,{soql:o,all:i,atMost:a}])=>async()=>{if(t()){r=!0,this.answers.set(n,{unread:po});return}try{let d=await(i?e.countAll(o):e.count(o));this.answers.set(n,{records:d,...a?{atMost:!0}:{}})}catch(d){this.answers.set(n,{unread:I(d)})}}),SI),r}answer(e){return this.answers.get(e)??{unread:po}}},kc=class{statements=new Map;answers=new Map;ask(e,t){let r=kI(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 js([...this.statements].map(([n,o])=>async()=>{if(t()){r=!0,this.answers.set(n,{counted:{unread:po}});return}try{let i=await e.readIds(n,o),a=i.ids.filter(d=>TD.test(d));this.answers.set(n,{counted:{records:i.totalSize},...a.length===i.totalSize?{ids:a}:{}})}catch(i){this.answers.set(n,{counted:{unread:I(i)}})}}),SI),r}answer(e){return this.answers.get(e)??{counted:{unread:po}}}};function gg(s,e){return s.records===void 0?s:e.records===void 0?{unread:e.unread??po}:{records:Math.max(0,s.records-e.records),...e.atMost?{atLeast:!0}:{}}}function lg(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 Ln(s){return s.records===0&&s.atLeast!==!0}function co(s){return s===void 0||s.records===void 0||s.records>0}function Sc(s){return{unread:`${s}: the lookup its records go by is hidden from the user`}}function fg(s){return s.records===void 0?s:{...s,atLeast:!0}}function yi(s){return s.records===void 0?s:{...s,atMost:!0}}function pg(s,e){let t=e.key?s.answer(e.key):Sc(e.objectApiName),r=e.going?gg(t,s.answer(e.going)):t,n=(r.records??0)>0;return e.more&&n&&(r={...r,atLeast:!0}),e.under&&n&&(r=fg(r)),e.over&&n&&(r=yi(r)),r}function hg(s,e){return s.every(t=>e.get(t.emptied)!=="unnamed"&&t.steps.every(r=>e.get(r.parent)!=="unnamed"))}function ED(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 uo(s){let e=s.filter(n=>n.records!==void 0);if(e.length===0)return s.length===0?{records:0}:{unread:s[0].unread??po};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 vc="Pricebook2";function PD(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 OI(s,e,t=()=>!1,r={undo:!0}){let{affected:n,order:o,relations:i,describes:a}=s,d=o.passes.map(D=>D.objectApiName),c=a.get(yr)?.fields.some(D=>D.name===qs)===!0,u=D=>{let W=vI(D,c);if(!(D.toLowerCase()===yr.toLowerCase()&&n.emptied.has(Ao)))return W},l=D=>{let W=u(D);return W===void 0?[]:[W]},g=new Map,p=D=>g.get(D),f=D=>p(D),h=D=>Rc(D,a,u,f),m=D=>mi(D,a,u,f),y=(D,W,X)=>bI(D,W,X,n,a,u,f),R=new lo,S=new Map;for(let D of d)S.set(D,R.ask(D,l(D)));let b=await R.run(e,t),O=new Map(d.map(D=>[D,R.answer(S.get(D)??"")])),P=D=>[...rs(D,n)].some(W=>co(O.get(W))),v=D=>D.filter(W=>co(O.get(W.emptied))),w=D=>!n.emptied.has(D)&&n.routesCut.has(D),C=new lo,k=[];for(let{parent:D,child:W,field:X,kind:F}of i){if(F!=="restricted"||W===D||n.emptied.has(W)||!P(D))continue;let ee=y(W,X,D),_=n.routes.has(W)?m(v(n.routes.get(W)??[])):void 0;k.push({objectApiName:W,field:X,parent:D,...ee?{key:C.ask(W,[ee])}:{},...ee&&_?{going:C.ask(W,[_,ee])}:{},..._&&w(W)?{over:!0}:{},...n.emptied.has(D)&&!n.routes.has(W)?{naming:""}:{}})}for(let{child:D,field:W,parent:X,rows:F}of $l){if(F===void 0||!P(X)||n.emptied.has(D)||!n.routes.has(D))continue;let _=a.get(D)?.fields.some(Se=>Se.name===F.field)===!0?y(D,W,X):void 0;if(!_)continue;let de=`${F.field} = ${String(F.value)}`;k.push({objectApiName:D,field:W,parent:X,key:C.ask(D,[de,_]),along:!0,...n.emptied.has(X)?{naming:de}:{}})}b=await C.run(e,t)||b;let E=new kc,x=new Map,V=new Map;k.forEach((D,W)=>{if(D.naming===void 0||D.key===void 0||(pg(C,D).records??0)===0)return;let X=`Id IN (SELECT ${ze(D.field)} FROM ${ze(D.objectApiName)}${D.naming!==""?` WHERE ${D.naming}`:""})`;x.set(W,E.ask(D.parent,[...l(D.parent),X])),V.set(D.parent,[...V.get(D.parent)??[],X])}),b=await E.run(e,t)||b;for(let D of V.keys()){let W=[...x].filter(([F])=>k[F].parent===D).map(([,F])=>E.answer(F));if(W.every(F=>F.counted.records===0))continue;let X=new Set(W.flatMap(F=>F.ids??[]));g.set(D,W.every(F=>F.ids!==void 0)&&X.size<=RI?[...X]:"unnamed")}let H=D=>{let W={archived:new Map,kept:new Map,goneBefore:new Map,along:new Map,refusals:[],undoLost:[]};for(let _ of o.passes){let de=_.objectApiName;if(!co(O.get(de)))continue;let Se=l(de);dg(de)&&W.archived.set(de,D.ask(de,[...Se,"IsArchived = true"]));let Ue=hI(de);Ue!==void 0&&W.kept.set(de,D.ask(de,[Ue]));let He=v(_.goneBefore);if(He.length>0){let Ee=m(He);W.goneBefore.set(de,Ee?{key:D.ask(de,[...Se,Ee]),unreadable:!1}:{unreadable:!0})}let ie=r.undo?v(_.sentBeforeTheirParent):[];for(let Ee of ie){let Ne=h(Ee.steps),st=Ee.steps[0],Be=Ne?[...Se,Ne]:void 0;W.undoLost.push({objectApiName:de,field:st.field,parent:st.parent,reason:"unordered",...Be?{key:D.ask(de,Be),conditions:Be}:{}})}}for(let _ of n.along){let de=v(n.routes.get(_)??[]);if(de.length===0)continue;let Se=de.map(He=>{let ie=h(He.steps);return{route:He,...ie?{key:D.ask(_,[ie])}:{}}}),Ue=de.length>1?m(de):void 0;W.along.set(_,{...Ue?{total:D.ask(_,[Ue])}:Se[0].key?{total:Se[0].key}:{},via:Se})}let X=_=>o.passes.findIndex(de=>de.objectApiName===_);for(let _ of r.undo?o.beforeParent:[]){if(_.reason==="customPrices"){if(!P(vc)||!P(_.parent)||X(vc)>X(_.parent))continue;let He=y(_.objectApiName,"Pricebook2Id",vc),ie=y(_.objectApiName,_.field,_.parent),Ee=He&&ie?[He,ie]:void 0;W.undoLost.push({objectApiName:_.objectApiName,field:_.field,parent:_.parent,reason:"restricted",...Ee?{key:D.ask(_.objectApiName,Ee),conditions:Ee}:{},...w(vc)||w(_.parent)?{under:!0}:{}});continue}if(!P(_.objectApiName)||!P(_.parent))continue;let de=y(_.objectApiName,_.field,_.parent),Se=[];if(!n.emptied.has(_.objectApiName)){let He=m(v(n.routes.get(_.objectApiName)??[]));He&&Se.push(He)}let Ue=w(_.objectApiName)||w(_.parent);W.undoLost.push({objectApiName:_.objectApiName,field:_.field,parent:_.parent,reason:"restricted",...de?{key:D.ask(_.objectApiName,[...Se,de]),conditions:[...Se,de]}:{},...Ue?{under:!0}:{}})}for(let{child:_,field:de,parent:Se,rows:Ue}of $l){if(Ue===void 0||!P(Se)||!n.emptied.has(_))continue;let ie=a.get(_)?.fields.some(Ne=>Ne.name===Ue.field)===!0?y(_,de,Se):void 0;if(!ie||!r.undo||!co(O.get(_)))continue;let Ee=`${Ue.field} = ${String(Ue.value)}`;W.undoLost.push({objectApiName:_,field:de,parent:Se,reason:"restricted",key:D.ask(_,[Ee,ie]),conditions:[Ee,ie],more:!0})}let F=(_,de,Se,Ue=!1)=>{W.refusals.push({code:_,objectApiName:de,key:D.ask(de,Se),...Ue?{under:!0}:{}})};for(let _ of o.toDraft){if(!P(_))continue;let de="StatusCode != 'Draft'";if(n.emptied.has(_)){F("activatedOrder",_,[de]);continue}let Se=v(n.routes.get(_)??[]),Ue=m(Se);F(hg(Se,g)?"activatedOrder":"activatedOrderLeft",_,Ue?[Ue,de]:[{soql:de,exact:!1}],Ue!==void 0&&w(_))}for(let[_,de]of W.kept)W.refusals.push({code:"standardPriceBook",objectApiName:_,key:de});n.emptied.has(ea)&&co(O.get(ea))&&(n.emptied.has(yr)||F("directContactRelation",ea,[{soql:"IsDirect = true",exact:!n.routes.has(yr)}]));let ee=a.get(yr);return n.emptied.has(yr)&&!n.emptied.has(Ao)&&co(O.get(yr))&&ee?.fields.some(_=>_.name===qs)===!0&&F("personAccountContact",yr,[`${qs} = true`]),W},Y=new kc,B=new Map;if(g.size>0){let D=new Set;p=W=>(n.emptied.has(W)||D.add(W),g.get(W)),H(new lo),p=W=>g.get(W);for(let W of[...D].sort()){let X=v(n.routes.get(W)??[]),F=X.filter(de=>g.has(de.emptied));if(F.length===0)continue;let ee=g.get(F[0].emptied),_=X.length===1&&Array.isArray(ee)?wI(X[0].steps,a,ee):void 0;_===void 0?g.set(W,"unnamed"):B.set(W,Y.ask(W,[_]))}b=await Y.run(e,t)||b;for(let[W,X]of B){let F=Y.answer(X);g.set(W,F.ids!==void 0&&F.ids.length<=RI?F.ids:"unnamed")}}let N=new lo,L=H(N);b=await N.run(e,t)||b;let Q=D=>pg(N,D),K=new lo,ae=new Map;for(let[D,W]of V)W.length===2&&g.get(D)==="unnamed"&&ae.set(D,K.ask(D,[...l(D),...W]));let U=new Map,re=new Map;for(let D of L.undoLost)re.set(D.objectApiName,[...re.get(D.objectApiName)??[],D]);for(let[D,W]of re){let X=W.filter(ee=>!Ln(Q(ee)));if(X.length<2)continue;let F=X.map(ee=>ee.conditions);F.some(ee=>ee===void 0)||U.set(D,K.ask(D,[ED(F)]))}b=await K.run(e,t)||b;let ne=k.map((D,W)=>{let X=x.get(W);return{objectApiName:D.objectApiName,field:D.field,parent:D.parent,records:pg(C,D),...X!==void 0?{keeps:E.answer(X).counted}:{}}}).filter(D=>!Ln(D.records)),ue=D=>{let W=ne.flatMap(_=>_.parent===D&&_.keeps!==void 0?[_.keeps]:[]);if(W.length===0)return;let X=g.get(D);if(Array.isArray(X))return{records:X.length};let F=uo(W),ee=ae.get(D);return ee!==void 0?lg(F,K.answer(ee)):W.length>1&&(F.records??0)>0?yi(F):F},ce=ne.filter(D=>!Array.isArray(g.get(D.parent))&&k.some(W=>W.along===!0&&W.objectApiName===D.objectApiName&&W.field===D.field&&W.parent===D.parent)),be=ne.filter(D=>k.some(W=>W.along===!0&&W.objectApiName===D.objectApiName&&W.field===D.field&&W.parent===D.parent)),Xe=o.passes.map(D=>{let W=D.objectApiName,X=vI(W,c),F=O.get(W)??{unread:po};if(!co(F))return{objectApiName:W,...X!==void 0?{rows:X}:{},records:F,sent:F};let ee=L.goneBefore.get(W),_=ee===void 0?F:ee.unreadable||ee.key===void 0?Sc(W):n.routesCut.has(W)?yi(gg(F,N.answer(ee.key))):gg(F,N.answer(ee.key)),de=L.archived.get(W),Se=L.kept.get(W),Ue=ue(W);return{objectApiName:W,...X!==void 0?{rows:X}:{},records:F,sent:_,...de?{archived:N.answer(de)}:{},...Se?{kept:N.answer(Se)}:{},...Ue&&!Ln(Ue)?{blocked:Ue}:{}}}),De=r.undo?Xe.filter(D=>a.get(D.objectApiName)?.undeletable===!1&&!Ln(D.sent)).map(D=>({objectApiName:D.objectApiName,reason:"notRestorable",records:D.sent})):[],_e=[...L.along].map(([D,{total:W,via:X}])=>{let F=W?N.answer(W):Sc(D),ee=n.routesCut.get(D),_=ce.filter(ie=>ie.objectApiName===D),de=be.filter(ie=>ie.objectApiName===D),Se=_.length>0?uo(_.map(ie=>ie.records)):void 0,Ue=de.length>0?uo(de.map(ie=>ie.records)):void 0,He=Se?lg(F,Se):F;return{objectApiName:D,records:ee?fg(He):He,via:X.map(({route:ie,key:Ee})=>{let Ne=Ee?N.answer(Ee):Sc(D),st=ie.steps[0],Be=_.filter(Ve=>Ve.field===st.field&&Ve.parent===st.parent);return{field:st.field,parent:st.parent,emptied:ie.emptied,records:Be.length>0?lg(Ne,uo(Be.map(Ve=>Ve.records))):Ne}}).filter(ie=>!Ln(ie.records)),...Ue&&!Ln(Ue)?{blocking:Ue}:{},...ee?{routesNotRead:[...ee]}:{}}}).filter(D=>!Ln(D.records)),z=(D,W)=>D.map(X=>({...W(X),records:Q(X)})).filter(X=>!Ln(X.records)),se=PD([...z(L.undoLost,D=>({objectApiName:D.objectApiName,...D.field!==void 0?{field:D.field}:{},...D.parent!==void 0?{parent:D.parent}:{},reason:D.reason})),...De]),te=new Map;for(let D of se)te.set(D.objectApiName,[...te.get(D.objectApiName)??[],D]);let he=uo([...te].map(([D,W])=>{let X=U.get(D),F=W.filter(_=>_.reason==="notRestorable");if(X===void 0){let _=uo(W.map(de=>de.records));return W.length>1&&(_.records??0)>0?yi(_):_}let ee=K.answer(X);return W.some(_=>_.reason!=="notRestorable"&&_.records.atLeast)&&(ee.records??0)>0&&(ee=fg(ee)),F.length>0?yi(uo([ee,...F.map(_=>_.records)])):ee}));return{objects:Xe,along:_e,refusals:z(L.refusals,D=>({code:D.code,objectApiName:D.objectApiName})),blockers:ne,undoLost:se,undoLostRecords:he,kept:g,statements:R.size+C.size+E.size+Y.size+N.size+K.size,...b?{stopped:!0}:{}}}var TI={lookup:0,cascade:1,restricted:2,customPrices:2},II="Pricebook2",mg="Product2",AI="PricebookEntry";function CD(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 rs(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=rs(i,s),u=s.emptied.has(i)?[i]:[...c],l=!1;for(let g of rs(o,s))if(!c.has(g))for(let p of u)p!==g&&(t.push({first:p,then:g,reason:"restricted"}),l=!0);l&&r.push({objectApiName:i,field:a,parent:o,reason:"restricted"})}return s.emptied.has(II)&&s.emptied.has(mg)&&(t.push({first:II,then:mg,reason:"customPrices"}),n(AI)&&r.push({objectApiName:AI,field:"Product2Id",parent:mg,reason:"customPrices"})),{constraints:t,beforeParent:r}}function $D(s){return Object.hasOwn(TI,s)}function EI(s,e){let{constraints:t,beforeParent:r}=CD(s,e),n=[...s.emptied].sort(),o=new Map(n.map(l=>[l,[]]));for(let{first:l,then:g,reason:p}of t)p==="cascade"?o.get(l)?.push({childSObject:g,field:p,cascadeDelete:!0}):o.get(g)?.push({childSObject:l,field:p});let i=new Map(n.map(l=>[l,{name:l,fields:[],childRelationships:o.get(l)??[]}])),a=Nh(n,i,({field:l})=>{let g=$D(l)?l:"lookup";return{first:g==="cascade"?"parent":"child",firmness:TI[g]}}),d=new Map(a.map((l,g)=>[l,g])),c=(l,g)=>(d.get(l)??0)<(d.get(g)??0);return{passes:a.map(l=>{let g=s.routes.get(l)??[];return{objectApiName:l,goneBefore:g.filter(p=>c(p.emptied,l)),sentBeforeTheirParent:g.filter(p=>!c(p.emptied,l))}}),beforeParent:r,unordered:xD(t.filter(({first:l,then:g})=>!c(l,g))),toDraft:sr([...n,...s.along])}}function xD(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 DD(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 ND=(s,e,t)=>{let r=Nb(s,e,"empty",t.customSettings?{customSettings:xh}:{});return{candidates:r.candidates,leftOut:r.leftOut.map(({objectApiName:n,reason:o,detail:i})=>({objectApiName:n,reason:DD(o),...i===void 0?{}:{detail:i}}))}},jD=new Set([Ch,$h].map(s=>s.toLowerCase()));function PI(s,e){return s.objectApiName<e.objectApiName?-1:s.objectApiName>e.objectApiName?1:0}function MD(s,e){if(s.customSetting===!0&&e.customSettings!==!0)return"customSetting";if(jD.has(s.name.toLowerCase())&&e.files!==!0)return"files";if(Dh(s.name)!==void 0&&e.managedPackages!==!0)return"managedPackage";if(s.undeletable===!1&&e.unrestorable!==!0)return"notRestorable"}function Oc(s,e,t,r=ND){let n=r(s,e,{customSettings:!0}),o=new Map(s.map(l=>[l.name.toLowerCase(),l])),i=new Set(n.candidates.map(l=>l.toLowerCase())),a=new Map(n.leftOut.map(l=>[l.objectApiName.toLowerCase(),l])),d=[],c=[],u=l=>{let g=a.get(l.name.toLowerCase());return g?{...g,objectApiName:l.name}:{objectApiName:l.name,reason:"notDeletable"}};if(t.mode==="objects"){let l=new Set;for(let g of t.objects??[]){let p=g.toLowerCase();if(l.has(p))continue;l.add(p);let f=o.get(p);f?i.has(p)?d.push(f.name):c.push(u(f)):c.push({objectApiName:g,reason:"notFound"})}}else{let l=new Set((t.excluded??[]).map(g=>g.toLowerCase()));for(let g of t.excluded??[])o.has(g.toLowerCase())||c.push({objectApiName:g,reason:"notFound"});for(let g of o.values()){let p=g.name.toLowerCase();if(l.has(p)){c.push({objectApiName:g.name,reason:"excludedByUser"});continue}if(!i.has(p)){c.push(u(g));continue}let f=MD(g,t);f===void 0?d.push(g.name):c.push({objectApiName:g.name,reason:f})}}return d.sort(),c.sort(PI),{mode:t.mode,objects:d,leftOut:c,worked:[...n.candidates].sort()}}function CI(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(PI)}}async function yg(s,e,t,r){await js(e.map(n=>async()=>{try{t.set(n,gI.parse(await s.describe(n)))}catch(o){r.set(n,I(o))}}),6)}function FD(s,e){if(e!=="hard")return s;let t=s.objects.filter(r=>!ig(r));return t.length===0?s:{...s,objects:s.objects.filter(ig),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 go(s){return s.records}async function $I(s,e){let t=Oc(s.global,s.tooling,s.request,s.rule),r=new Map,n=new Map;await yg(e,t.objects,r,n);let o=FD(CI(t,r,n),s.deleteMode),i=new Map([...t.worked,...s.global.map(w=>w.name)].map(w=>[w.toLowerCase(),w])),a=w=>i.get(w.toLowerCase())??w,d=ug(o.objects,t.worked,r);for(let w=0;w<hi;w++){let C=d.undescribed.filter(k=>!r.has(k)&&!n.has(k));if(C.length===0)break;await yg(e,C,r,n),d=ug(o.objects,t.worked,r)}let c=w=>d.emptied.has(w)||d.routes.has(w),u=[...new Set(cg(r,a).filter(({kind:w,parent:C,child:k})=>w==="restricted"&&c(C)&&!c(k)).map(({child:w})=>w))].filter(w=>!r.has(w)&&!n.has(w));await yg(e,u,r,n);let l=cg(r,a),g=EI(d,l),p=await OI({affected:d,order:g,relations:l,describes:r},e,s.stopped,{undo:s.deleteMode==="recycle"}),f=[...p.objects.filter(w=>go(w.records)===void 0),...p.along.filter(w=>go(w.records)===void 0)].map(w=>w.objectApiName),h=[...p.objects.map(w=>Math.max(0,(go(w.records)??0)-(w.blocked?.records??0))),...p.along.map(w=>go(w.records)??0)].filter(w=>w>0),m=h.reduce((w,C)=>w+C,0),y=p.along.some(w=>w.records.atLeast===!0)||p.objects.some(w=>w.blocked?.atMost===!0),R=p.refusals.filter(w=>w.code==="activatedOrder").reduce((w,C)=>w+(go(C.records)??0),0),S=g.toDraft.filter(w=>!d.emptied.has(w)).map(w=>{let C=d.routes.get(w)??[];if(!hg(C,p.kept))return{objectApiName:w};let k=mi(C,r,void 0,E=>p.kept.get(E));return{objectApiName:w,...k?{condition:k.soql}:{}}}),b=w=>w.records===void 0||w.records>0,O=p.objects.filter(w=>b(w.records)).length+p.along.filter(w=>b(w.records)).length,P=sI+r.size+n.size+p.statements+2*O,v=cI({mode:s.deleteMode,passes:p.objects.map(w=>({objectApiName:w.objectApiName,records:go(sr([w.objectApiName]).length>0?w.records:w.sent)??0})),toDraft:R,deleted:m,reads:P,draftReads:S.filter(w=>w.condition!==void 0).length,refused:p.blockers.map(w=>go(w.records)??0),...s.apiBudget?{apiBudget:s.apiBudget}:{},...s.bulkBatches?{bulkBatches:s.bulkBatches}:{},...s.dataStorageMB===void 0?{}:{dataStorageMB:s.dataStorageMB}});return{mode:t.mode,deleteMode:s.deleteMode,passes:p.objects,along:p.along,leftOut:o.leftOut,refusals:p.refusals,blockers:p.blockers,beforeParent:g.beforeParent,unordered:g.unordered,undoLost:p.undoLost,undoLostRecords:p.undoLostRecords,undo:s.deleteMode==="recycle",affected:[...d.emptied,...d.along].sort(),toDraftAlong:S,cost:v,total:{records:m,objects:h.length,uncounted:f,...y?{atLeast:!0}:{}},statements:p.statements,...p.stopped?{stopped:!0}:{}}}var _D=5,UD=Ms,Ic=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!==xw};this.refused.has(r)||this.refused.size<UD?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=[...Dw(this.objectApiName,e),...Nw(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,_D)}}};async function xI(s,e,t){let{mode:r}=t,n=()=>t.signal?.aborted===!0,o=t.splitting??ma(),i=e.objects.reduce((h,m)=>h+m.count,0),a=[],d=0,c=[],u=h=>{let m=a.find(y=>y.objectApiName===h);if(!m){let y=e.objects.find(R=>R.objectApiName===h);m=new Ic(h,y?.count??0),a.push(m)}return m},l=async(h,m)=>{await va(s,c,{note:(R,S,b,O)=>u(R).note(b?Ra(R,S,O,c):S)});let y=a.map(R=>R.result(o,h));if(h)for(let{objectApiName:R,count:S}of e.objects)y.some(b=>b.objectApiName===R)||y.push({...new Ic(R,S).result(o,!1),...S>0?{notReached:S}:{}});return{hard:r==="hard",objects:y,cancelled:h,...m!==void 0?{hardRefused:m}:{}}},g=(h,m)=>jw(s,h.objectApiName,m,{mode:r,stopped:n,splitting:o,...t.signal?{signal:t.signal}:{},...t.wait?{wait:t.wait}:{},settle:(y,R)=>{let S=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-S,t.onProgress?.(d,i,h.objectApiName)}});if(r==="hard"&&s.bulkHardDestroy===void 0)return l(!0,$w);if(t.toDraft!==!1){let h=await ba(s,e.objects,e,()=>!0,n,async()=>new Set);if(c=h.drafted,h.cancelled)return l(!0)}for(let{objectApiName:h,count:m}of e.objects){if(n())return l(!0);let y=u(h),R=Ls(s,h,m,r),S=[],b=async()=>{let O=S;return S=[],g(y,O)};for await(let O of e.pages(h)){if(n())return l(!0);if(S.push(...O),R&&S.length<Ms)continue;let P=await b();if(P.stopped)return l(!0,P.hardRefused)}if(S.length>0){if(n())return l(!0);let O=await b();if(O.stopped)return l(!0,O.hardRefused)}}let p;if(await Mw(a,{stopped:n,idsOf:(h,m)=>m===0?h.toSendAgain():h.heldByDependents(),send:async(h,m)=>{let y=await g(h,[...m]);return p=y.hardRefused,y.stopped},deleted:h=>h.deleted}))return l(!0,p);for(let h of a){if(n())return l(!0);let{gone:m,unchecked:y,failure:R}=await Lw([...h.refused.keys()],S=>Sn(s,h.objectApiName,[],S),()=>!0);for(let S of m)h.refused.delete(S),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 l(!1)}function HD(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 BD(s){return/CreatedDate/.test(I(s))}function wg(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 qD(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 WD(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 DI(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 Na,d=new Map;if(s.resumed){for await(let N of e.lines())if(N.kind==="settled"){for(let L of[...N.deleted,...N.gone])a.add(L);d.set(N.objectApiName,(d.get(N.objectApiName)??0)+N.deleted.length+N.gone.length)}}let c=new AbortController,u=s.signal?AbortSignal.any([s.signal,c.signal]):c.signal,l=()=>u.aborted,g,p=!1,f=HD(r.readAt),h=new Map(r.passes.map(N=>[N.objectApiName,N])),m=N=>h.get(N)?.rows??ao(N),y=new Map,R=new Map,S=()=>r.passes.reduce((N,L)=>N+Math.max(0,(R.get(L.objectApiName)??L.sent??L.records??0)-(d.get(L.objectApiName)??0)),0),b=async(N,L)=>{let Q=async K=>{let ae=await Db(t.ids,N,[{objectApiName:L.objectApiName,...K!==void 0?{filter:K}:{}}],{signal:u});return ae.stopped?void 0:ae.spool};try{let K=await Q(wg([L.filter,L.own,f]));return K?{spool:K,sinceRead:!0}:void 0}catch(K){if(!BD(K))throw K;i.push(`${L.objectApiName} has no CreatedDate: its records were read whole, those made after the simulation among them.`);let ae=await Q(wg([L.filter,L.own]));return ae?{spool:ae,sinceRead:!1}:void 0}},O=N=>{let L=y.get(N);if(L)return L;let Q=(async()=>{let K=r.passes.findIndex(be=>be.objectApiName===N),ae=e.idsDirOf(K,N),U=o.spooled.get(N);if(s.resumed&&U)return R.set(N,U.count),{spool:await ja.open(ae,La),count:U.count,sinceRead:U.sinceRead};if(l())return;let re=m(N),ne=await b(ae,{objectApiName:N,...re!==void 0?{own:re}:{}});if(!ne)return;let ue=ne.spool.count,ce=h.get(N)?.records;if(ce!==void 0&&ue>ce){g={code:"ORG_CHANGED",message:`${N} now holds ${ue.toLocaleString("en-US")} records to delete, where the simulation counted ${ce.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:N,place:K,count:ue,sinceRead:ne.sinceRead}),R.set(N,ue),{spool:ne.spool,count:ue,sinceRead:ne.sinceRead}})();return y.set(N,Q),Q},P={objects:r.passes.map(N=>({objectApiName:N.objectApiName,count:N.sent??N.records??0})),pages:N=>({async*[Symbol.asyncIterator](){let L=await O(N);if(L)for await(let Q of L.spool.pages(N)){let K=a.size>0?Q.filter(ae=>!a.has(ae)):Q;K.length>0&&(yield K)}}})},v=Promise.resolve(),w,C=(N,L,Q)=>{let K=[],ae=[];L.forEach((U,re)=>{let ne=Q[re]?.kind;ne==="deleted"?K.push(U):ne==="gone"&&ae.push(U)}),K.length>0&&(p=!0),K.length+ae.length!==0&&(v=v.then(async()=>{if(w===void 0)try{await e.settled(N,K,ae)}catch(U){w=I(U),c.abort()}}))},k=[];for(let[N,L]of r.toDraftAlong.entries()){if(L.condition===void 0||l())continue;let Q=e.idsDirOf(r.passes.length+N,L.objectApiName),K=await b(Q,{objectApiName:L.objectApiName,filter:L.condition});if(!K)break;let{drafted:ae}=await ba(t.deletion,[{objectApiName:L.objectApiName}],K.spool,()=>!0,l,async()=>new Set);k.push(...ae)}let E=await xI(t.deletion,P,{mode:r.deleteMode,signal:u,...s.splitting?{splitting:s.splitting}:{},...s.wait?{wait:s.wait}:{},onSettled:C,onProgress:(N,L,Q)=>{let K=Math.max(N,S());s.onProgress?.({percentage:K>0?Math.min(99,Math.round(N/K*100)):99,step:`${Q}: ${N.toLocaleString("en-US")} of about ${K.toLocaleString("en-US")} settled`})}}).finally(async()=>{await v,await va(t.deletion,k,{note:(N,L,Q,K)=>i.push(Ra(N,L,K,k))})});w!==void 0&&i.push(`The journal of this emptying could not be written (${w}): it stopped there, so that its Undo misses nothing it deleted.`);let x=new Map;for(let[N,L]of y)x.set(N,await L.catch(()=>{}));let V=E.objects.map(N=>qD(N,x.get(N.objectApiName),h.get(N.objectApiName)?.records,E.cancelled));if(!E.cancelled)for(let N of V){if(!x.get(N.objectApiName)?.sinceRead)continue;let Q=m(N.objectApiName),K=f.replace("CreatedDate <","CreatedDate >=");try{let ae=await t.deletion.query(`SELECT COUNT() FROM ${ze(N.objectApiName)} WHERE ${wg([Q,K])}`);ae.totalSize>0&&(N.madeSince=ae.totalSize)}catch(ae){i.push(`Whether ${N.objectApiName} records were made after the simulation could not be read: `+I(ae))}}let H=E.cancelled&&g===void 0&&w===void 0,Y=g!==void 0||w!==void 0?p?"partial":"failure":WD(V,H,E.hardRefused,s.resumed&&o.deletedAny),B=V.reduce((N,L)=>N+L.refused,0);return s.resumed&&Y==="partial"&&!p&&B>0&&i.push(`The org refused again the ${B.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:E.hard,passes:V,...E.hardRefused!==void 0?{hardRefused:E.hardRefused}:{},...g!==void 0?{changed:g}:{},deletedAny:p,notes:i}}var zD=/Entity is not in the recycle bin/,GD=/INSUFFICIENT_ACCESS/,JD=5,NI=5e4;function Ac(s){return s.slice(0,15)}function bg(s){let e=new Set;for(let t of s){let r=t?.Id;typeof r=="string"&&e.add(Ac(r))}return e}function VD(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 KD(s){return{objectApiName:s,planned:0,undeleted:0,alreadyBack:0,notInBin:0,othersDeletion:0,refused:0,reasons:[]}}function wi(s,e){s.reasons.length<JD&&!s.reasons.includes(e)&&s.reasons.push(e)}async function*XD(s,e,t){let r=t?new Na: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 ja.open(s.idsDirOf(t.place,e),La);for await(let o of n.pages(e)){let i=o.filter(a=>!r.has(a));i.length>0&&(yield i)}}async function jI(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 MI(s,e){let t=s.spooledIn.get(e);return t!==void 0&&s.unendedAttempt!==void 0&&t.attempt===s.unendedAttempt?t:void 0}function YD(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 LI(s){let e=await jI(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/Wt)*ag);let o=MI(e,r);o&&(n+=o.count,t+=Math.ceil(o.count/Wt)*ag);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)/Wt)}return t}async function FI(s){let{journal:e,org:t}=s,r=e.head,n=[],o=()=>s.signal?.aborted===!0,i=await jI(e),a=[],d=new Map,c=!1,u=[...r.passes].reverse();for(let[h,{objectApiName:m}]of u.entries()){let y=KD(m);a.push(y);let R=ze(m),S=MI(i,m);for await(let b of XD(e,m,S)){y.planned+=b.length;for(let O=0;O<b.length;O+=Wt){let P=b.slice(O,O+Wt);if(c||o()){c=!0,y.notReached=(y.notReached??0)+P.length;continue}let[v]=Ns(P,Wt),w,C;try{w=bg((await t.queryDeleted(`SELECT Id FROM ${R} WHERE Id IN (${v}) AND IsDeleted = true`)).records),C=bg((await t.query(`SELECT Id FROM ${R} WHERE Id IN (${v})`)).records)}catch(x){y.refused+=P.length,wi(y,`The recycle bin could not be read: ${I(x)}`);continue}let k=P.filter(x=>w.has(Ac(x)));for(let x of P)w.has(Ac(x))||(C.has(Ac(x))?y.alreadyBack++:(y.notInBin++,wi(y,"No longer in the recycle bin, nor in the org: emptied from the bin, or pushed out of it.")));if(k.length===0)continue;let E;try{let x=await s.undelete(k),V=Array.isArray(x)?x:[x];E=k.map((H,Y)=>V[Y]??{success:!1})}catch(x){let V=I(x);E=k.map(()=>({success:!1,errors:[V]}))}E.forEach((x,V)=>{if(x.success===!0){y.undeleted++;return}let H=VD(x);if(zD.test(H)){y.notInBin++;let Y=d.get(m)??[];Y.length<NI&&Y.push(k[V]),d.set(m,Y),wi(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 GD.test(H)?(y.othersDeletion++,wi(y,`Deleted by another user than the one bringing it back: only Modify All Data brings back another's deletions (${H})`)):(y.refused++,wi(y,H))})}s.onProgress?.({percentage:Math.round((h+1)/Math.max(1,u.length)*100),step:`${m}: ${y.undeleted.toLocaleString("en-US")} brought back`})}}if(!c)for(let h of a){let m=d.get(h.objectApiName)??[];if(m.length===0)continue;h.notInBin>m.length&&n.push(`${h.objectApiName}: past ${NI.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=ze(h.objectApiName);try{let R=0;for(let b of Ns(m,Wt)){let O=await t.query(`SELECT Id FROM ${y} WHERE Id IN (${b})`);R+=bg(O.records).size}let S=Math.min(R,h.notInBin);h.notInBin-=S,h.alreadyBack+=S}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 (${I(R)}): they are counted as not back.`)}}let l=i.wentThrough?YD(e):[],g=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)+l.length;return{status:c?"cancelled":p===0?"success":g>0?"partial":"failure",objects:a.filter(h=>h.planned>0),notes:n,...l.length>0?{previewedLost:l}:{}}}var fr="Nothing was deleted.";function Ec(s){return{query:e=>s.query(e),queryMore:e=>s.queryMore(e)}}var Rg=J({Max:Te(),Remaining:Te()}).loose(),QD=J({DailyApiRequests:Rg.optional(),DailyBulkApiBatches:Rg.optional(),DataStorageMB:Rg.optional()}).loose();async function ZD(s){try{let e=QD.parse(await s.limits()),t=o=>o?{max:o.Max,remaining:o.Remaining}:void 0,r=t(e.DailyApiRequests),n=t(e.DailyBulkApiBatches);return{apiBudget:r??{unread:"the limits the org answered list no DailyApiRequests"},...n?{bulkBatches:n}:{},...e.DataStorageMB?{dataStorageMB:e.DataStorageMB.Max}:{}}}catch(e){return{apiBudget:{unread:I(e)}}}}async function UI(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 kg(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 eN(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 tN(s,e){let t=[];for(let r of e)try{let n=Fa.safeParse(await s.describe(r));n.success&&t.push(n.data)}catch{}return t}function HI(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. ${fr}`}}function ns(s,e={}){let[t,...r]=s;return{ran:!1,refusal:t,...r.length>0?{alsoRefused:r}:{},...e}}async function vg(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 Pr)return;throw o}let n=await r.state();return n.open?{runId:t.runId,startedAt:n.head.startedAt,journal:r}:void 0}function BI(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. ${fr}`}}function rN(s){return s.reason==="notRestorable"?`${s.objectApiName}, which Salesforce does not bring back`:`${s.objectApiName} before ${s.parent??"their parent"}`}function qI(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 nN(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=qI(s),r=`${t.atLeast?"at least ":""}${t.records.toLocaleString("en-US")}`,n=[...new Set(e.map(rN))],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. "+fr}}function oN(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. ${fr}`}),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. ${fr}`}),t}function Tc(s){return s.records}function sN(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=Tc(o.records);if(!i){(a===void 0||a>0)&&t.push(`${o.objectApiName} is now emptied too`);continue}a===void 0&&Tc(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=Tc(o.records),d=i?Tc(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=>qI(c).records,i=c=>new Set(c.undoLost.map(u=>`${u.objectApiName}.${u.field??""}.${u.reason}`)),a=i(s);([...i(e)].filter(c=>!a.has(c)).length>0||o(e)>o(s))&&t.push("more records would go beyond what Undo brings back")}return t}function _I(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. ${fr}`}}function Sg(s,e,t){let r=t.automation?Jr(t.automation,t.mutePlan,Gr(t.steps)):{firing:[]};return{module:"empty",written:kg(e),running:{firing:r.firing},request:{},orgId:s.orgId,operationId:s.operationId}}async function WI(s,e){let{org:t,orgName:r}=s,n=s.requestsSent?.()??0,o=Ec(t),i=await oo(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 Zr({act:"empty",target:r,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{},...GI(a.preview)}),c=await vg(s.store,i.org.id),u=e.checkpointFirst===!0&&s.checkpoints?await s.checkpoints.scope(Sg(s,a.preview,d.answer),{operationId:s.operationId}):void 0,l=s.requestsSent!==void 0?s.requestsSent()-n:void 0,g=zI(a,l,2,Qr(d.mute?.plan)),p={previewId:iN(s.now?.()??new Date),readAt:g.readAt,orgName:r,tier:i.tier,preview:g.preview,request:e.request,organizationId:i.org.id,access:g.access,hardDelete:{permitted:g.permissions.hardDelete,...g.permissions.unread!==void 0?{unread:g.permissions.unread}:{}},peopleActive:aN(g.people),...u?{checkpoint:u}:{},...c?{openRun:{runId:c.runId,startedAt:c.startedAt}}:{}},f=await KI(s,i.org.id,g,{deleteMode:e.deleteMode,acceptNoUndo:e.acceptNoUndo===!0,...e.acceptPeopleActive===!0?{peopleAccepted:!0}:{},automation:d.answer,...u?{checkpoint:u}:{},...c?{open:c.runId}:{}});return{previewed:!0,kept:p,automation:d.answer,refusals:f,...l!==void 0?{requestsSent:l}:{}}}function zI(s,e,t,r){let n=e??s.preview.cost.requests.reads;return{...s,preview:{...s.preview,cost:pI(s.preview.cost,n,t,r)}}}function iN(s){return dp(s).replace(/^em-/,"ep-")}function GI(s){let e=eN(s);return{objects:e.objects,writes:{steps:e.steps,written:e.written}}}async function JI(s,e,t){let{org:r}=s,n=Ec(r),o=await r.serverTime(),i=J({sobjects:ve(na)}).loose().parse(await r.describeGlobal()).sobjects,a=await r.toolingObjects(),d=await ZD(r),c=await $I({global:i,tooling:a,request:e,deleteMode:t,apiBudget:d.apiBudget,...d.bulkBatches?{bulkBatches:d.bulkBatches}:{},...d.dataStorageMB!==void 0?{dataStorageMB:d.dataStorageMB}:{},stopped:()=>s.signal?.aborted===!0},r),u=await Js(n),l=kg(c),g=new Set(i.filter(R=>R.customSetting===!0).map(R=>R.name)),p=await tI({permissions:u,objects:l,customSettings:l.filter(R=>g.has(R)),grants:async()=>Bb(n,()=>r.userId()),describe:R=>tN(r,R)}),f=await r.userId(),h=new Date(Date.parse(o)-tp).toISOString(),m=await rp(r,l,[f,...await UI(r)],h),y=s.voice==="page"?await aS(r,m):m;return{readAt:o,preview:c,permissions:u,access:p,people:y}}function aN(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 VI(s){return s.voice==="page"?"page":"flags"}async function KI(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(BI(s.orgName,r.open)),t.preview.stopped&&n.push({code:"PREVIEW_STOPPED",message:`The simulation was stopped before every count was in: simulate again. ${iS}`}),r.deleteMode==="hard"&&!t.permissions.hardDelete&&n.push(ep(t.permissions));let i=np(s.orgName,t.people,{...r.peopleAccepted!==void 0?{accepted:r.peopleAccepted}:{},voice:VI(s)});i&&n.push(i);let a=r.acceptNoUndo?void 0:nN(t.preview);a&&n.push(a),n.push(...oN(t.preview,s.orgName)),r.checkpoint?.refusal&&n.push({...r.checkpoint.refusal});let d=Tn(r.automation);return d&&n.push({code:d.code,message:d.message},...d.alsoRefused),n}function dN(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 cN(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 uN(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 lN(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 pN(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 XI(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=Ec(t),a=await oo(i,{orgName:r,registered:s.registered,mode:e.confirmed?.request.mode??"objects"});if(!a.allowed)return{ran:!1,refusal:a.refusal};let d=a.org.id,c,u=await vg(s.store,d);if(e.resumeRunId!==void 0){if(!u||u.runId!==e.resumeRunId)return{ran:!1,refusal:{code:"RUN_GONE",message:`${e.resumeRunId} is not the last emptying of ${r} stopped part way: there is nothing of it to take up. ${fr}`}};if(c=u.journal,c.head.mode==="org"&&a.tier==="staging"){let k=await oo(i,{orgName:r,registered:s.registered,mode:"org"});if(!k.allowed)return{ran:!1,refusal:k.refusal}}}else if(e.confirmed&&e.confirmed.organizationId.slice(0,15)!==d.slice(0,15))return{ran:!1,refusal:_I(r,["it is another org than the one the simulation read \u2014 a refreshed sandbox is a new org"])};let l=e.confirmed,g=c?c.head.deleteMode:l?.preview.deleteMode??"recycle",p=[],f,h,m,y;if(l){f=await JI(s,l.request,g);let k=[...sN(l.preview,f.preview),...rI(l.access,f.access).map(E=>`the user is no longer proven to see every record of ${E}`)];if(k.length>0&&p.push(_I(r,k)),f.preview.total.records===0&&f.preview.total.uncounted.length===0&&k.length===0)return{ran:!0,result:dN(n())};h=await Zr({act:"empty",target:r,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{},...GI(f.preview)}),e.checkpointFirst===!0&&(m=s.checkpoints?await s.checkpoints.scope(Sg(s,f.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. ${fr}`})),f=zI(f,s.requestsSent!==void 0?s.requestsSent()-o:void 0,1,Qr(h.mute?.plan)),p.push(...await KI(s,d,f,{deleteMode:g,acceptNoUndo:e.acceptNoUndo===!0,...e.acceptPeopleActive===!0?{peopleAccepted:(l.peopleActive.who??[]).map(E=>E.userId)}:{},automation:h.answer,...m?{checkpoint:m}:{},...u?{open:u.runId}:{}}))}else{let k=c.head,E=await Js(i);g==="hard"&&!E.hardDelete&&p.push(ep(E));let x=await s.runWriting?.(d);x!==void 0&&p.push({code:"RUN_WRITING",message:x});let V=k.passes.map(K=>K.objectApiName),H=await t.userId(),Y=await t.serverTime(),B=await rp(t,V,[H,...await UI(t)],new Date(Date.parse(Y)-tp).toISOString()),N=np(r,B,{...e.acceptPeopleActive===!0?{accepted:!0}:{},voice:VI(s)});N&&p.push(N);let L=k.passes.map(K=>({objectApiName:K.objectApiName,records:K.sent??K.records??0})).filter(K=>K.records>0);h=await Zr({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 Q=Tn(h.answer);Q&&p.push({code:Q.code,message:Q.message},...Q.alsoRefused),y=uI(g,await lN(c),s.requestsSent!==void 0?s.requestsSent()-o:0,Qr(h.mute?.plan))}if(p.length>0)return ns(p);let R=l&&f?f.preview:void 0,S=R?R.total.records:c.head.passes.reduce((k,E)=>k+(E.records??0),0),b=R?kg(R):c.head.passes.map(k=>k.objectApiName),O=await s.askGuard({operation:g==="hard"?"hardDelete":"delete",objectNames:b,recordCount:S});if(O.decision==="refused"||O.decision==="declined")return ns([{code:"GUARD",message:O.decision==="refused"?`Production Guard refused the emptying: ${O.reason??"no reason given"}. ${fr}`:`The emptying was declined at Production Guard's confirmation. ${fr}`}],{guard:O.decision});let P=O.decision,v;if(m&&s.checkpoints&&R){let k=await s.checkpoints.take(Sg(s,R,h.answer),{operationId:s.operationId},{planned:m,...s.signal?{signal:s.signal}:{},onProgress:({percentage:E})=>s.onProgress?.(Math.round(E/10),`Taking the checkpoint first (${Math.round(E)}%)`)});if(!k.taken)return ns(["stopped"in k?{code:"CANCELLED",message:`The emptying was stopped while its checkpoint was taken. ${fr}`}:{code:k.refusal.code,message:k.refusal.message}],{guard:P});v=k.checkpoint}let w=async k=>{if(!v||v.state!=="taken"||!s.checkpoints)return v;try{return await s.checkpoints.settle(v,k)}catch{return v}},C=s.lock(d);if("busy"in C)return await w(!1),ns([HI(r,C.busy)],{guard:P});try{let k=await vg(s.store,d);if(!c&&k)return await w(!1),ns([BI(r,k.runId)],{guard:P});let E=await to(h,s.operationId,e.accord.acceptEmails===!0,s.voice);if("refused"in E)return await w(!1),ns([{code:E.refused.code,message:E.refused.message}],{guard:P});let x=E.held,V=n(),H=c??await s.store.begin(d,{runId:dp(V),orgName:r,startedAt:V.toISOString(),readAt:l.readAt,previewId:l.previewId,mode:R.mode,deleteMode:g,request:cN(l.request),passes:R.passes.map(ue=>({objectApiName:ue.objectApiName,...ue.records.records!==void 0?{records:ue.records.records}:{},...ue.sent.records!==void 0?{sent:ue.sent.records}:{},...ue.rows!==void 0?{rows:ue.rows}:{}})),toDraftAlong:R.toDraftAlong,beforeParent:R.beforeParent,...g==="recycle"?{undoLost:uN(R)}:{}}),Y=R&&R.cost.api.verdict!=="unread"?ya(R.cost.api).splitAllowance:void 0,B,N,L=[];try{B=await DI({org:{deletion:t,ids:t},journal:H,resumed:c!==void 0,...s.signal?{signal:s.signal}:{},splitting:ma(Y),now:n,onProgress:({percentage:ue,step:ce})=>s.onProgress?.(ue,ce)})}catch(ue){throw await H.ended("failure",[],n()).catch(()=>{}),ue}finally{let ue=t.lostJobs?.()??[];if(ue.length>0&&t.stillRunning){let ce=await t.stillRunning(ue);ce.length>0&&L.push(`${ce.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.`)}x&&(N=await x.release(),L.push(...Kt(N,r).map(ce=>ce.trim())))}let Q=B.passes,K=n();await H.ended(B.status,Q,K,B.hardRefused);let ae=await w(B.deletedAny),U=[];if(B.status==="success"||B.status==="partial")for(let ue of await s.store.runsOf(d))ue.runId>=H.head.runId||(await s.store.remove(d,ue.runId),U.push(ue.runId));let re=await H.state();return{ran:!0,result:{runId:H.head.runId,status:B.status,hard:B.hard,passes:Q,totals:pN(Q),...B.hardRefused!==void 0?{hardRefused:B.hardRefused}:{},undo:B.hard?{offered:!1,why:"hard"}:re.deletedAny?{offered:!0}:{offered:!1,why:"nothingDeleted"},...c?{resumed:!0}:{},notes:[...B.notes,...B.changed?[B.changed.message]:[],...L],...N?{mutedAutomation:N}:{},...ae?{checkpoint:ae}:{},...U.length>0?{removedRuns:U}:{},...s.requestsSent!==void 0?{requestsSent:s.requestsSent()-o}:{},...y!==void 0?{requestsEstimate:y}:{},startedAt:V.toISOString(),finishedAt:K.toISOString()},guard:P}}finally{C.lock.release()}}async function YI(s,e){let{org:t,orgName:r}=s,n=s.now??(()=>new Date),o=s.requestsSent?.()??0,i=Ec(t),a=await oo(i,{orgName:r,registered:s.registered,mode:"objects"});if(!a.allowed)return{ran:!1,refusal:a.refusal};let d=a.org.id,c=(b,O)=>({ran:!1,refusal:{code:b,message:`${O} Nothing was brought back.`}}),u;try{u=await s.store.open(d,e.runId)}catch(b){if(b instanceof Pr)return c("RUN_GONE",b.message);throw b}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 g=await u.state();if(u.head.deleteMode==="hard")return c("UNDO_UNAVAILABLE",`${e.runId} deleted for good: Salesforce brings back nothing a hard delete took, what went along included.`);if(g.undone)return c("UNDO_UNAVAILABLE",`${e.runId} was undone already.`);let p=await s.runWriting?.(d),f=[];p!==void 0&&f.push({code:"RUN_WRITING",message:p});let h=u.head.passes.map(b=>({objectApiName:b.objectApiName,records:b.records??0})),m=await Zr({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(b=>b.objectApiName)},written:[]}}),y=Tn(m.answer);if(y&&f.push({code:y.code,message:y.message},...y.alsoRefused),f.length>0){let[b,...O]=f;return{ran:!1,refusal:b,...O.length>0?{alsoRefused:O}:{}}}let R=lI(await LI(u),s.requestsSent!==void 0?s.requestsSent()-o:0,Qr(m.mute?.plan)),S=s.lock(d);if("busy"in S)return{ran:!1,refusal:HI(r,S.busy)};try{let b=await to(m,s.operationId,e.accord.acceptEmails===!0,s.voice);if("refused"in b)return{ran:!1,refusal:{code:b.refused.code,message:b.refused.message}};let O,P;try{P=await FI({org:t,undelete:w=>t.undelete(w),journal:u,...s.signal?{signal:s.signal}:{},onProgress:({percentage:w,step:C})=>s.onProgress?.(w,C)})}finally{b.held&&(O=await b.held.release())}let v=n();return P.status!=="cancelled"&&await u.undone(P.status,v),{ran:!0,result:{runId:e.runId,status:P.status,objects:P.objects,notes:[...P.notes,...O?Kt(O,r).map(w=>w.trim()):[]],...O?{mutedAutomation:O}:{},...s.requestsSent!==void 0?{requestsSent:s.requestsSent()-o}:{},requestsEstimate:R,...P.previewedLost?{previewedLost:P.previewedLost}:{},finishedAt:v.toISOString()}}}finally{S.lock.release()}}function gN(s){let e=Xn(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=Iw(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 QI(s,e,t){let r=Qi(s),n=Cw(s,t),o=gN(s),i=[],a=new YR(async(u,l)=>(await Xn(s).bulk2.job("ingest",{id:l}).check()).state),d=u=>async(l,g,p)=>{try{return await Pw(o.bulk,l,g,p,u)}catch(f){let h=o.last();throw h.closed&&i.push({orgId:e,objectApiName:l,...h.jobId?{jobId:h.jobId}:{}}),f}},c=u=>({totalSize:u.totalSize,done:u.done,records:u.records,...u.nextRecordsUrl?{nextRecordsUrl:u.nextRecordsUrl}:{}});return{describe:u=>s.describe(u),count:async u=>(await s.query(u)).totalSize,countAll:async u=>(await s.query(u,{scanAll:!0})).totalSize,readIds:async(u,l)=>{let g=await s.query(u,{scanAll:l});return{totalSize:g.totalSize,ids:g.records.flatMap(p=>typeof p.Id=="string"?[p.Id]:[])}},query:async(u,l)=>c(await s.query(u,{scanAll:l?.scanAll===!0})),queryMore:async u=>c(await s.queryMore(u)),queryDeleted:u=>n.queryDeleted(u),describeGlobal:()=>s.describeGlobal(),toolingObjects:async()=>{try{return(await s.tooling.describeGlobal()).sobjects.map(u=>u.name)}catch{return[]}},serverTime:async()=>(await s.soap.getServerTimestamp()).timestamp,userId:async()=>(await s.soap.getUserInfo()).userId,limits:()=>s.request({method:"GET",url:"/limits"}),update:(u,l)=>n.update(u,l),destroy:(u,l)=>n.destroy(u,l),bulkDestroy:d("delete"),bulkHardDestroy:d("hardDelete"),undelete:u=>s.soap.undelete(u),lostJobs:()=>[...i],stillRunning:u=>a.stillRunning(u),requestsSent:r}}import{readdir as fN,readFile as hN,rm as ZI,stat as eA,writeFile as mN}from"node:fs/promises";import{join as Pc}from"node:path";var rA=/^ep-\d{8}-\d{6}-[a-z0-9]{4}$/,yN=50;function Cc(s){return rA.test(s)}var tA=J({records:Te().optional(),unread:j().optional()}).loose(),wN=J({v:yt(1),orgId:j().min(1),kept:J({previewId:j().regex(rA),readAt:j(),orgName:j(),organizationId:j().min(15).max(18),request:J({mode:We(["objects","org"])}).loose(),preview:J({mode:We(["objects","org"]),deleteMode:We(["recycle","hard"]),passes:ve(J({objectApiName:j(),records:tA}).loose()),along:ve(J({objectApiName:j(),records:tA}).loose()),undoLost:ve(J({objectApiName:j()}).loose()),total:J({records:Te()}).loose()}).loose(),access:J({kind:We(["org","perObject"])}).loose(),peopleActive:J({people:Te(),who:ve(J({userId:j()}).loose()).optional()}).loose()}).loose()}),$c=class{constructor(e,t=xa){this.root=e;this.keepMs=t}root;keepMs;async keep(e,t,r=Date.now()){if(!Cc(t.previewId))throw new Error(`Not a preview's id: ${t.previewId}`);await Da(this.root),await mN(Pc(this.root,`${t.previewId}.json`),JSON.stringify({v:1,orgId:e,kept:t}),{mode:$a}),await this.sweep(r)}async read(e,t=Date.now()){if(!Cc(e))return;let r=Pc(this.root,`${e}.json`);try{if((await eA(r)).mtimeMs+this.keepMs<=t)return;let n=wN.safeParse(JSON.parse(await hN(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){Cc(e)&&await ZI(Pc(this.root,`${e}.json`),{force:!0})}async sweep(e){let t;try{t=await fN(this.root)}catch{return}let r=t.filter(o=>o.endsWith(".json")&&Cc(o.slice(0,-5))).sort(),n=Math.max(0,r.length-yN);for(let[o,i]of r.entries()){let a=Pc(this.root,i);try{(o<n||(await eA(a)).mtimeMs+this.keepMs<=e)&&await ZI(a,{force:!0})}catch{}}}};var RN=6e4,vN=20,os="dataops",SN=new Set(["dataops:empty:scope","dataops:empty:preview","dataops:empty:run","dataops:empty:cancel","dataops:empty:undo"]),ln=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 kN(s){return s.passes.filter(e=>e.deleted+e.refused+(e.notReached??0)>0).map(e=>({...mt(e.objectApiName),deleted:e.deleted,failed:e.refused,...(e.notReached??0)>0?{notSent:e.notReached}:{}}))}function ON(s){return s.objects.filter(e=>e.undeleted+e.notInBin+e.othersDeletion+e.refused>0).map(e=>({...mt(e.objectApiName),created:e.undeleted,failed:e.notInBin+e.othersDeletion+e.refused,...(e.notReached??0)>0?{notSent:e.notReached}:{}}))}function IN(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 xc=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)=>QI(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(!SN.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-GOOVPVWX.mjs");return new t(r(async n=>{let o=await q(n,this.deps.orgRegistry,this.deps.orgManager);return e(o),o}))}ownStores(){if(this.stores)return this.stores;let e=Ob({root:Sb()});if("refusal"in e)throw new ln({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 hd(cp()),previews:new $c(bN(cp(),"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 q(e,this.deps.orgRegistry,this.deps.orgManager),d=ye(i,e),c=this.ownStores(),u=this.orgOf(a,e),l=[],g,p=()=>this.targetAutomation?Promise.resolve(this.targetAutomation):(g??=this.countingReader(m=>l.push(Qi(m))),g),f=Pa(r),h=this.runWriting?.(e,d,t);return{org:u,...u.requestsSent?{requestsSent:()=>(u.requestsSent?.()??0)+l.reduce((m,y)=>m+y(),0)}:{},orgId:e,orgName:d,username:i?.username??d,registered:i,store:c.journals,lock:c.lock,...h?{runWriting:h}:{},automation:No(a,async m=>{let y=await p();return new fe(RN).withTimeout("dataops automation",()=>y.read(e,m,{undeletes:!0}))},!1),muteLeases:this.muteLeases,...f?{voice:f}:{},...this.checkpoints?{checkpoints:this.checkpoints}:{},askGuard:async m=>{let y=this.deps.infraServices?.productionGuard;if(!y)return{decision:"refused",reason:Re.message};let{check:R,decision:S}=await et(y,{orgId:e,orgTier:Pe(i),operation:m.operation,objectName:m.objectNames.join(", "),recordCount:m.recordCount,module:os});return{decision:S,...S==="refused"?{reason:R.blockedReason??R.impactSummary}:{}}},operationId:t,tool:"panel",...n?{signal:n}:{},...o?{onProgress:o}:{}}}fail(e,t,r){if(t instanceof ln){T(this.deps,e.type,"dataops:error",e,t,{code:t.refusal.code,retryable:!1,...t.alsoRefused.length>0||t.mutedAutomation?{extraPayload:{...t.alsoRefused.length>0?{alsoRefused:[...t.alsoRefused]}:{},...t.mutedAutomation?{mutedAutomation:t.mutedAutomation}:{}}}:{}});return}T(this.deps,e.type,"dataops:error",e,t,{code:r})}respond(e,t,r){let n=A(this.deps,e,t,r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}async handleScope(e){let t=$(Jm,e,"dataops:error",this.deps);if(t)try{let{orgId:r,...n}=t,o=await this.contextOf(r,e.id,{}),i={query:l=>o.org.query(l)},a=await oo(i,{orgName:o.orgName,registered:o.registered,mode:n.mode});if(!a.allowed)throw new ln(a.refusal);let d=J({sobjects:ve(na)}).loose().parse(await o.org.describeGlobal()).sobjects,c=Oc(d,await o.org.toolingObjects(),n),u=await Js(i);this.respond(e,"dataops:empty:scope:response",{mode:c.mode,objects:c.objects,leftOut:c.leftOut,candidates:c.worked,tier:a.tier,hardDelete:{permitted:u.hardDelete,...u.unread!==void 0?{unread:u.unread}:{}}})}catch(r){this.fail(e,r,"EMPTY_SCOPE_ERROR")}}previewStore(){return this.ownStores().previews}async keep(e,t){for(this.previews.set(t.previewId,{orgId:e,kept:t,at:Date.now()});this.previews.size>vN;){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<=xa?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=$(Vm,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 WI(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 ln(o.refusal);await this.keep(t.orgId,o.kept),this.respond(e,"dataops:empty:preview:response",{...IN(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=$(Xm,e,"dataops:error",this.deps);if(!t)return;let r=this.running.get(t.operationId);r&&(this.deps.infraServices?.backgroundRegistry?.abort(t.operationId),r.abort()),this.respond(e,"dataops:empty:cancel:response",{operationId:t.operationId,cancelled:r!==void 0})}async writeAct(e,t,r,n,o,i,a){let d=e.id,c=this.deps.infraServices?.backgroundRegistry,u=new AbortController;this.running.set(d,u),this.writing.set(d,t);let l=()=>{},g=new Promise((h,m)=>{l=y=>y===void 0?h():m(y)});g.catch(()=>{}),Je(this.deps,d,os,r),c?.register(d,os,r,g,u);let p=ar(this.liveTracker,d,os,r),f=(h,m)=>{Fe(this.deps,d,h,0,0,m),u.signal.aborted||c?.updateProgress(d,h),p.progress(h,0,0,m)};try{let h=await this.contextOf(t,d,a,u.signal,f),m=await n(h);if(!m.ran)throw o("stopped",{code:m.refusal.code,...m.guard?{guard:m.guard}:{}}),ge(this.deps,d,{status:"refused",code:m.refusal.code}),p.fail(m.refusal.message),l(new Error(m.refusal.message)),new ln(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),ge(this.deps,d,{aborted:!0}),p.cancel(),l();else if(y.status==="failure"){let R="Nothing the emptying set out to do went through: its result says why.";ge(this.deps,d,{status:y.status}),p.fail(R),l(new Error(R))}else ge(this.deps,d,{status:y.status}),y.status==="success"?p.complete():p.partial(),l()}catch(h){throw h instanceof ln||(o("failure",{}),ge(this.deps,d,{status:"failure"}),p.fail(h instanceof Error?h.message:String(h)),l(h)),h}finally{this.running.delete(d),this.writing.delete(d)}}async handleRun(e){let t=$(Km,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 ln({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=>XI(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:os,operationId:e.id,orgId:t.orgId,outcome:o,...i.guard?{guard:i.guard}:{},...i.code!==void 0?{code:i.code}:{},...i.result?{objects:kN(i.result)}:{},...i.result?.mutedAutomation?{muted:ut(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=$(Ym,e,"dataops:error",this.deps);if(t)try{await this.writeAct(e,t.orgId,`Undoing the emptying ${t.runId}`,r=>YI(r,{runId:t.runId,accord:t}),(r,n)=>Z(this.deps,{action:"empty_undo",module:os,operationId:e.id,orgId:t.orgId,outcome:r,...n.code!==void 0?{code:n.code}:{},...n.result?{objects:ON(n.result)}:{},...n.result?.mutedAutomation?{muted:ut(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 xN}from"node:os";var nA=6e4,AN=2*6e4,TN=50,EN=2880*6e4,PN=60*6e4,CN=250,oA="pipeline-triggers",$N=J({cron:j().optional(),timezone:j().optional(),nextRunAt:Te().optional(),lastFiredAt:Te().optional(),lastOutcome:We(["started","missed"]).optional()});function bi(s,e){return`pipeline-trigger:${s}:${e}`}var Dc=class{constructor(e){this.deps=e;this.now=e.now??(()=>Date.now()),this.newId=e.newId??(()=>globalThis.crypto.randomUUID())}deps;engine=new uS;now;newId;timer;started=!1;firstLook=!0;looking;lookAgain=!1;lastPrune=0;soonest;busyMisses=new Map;refusedMisses=new Map;unscheduled=new Map;start(){this.started||(this.started=!0,this.firstLook=!0,this.deps.log("[pipeline-triggers] started"),this.look())}stop(){this.started&&(this.started=!1,clearTimeout(this.timer),this.timer=void 0,this.deps.log("[pipeline-triggers] stopped"))}reload(){return this.started?this.look():Promise.resolve()}async onSandboxRefresh(e){if(!this.started)return;let t=this.deps.org(e.orgId);for(let r of this.deps.pipelines())for(let n of this.triggersOf(r)){if(!this.engine.firesOnRefreshOf(n,e.orgId)||this.engine.idleReason(n,t)||!this.deps.claims.claim(`refresh:${r.id}:${n.id}:${e.key}`))continue;let o=this.now(),i=await this.problemsOf(r);if(i.length>0){this.refuseStart(r,n,"sandbox_refresh",o,i,{sandboxName:t?.name});continue}this.fire(r,n,"sandbox_refresh",o,t?.name)}}async statuses(){let e=[],t=this.now();for(let r of this.deps.pipelines()){let n=this.triggersOf(r),o;for(let i of n){let a=this.read(r.id,i.id),d=i.type,c={pipelineId:r.id,triggerId:i.id,type:d,armed:!1,...a.lastFiredAt!==void 0?{lastFiredAt:new Date(a.lastFiredAt).toISOString(),...a.lastOutcome?{lastOutcome:a.lastOutcome}:{}}:{},...d==="schedule"?{timezone:this.engine.timezoneOf(i)}:{}},u=this.engine.idleReason(i,this.orgOf(i),t);u||(o??=await this.problemsOf(r),o.length>0&&(u={idle:"cannotRun",detail:o.join(" ")})),!u&&!this.started&&(u={idle:"stopped"});let l;if(!u&&d==="schedule"){let g=this.planOf(i,a)??this.engine.nextRun(i,t);typeof g=="number"?l=g:u=g}e.push(u?{...c,idle:u.idle,...u.detail?{detail:u.detail}:{}}:{...c,armed:!0,...l!==void 0?{nextRunAt:new Date(l).toISOString()}:{}})}}return e}look(){return this.looking?(this.lookAgain=!0,this.looking):(this.looking=this.lookNow().catch(e=>{this.deps.log(`[pipeline-triggers] a look failed: ${I(e)}`)}).finally(()=>{this.looking=void 0,this.lookAgain?(this.lookAgain=!1,this.look()):this.arm()}),this.looking)}async lookNow(){if(!this.started)return;let e=this.now(),t=this.firstLook;this.firstLook=!1,e-this.lastPrune>=PN&&(this.lastPrune=e,this.deps.claims.prune(EN));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(bi(i.id,d.id));let c=this.engine.idleReason(d,this.orgOf(d),e);if(c||(a??=await this.problemsOf(i)),d.type!=="schedule")continue;let u=c?this.unplan(i,d):this.lookAt(i,d,e,t,a??[]);u!==void 0&&(o===void 0||u<o)&&(o=u)}this.sayWhyUnscheduled(i,a)}for(let i of[...this.unscheduled.keys()])n.has(i)||this.unscheduled.delete(i);this.soonest=o,this.forgetAllBut(r)}sayWhyUnscheduled(e,t){if(t===void 0)return;let r=this.unscheduled.get(e.id);if(t.length===0){if(r===void 0)return;this.unscheduled.delete(e.id),this.deps.log(`[pipeline-triggers] "${e.name}" can run again: its triggers start it`);return}let n=t.join(" ");r!==n&&(this.unscheduled.set(e.id,n),this.deps.log(`[pipeline-triggers] "${e.name}" is not scheduled: its triggers start nothing while a step cannot run. ${n}`))}lookAt(e,t,r,n,o){let i=this.read(e.id,t.id),a=this.planOf(t,i);if(a===void 0)return this.plan(e,t,i,r);if(a>r)return a;let d=this.engine.dueBetween(t,a,r,TN),c=[a,...d.times],u=c[c.length-1],l=!n&&r-u<=AN?u:void 0,g=l===void 0?c:c.slice(0,-1),p=this.plan(e,t,i,r),f=g.filter(h=>this.deps.claims.claim(this.dueKey(e,t,h)));if(f.length>0){let h={reason:n?"closed":"asleep",count:f.length,...f.length>1?{lastDueAt:new Date(f[f.length-1]).toISOString()}:{},...d.more?{atLeast:!0}:{}};this.recordMissed(e,"schedule",f[0],h),this.remember(e,t,{lastFiredAt:f[f.length-1],lastOutcome:"missed"}),this.deps.report({kind:"missed",pipelineName:e.name,triggeredBy:"schedule",dueAt:new Date(f[0]).toISOString(),missed:h,...p!==void 0?{nextRunAt:new Date(p).toISOString()}:{}})}return l!==void 0&&this.deps.claims.claim(this.dueKey(e,t,l))&&(o.length>0?this.refuseStart(e,t,"schedule",l,o,{...p!==void 0?{nextRunAt:new Date(p).toISOString()}:{}}):this.fire(e,t,"schedule",l)),p}refuseStart(e,t,r,n,o,i){let a=o.join(" "),d=bi(e.id,t.id),c=r==="schedule"?this.refusedMisses.get(d):void 0,u=c&&c.detail===a?{...c,count:c.count+1}:{runId:`missed-${this.newId()}`,detail:a,firstDueAt:n,count:1};r==="schedule"&&this.refusedMisses.set(d,u);let l={reason:"cannotRun",count:u.count,...u.count>1?{lastDueAt:new Date(n).toISOString()}:{},detail:a};this.recordMissed(e,r,u.firstDueAt,l,u.runId),this.remember(e,t,{lastFiredAt:n,lastOutcome:"missed"}),!(u.count>1)&&this.deps.report({kind:"missed",pipelineName:e.name,triggeredBy:r,dueAt:new Date(n).toISOString(),missed:l,...i})}dueKey(e,t,r){return`due:${e.id}:${t.id}:${r}`}fire(e,t,r,n,o){let i=bi(e.id,t.id);this.refusedMisses.delete(i);let a=this.deps.start(e,r);if(a.started){this.busyMisses.delete(i),this.remember(e,t,{lastFiredAt:n,lastOutcome:"started"}),this.deps.log(`[pipeline-triggers] started "${e.name}" (${r})`),a.run.then(l=>{l?.status==="failed"&&this.deps.report({kind:"failed",pipelineName:e.name,triggeredBy:r,error:l.error??"the run failed",...o?{sandboxName:o}:{}})},l=>{this.deps.report({kind:"failed",pipelineName:e.name,triggeredBy:r,error:I(l),...o?{sandboxName:o}:{}})});return}let d=this.busyMisses.get(i),c=d&&d.busySince===a.busy.startedAt?{...d,count:d.count+1,lastDueAt:n}:{runId:`missed-${this.newId()}`,busySince:a.busy.startedAt,firstDueAt:n,count:1,lastDueAt:n};this.busyMisses.set(i,c);let u={reason:"busy",count:c.count,busySince:c.busySince,...c.count>1?{lastDueAt:new Date(c.lastDueAt).toISOString()}:{}};this.recordMissed(e,r,c.firstDueAt,u,c.runId),this.remember(e,t,{lastFiredAt:n,lastOutcome:"missed"}),this.deps.log(`[pipeline-triggers] "${e.name}" not started (${r}): a run started at ${a.busy.startedAt} is going`),c.count===1&&this.deps.report({kind:"missed",pipelineName:e.name,triggeredBy:r,dueAt:new Date(n).toISOString(),missed:u,...o?{sandboxName:o}:{}})}recordMissed(e,t,r,n,o=`missed-${this.newId()}`){this.deps.record({runId:o,pipelineId:e.id,pipelineName:e.name,status:"missed",triggeredBy:t,startTime:new Date(r).toISOString(),duration:0,stepCount:0,errorCount:0,missed:n})}planOf(e,t){return t.cron===(e.config.cron??"").trim()&&t.timezone===this.engine.timezoneOf(e)?t.nextRunAt:void 0}plan(e,t,r,n){let o=this.engine.nextRun(t,n),i=typeof o=="number"?o:void 0;return this.write(e.id,t.id,{...r,cron:(t.config.cron??"").trim(),timezone:this.engine.timezoneOf(t),nextRunAt:i}),i}unplan(e,t){let r=this.read(e.id,t.id);(r.nextRunAt!==void 0||r.cron!==void 0)&&this.write(e.id,t.id,{...r.lastFiredAt!==void 0?{lastFiredAt:r.lastFiredAt}:{},...r.lastOutcome?{lastOutcome:r.lastOutcome}:{}})}remember(e,t,r){this.write(e.id,t.id,{...this.read(e.id,t.id),...r})}forgetAllBut(e){for(let t of Object.keys(this.deps.store.getByCategory(oA)))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?nA:this.soonest-this.now(),t=Math.min(Math.max(e,CN),nA);this.timer=setTimeout(()=>{this.look()},t),this.timer.unref?.()}triggersOf(e){return(Array.isArray(e.triggers)?e.triggers:[]).flatMap(r=>{let n=cS.safeParse(r);if(!n.success)return[];let o=n.data;return o.type==="schedule"||o.type==="sandbox_refresh"?[o]:[]})}orgOf(e){let t=e.config.orgId;return e.type==="sandbox_refresh"&&t?this.deps.org(t):void 0}async problemsOf(e){try{return await this.deps.problems(e)}catch(t){return[`The saved pipeline cannot be read: ${I(t)}.`]}}read(e,t){let r=$N.safeParse(this.deps.store.get(bi(e,t)));return r.success?r.data:{}}write(e,t,r){this.deps.store.set(bi(e,t),r,oA)}};function ss(){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 W1=65*6e4;var sA=[{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 Og(s,e){return`${s}\0${e}`}var Nc=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=Og(e.operationId,e.stepId),o={...e,expiresAt:new Date(r().getTime()+e.timeoutMs).toISOString()};return new Promise(i=>{let a=u=>{this.waiting.get(n)?.settle===a&&(this.waiting.delete(n),clearTimeout(c),t?.removeEventListener("abort",d),i(u))},d=()=>a({decision:"cancelled",at:r().toISOString()}),c=setTimeout(()=>a({decision:"timedOut",at:r().toISOString()}),e.timeoutMs);if(this.waiting.set(n,{question:o,settle:a}),t?.aborted){d();return}t?.addEventListener("abort",d,{once:!0}),this.deps.announce?.(o),this.deps.ask?.(o).then(u=>{if(u===void 0)return;let l=typeof u=="string"?{decision:u,via:void 0}:u,g=l.decision==="approve"?"approved":"rejected",p=l.via??"notification";this.answer(e.operationId,e.stepId,g,p)||this.deps.tooLate?.(o)},()=>{})})}answer(e,t,r,n){let o=this.waiting.get(Og(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(Og(e,t))}};var iA=50,uA={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 DN(s,e){return`Pipeline "${s}" is already running: the run started ${uA[e.triggeredBy]} at ${e.startedAt} has not ended. A pipeline runs once at a time.`}function NN(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 jN={approved:"success",rejected:"stopped",timedOut:"stopped",cancelled:"cancelled"};function aA(){try{return Lh(xN().username)}catch{return}}function MN(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 dA="A simulation of a pipeline is not available here: nothing ran. Run it, or simulate it again once SandForge has finished starting.",cA={release:()=>{}};function Ig(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 LN=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"]),jc=class{constructor(e){this.deps=e}deps;pipelineMarketplace;stepRunners;claims=ss();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??ES()}takeRunLock(e,t,r){if(typeof e.id!="string"||e.id==="")return cA;try{let n=CS(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] ${xS(n.tookOver)}`),n.lock)}catch(n){return this.deps.log(`[WARN] the run lock of pipeline "${e.name}" could not be taken (${I(n)}): a run from the command line is not kept apart from this one.`),cA}}setLiveOperationTracker(e){this.liveTracker=e}approvals(){let e=this.deps.services;return this.approvalGate??=new Nc({...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:aA}),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 Vs(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 To(this.deps.configStore).append({id:crypto.randomUUID(),action:"pipeline_approval",module:"automation",operationId:r,outcome:jN[t.decision],objects:[],details:{pipeline:e.pipelineName??"",step:e.stepName,decision:t.decision,...t.via?{via:t.via}:{},...t.by?{answeredBy:t.by}:{}},timestamp:t.at})}catch(n){this.deps.log(`[WARN] audit trail: approval of run ${r} was not recorded \u2014 ${I(n)}`)}}setPipelineMarketplace(e){this.pipelineMarketplace=e}setStepRunners(e){this.stepRunners=e}startTriggers(e){e.claims&&(this.claims=e.claims),this.reportTrigger=e.report,this.triggerScheduler().start()}stopTriggers(){this.scheduler?.stop()}noticeSandboxRefresh(e){return this.scheduler?.onSandboxRefresh(e)??Promise.resolve()}triggerScheduler(){return this.scheduler??=new Dc({pipelines:()=>this.savedPipelines(),problems:e=>this.pipelineProblems(e),org:e=>{let t=this.deps.orgManager.getOrg(e);return t?{name:ye(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=la.safeParse(o);return i.success?[i.data]:(t.set(n,bl(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] ${pp(n.busy,e.name)}`),{started:!1,busy:{startedAt:n.busy.acquiredAt,triggeredBy:n.busy.triggeredBy}};let o=`${Lf}${crypto.randomUUID()}`;return{started:!0,run:this.runPipeline(e,{},t,o).catch(a=>{throw this.deps.log(`[ERR] ${t} run of "${e.name}": ${I(a)}`),je(this.deps,o,I(a),!1,{context:{module:"automation",operation:"pipeline:execute"}}),a}).finally(()=>{n.release(),r.release()})}}async handle(e){if(!LN.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=$(ow,e,"pipeline:error",this.deps);if(!t)return;let r=t,n=e.id,o={module:"automation",operation:e.type},i=r.pipeline,a=r.dryRun===!0;if(a&&(!this.dryRunApplier||!this.stepRunners)){T(this.deps,"pipeline:execute","pipeline:error",e,new Error(dA),{code:"DRY_RUN_UNAVAILABLE",retryable:!0});return}let d=typeof i.id=="string"&&i.id!==""?this.claims.hold(i.id,{startedAt:new Date().toISOString(),triggeredBy:"manual"}):{release:()=>{}};if("busy"in d){T(this.deps,"pipeline:execute","pipeline:error",e,new Error(DN(i.name,d.busy)),{code:"PIPELINE_RUNNING",retryable:!0});return}let c=this.takeRunLock(i,"manual",a);if("busy"in c){d.release(),T(this.deps,"pipeline:execute","pipeline:error",e,new Error(pp(c.busy,i.name)),{code:"PIPELINE_RUNNING",retryable:!0});return}try{let u=await this.runPipeline(i,r.variables??{},"manual",n,{dryRun:a}),l=A(this.deps,e,"pipeline:run:response",{...u,...a?{dryRun:!0}:{}});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`)}catch(u){T(this.deps,"pipeline:execute","pipeline:error",e,u),je(this.deps,n,I(u),!1,{context:o})}finally{c.release(),d.release()}}handlePipelineApproval(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(cw,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 Ig(e.steps)){let o=$t.safeParse(n.config);if(!(!o.success||t.has(o.data.checkpointId)))try{t.set(o.data.checkpointId,await r(o.data.checkpointId))}catch(i){this.deps.log(`[WARN] checkpoint ${o.data.checkpointId} not read for a check: ${I(i)}`)}}return t}async revokeVoidGrants(){try{let e=this.stepRunners?.readCheckpoint,t=await this.rewindGrants().revokeVoid(e?async r=>(await e(r)).kept:void 0);for(let r of t)this.deps.log(`[INFO] the confirmation of Rewind step ${r.stepId} of pipeline ${r.pipelineId} was taken back: its pipeline is no longer saved, or its checkpoint ${r.checkpointId} is no longer kept`)}catch(e){this.deps.log(`[WARN] confirmations of Rewind steps not checked: ${I(e)}`)}}savedPipeline(e){let t=la.safeParse(this.deps.configStore.get(`pipeline:saved:${e}`));return t.success?t.data:void 0}async describeRewindStep(e,t){let r=this.stepRunners,n=$t.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&&Ks(t.config)===i.digest}:void 0;return r?{info:yk(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=$(uw,e,"pipeline:error",this.deps);if(t)try{let r=this.savedPipeline(t.pipelineId),n=[];for(let i of Ig(r?.steps??[]))n.push((await this.describeRewindStep(t.pipelineId,i)).info);let o=A(this.deps,e,"pipeline:rewind-steps:response",{pipelineId:t.pipelineId,steps:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} (${n.length} Rewind steps)`)}catch(r){T(this.deps,"pipeline:rewind-steps","pipeline:error",e,r)}}async handleRewindGrant(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(lw,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=Ig(d?.steps??[]).find(h=>h.id===n);if(!c)return a("NOT_SAVED");let u=$t.safeParse(c.config);if(!u.success)return a("CONFIG_INVALID",{reason:u.error.issues[0]?.message??""});let l=this.deps.orgManager.getOrg(u.data.orgId);if(!l)return a("ORG_UNKNOWN");if(o!==ye(l))return a("TYPED_MISMATCH");let{info:g,checkpoint:p}=await this.describeRewindStep(r,c);if(!g.valid)return a("CHECKPOINT_INVALID",{why:g.why??"missing"});if(!p?.kept||p.organizationId===void 0)return a("CHECKPOINT_INVALID",{why:"missing"});let f=aA();this.rewindGrants().write({pipelineId:r,stepId:n,organizationId:p.organizationId,checkpointId:u.data.checkpointId,digest:Ks(c.config)??"",grantedAt:new Date().toISOString(),...f!==void 0?{grantedBy:f}:{}}),this.deps.log(`[INFO] pipeline:rewind-grant: Rewind step ${n} of pipeline ${r} confirmed for ${ye(l)}, to checkpoint ${u.data.checkpointId}`),i({granted:!0,pipelineId:r,stepId:n,step:(await this.describeRewindStep(r,c)).info})}catch(d){T(this.deps,"pipeline:rewind-grant","pipeline:error",e,d)}}handleRewindRevoke(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(pw,e,"pipeline:error",this.deps);if(t)try{let r=this.rewindGrants().revoke(t.pipelineId,t.stepId),n=A(this.deps,e,"pipeline:rewind-revoke:response",{pipelineId:t.pipelineId,stepId:t.stepId,revoked:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} revoked=${r}`)}catch(r){T(this.deps,"pipeline:rewind-revoke","pipeline:error",e,r)}}handleSeedTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.stepRunners?fk(this.stepRunners):[],r=A(this.deps,e,"pipeline:seed-templates:response",{templates:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} (${t.length} templates)`)}catch(t){T(this.deps,"pipeline:seed-templates","pipeline:error",e,t)}}handleMaskingTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.stepRunners?hk(this.stepRunners):[],r=A(this.deps,e,"pipeline:masking-templates:response",{templates:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} (${t.length} templates)`)}catch(t){T(this.deps,"pipeline:masking-templates","pipeline:error",e,t)}}handleSyncConfigs(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.stepRunners?ck(this.stepRunners):[],r=A(this.deps,e,"pipeline:sync-configs:response",{configs:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} (${t.length} configurations)`)}catch(t){T(this.deps,"pipeline:sync-configs","pipeline:error",e,t)}}async buildOrchestrator(e,t){return(await this.buildRunParts(e,t)).orchestrator}async buildRunParts(e,t){let{PipelineBuilder:r}=await import("./chunk-4HW535YJ.mjs"),{TriggerEngine:n}=await import("./chunk-MIDBQ7SD.mjs"),{StepLibrary:o}=await import("./chunk-DGDRQRCW.mjs"),{StepExecutor:i}=await import("./chunk-5SMWFNE7.mjs"),{ConditionalRouter:a}=await import("./chunk-BAWCOKRW.mjs"),{PipelineHistory:d}=await import("./chunk-ZHJP7L3K.mjs"),c=new i,u=e??{operationId:"",holdBudget:()=>{}};c.wrapHandler("delay",p=>(f,h)=>this.untimed(()=>p(f,h),u));let l;if(this.stepRunners){let{runSync:p,seed:f,anonymize:h,takeCheckpoint:m,rewind:y,backup:R}=this.stepRunners,{simulateSync:S,previewSeed:b,previewMasking:O,estimateTake:P,previewRewind:v}=this.stepRunners,w=await this.checkpointsOf(t),C=this.rewindGrants();l={...this.stepRunners,...t?.id?{pipelineId:t.id}:{},...u.triggeredBy?{trigger:u.triggeredBy}:{},rewindGrant:(k,E)=>C.verify(k,E),checkpointKept:k=>w.get(k),...p?{runSync:(k,E,x)=>this.runSyncUntimed(p,k,E,x,u)}:{},backup:(k,E)=>this.untimed(()=>R(k,E),u),...f?{seed:(k,E)=>this.untimed(()=>f(k,E),u)}:{},...h?{anonymize:(k,E)=>this.untimed(()=>h(k,E),u)}:{},...m?{takeCheckpoint:(k,E)=>this.untimed(()=>m(k,E),u)}:{},...y?{rewind:(k,E)=>this.untimed(()=>y(k,E),u)}:{},...S?{simulateSync:(k,E)=>this.untimed(()=>S(k,E),u)}:{},...b?{previewSeed:(k,E)=>this.untimed(()=>b(k,E),u)}:{},...O?{previewMasking:(k,E)=>this.untimed(()=>O(k,E),u)}:{},...P?{estimateTake:(k,E)=>this.untimed(()=>P(k,E),u)}:{},...v?{previewRewind:(k,E)=>this.untimed(()=>v(k,E),u)}:{},...this.approvals().canAsk?{askApproval:(k,E)=>this.askApproval(k,E,u)}:{}},wk(c,l)}if(u.dryRun){if(!this.dryRunApplier||!l)throw new Error(dA);await this.dryRunApplier(c,l)}if(!this.deps.services)throw new Error("AutomationHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");return{orchestrator:this.deps.services.automationOrchestrator({builder:new r,triggerEngine:new n,stepLibrary:new o,stepExecutor:c,conditionalRouter:new a,history:new d,services:this.deps.services}),stepExecutor:c}}async runPipeline(e,t,r,n,o={}){let i=o.dryRun===!0,a={module:"automation",operation:"pipeline:execute"},d=this.deps.services?.getSandforgeSetting?.("pipeline.timeout",3e5)??3e5,c=new AbortController,u=!1,l=MN(d,()=>{u=!0,c.abort()}),g=await this.buildOrchestrator({operationId:n,holdBudget:v=>v?l.hold():l.resume(),triggeredBy:r,...i?{dryRun:!0}:{}},e);this.deps.infraServices?.performanceTracker?.start(n,"automation");let p=`${i?"Pipeline simulation":"Pipeline"}: ${e.name}`;Je(this.deps,n,"automation",p);let f=ar(this.liveTracker,n,"automation",p,e.steps.length),h=v=>u&&v.status==="stopped"?{...v,status:"failed"}:v,m=(v,w)=>{let C=w,k=g.getActiveRuns(),E=e.steps.length,x=k[0]?.stepResults.length??0,V=Math.round(x/E*100),H=`Step: ${C.stepResult.stepName} (${C.stepResult.status})`;Fe(this.deps,n,V,x,E,H),f.progress(V,x,E,H)},y=(v,w)=>{let{stepId:C}=w;this.postStepUpdate({operationId:n,stepId:C,status:"running"})},R=(v,w)=>{let C=h(w.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}:{}})};g.on("stepCompleted",m),g.on("stepStarted",y),g.on("stepCompleted",R),g.on("stepSkipped",R),l.start();let S=()=>{};this.deps.infraServices?.backgroundRegistry?.register(n,"automation",p,new Promise((v,w)=>{S=C=>C?w(C):v()}),c);let b;try{b=await g.execute(e,t,r,c.signal)}catch(v){throw S(new Error(I(v))),f.fail(I(v)),v}finally{l.end(),g.off?.("stepCompleted",m),g.off?.("stepStarted",y),g.off?.("stepCompleted",R),g.off?.("stepSkipped",R)}let O=u&&b.status==="cancelled",P=O?{...b,status:"failed",error:`Pipeline ran out of time: sandforge.pipeline.timeout stopped it after ${d} ms.`,stepResults:b.stepResults.map(h)}:b;return S(P.status==="failed"?new Error(P.error??"Pipeline failed"):void 0),P.status==="failed"?f.fail(P.error??"Pipeline failed"):P.status==="cancelled"?f.cancel():P.status==="completed_with_warnings"?f.partial():f.complete(),this.deps.infraServices?.performanceTracker?.complete(n),i||this.recordRun(P,e),P.status==="failed"?je(this.deps,n,P.error??"Pipeline failed",O,{context:a}):ge(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(NN)},{pipeline:t})}recordEntry(e){this.writeHistory(e)}writeHistory(e,t={}){try{let r=new Date(e.startTime).getTime();this.deps.configStore.set(`pipeline:history:${e.runId}`,{...e,timestamp:Number.isNaN(r)?Date.now():r,...t},"pipeline-history"),this.trimHistory()}catch(r){this.deps.log(`[ERR] pipeline history write: ${I(r)}`)}}trimHistory(){let e=Object.entries(this.deps.configStore.getByCategory("pipeline-history"));if(e.length<=iA)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-iA))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 cn(r).load(o),maskingTemplate:o=>new Ia(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=la.safeParse(r);if(!n.success||n.data.runsOutside===void 0)continue;let o=n.data;try{let i=GS(this.exportInput(o,"0.0.0"));t.push({pipelineId:o.id,matches:i===n.data.runsOutside.digest,...i!==void 0?{digest:i}:{}})}catch(i){this.deps.log(`[WARN] pipeline "${o.name}": whether its exported file is up to date was not read: ${I(i)}`),t.push({pipelineId:o.id,matches:!1})}}return t}async exportPipeline(e){let t=this.savedPipeline(e);if(!t)return{exported:!1,pipelineId:e,code:"NOT_SAVED",message:"No pipeline is saved under this id: save the pipeline, then export it. An export takes the pipeline as saved."};let r=this.sandforgeVersion??this.deps.infraServices?.checkpointFiles?.sandforgeVersion;if(r===void 0)return{exported:!1,pipelineId:e,code:"VERSION_UNKNOWN",message:"This SandForge does not say which release it is, which the file and its launchers name: nothing was exported."};let{stepExecutor:n,orchestrator:o}=await this.buildRunParts(void 0,t),i=new Set((t.variables??[]).map(a=>a.name));return zS({...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=$(iw,e,"pipeline:error",this.deps);if(t)try{let r=await this.exportPipeline(t.pipelineId),n=A(this.deps,e,"pipeline:export:response",r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} ${r.exported?`exported ${r.fileName}`:`refused ${r.code}`}`)}catch(r){T(this.deps,"pipeline:export","pipeline:error",e,r)}}handlePipelineTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=A(this.deps,e,"pipeline:templates:response",{templates:sA});this.deps.broker.postToWebview(t),this.deps.log("[TX] pipeline:templates:response")}async handlePipelineList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.deps.configStore.getByCategory("pipelines"),r=Object.entries(t).map(([a,d])=>({key:a,...d})),n=await this.triggerScheduler().statuses();await this.revokeVoidGrants();let o=this.outsideStatuses(Object.values(t)),i=A(this.deps,e,"pipeline:list:response",{pipelines:r,triggers:n,...o.length>0?{outside:o}:{}});this.deps.broker.postToWebview(i),this.deps.log(`[TX] pipeline:list:response (${r.length} pipelines)`)}catch(t){T(this.deps,"pipeline:list","pipeline:error",e,t)}}commandLineRuns(){try{return this.commandLineHistory??=LS(this.pipelinesRoot(),this.deps.log),this.commandLineHistory.read()}catch(e){return this.deps.log(`[WARN] the pipeline runs of the command line are not listed: ${I(e)}`),[]}}handlePipelineHistory(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.deps.configStore.getByCategory("pipeline-history"),n=[...Object.values(t).map(i=>{let a={...i};return delete a.pipeline,a}),...this.commandLineRuns()].sort((i,a)=>{let d=typeof i.timestamp=="number"?i.timestamp:0;return(typeof a.timestamp=="number"?a.timestamp:0)-d}),o=A(this.deps,e,"pipeline:history:response",{history:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] pipeline:history:response (${n.length} entries)`)}catch(t){T(this.deps,"pipeline:history","pipeline:error",e,t)}}handlePipelineSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=$(aw,e,"pipeline:error",this.deps);if(!t)return;let r=t,n=r.config.runsOutside;if(n!==void 0){let u=sw.safeParse(n);if(!u.success){T(this.deps,"pipeline:save","pipeline:error",e,new Error(`The pipeline was not saved: runsOutside.${bl(u.error)}`),{code:"INVALID_PAYLOAD",retryable:!1});return}}let o=r.id||crypto.randomUUID(),i=`pipeline:saved:${o}`;this.deps.configStore.set(i,{...r.config,id:o,savedAt:new Date().toISOString()},"pipelines");let a=Array.isArray(r.config.steps)?r.config.steps:[],d=this.rewindGrants().revokeChanged(o,a.map(u=>({...typeof u.id=="string"?{id:u.id}:{},...u.type==="rewind"?{type:"rewind"}:{},config:typeof u.config=="object"&&u.config!==null?u.config:{}})));for(let u of d)this.deps.log(`[INFO] pipeline:save ${o}: the confirmation of Rewind step ${u} was taken back, since the save changed what it does`);this.scheduler?.reload();let c=A(this.deps,e,"pipeline:save:response",{success:!0,id:o});this.deps.broker.postToWebview(c),this.deps.log(`[TX] pipeline:save:response id=${o}`)}catch(t){T(this.deps,"pipeline:save","pipeline:error",e,t)}}handlePipelineDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=$(dw,e,"pipeline:error",this.deps);if(!t)return;let{id:r}=t,n=this.claims.hold(r,{startedAt:new Date().toISOString(),triggeredBy:"manual"});if("busy"in n){let a=this.deps.configStore.get(`pipeline:saved:${r}`),d=typeof a?.name=="string"?a.name:r;T(this.deps,"pipeline:delete","pipeline:error",e,new Error(`Pipeline "${d}" is running: the run started ${uA[n.busy.triggeredBy]} at ${n.busy.startedAt} has not ended. Delete it once that run has ended.`),{code:"PIPELINE_RUNNING",retryable:!0});return}let o;try{o=this.deps.configStore.delete(`pipeline:saved:${r}`);let a=this.rewindGrants().revokePipeline(r);a.length>0&&this.deps.log(`[INFO] pipeline:delete ${r}: the confirmations of Rewind steps ${a.join(", ")} were taken back`)}finally{n.release()}this.scheduler?.reload();let i=A(this.deps,e,"pipeline:delete:response",{id:r,deleted:o});this.deps.broker.postToWebview(i),this.deps.log(`[TX] pipeline:delete:response id=${r} deleted=${o}`)}catch(t){T(this.deps,"pipeline:delete","pipeline:error",e,t)}}handleMarketplaceList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{if(!this.pipelineMarketplace)throw new Error("Pipeline Marketplace not available.");let t=$(gw,e,"pipeline:error",this.deps);if(t===null)return;let r;t?.query?r=this.pipelineMarketplace.search(t.query):t?.category?r=this.pipelineMarketplace.getByCategory(t.category):r=this.pipelineMarketplace.getTemplates();let n=A(this.deps,e,"marketplace:list:response",{success:!0,templates:r.map(o=>({id:o.id,name:o.name,description:o.description,category:o.category,author:"SandForge",stepTypes:o.steps.map(i=>i.type),steps:o.steps.map(i=>({name:i.name,type:i.type,config:i.config,...i.condition?{condition:i.condition}:{}}))}))});this.deps.broker.postToWebview(n)}catch(t){this.deps.log(`[ERR] marketplace:list: ${I(t)}`);let r=A(this.deps,e,"marketplace:list:response",{success:!1,error:I(t)});this.deps.broker.postToWebview(r)}}handleMarketplaceInstall(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(fw,e,"pipeline:error",this.deps);if(!t)return;let{templateId:r}=t;try{if(!this.pipelineMarketplace)throw new Error("Pipeline Marketplace not available.");if(!this.pipelineMarketplace.getById(r))throw new Error(`Template "${r}" not found.`);let o=this.pipelineMarketplace.exportTemplate(r),i;try{i=JSON.parse(o)}catch{throw new Error(`Template "${r}" contains invalid JSON.`)}let a=i.id;typeof a=="string"&&a!==""&&this.rewindGrants().revokePipeline(a);let d=A(this.deps,e,"marketplace:install:response",{success:!0,pipeline:i});this.deps.broker.postToWebview(d)}catch(n){this.deps.log(`[ERR] marketplace:install: ${I(n)}`);let o=A(this.deps,e,"marketplace:install:response",{success:!1,error:I(n)});this.deps.broker.postToWebview(o)}}};var is=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 fo(s,e){return e.aborted?(s.catch(()=>{}),Promise.reject(lA())):new Promise((t,r)=>{let n=()=>r(lA());e.addEventListener("abort",n,{once:!0}),s.then(o=>{e.removeEventListener("abort",n),t(o)},o=>{e.removeEventListener("abort",n),r(o)})})}function lA(){return Object.assign(new Error("Stopped before its answer came."),{code:"CANCELLED"})}var pA=200,Ag=50,Tg="ai.enabled",Eg="ai.errorResolution",gA="ai:conversations:index",fA="ai",Mc="ai.anthropic.key",FN=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"]),Lc=class{constructor(e){this.deps=e}deps;aiAssistant;asking=new is;setAIAssistant(e){this.aiAssistant=e}async handle(e){if(!FN.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(gA)??[]}saveIndex(e){this.deps.configStore.set(gA,e,fA)}loadConversation(e){return this.deps.configStore.get(this.conversationKey(e))}saveConversation(e){this.deps.configStore.set(this.conversationKey(e.id),e,fA),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<=Ag)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-Ag).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 (${Ag} 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<=pA)return e;let t=e.filter(o=>o.role==="system"),r=e.filter(o=>o.role!=="system"),n=pA-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=$(Ay,e,"ai:error",this.deps);if(!t)return;let r=t,n=this.aiAssistant;if(!n){let i=A(this.deps,e,"ai:error",{message:"AI is not configured. Set your API key in Settings > AI."});this.deps.broker.postToWebview(i);return}this.restoreConversationIfNeeded(r.conversationId);let o=this.asking.begin(r.conversationId);try{let i=await n.chat(r.conversationId,r.message,{signal:o.signal}),a=n.getConversation(r.conversationId);a&&this.persistConversationFromMemory(a);let d=A(this.deps,e,"ai:chat:response",{conversationId:r.conversationId,message:{id:i.id,role:i.role,content:i.content,timestamp:i.timestamp,tokenCount:i.tokenCount},...a?{title:a.title}:{}});this.deps.broker.postToWebview(d),this.deps.log("[TX] ai:chat:response")}catch(i){if(o.signal.aborted){let c=A(this.deps,e,"ai:chat:response",{conversationId:r.conversationId,code:"CANCELLED"});this.deps.broker.postToWebview(c),this.deps.log("[TX] ai:chat:response cancelled");return}let a=I(i),d=A(this.deps,e,"ai:error",{message:a});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ai:error: ${a}`)}finally{o.end()}}handleChatCancel(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ua,e,"ai:error",this.deps);t&&this.asking.abort(t.conversationId)}handleConversationCreate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Ty,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=$(ua,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=$(ua,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(Mc),r=A(this.deps,e,"ai:status:response",{enabled:!!this.aiAssistant&&t,provider:this.aiAssistant?Pf:"none",model:this.aiAssistant?$f(this.deps.services?.getSandforgeSetting?.("ai.model",Cf.MODEL)):"",budget:this.aiAssistant?this.deps.services?.sessionBudget?.getState():void 0,hasKey:t,errorResolution:this.deps.services?.getSandforgeSetting?.(Eg,!0)??!0});this.deps.broker.postToWebview(r),this.deps.log("[TX] ai:status:response")}async enableAIFeature(){await this.writeSetting("ai:save-key",Tg,!0)}async writeSetting(e,t,r){if(!this.deps.services?.setSandforgeSetting)return this.deps.log(`[WARN] ${e}: no settings backend \u2014 sandforge.${t} left as-is.`),!1;try{return await this.deps.services.setSandforgeSetting(t,r),!0}catch(n){return this.deps.log(`[ERR] ${e}: writing sandforge.${t} failed: ${I(n)}`),!1}}async rebuildAIStack(e="ai:save-key"){let t=this.deps.services?.reinitAI;if(!t){this.deps.log(`[WARN] ${e}: no AI rebuild wired \u2014 the change applies after a reload.`);return}try{await t()}catch(r){this.deps.log(`[ERR] ${e}: rebuilding the AI stack failed: ${I(r)}`)}}async handleSaveKey(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Ey,e,"ai:error",this.deps);if(!t)return;let{apiKey:r,errorResolution:n}=t;try{let o=await this.deps.secretVault.hasSecret(Mc);await this.deps.secretVault.storeSecret(Mc,r),(!o||n!==void 0)&&await this.writeSetting("ai:save-key",Eg,n===!0),await this.enableAIFeature(),await this.rebuildAIStack();let i=A(this.deps,e,"ai:save-key:response",{success:!0});this.deps.broker.postToWebview(i),this.deps.log("[TX] ai:save-key:response success"),await this.postStatus(e)}catch(o){let i=I(o);this.deps.log(`[ERR] ai:save-key: ${i}`);let a=A(this.deps,e,"ai:save-key:response",{success:!1,error:i});this.deps.broker.postToWebview(a)}}async handleSettings(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Py,e,"ai:error",this.deps);if(!t)return;let r=[];t.errorResolution!==void 0&&r.push([Eg,t.errorResolution]),t.enabled!==void 0&&r.push([Tg,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(Mc);let t=this.deleteAllConversations();await this.writeSetting("ai:remove-key",Tg,!1),await this.rebuildAIStack("ai:remove-key");let r=A(this.deps,e,"ai:remove-key:response",{success:!0,conversationsDeleted:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ai:remove-key:response conversations=${t}`),await this.postStatus(e)}catch(t){let r=I(t);this.deps.log(`[ERR] ai:remove-key: ${r}`);let n=A(this.deps,e,"ai:remove-key:response",{success:!1,error:r});this.deps.broker.postToWebview(n)}}persistConversationFromMemory(e){let t=e.messages.map(n=>({id:n.id,role:n.role,content:n.content,timestamp:n.timestamp,tokenCount:n.tokenCount})),r={id:e.id,title:e.title,messages:this.pruneMessages(t),createdAt:e.createdAt,updatedAt:e.updatedAt};this.saveConversation(r)}};var _N=new Set(["ai:anomaly-scan"]),Fc=class{constructor(e){this.deps=e}deps;ruleModules;setRuleModules(e){this.ruleModules=e}async handle(e){return _N.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=$(Cy,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 q(r,this.deps.orgRegistry,this.deps.orgManager),a=wt(n),d=o??mn.anomalyScan,c=`SELECT FIELDS(ALL) FROM ${a} LIMIT ${d}`,u=await qh(i,a,c),l=u.records,g={records:l,fields:Object.keys(l[0]??{})},p=this.ruleModules.anomalyDetector.detectAnomalies(g,n),f=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:l.length,limit:u.limit??d}});this.deps.broker.postToWebview(f)}catch(i){this.deps.log(`[ERR] ai:anomaly-scan: ${I(i)}`);let a=A(this.deps,e,"ai:anomaly-scan:response",{success:!1,error:I(i)});this.deps.broker.postToWebview(a)}}};function hA(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"")}function UN(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 HN(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=hA(r);n&&!e.has(n)&&e.set(n,t.name)}return e}function mA(s,e,t=5){if(t<=0)return[];let r=HN(e),n=s.split(/[^A-Za-z0-9_]+/).filter(Boolean),o=[],i=new Set;for(let a=0;a<n.length;a++){let d=Math.min(4,n.length-a);for(let c=d;c>=1;c--){let u=n.slice(a,a+c).join(""),l=UN(hA(u)).map(g=>r.get(g)).find(g=>g!==void 0);if(l){if(!i.has(l)&&(i.add(l),o.push(l),o.length>=t))return o;a+=c-1;break}}}return o}var BN={sync:"Sync",seed:"Seed",dataops:"DataOps"};function yA(s){if(s.code==="STEP_NOT_RUNNABLE")return`A pipeline cannot run a ${s.stepType} step, so the draft leaves it out.`;let e=BN[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 qN=new Set(["WHERE","USING","WITH","GROUP","ORDER","LIMIT","OFFSET","FOR","UPDATE"]),WN=new Set(["WITH","GROUP","ORDER","LIMIT","OFFSET","FOR","UPDATE"]),zN=new Set(["AND","OR","NOT","WHERE"]),GN=/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/,JN=/^([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)(?:\s+[A-Za-z_]\w*)?$/,VN=/^[A-Za-z_]\w*\s*\(([^()]*)\)(?:\s+[A-Za-z_]\w*)?$/,KN=/([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*(?:!=|<>|<=|>=|=|<|>|\bNOT\s+IN\b|\bIN\b|\bLIKE\b|\bINCLUDES\b|\bEXCLUDES\b)/gi;function XN(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 wA=/\(\s*SELECT\b/iy;function YN(s){let e="",t=0;for(;t<s.length;){if(wA.lastIndex=t,s[t]!=="("||!wA.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 QN(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 ZN(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 ej(s){let e=JN.exec(s);if(e)return e[1];let t=VN.exec(s);if(t){let r=t[1].trim();return GN.test(r)?r:null}return null}function tj(s){let e=YN(XN(s)).replace(/\bTYPEOF\b[\s\S]*?\bEND\b/gi,"()"),t=QN(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&&!qN.has(d)&&!c.includes(",")&&i.add(d);let u=[],l=e.slice(t[0].end,t[n].start);for(let h of ZN(l)){let m=ej(h.trim());m&&u.push(m)}let g=t.findIndex((h,m)=>m>n+1&&h.word.toUpperCase()==="WHERE");if(g>=0){let h=t.findIndex((y,R)=>R>g&&WN.has(r(R)??"")),m=e.slice(t[g].end,h<0?e.length:t[h].start);for(let y of m.matchAll(KN))zN.has(y[1].toUpperCase())||u.push(y[1])}let p=new Set,f=[];for(let h of u){let[m,...y]=h.split("."),R=y.length>0&&i.has(m.toUpperCase())?y.join("."):h,S=R.toUpperCase();p.has(S)||(p.add(S),f.push(R))}return{objectApiName:o,fieldRefs:f}}async function bA(s,e){let t=tj(s);if(!t)return{fieldsChecked:0,problems:[{kind:"no-from"}]};let r=t.objectApiName.toLowerCase(),n=e.catalog.find(u=>u.name.toLowerCase()===r);if(!n)return{rootObject:t.objectApiName,fieldsChecked:0,problems:[{kind:"object-missing",object:t.objectApiName}]};let o;try{o=await e.describe(n.name)}catch(u){return{rootObject:n.name,rootLabel:n.label,fieldsChecked:0,problems:[{kind:"describe-failed",object:n.name,detail:I(u)}]}}let i=new Set(o.fields.map(u=>u.name.toLowerCase())),a=new Set(o.fields.flatMap(u=>u.relationshipName?[u.relationshipName.toLowerCase()]:[])),d=[],c=new Set;for(let u of t.fieldRefs){let[l,...g]=u.split(".");g.length===0?i.has(l.toLowerCase())||d.push({kind:"field-missing",object:n.name,field:l}):!a.has(l.toLowerCase())&&!c.has(l.toLowerCase())&&(c.add(l.toLowerCase()),d.push({kind:"relationship-missing",object:n.name,relationship:l}))}if(d.length===0)try{await e.explain(s)}catch(u){d.push({kind:"org-refused",detail:I(u)})}return{rootObject:n.name,rootLabel:o.label||n.label,fieldsChecked:t.fieldRefs.length,problems:d}}function Pg(s){return oj().text(s)}var nj=new Set;function oj(){let s=Jv(),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=Vv({text:o},nj,t).text;return typeof i=="string"?i:o},n=o=>typeof o=="string"?r(o):Array.isArray(o)?o.map(n):o!==null&&typeof o=="object"?Object.fromEntries(Object.entries(o).map(([i,a])=>[i,n(a)])):o;return{text:r,deep:o=>n(o)}}var Bt=zu,Vt=zu.text,RA="{firstName}, {lastName}, {company}, {email} and {caseSubject}";var VJ=[`- "id" and each topic's "key": lower-case letters and digits in words joined by single hyphens, starting with a letter, ${Bt.maxKeyLength} characters at most.`,`- "name": at most ${Vt.name} characters. "businessContext": what the company does and who its customers are, in two or three sentences, at most ${Vt.businessContext} characters.`,`- "customers": "count" is 10 unless the scenario asks for another number, at least the number of topics and at most ${Bt.maxCustomers}; "industry" is the customers' industry as an Account Industry value of Salesforce (Retail, Telecommunications, Technology...), at most ${Vt.industry} characters.`,`- "topics": ${Bt.topics.min} to ${Bt.topics.max}, five unless the scenario calls for more or fewer: the subjects customers write to support about. "label": at most ${Vt.label} characters.`,`- "utterances": ${Bt.utterances.min} to ${Bt.utterances.max} a topic, two unless it needs more: what a customer whose case on the topic is still open says to the agent ("text"), and what the agent should do, in plain words ("expectedOutcome"), each at most ${Vt.utterance} characters. They may name the customer and the case with ${RA}, 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 ${Vt.articleTitle} characters, "summary" at most ${Vt.articleSummary}, "body" plain-text paragraphs of 600 to 1,500 characters. No placeholder.`,`- "outOfScope": ${Bt.outOfScope.min} to ${Bt.outOfScope.max}, three unless more are useful: what a customer may say that no topic covers, and that the agent should decline ("expectedOutcome"), each at most ${Vt.utterance} characters. No placeholder.`,"- No word in braces but the placeholders named here, where they are allowed."];var KJ=[`- "article": what the agent answers the topic from. "title" at most ${Vt.articleTitle} characters and none of the titles above; "summary" at most ${Vt.articleSummary}; "body" plain-text paragraphs of 1,200 to 3,000 characters, at most ${Vt.articleBody}: the policy or the procedure, with the figures, delays and conditions customers ask about. No placeholder in the article.`,`- "facts": ${Bt.facts.min} to ${Bt.facts.max}, each a sentence of the body copied word for word, at most ${Vt.fact} characters: what an answer drawn from the article has to say.`,`- "caseTemplates": ${Bt.caseTemplates.min} to ${Bt.caseTemplates.max}, two unless the topic needs more: cases customers open on the topic. "subject" at most ${Vt.caseSubject} characters, and may name {firstName}, {lastName}, {company} and {email}; "description" what the customer writes, under 600 characters; "priority" is High, Medium or Low; "origin" is Phone, Email or Web; "followUp" what the customer writes again while the case is open, under 300 characters; "resolution" ${Bt.resolutionSteps.min} to ${Bt.resolutionSteps.max} steps, each a comment of the agent who resolved the case, under 400 characters. "description", "followUp" and "resolution" may name ${RA}.`,"- No word in braces but the placeholders named here, where they are allowed."];var sj=new Set(["ai:forge-plan","ai:generate-pipeline","ai:scenario-draft","ai:tool:cancel"]),Cg={success:!1,code:"CANCELLED"},vA="AI not configured. Set your API key in Settings > AI.";function ij(s){switch(s){case"Production":return"production";case"Sandbox":return"sandbox";case"Developer":return"developer";case"Scratch":return"scratch";default:return"production"}}var _c=class{constructor(e){this.deps=e}deps;aiModules;drafting=new is;describeGlobalCache=new Gs({defaultTtl:5*6e4,maxSize:16,maxSizeBytes:50*1024*1024});describeCache=new Gs({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(!sj.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=$(Dy,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=$($y,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:vA}));return}let a=await fo(this.connect(r),o.signal),d=await fo(this.loadCatalog(r,a),o.signal),c=t.soql??"",u;if(n!==void 0&&i){let{result:g}=await this.draft(i,n,r,a,d,o.signal);c=g.soql,u=g.explanation}let l=await fo(bA(c,{catalog:d,describe:async g=>{let p=await this.describeObject(r,a,g);return{name:p.apiName,label:p.label,fields:p.fields.map(f=>({name:f.apiName,relationshipName:f.relationshipName}))}},explain:g=>a.request(`/query/?explain=${encodeURIComponent(g)}`)}),o.signal);this.deps.broker.postToWebview(A(this.deps,e,"ai:forge-plan:response",{success:l.problems.length===0,soql:c,...u?{explanation:u}:{},...l.rootObject?{rootObject:l.rootObject}:{},...l.rootLabel?{rootLabel:l.rootLabel}:{},fieldsChecked:l.fieldsChecked,problems:l.problems}))}catch(i){if(o.signal.aborted){this.deps.broker.postToWebview(A(this.deps,e,"ai:forge-plan:response",{...Cg})),this.deps.log("[TX] ai:forge-plan:response cancelled");return}this.deps.log(`[ERR] ai:forge-plan: ${I(i)}`),this.deps.broker.postToWebview(A(this.deps,e,"ai:forge-plan:response",{success:!1,error:I(i)}))}finally{o.end()}}async connect(e){return await q(e,this.deps.orgRegistry,this.deps.orgManager)}async draft(e,t,r,n,o,i){let a=mA(t,o),d=await fo(this.describeObjects(r,n,a),i),c={objects:d.length>0?d:o.map(l=>({apiName:l.name,label:l.label,fields:[]}))};return{result:await fo(e.generateSOQL(t,c,{signal:i}),i),described:d}}async loadCatalog(e,t){let r=this.describeGlobalCache.get(e);if(r)return r;let o=(await t.describeGlobal()).sobjects.filter(i=>i.queryable!==!1).map(i=>({name:i.name,label:i.label,labelPlural:i.labelPlural,queryable:i.queryable}));return this.describeGlobalCache.set(e,o),o}async describeObjects(e,t,r){let n=[];for(let o of r)try{n.push(await this.describeObject(e,t,o))}catch(i){this.deps.log(`[WARN] ai:nl2soql describe ${o}: ${I(i)}`)}return n}async describeObject(e,t,r){let n=`${e}::${r}`,o=this.describeCache.get(n);if(o)return o;let i=await t.describe(r),a={apiName:i.name,label:i.label??i.name,fields:i.fields.map(d=>({apiName:d.name,label:d.label??d.name,type:d.type,...d.relationshipName?{relationshipName:d.relationshipName}:{}}))};return this.describeCache.set(n,a),a}async handleGeneratePipeline(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(xy,e,"ai:error",this.deps);if(!t)return;let{description:r,orgIds:n}=t,o=this.drafting.begin(e.id);try{if(!this.aiModules?.pipelineGenerator)throw new Error("AI not configured. Set your API key in Settings > AI to enable this feature.");let i=(n??[]).map(u=>{let l=this.deps.orgManager.getOrg(u);return{orgId:u,alias:l?.alias??u,type:ij(l?.orgType)}}),{suggestions:a=[],...d}=await fo(this.aiModules.pipelineGenerator.generatePipeline(r,i,{signal:o.signal}),o.signal);if(d.steps.length===0&&a.length>0){let u=a.map(yA).join(" ");this.deps.log(`[ERR] ai:generate-pipeline: ${u}`),this.deps.broker.postToWebview(A(this.deps,e,"ai:generate-pipeline:response",{success:!1,error:u,suggestions:a}));return}if(d.steps.length===0)throw new Error("The AI returned a pipeline with no steps, so there is nothing to load. Name the operations it should run, for example: back up Account daily, then compare dev with uat.");let c=A(this.deps,e,"ai:generate-pipeline:response",{success:!0,pipeline:d,...a.length>0?{suggestions:a}:{}});this.deps.broker.postToWebview(c)}catch(i){if(o.signal.aborted){this.deps.broker.postToWebview(A(this.deps,e,"ai:generate-pipeline:response",{...Cg})),this.deps.log("[TX] ai:generate-pipeline:response cancelled");return}this.deps.log(`[ERR] ai:generate-pipeline: ${I(i)}`);let a=A(this.deps,e,"ai:generate-pipeline:response",{success:!1,error:I(i)});this.deps.broker.postToWebview(a)}finally{o.end()}}async handleScenarioDraft(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Ny,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:Pg(t.text)});return}let n=this.aiModules?.scenarioDrafter;if(!n){r({success:!1,code:"AI_NOT_CONFIGURED",error:vA,sentText:Pg(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(aj(i))}catch(i){this.deps.log(`[ERR] ai:scenario-draft: ${I(i)}`),r({success:!1,error:I(i)})}finally{o.end()}}};function aj(s){switch(s.kind){case"complete":return{success:!0,sentText:s.sentText,pack:s.pack};case"stopped":return{...Cg,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 dj=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"]),Uc=class{chatHandler;analysisHandler;toolsHandler;subHandlers;constructor(e){this.chatHandler=new Lc(e),this.analysisHandler=new Fc(e),this.toolsHandler=new _c(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(!dj.has(e.type))return!1;for(let t of this.subHandlers)if(await t.handle(e))return!0;return!1}};function SA(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 kA(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 cj=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"]),uj=10,$g=3e4,IA=6e4;function AA(s){return`autopilot:${s}`}var xg=(s,e)=>e==="insert"||e==="update",Hc={code:"AUTOPILOT_NOT_READY",message:"Autopilot module is not initialized."},as={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."},lj=new Set(["autopilot:pause","autopilot:resume","autopilot:skip-node"]),Bc=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-GOOVPVWX.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(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!==AA(r))}async handle(e){if(!cj.has(e.type))return!1;switch(e.type){case"autopilot:list-objects":return await this.handleListObjects(e),!0;case"autopilot:count-objects":return await this.handleCountObjects(e),!0;case"autopilot:scan-schema":return await this.handleScanSchema(e),!0;case"autopilot:generate-plan":return await this.handleGeneratePlan(e),!0;case"autopilot:fit-plan":return await this.handleFitPlan(e),!0;case"autopilot:fit-undo":return await this.handleFitUndo(e),!0;case"autopilot:execute":return await this.handleExecute(e),!0;case"autopilot:pause":return this.handlePause(e),!0;case"autopilot:resume":return this.handleResume(e),!0;case"autopilot:skip-node":return this.handleSkipNode(e),!0;case"autopilot:compliance-report":return this.handleComplianceReport(e),!0;default:return!1}}refuseNotReady(e){T(this.deps,e.type,"autopilot:error",e,new Error(Hc.message),{code:Hc.code}),lj.has(e.type)&&Ie(this.deps,"error","Autopilot",Hc.message,{code:Hc.code})}resolveCurrentOperation(){return this.currentOperationId!==void 0?this.operations.get(this.currentOperationId):void 0}evictOldOperations(){for(;this.operations.size>uj;){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=$(hy,e,"autopilot:error",this.deps);if(t)try{let r=await q(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),o=await this.orchestrator.listObjects(r,n,t.includeStandardObjects),i=A(this.deps,e,"autopilot:objects-listed",{objects:o});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} count=${o.length}`)}catch(r){T(this.deps,"autopilot:list-objects","autopilot:error",e,r)}}async handleCountObjects(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=$(my,e,"autopilot:error",this.deps);if(t)try{let r=await q(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await this.orchestrator.countObjects(r,t.objectApiNames),o=A(this.deps,e,"autopilot:objects-counted",{counts:Object.fromEntries(n)});this.deps.broker.postToWebview(o)}catch(r){T(this.deps,"autopilot:count-objects","autopilot:error",e,r)}}async handleScanSchema(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=$(yy,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 q(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),a=await q(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),d=await this.orchestrator.scanSchemas(i,a,{selectedObjects:r.selectedObjects,includeStandardObjects:r.includeStandardObjects,...r.maxDepth!==void 0?{maxDepth:r.maxDepth}:{},...r.maxObjects!==void 0?{maxObjects:r.maxObjects}:{},maxRecordsPerObject:this.maxRecordsPerObject()});o.scanResult=d;let c=this.orchestrator.buildGraph(d);o.graph=c;let u=A(this.deps,e,"autopilot:schema-result",{graph:c});this.deps.broker.postToWebview(u)}catch(i){this.operations.delete(e.id),this.currentOperationId===e.id&&(this.currentOperationId=n),T(this.deps,"autopilot:scan-schema","autopilot:error",e,i),Ie(this.deps,"error","Autopilot",`Schema scan failed: ${I(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=$(wy,e,"autopilot:error",this.deps);if(!r)return;let n=r;try{let o=n.complianceFramework!=="none"&&t.scanResult?yR(this.deps.infraServices?.piiDetector??new Ta,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){T(this.deps,"autopilot:generate-plan","autopilot:error",e,o),Ie(this.deps,"error","Autopilot",`Plan generation failed: ${I(o)}`)}}async sendPlanReady(e,t,r,n){let{plan:o,graph:i}=t.fit??t,a=t.fit?.scan??t.scanResult;if(!o||!i)return;let d;try{d=a?await this.planWriteGate(t.targetOrgId,Ul(o,a.recordCounts,a.personAccounts),r??await this.readTargetDataStorage(t.targetOrgId)):void 0}catch(u){this.deps.log(`[WARN] ${e.type}: what the plan comes to against the target could not be told (${I(u)})`)}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 ER(t,r,()=>this.readApiBudgetOf(e),n);return SA(t,Or(t,r),o)}refuseFit(e,t,r,n){T(this.deps,e.type,"autopilot:error",e,new Error(r),{code:t,...n?{extraPayload:n}:{}})}async handleFitPlan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let{orchestrator:t}=this;if(!t){this.refuseNotReady(e);return}let r=$(Ry,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,_o.NO_PLAN,"No execution plan available. Run generate-plan first.");return}let{targetOrgId:c}=n;if(this.writingTargets.has(c)){this.refuseFit(e,as.code,as.message);return}try{let u=await this.readTargetAutomation(c,o),l=r.muteAutomation===!0?await this.planMute(c,u).catch(R=>{if(!Dt(R))throw R}):void 0,g=await this.readTargetDataStorage(c),p=r.checkpointFirst!==void 0?await this.checkpointFirstOf(e,c,o,r.checkpointFirst,{read:u,...l?{mute:l}:{}},new AbortController().signal):void 0,f=mR({storage:g,...r.mode.withinMB!==void 0?{withinMB:r.mode.withinMB}:{},api:"unread"in g?await this.readApiBudgetOf(c).catch(R=>({unread:I(R)})):g.dailyApiRequests??{unread:"the target's /limits did not list them"},otherRequests:Fo(p&&"estimate"in p?p.estimate:void 0)});if("unread"in f){this.refuseFit(e,_o.STORAGE_UNREAD,`The plan cannot be fitted: the target's data storage left could not be read (${f.unread}). Give the most MB it may use to fit it to that.`,{reason:f.unread});return}let h=await q(n.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),m=await q(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:f,automation:u,...l?.plan?{mutePlan:l.plan}:{},describeLookups:async R=>IR((await m.describe(R)).fields)})}catch(R){let S=I(R);this.refuseFit(e,_o.READ_REFUSED,`The plan could not be fitted: the source refused a read of it (${S}).`,{reason:S});return}if(n.plan!==o||this.currentOperationId!==n.id||this.writingTargets.has(c)){this.refuseFit(e,_o.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,g);return}y.report.cannotFit===void 0&&(n.fit=void 0),await this.sendPlanReady(e,n,g,y.report)}catch(u){T(this.deps,"autopilot:fit-plan","autopilot:error",e,u)}}async handleFitUndo(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=this.resolveCurrentOperation();if(!t?.plan){this.refuseFit(e,_o.NO_PLAN,"No execution plan available. Run generate-plan first.");return}if(this.writingTargets.has(t.targetOrgId)){this.refuseFit(e,as.code,as.message);return}t.fit=void 0;try{await this.sendPlanReady(e,t)}catch(r){T(this.deps,"autopilot:fit-undo","autopilot:error",e,r)}}async handleExecute(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=this.resolveCurrentOperation();if(!t?.plan||!t.graph||!t.rules||!t.scanResult){Ie(this.deps,"error","Autopilot","No execution plan available. Run generate-plan first.");return}let r=$(by,e,"autopilot:error",this.deps);if(!r)return;let n=r,{rules:o,fit:i}=t,a=i?.plan??t.plan,d=i?.graph??t.graph,c=i?.scan??t.scanResult,u=this.deps.infraServices?.productionGuard;if(!u){Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:Re.code}),T(this.deps,"autopilot:execute","autopilot:error",e,new Error(Re.message),{code:Re.code});return}if(this.writingTargets.has(t.targetOrgId)){T(this.deps,"autopilot:execute","autopilot:error",e,new Error(as.message),{code:as.code});return}this.writingTargets.set(t.targetOrgId,e.id),this.runningRequests.add(e.id);try{await this.executeRun(e,t,{plan:a,graph:d,rules:o,scanResult:c,...i?{fit:i}:{}},n,u)}finally{this.writingTargets.delete(t.targetOrgId),this.runningRequests.delete(e.id)}}async executeRun(e,t,{plan:r,graph:n,rules:o,scanResult:i,fit:a},d,c){if(!this.orchestrator)return;let u=Array.from(i.recordCounts.values()).reduce((U,re)=>U+re,0),l=a?kA(a.report,u,[...t.scanResult?.recordCounts.values()??[]].reduce((U,re)=>U+re,0)):void 0,g=new AbortController,p=()=>{},f=new Promise((U,re)=>{p=ne=>ne===void 0?U():re(ne)});f.catch(()=>{}),this.registry?.register(e.id,"autopilot","Autopilot run",f,g);let h=this.deps.orgManager.getOrg(t.targetOrgId),m={orgId:t.targetOrgId,orgTier:Pe(h),operation:"insert",objectName:r.waves[0]?.objects[0]??"AutopilotData",recordCount:u,module:"autopilot"},{check:y,decision:R}=await et(c,m),S=R;if((R==="refused"||R==="declined")&&Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:R,...l?{fit:l}:{}}),R==="refused"){let U=bn(y.blockedReason??y.impactSummary);T(this.deps,"autopilot:execute","autopilot:error",e,U,{code:xt.blocked}),p(U);return}if(R==="declined"){let U="Operation cancelled by user (confirmation declined).";T(this.deps,"autopilot:execute","autopilot:error",e,new Error(U),{code:xt.declined}),p(new Error(U));return}let b=Ul(r,i.recordCounts,i.personAccounts),O,P;if(d.muteAutomation===!0)try{({mute:O,read:P}=await this.runMute(t.targetOrgId,r))}catch(U){if(!Dt(U))throw U;Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:S,...l?{fit:l}:{},code:U.code}),T(this.deps,"autopilot:execute","autopilot:error",e,U,{code:U.code}),p(U);return}let v;if(d.checkpointFirst!==void 0&&b.totalRows>0){P??=await this.readTargetAutomation(t.targetOrgId,r);let U=await this.checkpointFirstOf(e,t.targetOrgId,r,d.checkpointFirst,{read:P,mute:O},g.signal);if("refused"in U){Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:S,...l?{fit:l}:{},code:zs.CHECKPOINT_REFUSED});let re=new Error(U.refused);T(this.deps,"autopilot:execute","autopilot:error",e,re,{code:zs.CHECKPOINT_REFUSED}),p(re);return}v=U}b.totalRows>0&&(P??=await this.readTargetAutomation(t.targetOrgId,r));let w=await this.targetEmails(t.targetOrgId,r,b,O?O.automation:P),C=new Set(b.objects.map(({objectApiName:U})=>U)),k=(U,re)=>C.has(U)&&xg(U,re),E=ye(h,t.targetOrgId),x=ye(this.deps.orgManager.getOrg(t.sourceOrgId),t.sourceOrgId),V=P?await dr({read:P,...O?.plan?{plan:O.plan}:{},writes:k,readDeliverability:async()=>m.orgTier==="production"?zt:Gt(await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager)),accepted:!1,target:E,run:"autopilot",keepsAddresses:d.keepContactPoints===!0}):void 0,H=await PR({plan:b,storage:await this.readTargetDataStorage(t.targetOrgId),readApiBudget:()=>this.readApiBudgetOf(t.targetOrgId),confirmAboveRecords:this.confirmAboveRecords(),emails:w.checks,...w.unread!==void 0?{emailsUncounted:w.unread}:{},org:E,orgTier:m.orgTier,confirm:U=>c.confirmRun(U),...v?{checkpointFirst:v}:{},readBack:TR(b),mute:Qr(O?.plan),...V?{runEmails:V}:{},source:{org:x,readApiBudget:()=>this.readApiBudgetOf(t.sourceOrgId)}});if(!H.go){Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:S,...l?{fit:l}:{},code:H.code,details:eo(H.emails)});let U=new Error(H.message),re="source"in H?H.source:void 0;T(this.deps,"autopilot:execute","autopilot:error",e,U,{code:zs[H.code],...re?{extraPayload:{source:{org:x,...re}}}:await this.fitOffer(t,H,b,v)}),p(U);return}this.liveTracker?.register(e.id,"autopilot","Autopilot run",u),this.executingOperations.add(t.id);let Y=new Map,B=!1,N=O?.muted,L=H.checkpoint,Q,K=!1,ae=U=>{B||(B=!0,Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:U,guard:S,objects:[...Y.values()],source:{origin:"org",orgId:t.sourceOrgId},...U==="stopped"?{code:rt}:{},...N?{muted:ut(N)}:{},...Q?.state==="taken"?{checkpointId:Q.checkpointId}:{},...l?{fit:l}:{},details:eo(H.emails)}))};try{d.grappeThreshold&&this.deps.log(`[GRAPPE] autopilot threshold set to ${d.grappeThreshold}`);for(let X of r.waves)for(let F of X.objects)this.sendNodeProgress(e,String(F),"processing",X.order);let U=new Map;for(let X of r.waves)for(let F of X.objects)U.set(String(F),X.order);let re=O?.prepared?await O.prepared.acquire(e.id).catch(X=>{if(!Dt(X))throw X;return X}):void 0;if(Dt(re)){L&&(Q=await this.settleCheckpoint(L,!1)),B=!0,Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:S,...l?{fit:l}:{},code:re.code}),this.liveTracker?.fail(e.id,re.message),T(this.deps,"autopilot:execute","autopilot:error",e,re,{code:re.code,...Q?{extraPayload:{checkpoint:Q}}:{}}),p(re);return}re&&(N=re.outcome);let ne=re?V?.afterLease(re.outcome,H.emails?.accepted===!0):void 0;if(re&&ne){N=await re.release(),L&&(Q=await this.settleCheckpoint(L,!1)),B=!0,Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:S,code:ne.code,muted:ut(N),details:eo(H.emails)});let X=Rb(ne.message,"autopilot","Untick Mute automation to be asked about them and run it all the same"),F=new Error(X);this.liveTracker?.fail(e.id,X),T(this.deps,"autopilot:execute","autopilot:error",e,F,{code:zs.EMAILS_NOT_ACCEPTED,...Q?{extraPayload:{checkpoint:Q}}:{}}),p(F);return}K=!0;let ce=await this.orchestrator.executePlan(r,n,o,i.recordCounts,X=>{let F=String(X.objectApiName);Y.set(F,{...mt(F),...X.type==="node-completed"?{created:X.successCount,failed:X.failureCount}:{created:X.partialSuccessCount,failed:X.failureCount??0}});let ee=[...Y.values()].reduce((_,de)=>_+de.created+de.failed,0);this.liveTracker?.updateProgress(e.id,u>0?Math.round(ee/u*100):0,ee,u,F),X.type==="node-completed"?this.sendNodeProgress(e,F,"completed",U.get(F)??0,{recordCount:X.successCount,failureCount:X.failureCount,linkedCount:X.linkedCount,refusals:X.refusals,apiCallsUsed:X.apiCallsUsed}):this.sendNodeProgress(e,F,"failed",U.get(F)??0,{recordCount:X.partialSuccessCount,failureCount:X.failureCount,linkedCount:X.linkedCount,refusals:X.refusals,error:X.errors[0]??`Execution failed for ${F}`})},g.signal,i.parentIds,{...d.keepContactPoints===!0?{keepContactPoints:!0}:{},...re?{lease:{assigned:re.outcome.assigned.length,giveBack:()=>re.release()}}:{},...a?{fit:a.run}:{}}).finally(async()=>{re&&(N=await re.release())});L&&(Q=await this.settleCheckpoint(L,ce.totalSuccess>0));let be=new Set(ce.completedObjects),Xe=new Set(ce.failedObjects),De=new Set(ce.skippedObjects),_e=new Set(ce.stoppedObjects??[]),z=[],se=0,te=[],he=[];for(let X of r.waves)for(let F of X.objects){let ee=String(F),_=ce.objectOutcomes?.[ee],de=ce.statuses?.[ee],Se=ce.lookups?.[ee],Ue=(_?.leftToThePlatform??[]).reduce((Be,Ve)=>Be+Ve.count,0),He={..._?{recordCount:_.written,failureCount:_.failed,linkedCount:_.linked,refusals:_.refusals,...Ue>0?{leftToThePlatform:Ue}:{},..._.currenciesReplaced?{currenciesReplaced:_.currenciesReplaced}:{},..._.pricesSettled?{pricesSettled:_.pricesSettled}:{},..._.recordTypeGiven?{recordTypeGiven:_.recordTypeGiven}:{},..._.cutSinceFit!==void 0?{cutSinceFit:_.cutSinceFit}:{},..._.sentAgainForALock?{sentAgainForALock:_.sentAgainForALock}:{}}:{},...de?{statusesApplied:de.applied,statusRefusals:de.refusals}:{},...Se?{lookupsFilled:Se.filled,lookupRefusals:Se.refusals}:{}};if(be.has(ee))this.sendNodeProgress(e,ee,"completed",X.order,{recordCount:i.recordCounts.get(ee)??0,failureCount:0,...He});else if(Xe.has(ee))this.sendNodeProgress(e,ee,"failed",X.order,{...He,error:ce.nodeErrors?.[ee]??`Execution failed for ${ee}`});else if(De.has(ee)){let Be=i.recordCounts.get(ee)??0;Y.set(ee,{...mt(ee),skipped:"counted",...Be>0?{notSent:Be}:{}}),this.sendNodeProgress(e,ee,"skipped",X.order,{recordCount:0,failureCount:0,...Be>0?{notSent:Be}:{}})}else if(_e.has(ee)){let Be=_?.notSent??0;se+=_?.heldForTheirTask??0,Y.set(ee,{...mt(ee),created:_?.written??0,failed:_?.failed??0,...Be>0?{notSent:Be}:{}}),this.sendNodeProgress(e,ee,"stopped",X.order,{...He,recordCount:_?.written??0,failureCount:_?.failed??0,...Be>0?{notSent:Be}:{}})}let ie=()=>Y.get(ee)??{...mt(ee),created:_?.written??0,failed:_?.failed??0},Ee=_?.lookupsLeftEmpty??0,Ne=_?.statusesNotGivenBack??0;if(Ee+Ne>0){let Be={...Ee>0?{lookupsLeftEmpty:Ee}:{},...Ne>0?{statusesNotGivenBack:Ne}:{}};z.push({objectApiName:ee,...Be}),Y.set(ee,{...ie(),...Be})}Se?.leftEmpty!==void 0&&(te.push({objectApiName:ee,records:Se.leftEmpty,refusals:Se.refusals}),Y.set(ee,{...ie(),lookupsNotFilled:Se.leftEmpty}));let st=de?.leftDraft??0;de&&st>0&&(he.push({objectApiName:ee,records:st,refusals:de.refusals}),Y.set(ee,{...ie(),statusesNotApplied:st}))}let D=OR(ce);ae(ce.stopped?ce.totalSuccess+ce.totalFailure>0?"cancelled":"stopped":D);let W=A(this.deps,e,"autopilot:completed",{status:D,totalRecords:ce.totalSuccess+ce.totalFailure+ce.totalSkipped,totalSuccessCount:ce.totalSuccess,totalFailureCount:ce.totalFailure,totalElapsedMs:ce.elapsedMs,totalApiCalls:0,...N?{mutedAutomation:N}:{},...Q?{checkpoint:Q}:{},...ce.cutSinceFit!==void 0?{cutSinceFit:ce.cutSinceFit}:{},...te.length>0?{lookupsNotFilled:te}:{},...he.length>0?{statusesNotApplied:he}:{},...ce.stopped?{stopped:!0,notWritten:ce.stoppedObjects??[],...z.length>0?{leftByStop:z}:{},...se>0?{emailsHeldForTheirTask:se}:{}}:{}});this.deps.broker.postToWebview(W),ce.stopped?this.liveTracker?.cancel(e.id):D==="failure"?this.liveTracker?.fail(e.id,ce.fatalError??"No record could be written."):D==="partial"?this.liveTracker?.partial(e.id):this.liveTracker?.complete(e.id),p()}catch(U){this.liveTracker?.fail(e.id,I(U)),p(U),L&&Q===void 0&&(Q=await this.settleCheckpoint(L,K)),ae("failure"),T(this.deps,"autopilot:execute","autopilot:error",e,U,Q?{extraPayload:{checkpoint:Q}}:void 0),Ie(this.deps,"error","Autopilot",`Execution failed: ${I(U)}`)}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),Li):5e4}confirmAboveRecords(){let e=this.deps.services?.getSandforgeSetting?.("safety.confirmAboveRecords",tn);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):tn}async readTargetDataStorage(e){try{let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return await new fe($g).withTimeout("autopilot:limits",()=>kr(cr(t,e)))}catch(t){return{unread:I(t)}}}setMuteLeases(e){this.muteLeases=e}muteLeases={};async runMute(e,t){let r=await this.readTargetAutomation(e,t);return{mute:await this.planMute(e,r),read:r}}planMute(e,t){return Ot(async()=>_t(await q(e,this.deps.orgRegistry,this.deps.orgManager)),t,{...this.muteLeases,writes:xg})}async readTargetAutomation(e,t){let r=this.targetAutomation;return new fe(IA).withTimeout("autopilot:automation",()=>r.read(e,Wa(t))).catch(n=>({unread:I(n)}))}async checkpointFirstOf(e,t,r,n,o,i){let a=this.beforeRunCheckpoints;if(!a)return{refused:Sr(new Error("SandForge's checkpoints are not set up in this window"))};let{read:d,mute:c}=o,u="objects"in d?Jr(d,c?.plan,xg):{firing:[]},l={module:"autopilot",orgId:t,operationId:e.id,written:Wa(r),running:u,request:n},g={operationId:AA(e.id)};try{return{estimate:await a.scope(l,g),take:f=>a.take(l,g,{planned:f,signal:i})}}catch(p){return{refused:Sr(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 (${I(n)})`),e}}async fitOffer(e,t,r,n){if(t.code!=="STORAGE_EXCEEDED"&&t.code!=="API_BUDGET_EXCEEDED")return{};let{targetOrgId:o}=e,{check:i}=t,a=this.deps.orgManager.getOrg(o),d={org:ye(a,o),estimateMB:i.estimateMB,...i.verdict==="unread"?{}:{remainingMB:i.remainingMB,maxMB:i.maxMB,...Ir(i)}};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 (${I(c)})`),{extraPayload:d}}}async readApiBudgetOf(e){let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return new fe($g).withTimeout("autopilot:limits",()=>ur(t))}async targetEmails(e,t,r,n){let o=this.targetAutomation,i=await AR({plan:r,objects:Wa(t),readAutomation:a=>n?"objects"in n?Promise.resolve(n):Promise.reject(new Error(n.unread)):new fe(IA).withTimeout("autopilot:automation",()=>o.read(e,a)),readLimits:async()=>{let a=await q(e,this.deps.orgRegistry,this.deps.orgManager);return new fe($g).withTimeout("autopilot:limits",()=>Ar(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){T(this.deps,"autopilot:pause","autopilot:error",e,t),Ie(this.deps,"error","Autopilot",`Pause failed: ${I(t)}`)}}handleResume(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}if(!this.hasExecutingOperation()){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){T(this.deps,"autopilot:resume","autopilot:error",e,t),Ie(this.deps,"error","Autopilot",`Resume failed: ${I(t)}`)}}handleSkipNode(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=$(vy,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){T(this.deps,"autopilot:skip-node","autopilot:error",e,n),Ie(this.deps,"error","Autopilot",`Skip failed: ${I(n)}`)}}handleComplianceReport(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=this.resolveCurrentOperation();if(!t?.profile||!t.rules||!t.scanResult){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){T(this.deps,"autopilot:compliance-report","autopilot:error",e,r),Ie(this.deps,"error","Autopilot",`Report generation failed: ${I(r)}`)}}};import{dirname as Mg}from"node:path";import{AsyncLocalStorage as pj}from"node:async_hooks";var gj=new pj;async function TA(s){let e=new Map;return{result:await gj.run(e,s),sent:e}}function EA(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 Dg from"node:path";var qc="forge:imported-templates",fj=10,PA="forge",hj=J({folder:j().min(1),templates:ve(hn()),replacing:ve(j())});function pn(s){if(typeof s!="object"||s===null||Array.isArray(s))return!1;let{id:e}=s;return typeof e=="string"&&e.length>0}function Ri(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 Ng(s,e){return Dg.resolve(s)===Dg.resolve(e)}function jg(s){let e=s.get(qc);if(!Array.isArray(e))return[];let t=[];for(let r of e){let n=hj.safeParse(r);if(!n.success)continue;let{folder:o,templates:i,replacing:a}=n.data;t.push({folder:o,templates:i.filter(pn),replacing:a})}return t}function Wc(s,e){return jg(s).find(t=>Ng(t.folder,e))}function CA(s,e,t,r){if(t.length===0)return;let n=jg(s),o=n.findIndex(d=>Ng(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(qc,n.slice(-fj),PA)}function $A(s,e){let t=jg(s).filter(r=>!Ng(r.folder,e));t.length>0?s.set(qc,t,PA):s.delete(qc)}function mj(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 yj(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:mj(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 xA(s){let{leftOut:e,...t}=s.graph,r=new Map;for(let l of e??[])r.set(l.reason,(r.get(l.reason)??0)+1);let n=[...r].map(([l,g])=>({reason:l,count:g})).sort((l,g)=>g.count-l.count||l.reason.localeCompare(g.reason)),{idRemapWithTheirRecord:o,sample:i,config:a,...d}=s,c=s.remapInJournal?void 0:o,u=a?.sample?{...a.sample}:void 0;return u&&delete u.plan,{...d,graph:{...t,edges:[],withoutEdges:!0},...a?{config:u?{...a,sample:u}:a}:{},...i?{sample:yj(i)}:{},...n.length>0?{leftOutCounts:n}:{},...c?{idRemapWithTheirRecord:c}:{}}}var DA="SELECT Id, Name, Username FROM User WHERE IsActive = true AND UserType = 'Standard' ORDER BY Name LIMIT 2001";function NA(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 Hg=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/,ho=j().min(1).max(128),bj=J({recordId:j().regex(Hg,"Invalid Salesforce record ID"),orgId:ho}),Hn=wf.superRefine((s,e)=>{if(s.inputMode!=="org"&&s.depth!=="all"&&s.sample===void 0)return;let t=Bu(s);t!==void 0&&e.addIssue({code:"custom",message:t,path:["inputMode"]});let r=Rj(s.sample);r!==void 0&&e.addIssue({code:"custom",message:r.message,path:r.path})});function Rj(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 vj=J({config:Hn}),Sj=J({graph:Br,config:Hn,anonymizationRules:Fi.optional(),files:Rf.optional(),retryOf:j().min(1).max(200).optional(),reviewSkipped:Ke().optional(),muteAutomation:Ke().optional(),checkpointFirst:rm.optional()}).superRefine((s,e)=>{let t=bf(s.config,s.files);t!==void 0&&e.addIssue({code:"custom",message:t,path:["files"]})});function kj(s,e){let t=s.check(e);return{check:t,decision:t.allowed?"allowed":"refused"}}var jA="FILES_NOT_ACCEPTED",MA="RETRY_UNAVAILABLE",Oj="GRAPH_WITHOUT_EDGES",Ij="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.",Aj="WHOLE_ORG_DIRECT",Tj="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.",Ej="WHOLE_ORG_REHEARSAL",Pj="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.",Cj="A clone of the whole org keeps its journal on disk, which could not be opened. Nothing was written.",Lg="JOURNAL_UNAVAILABLE",$j="RESUME_TARGET_UNREAD",gn=class extends Error{constructor(t,r){super(r);this.code=t;this.name="ForgeRunRefusal"}code};function LA(s){let e=s!==null&&typeof s=="object"&&"code"in s?String(s.code):void 0,t=e==="ENOSPC"||e==="EDQUOT"?"Free some space on that disk":e==="EACCES"||e==="EPERM"||e==="EROFS"?"Let your user write in that folder":"Free some space on that disk, or let your user write in that folder";return{reason:I(s),lift:t}}function xj(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 Gc="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.",ds="JOURNAL_GONE",Fn=`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. ${Gc}`,cs="RUN_NOT_IN_HISTORY",Fg="REMOVAL_RUNNING",vi="RUN_WRITING",Dj="VERIFY_RUNNING",FA="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.",Nj="RESUME_UNAVAILABLE",_A="remove the records it created (Forge \u2192 History), then run the clone again. Nothing was read or written.",UA="RESUME_TARGET_CHANGED",_g="RESUME_CHANGED",jj=J({forgeId:j().min(1).max(200),graph:Br.optional(),config:Hn.optional(),muteAutomation:Ke().optional()}).strict(),HA=new Set(["cancelled","failure","interrupted"]),_n="Forge execution was aborted before it started. Nothing was written.",Ug="FORGE_RUNNING",Mj="FORGE_STOP_AMBIGUOUS",Lj={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.`}},Fj=J({requestId:j().min(1).max(200).optional()}).optional(),_j=J({template:qu}),Uj=J({forgeId:j().min(1).max(200),includeChanged:Ke().optional(),sweep:Ke().optional(),again:Ke().optional(),muteAutomation:Ke().optional(),sweepLate:Ke().optional(),sweepUntied:Ke().optional()}),Hj=J({forgeId:j().min(1).max(200),again:Ke().optional(),sweptObjects:tm.optional()}),Bj=J({forgeId:j().min(1).max(200)}),qj=J({forgeId:j().min(1).max(200),recordId:j().regex(Hg,"Invalid Salesforce record ID")}).strict(),Wj=J({forgeId:j().min(1).max(200)}).strict(),zj=J({forgeId:j().min(1).max(200)}).strict(),Gj=5e3,Jj=J({templateId:j().min(1).max(200)}),Vj=J({graph:Br,config:Hn}),Kj=J({framework:j().min(1).max(50),graph:Br,config:Hn,anonymizationRules:Fi.optional()}),Xj=J({sourceOrgId:ho,targetOrgId:ho,objectApiNames:ve(j().regex(/^[A-Za-z][A-Za-z0-9_]*$/).max(80)).max(100)}),Yj=J({graph:Br,config:Hn,anonymizationRules:Fi.optional()}),Qj=J({targetOrgId:ho,graph:Br}),Zj=J({graph:Br,config:Hn}),e0=J({orgId:ho}),t0=J({targetOrgId:ho,objectApiNames:ve(j().min(1).max(255)).max(5e3)}),r0=J({graph:Br,config:Hn,muteAutomation:Ke().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"]}),n0=J({sourceOrgId:ho,soqlQuery:j().min(1).max(2e4),maxRoots:Te().int().min(1).max(mf).optional()}),o0=[[/Give the most it may take \(--fit-within <MB>\) or the most records \(--max-total <n>\)/g,"Set the MB it may take under Sample settings, on Review,"],[/Lower the bound \(--fit-within or --max-total\), or leave objects out \(--exclude-object\) or narrow them \(--filter\)\./g,"Let it take fewer MB under Sample settings, or leave objects out on Review or narrow them by their filter in Review \u2192 Controls."],[/ Or draw among fewer roots: a window of dates \(--fit-window\) or a filter on the roots of the large objects \(--fit-where\)\./g," Or draw among fewer roots, under Which roots: a window of dates, or a filter on the roots of the large objects."],[/ instead: --fit-where "[^"=]+=([^"]*)"/g," instead, under Which roots: $1"],[/ \(--fit-(?:window|where|strata)\b[^)]*\)/g," (under Which roots)"],[/ \(--exclude-object\)/g," (left out on Review)"],[/--filter leaves records of it out of the copy\./g,"Its filter, in Review \u2192 Controls, leaves records of it out of the copy."]],s0=[[/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"]],rT=new Set(["SAMPLE_DRAW_INVALID","SAMPLE_DRAW_EMPTY"]),i0=new Set([...rT,"SAMPLE_STORAGE_UNREAD","SAMPLE_TOO_LARGE"]);function a0(s){if(s.code==="ROOTS_EXCEEDED")return new pt(s.code,s0.reduce((t,[r,n])=>t.replace(r,n),s.message));if(!i0.has(s.code))return s;let e=o0.reduce((t,[r,n])=>t.replace(r,n),s.message);return new pt(s.code,e,void 0,void 0,void 0,{...s.sample?{sample:s.sample}:{}})}var d0="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.",c0="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.",u0=16;function BA(s){let e=s.fit();return e?{fit:e}:{}}function zc(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 l0(){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 it(s,e,t,r){return $(s,e,t,r)}var p0={holder:s=>dv(s),take:(s,e)=>{let t=av(s,{...e,ranFrom:"editor"});return"busy"in t?t:{release:()=>t.lock.release()}}};function Si(s){return s.charAt(0).toUpperCase()+s.slice(1)}function Un(s,e=1){s.requests+=e,s.target!==void 0&&(s.target+=e)}function g0(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 qA(s){return s.successCount+s.updatedCount>0}function WA(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 f0(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 h0(s,e){let t=s.remap.createdByObject.reduce((d,c)=>d+c.sourceIds.length,0),r=Object.keys(s.remap.table).length,n=f0(s),o=new Set(s.remap.withTheirRecord??[]),i=s.remap.linked.filter(d=>o.has(d)),a=r>Ga?{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 m0=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"]),zA=3e4,y0=6e4,w0=3e4,b0=6e4,ki=6e4,R0=12e4;function GA(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.",v0=6e4,S0=10*6e4,k0=8,O0=8,us=3e4,I0=3e4,VA="forge:templates",KA="forge:history";function XA(s){return s.runUserId!==void 0&&s.undo!==void 0&&!Uf(s.undo)}function A0(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 T0(s,e,t,r){let n=new Map;for(let i of[...e,...t])i.retryOf!==void 0&&!n.has(i.forgeId)&&n.set(i.forgeId,i.retryOf);let o=i=>{let a=new Set;for(let d=n.get(i);d!==void 0;d=n.get(d)){if(d===s)return!0;if(a.has(d))return!1;a.add(d)}return!1};return e.flatMap(i=>{if(!i.resumed||i.remapInJournal||i.targetOrgId!==r)return[];if(!o(i.forgeId))return[];let a=i.idRemapTable??{},d=(i.idRemapExisting??[]).flatMap(u=>{let l=a[u];return l!==void 0?[l]:[]}),c=i.wroteToEarlierParts??[];return c.length===0&&d.length===0?[]:[{span:nT(i.writtenBetween,i),...c.length>0?{wrote:c}:{},...d.length>0?{linked:d}:{}}]})}function nT(s,e){return s?{runStartedAt:new Date(s.first),runEndedAt:new Date(s.last)}:{runDurationMs:e.duration,runRecordedAt:new Date(e.timestamp)}}function E0(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=On(r.objects,n),i=t.filter(a=>o.includes(a));return i.length>0?[{forgeId:r.forgeId,objects:i}]:[]})}function P0(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 C0(s){return(s.mayHaveBeenWritten??[]).reduce((e,{sourceIds:t})=>e+t.length,0)}function $0(s,e){if(!e||e.calls===0)return C0({mayHaveBeenWritten:s});let t=e.lookedFor??new Set,r=(s??[]).reduce((n,{sourceIds:o})=>n+o.filter(i=>!t.has(i)).length,0);return Wl(e)+r}function x0(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 D0(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 YA="forge";function N0(s){let e={...s};return delete e.sourceOrgId,delete e.targetOrgId,e}function j0(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:M0(e)}:{},...s.failedReads?.length?{failedReads:s.failedReads}:{}}}function M0(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 L0(s,e){let t=s.nodes.filter(d=>d.included),r=t.map(d=>d.objectApiName).join(", ")||"ForgeData",n=sb,o=e.inputMode==="org"?void 0:e.maxRecordsPerObject,i=Hu(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 F0(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 QA(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 ZA(s,e){let t=(e.nodes??[]).map(r=>r.objectApiName).sort();return JSON.stringify([s.sourceOrgId,s.targetOrgId,t])}function _0(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 eT(s,e){return s.apiCalls===void 0?s:{...s,apiCalls:s.apiCalls+e}}function tT(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 U0(s){return s instanceof Error&&s.name==="ForgeAbortedError"}var Jc=class extends Error{constructor(t,r){super(r);this.code=t;this.name="RehearsalStoppedError"}code};function H0(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 Vc=class s{constructor(e,t,r){this.deps=e;this.externalBrowser=t??new jr,this.saveDialog=r??new An}deps;abortController=null;stops=new QR;executeOperationId=null;writingTo=null;orchestrator;planGenerator;complianceService;metadataDiff;targetAutomation;targetGaps;requestsSent;requestsSentTo;muteOrgOf;muteLeases;lostBulkJobs;beforeRunCheckpoints;rehearser;rehearseOperationId=null;templateStore;removalPlans;runJournal;otherModuleRuns=()=>Promise.resolve([]);journalsRunning=new Set;journalLocks=p0;describeGlobalCache=new Gs({defaultTtl:5*6e4,maxSize:16,maxSizeBytes:50*1024*1024});dmlTracker=new ia;removing=new Set;trials=new sv;simulations=new Gb;sampleSimulations=new Map;samplePlansSwept=new Set;verifying=new Set;automationReads=new Map;automationReadAgain=new Set;discoverySent=new Map;liveTracker;lastWriteAt=new Map;static DUPLICATE_COOLDOWN_MS=6e4;static MAX_HISTORY=20;externalBrowser;saveDialog;forgetOrg(e){this.describeGlobalCache.invalidate(e),this.orchestrator?.clearDiscoveryCache([e]);for(let[t,r]of this.automationReads)r.orgId===e&&this.automationReads.delete(t)}setForgeOrchestrator(e,t){this.orchestrator=e,t&&(this.planGenerator=t.planGenerator,this.complianceService=t.complianceService,this.metadataDiff=t.metadataDiff,this.targetAutomation=t.targetAutomation,this.targetGaps=t.targetGaps,this.templateStore=t.templateStore,this.removalPlans=t.removalPlans,this.runJournal=t.runJournal,this.requestsSent=t.requestsSent,this.requestsSentTo=t.requestsSentTo,this.muteOrgOf=t.muteOrg,this.muteLeases=t.muteLeases,this.lostBulkJobs=t.lostBulkJobs,this.rehearser=t.rehearser,t.journalLocks&&(this.journalLocks=t.journalLocks))}setLiveOperationTracker(e){this.liveTracker=e}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}trackRun(e,t,r,n=!1){let o=this.deps.infraServices?.backgroundRegistry;if(!o)return()=>{};let i=()=>{},a=new Promise((c,u)=>{i=l=>{l===void 0?c():u(l instanceof Error?l:new Error(String(l)))}}),d=new AbortController;return d.signal.addEventListener("abort",()=>{r.abort(),n&&this.orchestrator?.abort()},{once:!0}),o.register(e,"forge",t,a,d),i}isWritingTo(e,t){return this.writingTo===e&&(t===void 0||t!==this.executeOperationId)}async handle(e){if(!m0.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(VA);return{templates:Array.isArray(e)?e.filter(pn):[]}}return this.withImportedTemplates(this.templateStore)}async withImportedTemplates(e){let t=Wc(this.deps.configStore,e.workspacePath);if(!t)return{templates:await e.list()};let r;try{r=await e.merge(t.templates,new Set(t.replacing))}catch(n){let o=I(n);return oe.warn(`Imported forge templates not written into .sandforge/: ${o}`),{templates:await e.list(),importNotMerged:o}}return $A(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(VA,e,YA);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(KA)??[]}saveHistory(e){this.deps.configStore.set(KA,e,YA)}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=it(bj,e,"forge:preview:error",this.deps);if(!t)return;let{recordId:r,orgId:n}=t;try{let o=await q(n,this.deps.orgRegistry,this.deps.orgManager),i=r.substring(0,3),a=this.describeGlobalCache.get(n);if(!a){let b=await o.describeGlobal();xe(o.limitInfo,"forge:preview describeGlobal"),a=b.sobjects.map(O=>({name:O.name,label:O.label,keyPrefix:O.keyPrefix??null})),this.describeGlobalCache.set(n,a)}let d=a.find(b=>b.keyPrefix===i),c=ye(this.deps.orgManager.getOrg(n),n),u=(b,O)=>{this.deps.broker.postToWebview(A(this.deps,e,"forge:preview:error",{code:b,orgName:c,message:O}))};if(!d){u("UNKNOWN_KEY_PREFIX",`No object of ${c} has ids starting "${i}": the record is read from the source org picked.`);return}let l=await Bh(o,d.name,`SELECT FIELDS(STANDARD) FROM ${d.name} WHERE Id = '${tr(r)}' LIMIT 1`);if(xe(o.limitInfo,`forge:preview query ${d.name}`),!l||l.length===0){u("RECORD_NOT_FOUND",`Record ${r} is not in ${c}, or the user connected there cannot see it: the record is read from the source org picked.`);return}let g=l[0],p=new Set(["attributes","Id"]),f=Object.entries(g).filter(([b])=>!p.has(b)).filter(([,b])=>b!=null&&String(b)!=="").slice(0,8).map(([b,O])=>({name:b,value:String(O)})),h=await o.describe(d.name);xe(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,S=A(this.deps,e,"forge:preview:response",{objectApiName:d.name,objectLabel:d.label,recordId:r,fields:f,estimatedRecordCount:y,totalFieldCount:m,estimatedSize:R});this.deps.broker.postToWebview(S)}catch(o){T(this.deps,"forge:preview","forge:preview:error",e,o,{code:"PREVIEW_ERROR"})}}async handleDiscover(e){if(!this.orchestrator){T(this.deps,"forge:discover","forge:discover:error",e,new Error("Forge module is not initialized"),{code:"NOT_INITIALIZED"});return}let t=it(vj,e,"forge:discover:error",this.deps);if(!t)return;let r=this.withMaxRoots(t.config),n=new AbortController,o=`forge-discover-${this.deps.nextId()}`,{discovery:i,superseded:a}=this.stops.beginDiscovery(e.id,n,o);for(let l of a)this.stopDiscovery(l);Je(this.deps,o,"forge","Discovering object graph");let d=this.trackRun(o,"Discovering object graph",n),c,u=zc(l=>{let g=A(this.deps,e,"forge:discover:progress",l);this.deps.broker.postToWebview(g)},100);try{oe.info("Forge discover started");let l=this.orchestrator,{result:g,sent:p}=await TA(()=>l.discover(r,{...r.inputMode==="org"?{}:{maxNodes:r.maxNodes},signal:n.signal,onProgress:y=>{u(y)}}));if(u.flush(),n.signal.aborted){ge(this.deps,o,{aborted:!0}),this.answerStoppedDiscovery(e,i);return}let f=EA(p,r),h=ZA(r,g);this.discoverySent.delete(h),f&&this.discoverySent.set(h,f);for(let y of this.discoverySent.keys()){if(this.discoverySent.size<=O0)break;this.discoverySent.delete(y)}let m=A(this.deps,e,"forge:discover:response",{graph:f?{...g,discoveryRequests:f}:g});this.deps.broker.replyToRequester(m),ge(this.deps,o,{nodeCount:g.nodes?.length??0}),oe.info("Forge discover finished",{objects:g.nodes?.length??0,records:g.totalRecords})}catch(l){if(u.flush(),n.signal.aborted){ge(this.deps,o,{aborted:!0}),this.answerStoppedDiscovery(e,i);return}c=l,T(this.deps,"forge:discover","forge:discover:error",e,l,{code:"DISCOVER_ERROR",retryable:!0}),je(this.deps,o,I(l),!0)}finally{d(c),this.stops.endDiscovery(i)}}stopDiscovery(e){this.deps.infraServices?.backgroundRegistry?.abort(e.operationId),e.controller.abort()}answerStoppedDiscovery(e,t){let{code:r,message:n}=Lj[t.stop??"stopped"];T(this.deps,"forge:discover","forge:discover:error",e,new Error(n),{code:r,retryable:!0})}async handleExecute(e,t){if(!this.orchestrator){T(this.deps,"forge:execute","forge:execute:error",e,new Error("Forge module is not initialized"),{code:"NOT_INITIALIZED"});return}let r=t?t.startedWith:it(Sj,e,"forge:execute:error",this.deps);if(!r)return;let{graph:n,anonymizationRules:o,files:i,reviewSkipped:a,muteAutomation:d}=r,c=this.withMaxRoots(r.config),u=t?t.forgeId:r.retryOf,l=u!==void 0?g0(u,this.loadHistory()):void 0,g=u===void 0?r.checkpointFirst:void 0;u!==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:l?.checkpointId??"none"});let p=c.dryRun===!0,f=Vl(n,c),h=zb(c),m=new iv(c,{reviewSkipped:a===!0,...this.trials.before(f)}),y=c.inputMode==="org",R=y&&c.sample!==void 0,S=($e,Ge)=>{p||Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:$e,context:m.context()}),T(this.deps,"forge:execute","forge:execute:error",e,new Error(Ge),{code:$e})};if(n.withoutEdges===!0){S(Oj,Ij);return}if(y&&a===!0){S(Aj,Tj);return}let b=y?VR(n):void 0;if(b){S(b.code,b.message);return}let O=i?hf(c.anonymizePII,i.acceptedAsIs):null;if(O){Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:jA,context:m.context()}),T(this.deps,"forge:execute","forge:execute:error",e,new Error(O),{code:jA});return}let P,v,w;if(u!==void 0&&!t){let $e=await this.runToRetry(u,c.targetOrgId);if("refused"in $e){Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:MA,context:m.context()}),T(this.deps,"forge:execute","forge:execute:error",e,new Error($e.refused),{code:MA});return}P=$e.written,v=$e.journalId!==void 0?{journalId:$e.journalId}:{},w=$e.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:Re.code,context:m.context()}),T(this.deps,"forge:execute","forge:execute:error",e,new Error(Re.message),{code:Re.code});return}let k=this.deps.orgManager.getOrg(c.targetOrgId),E=Pe(k),x=ye(k,c.targetOrgId);if(E==="production"){this.refuseAtGate(e,c.targetOrgId,new pt("PRODUCTION_TARGET",`${x} 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 V=await this.ownerMapRefusal(c);if(V){p||Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:V.code,context:m.context()}),T(this.deps,"forge:execute","forge:execute:error",e,V,{code:V.code,retryable:!0});return}let H={orgId:c.targetOrgId,orgTier:E,operation:"insert",...L0(n,c),module:"forge"},Y=new AbortController,B=this.stops.awaitGuard(e.id,Y),{check:N,decision:L}=p?kj(C,H):await et(C,H).finally(B);p&&B();let Q=L;if(N.warnings.length>0&&oe.warn("Forge run: Production Guard warnings",{warnings:N.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"){T(this.deps,"forge:execute","forge:execute:error",e,new Error(`Operation blocked by Production Guard: ${N.blockedReason??N.impactSummary}`),{code:"GUARD_BLOCKED"});return}if(L==="declined"){T(this.deps,"forge:execute","forge:execute:error",e,new Error("Operation cancelled by user (confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}if(Y.signal.aborted){Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",guard:L,code:bt,context:m.context()}),T(this.deps,"forge:execute","forge:execute:error",e,new Error(_n),{code:bt,retryable:!0});return}let K=`${c.sourceOrgId}:${c.targetOrgId}:${c.recordId??""}`,ae=n.nodes?.map($e=>$e.objectApiName).join(",")??"",U=`forge:${K}:${ae}:${n.totalRecords??0}`+(u!==void 0?`:${t?"resume":"retry"}:${u}`:""),re=this.dmlTracker.isDuplicate(U)?this.dmlTracker.get(U):void 0,ne=this.lastWriteAt.get(U),ue=ne!==void 0&&Date.now()-ne<s.DUPLICATE_COOLDOWN_MS;if(re?.status==="pending"||ue){oe.warn("Duplicate forge execution detected",{operationId:U}),T(this.deps,"forge:execute","forge:execute:error",e,new Error(`Duplicate forge operation: ${U}`),{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:Ug,context:m.context()}),T(this.deps,"forge:execute","forge:execute:error",e,new Error("Another Forge run is still under way in this window: start this one once it has ended. A run asked to stop ends once the step under way is done."),{code:Ug,retryable:!0});return}let ce=n.totalRecords??0;re?(re.status="pending",re.recordCount=ce,re.registeredAt=new Date().toISOString()):this.dmlTracker.register(U,"forge","upsert",ce),this.abortController=Y;let be=`forge-execute-${this.deps.nextId()}`,Xe=p?"Simulating forge operation":"Executing forge operation";Je(this.deps,be,"forge",Xe);let De=this.trackRun(be,Xe,Y,!0);this.liveTracker?.register(be,"forge",Xe),this.executeOperationId=be,this.writingTo=p?null:c.targetOrgId,this.stops.beginRun(e.id,Y);let _e=Date.now(),z,se,te,he,D,W=!1,X=()=>{W||!se||(W=!0,se.close())},F={keep:!1},ee=!1,_,de=async()=>{if(!z||ee)return;ee=!0;let $e=z,Ge=F;X(),await(Ge.keep?this.runJournal?.stop($e,Ge.status,Ge.forgeId):this.runJournal?.end($e))?.catch(Qe=>{oe.warn(`Forge run journal not ${Ge.keep?"kept":"dropped"}: ${I(Qe)}`)}),this.journalsRunning.delete($e),_?.release(),_=void 0},Se={requests:0,target:0},Ue,He,ie=()=>{let $e=this.requestsSent?.();return $e===void 0||Ue===void 0?void 0:Se.requests+$e-Ue},Ee,Ne=!1,st=[],Be,Ve=0,fs=()=>{let $e=this.requestsSentTo?.(c.targetOrgId),Ge=$e===void 0||He===void 0?0:$e-He;return Ve+(this.discoverySent.get(ZA(c,n))?.target??0)+(Se.target??0)+Ge},qn,Wn,jt,Pi,hr=[],Ci,mo=()=>(Ci??=this.jobsStillRunning(c.targetOrgId,Pi,Se).then($e=>{hr=$e}),Ci),yo,zn={firing:[]},hs,mr,$i,_r,xi=!1,Et,fn,Qt=zc($e=>{let Ge=A(this.deps,e,"forge:progress",$e);this.deps.broker.postToWebview(Ge)},100),wo=zc($e=>{this.deps.broker.postToWebview(A(this.deps,e,"forge:sampling:progress",{...$e}))},100),Gn=this.liveProgressOf(be,n),Di=l0(),Ni=this.orchestrator.on("forge:progress",$e=>{let Ge=Di($e),Qe=ie(),at=Qe===void 0?Ge:{...Ge,apiCalls:Qe};Gn(at);let St=at.status;if(St==="done"||St==="error"||St==="skipped"||St==="stopped"){Qt.flush();let nt=A(this.deps,e,"forge:progress",at);this.deps.broker.postToWebview(nt);return}Qt(at)});try{oe.info("Forge execute started",{source:ye(this.deps.orgManager.getOrg(c.sourceOrgId),"unknown org"),target:ye(this.deps.orgManager.getOrg(c.targetOrgId),"unknown org")});let $e=this.maxRecordsPerObject(),Ge=Ll(n,{leftOut:new Set(n.nodes.filter(Gi).map(le=>le.objectApiName)),retry:u!==void 0}),Qe=new Set(Ge.map(le=>le.objectApiName)),at=(le,Me)=>Me==="insert"||Me==="update"&&Qe.has(le);if(p){if(g!==void 0||y||R){let le=await this.automationBeforeTheRun(c.targetOrgId,n);if("automation"in le){let Me=d===!0?await Ot(()=>this.muteOrg(c.targetOrgId),le.automation,{...this.muteLeases,writes:at}).then(ot=>ot.plan,ot=>{oe.warn(`Forge simulation: the mute could not be planned (${I(ot)})`)}):void 0;zn=Jr(le.automation,Me,at),hs=Me}}}else{let le=await this.automationBeforeTheRun(c.targetOrgId,n);Ve=Cn("automation"in le?le.automation:le);let Me=le,ot;if(d===!0){let Ae=await Ot(()=>this.muteOrg(c.targetOrgId),"automation"in le?le.automation:le,{...this.muteLeases,writes:at});Wn=Ae.prepared,jt=Ae.muted,ot=Ae.plan,"automation"in le&&Ae.automation&&(Me={...le,automation:Ae.automation})}if("automation"in le&&(zn=Jr(le.automation,ot,at)),Be=Me,"automation"in Me&&(st=Gf(Me.automation)),Y.signal.aborted)throw Ne=!0,new Error(_n);if(m.automationRead(Me,Ge),_r=await dr({read:"automation"in le?le.automation:le,...ot?{plan:ot}:{},writes:at,applyAssignmentRules:c.applyAssignmentRules===!0,readDeliverability:()=>this.readDeliverability(c.targetOrgId,Y.signal),accepted:!1,target:x,run:"clone",keepsAddresses:c.keepContactPoints===!0}),Se.requests+=_r.ofRun.read?.requests??0,Y.signal.aborted)throw Ne=!0,new Error(_n);m.emailsRead(_r.gate.audit);let Hr=await this.confirmAutomation(C,{orgId:c.targetOrgId,org:x,orgTier:E,username:k?.username},Me,Ge,a===!0,_r.gate.confirmation);Hr==="confirmed"&&(m.confirm("automation"),_r.gate.verdict==="asks"&&(xi=!0,m.confirm("emails"))),Q=Zn(Q,Hr);let ht=y?[]:qb(n,c.maxRecordsPerObject,$e);if(ht.length>0){if(Y.signal.aborted)throw Ne=!0,new Error(_n);let Ae=await this.confirmReadCeiling(C,{org:x,orgTier:E,source:ye(this.deps.orgManager.getOrg(c.sourceOrgId),c.sourceOrgId)},ht,$e);Ae==="confirmed"&&m.confirm("volume"),Q=Zn(Q,Ae)}}if(Y.signal.aborted)throw Ne=!0,new Error(_n);let St=p?void 0:this.runUserOf(c.targetOrgId),nt=await this.loadRecordTypeMappings(c,Y.signal,Se);if(Y.signal.aborted)throw Ne=!0,new Error(_n);te=await St,_e=Date.now(),Ue=this.requestsSent?.(),He=this.requestsSentTo?.(c.targetOrgId),Pi=this.lostBulkJobs?.count;let ct=p?void 0:this.runJournal,Mt;if(ct){let le=t?.journalId??`forge-run-${_e}`,Me;try{Me=this.journalLocks.take(ct.pathOf(le),{journalId:le,target:x,...t?{resumes:!0}:{}})}catch(ht){oe.warn(`Forge run journal: its lock not taken (${I(ht)})`)}if(Me&&"busy"in Me)throw new gn(vi,`${Si(Va(Me.busy))}: taken up now, two runs would write it; ${Ka(Me.busy)}, then resume it. Nothing was written.`);_=Me,z=le,this.journalsRunning.add(le);let ot=ht=>new gn($j,`${x} could not be read for the insert calls the run had under way when it stopped (${I(ht)}): taken up without them, the run would write their records twice. Reconnect ${x} on Organizations if its session expired, then resume the run again. Nothing was written.`);if(se=await(t?ct.resuming(le).then(async()=>{let ht=await q(c.targetOrgId,this.deps.orgRegistry,this.deps.orgManager).catch(Ct=>{throw ot(Ct)}),Ae={},qe=await ct.reconcile(le,xj(Bl(ht),Ae)).catch(Ct=>{throw Ae.err!==void 0?ot(Ae.err):Ct});for(let Ct of ql(qe,x))oe.info(`Forge resume: ${Ct.trim()}`);he=qe.uncertain,D=qe.underway;let Ze=this.loadHistory().find(Ct=>Ct.forgeId===t.forgeId);Ze&&qe.found.length>0&&await this.withRowsFoundAfterStop(Ze,qe.found)}):ct.begin(le,c.targetOrgId,new Date(_e),{...this.resumeHeadOf(n,c,o,$e),...d===!0?{muteAutomation:!0}:{},...i?{files:i}:{}},te)).then(()=>ct.open(le)).catch(ht=>{oe.warn(`Forge run journal not started: ${I(ht)}`),Mt={err:ht}}),t&&!se){let ht=Mt?.err;if(ht instanceof gn)throw ht;let{reason:Ae,lift:qe}=LA(ht);throw new gn(Lg,`The journal of the run to resume, in ${Mg(ct.pathOf(le))}, could not be opened (${Ae}). ${qe}, then resume it again. Nothing was written.`)}}if(y&&!p&&!se){if(!ct||!z||Mt===void 0)throw new gn(Lg,Cj);let{reason:le,lift:Me}=LA(Mt.err);throw new gn(Lg,`A clone of the whole org keeps its journal on disk, in ${Mg(ct.pathOf(z))}, which could not be opened (${le}). ${Me}, then run it again. Nothing was written.`)}R&&(Et=await this.sampleOf({graph:n,config:c,anonymizationRules:o,readCeiling:$e,dryRun:p,...z!==void 0?{journalId:z}:{},resumes:t!==void 0,...v?{retried:v}:{},volumeCase:h,target:x,lookup:Se,room:()=>_l(zn,at).perRecord,sentBefore:fs,updatedAfterInsert:[...Qe],onProgress:wo}));let Ur=await this.rootsOfTheRun({graph:n,config:c,anonymizationRules:o,readCeiling:$e,dryRun:p,resumes:t!==void 0,...w?{retried:w}:{},lookup:Se});if(Y.signal.aborted)throw Ne=!0,new Error(_n);let Pt,Zt=y?GR(c):void 0,er=this.writeGate({guard:C,targetOrgId:c.targetOrgId,org:x,source:ye(this.deps.orgManager.getOrg(c.sourceOrgId),c.sourceOrgId),orgTier:E,lookup:Se,emailsPerInsert:st,...Be!==void 0?{automation:Be}:{},...$n(_r?.ofRun),sentBefore:fs,mute:Qr(Wn?.plan??hs),mayBeInTarget:he,...D&&D.length>0?{jobsUnderway:D}:{},...p?{}:{simulated:this.simulations.of(h)},updatedAfterInsert:[...Qe],automationRoom:()=>_l(zn,at).perRecord,...y?{wholeOrg:{source:ye(this.deps.orgManager.getOrg(c.sourceOrgId),c.sourceOrgId),sourceOrgId:c.sourceOrgId,graph:n,anonymizePII:c.anonymizePII,...Zt?{carried:Zt}:{}}}:{},...g!==void 0?{checkpoint:{ask:{module:"forge",orgId:c.targetOrgId,operationId:be,running:zn,request:g},own:{operationId:be},signal:Y.signal,onEstimate:le=>{$i=le},onTaken:le=>{mr=le,ct&&z&&se&&ct.keepCheckpoint(z,le).catch(Me=>{oe.warn(`Forge run journal: the checkpoint taken first not named (${I(Me)})`)})},onProgress:le=>{let Me=jo(le);Fe(this.deps,be,le,0,0,Me),this.liveTracker?.updateProgress(be,le,0,0,Me)}}}:{},onSimulated:le=>{qn=le},...R?{sampled:le=>{wo.flush();let Me=Et?.drawnAgain,ot=Me||Et?.ofTheRunRetried?{...le,plan:{...le.plan,...Me?{drawnAgain:Me}:{},...Et?.ofTheRunRetried?{ofTheRunRetried:!0}:{}}}:le;return m.sampled(ot),ot}}:y?{onSampleOffer:le=>{fn=le}}:{},onConfirmed:()=>{Q=Zn(Q,"confirmed"),m.confirm("volume")}}),M=await this.orchestrator.execute(n,c,{recordTypeMappings:nt,anonymizationRules:o,files:i,writtenBefore:P,stream:{ceiling:$e,...se?{store:se,summaryBound:Ga}:{},...Et?{sample:Et.stream}:{}},...te?{runUserId:te}:{},...Ur?{roots:Ur}:{},beforeWrite:async le=>{let Me=await er(le);if(!Wn||le.dryRun||Pt)return Me;let ot=await Wn.acquire(be);Pt=ot,jt=ot.outcome;let Hr=_r?.afterLease(ot.outcome,xi);if(Hr)throw new pt(Hr.code,Hr.message);return{...Me,lease:{assigned:ot.outcome.assigned.length,giveBack:async()=>(await mo(),ot.release())}}}}).catch(le=>{if(!KR(le))throw le;return yo=le.dryRun,F0(n,_e,le.dryRun)}).finally(X).finally(async()=>{Pt&&(await mo(),jt=await Pt.release())}),G=tT(eT(M,Se.requests),Et),ke=(G.remapInJournal===!0||Et!==void 0&&G.status!=="success")&&se&&z?{journalId:z,journalPart:Math.max(0,se.partCount-1)}:{},we=jt?{mutedAutomation:jt,...hr.length>0?{bulkJobsPastMute:hr,errors:[...G.errors??[],...Jl(hr)]}:{}}:{},Le=p?$i:mr?await this.settleCheckpoint(mr,(G.createdCount??G.idRemapCount-(G.linkedExistingCount??0))+(G.updatedCount??0)>0):l,me=Le?{checkpoint:Le}:{},Ye=t&&!p&&se&&z?await this.wroteToEarlierPartsOf(G,z,se.partCount-1):{},Ce=u!==void 0?{...G,...ke,...we,...me,retryOf:u,...t?{resumed:!0}:{},...Ye}:{...G,...ke,...we,...me};"journalId"in ke&&!p&&(F={keep:!0,status:"success",forgeId:Ce.forgeId});let qt=Ce.createdCount??Ce.idRemapCount-(Ce.linkedExistingCount??0);Ce.status!=="failure"&&qt>0&&this.noteForgeWrite(U),Ce.status==="failure"&&(Ee=new Error("Forge execution finished with a failure status.")),p?(this.trials.note("simulation",f),qn&&this.simulations.note(h,qn),Et&&yo?.sample&&this.noteSampleSimulation(h,Et.fingerprint)):(Z(this.deps,{action:"forge_execute",module:"forge",operationId:be,orgId:c.targetOrgId,outcome:Ce.status,guard:Q,objects:ll(Ce),source:{origin:"org",orgId:c.sourceOrgId},carried:pl(Ce),...Es(Ce.contactPoints),...BA(m),context:m.context(Ce.decisionsApplied),...jt?{muted:ut(jt)}:{},...Le?.state==="taken"?{checkpointId:Le.checkpointId}:{}}),this.addToHistory(Ce,c)),oe.info("Forge execute finished",j0(Ce)),await de(),wo.flush();let kt=A(this.deps,e,"forge:execute:response",{result:Ce,operationId:be,...yo?{wholeOrgDryRun:yo}:{},...fn?{sampleOffer:fn}:{}});this.deps.broker.postToWebview(kt),this.dmlTracker.markCompleted(U),ge(this.deps,be,{status:Ce.status}),Ce.status==="failure"?this.liveTracker?.fail(be,"Forge execution finished with a failure status."):Ce.status==="partial"?this.liveTracker?.partial(be):this.liveTracker?.complete(be)}catch($e){wo.flush();let Ge=nR($e,t?"resume":"draw")??$e,Qe=qa(Ge)?Ge:fR(Ge),at=Dt(Ge)?Ge:void 0;(Qe?.code==="AUTOMATION_DECLINED"||Qe?.code==="READ_DECLINED"||Qe?.code==="WRITE_DECLINED")&&(Q=Zn(Q,"declined"));let St=Ne||U0(Ge)||Qe!==void 0||at!==void 0;St||(Ee=Ge);let nt=Qe||at?void 0:DR(Ge),ct=nt?Uh(nt):void 0,Mt=ct?ll(ct):[],Ur=Ne||Qe||at?"stopped":St?Hh(nt,Mt):"failure",Pt=Qe?Qe.code:at?at.code:Ne?bt:Ur==="stopped"?rt:Ge instanceof gn?Ge.code:void 0,Zt=mr?await this.settleCheckpoint(mr,nt?qA(nt):!(Ne||Qe||at)):l;oe.info("Forge execute stopped",{outcome:Ur,...Pt?{code:Pt}:{},...nt?{created:nt.successCount,linked:nt.linkedCount,failed:nt.failedCount}:{}});let er=nt&&!p?this.keepStoppedRun(tT(nt,Et),n,c,{startedAt:_e,cancelled:St,retryOf:u,resumed:t!==void 0,callsBefore:Se.requests,...se&&z?{journalId:z,journalPart:Math.max(0,se.partCount-1)}:{},...Zt?{checkpoint:Zt}:{},...te?{runUserId:te}:{},...hr.length>0?{bulkJobsPastMute:hr}:{},...t&&se&&z?await this.wroteToEarlierPartsOf({idRemapTable:nt.remapTable,idRemapCreated:nt.createdByObject,...nt.remapInJournal?{remapInJournal:!0}:{}},z,se.partCount-1):{}}):void 0;se&&z&&er?F={keep:!0,status:St?"cancelled":"failure",forgeId:er.forgeId}:t&&(F={keep:!0,...t.end}),p||Z(this.deps,{action:"forge_execute",module:"forge",operationId:be,orgId:c.targetOrgId,outcome:Ur,...Pt?{code:Pt}:{},guard:Q,...ct?{objects:Mt,source:{origin:"org",orgId:c.sourceOrgId},carried:pl(ct)}:{},...Es(nt?.contactPoints),...BA(m),context:m.context(nt?.decisionsApplied),...jt?{muted:ut(jt)}:{},...Zt?.state==="taken"?{checkpointId:Zt.checkpointId}:{}}),this.dmlTracker.markFailed(U),this.lastWriteAt.delete(U),Et?.adoptedFrom!==void 0&&z!==void 0&&!F.keep&&!(nt&&qA(nt))&&await this.giveThePlanBack(z,Et.adoptedFrom),await de();let M=mr&&Zt?{checkpoint:Zt}:{},G=Qe&&qa(Qe)?a0(Qe):Ge;T(this.deps,"forge:execute","forge:execute:error",e,G,{code:Pt??(St?rt:"EXECUTE_ERROR"),retryable:!(Qe&&qa(Qe)&&rT.has(Qe.code)),...er?{extraPayload:{result:F.keep?{...er,resumable:!0}:er}}:Qe?.stop?{extraPayload:{gate:Qe.stop,...M,...fn?{sampleOffer:fn}:{}}}:mr?{extraPayload:M}:{}}),St?(this.deps.infraServices?.backgroundRegistry?.abort(be),ge(this.deps,be,{aborted:!0}),this.liveTracker?.cancel(be)):(je(this.deps,be,I(Ge),!0),this.liveTracker?.fail(be,I(Ge))),F.keep&&this.liveTracker?.offerResume(be,F.forgeId)}finally{await de(),_?.release(),De(Ee),this.executeOperationId===be&&(this.executeOperationId=null,this.writingTo=null),this.stops.endRun(e.id),Ni(),Qt.flush(),this.abortController=null}}addToHistory(e,t){let r={...t.inputMode==="org"?xA(e):e,config:N0(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=eT(_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??[],...Jl(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(Wr(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<=Ga?{wroteToEarlierParts:i}:{}}catch(i){return oe.warn(`Forge run journal not read for what the part wrote: ${I(i)}`),{}}}async ownerMapRefusal(e){let t=e.ownerMappings??{};if(Object.keys(t).length!==0)try{let r=await q(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager);return await xR(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 (${I(r)})`);return}}runUserOf(e){return rv(async()=>(await q(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 (${I(n)})`),e}}async runToRetry(e,t){let r=this.loadHistory(),n=r.find(c=>c.forgeId===e);if(!n)return{refused:"The run to retry is no longer in the history, so what it wrote is not known. Run the clone again from Review."};if(n.targetOrgId!==t)return{refused:"The run to retry wrote to another org than this one."};if(!n.idRemapTable)return{refused:"The run to retry kept no record of what it wrote. Run the clone again from Review."};let o=new Set,i=n;for(;i&&!o.has(i.forgeId);){if(o.add(i.forgeId),i.undo)return{refused:`The records ${i===n?"the run to retry created":"a run it was built on created"} were removed on ${i.undo.removedAt}: there is nothing to retry against. Run the clone again from Review.`};let c=i.retryOf;i=c===void 0?void 0:r.find(u=>u.forgeId===c)}let a=await this.withIdsOf(n);if("gone"in a)return{refused:a.gone};let d=n.roots?await this.rootsOfTheRunRetried(n):void 0;return n.roots&&!d?{refused:d0}:{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 (${I(a)})`)}))?.roots;if(i&&i.objectApiName.toLowerCase()===t.objectApiName.toLowerCase()&&Cl(i.ids)===i.sha256)return i}if(!t.ids||t.idsLeftOut!==void 0||t.ids.length!==t.asked)return;let n=Cb(t.ids.map(o=>o.source));if(Cl(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=it(Fj,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}T(this.deps,"forge:abort","forge:abort:error",e,new Error(`${r.live} Forge operations are under way in this window, and the stop did not say which one it was for: nothing was stopped. Stop it from its own screen, or from Live Operations.`),{code:Mj});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}:{}}),T(this.deps,"forge:execute","forge:execute:error",e,r,{code:r.code,retryable:!0,...r.stop?{extraPayload:{gate:r.stop}}:{}})}keepAutomationRead(e,t,r){let n=QA(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<=k0)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([...On(t,n,{userKept:o}),...r])],d=i?await new fe(ki).withTimeout("forge:undo-automation",()=>i.read(e,a)).catch(u=>({unread:I(u)})):{unread:"no reader of the target org's automation is set up"},c=new Set(sr(t));return Ot(()=>this.muteOrg(e),d,{...this.muteLeases,writes:(u,l)=>l==="delete"||l==="update"&&c.has(u)})}async muteOrg(e){return this.muteOrgOf?this.muteOrgOf(e):_t(await q(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(QA(e,t));if(o&&Date.now()-o.at<S0)try{return{automation:_0(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(Gi).map(d=>d.objectApiName));try{return{automation:await new fe(ki).withTimeout("forge:automation",()=>i.readForGraph(e,t,a)),reused:!1}}catch(d){return{unread:I(d)}}}async confirmAutomation(e,t,r,n,o,i={}){let a="automation"in r?r.automation:void 0,d=n.map(y=>y.objectApiName),c=a?jl(a):[],u=a?Ml(a,d):[],l=a?Fl(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:u.length,unread:l.map(y=>y.part)});let g=c.length===0&&u.length===0&&l.length===0,p=a?Jf(a):[],f=i.deliverability!==void 0;if(g&&!f&&!(o&&p.length>0))return"allowed";let h=a&&!g?pR(a,d):[],m=await e.confirmRun({stage:"automation",org:t.org,orgTier:t.orgTier,fired:c,firedOnUpdate:u,updateSteps:lR(n.filter(y=>u.some(R=>R.objectApiName===y.objectApiName))),unread:l,bypass:h,assign:a&&!g?gR(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 pt("AUTOMATION_DECLINED",g&&!f?"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 pt("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 pt("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 pt("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",xl);return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.floor(e),Li):xl}confirmAboveRecords(){let e=this.deps.services?.getSandforgeSetting?.("safety.confirmAboveRecords",tn);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):tn}async readTargetEmailLimits(e){try{let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return await new fe(us).withTimeout("forge:limits",()=>Ar(t))}catch(t){return{unread:I(t)}}}async readTargetDataStorage(e){try{let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return await new fe(us).withTimeout("forge:limits",()=>kr(cr(t,e)))}catch(t){return{unread:I(t)}}}async readTargetApiBudget(e){try{let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return await new fe(us).withTimeout("forge:limits",()=>ur(t))}catch(t){return{unread:I(t)}}}async readSourceApiBudget(e,t){t.requests++;try{let r=await q(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager);return await new fe(us).withTimeout("forge:limits",()=>ur(r))}catch(r){return{unread:I(r)}}}limitsTransportOf(e,t){return{request:async r=>{t();let n=await q(e,this.deps.orgRegistry,this.deps.orgManager);return new fe(us).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,()=>{Un(r)});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(c0);let n=this.setupFingerprintOf(e.graph,t,e.anonymizationRules,e.readCeiling),o=new Date,i,a,d,c=!1,u,l=h=>{if(!(h instanceof NR))throw h};if(e.dryRun||e.journalId===void 0)i=jR(r,n);else if(e.retried&&!e.resumes){i=za(r,e.journalId);let h=e.retried.journalId,m=h!==void 0?await Hl.open(za(r,h),{fingerprint:n}).catch(l):void 0;m?(a=await _R(m,r,e.journalId),c=!0):d="planGone"}else if(i=za(r,e.journalId),!e.resumes){let h=await MR(r,n,o);if(h instanceof Hl)a=await LR(h,r,e.journalId).catch(l),a?u=h.dir:d="planTaken";else if(h==="tooOld"||this.samplePlansSwept.has(n))d="tooOld";else{let m=this.sampleSimulations.get(e.volumeCase);m!==void 0&&(d=m===n?"planTaken":"setUpOtherwise")}}await this.sweepSamplePlansOf(r,o);let g;if(!a&&!e.resumes){let h=await this.readSourceApiBudget(t,e.lookup);"unread"in h||(g=h.remaining)}let p=t.sample?.withinMB;return{stream:{options:t.sample??{},budget:async()=>{Un(e.lookup);let h=await this.readTargetDataStorage(t.targetOrgId),m=tR({storage:h,bounds:p!==void 0?{withinMB:p}:{},target:e.target});if(m)throw pt.of(m);let y;"unread"in h?(Un(e.lookup),y=await this.readTargetApiBudget(t.targetOrgId)):y=h.dailyApiRequests;let R="unread"in h?void 0:h.dailyBulkApiBatches,S=Ja({storage:h,...p!==void 0?{withinMB:p}:{},automation:e.room(),allowances:{...y?{requests:y}:{},...R?{bulkBatches:R}:{},...e.sentBefore?{sentBefore:e.sentBefore()}:{},...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{}}});if(!S)throw new Error("No budget of the sample could be read. Nothing was written.");return S},keepAt:i,fingerprint:n,...a?{plan:a}:{},...g!==void 0?{sourceRequestsLeft:g}:{},onProgress:e.onProgress},fingerprint:n,...d?{drawnAgain:d}:{},...c?{ofTheRunRetried:!0}:{},...u!==void 0?{adoptedFrom:u}:{}}}async giveThePlanBack(e,t){let r=this.runJournal?.storagePath;r!==void 0&&await FR(r,e,t).catch(n=>{oe.warn(`Forge sample: the plan of the simulation was not put back (${I(n)})`)})}async sweepSimulationPlans(e=new Date){let t=this.runJournal?.storagePath;t!==void 0&&(await this.sweepSamplePlansOf(t,e),await Gl(t,e).catch(r=>{oe.warn(`Forge roots: the roots of past simulations were not swept (${I(r)})`)}))}async sweepSamplePlansOf(e,t){try{for(let r of await UR(e,t))this.samplePlansSwept.add(r)}catch(r){oe.warn(`Forge sample: the plans of past simulations were not swept (${I(r)})`)}}noteSampleSimulation(e,t){this.samplePlansSwept.delete(t),this.sampleSimulations.delete(e),this.sampleSimulations.set(e,t);for(let r of this.sampleSimulations.keys()){if(this.sampleSimulations.size<=u0)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{sentBefore:B}=e,N=Nl(n.objects,i);e.onSimulated?.(N);let L=r(N),Q;t&&L&&this.beforeRunCheckpoints&&N.totalRows>0&&(Q=await this.beforeRunCheckpoints.scope(L,t.own).then(ae=>(t.onEstimate(ae),ae),ae=>{oe.warn(`Forge simulation: ${Sr(ae)}`)}));let K=await eR({objects:n.objects,measures:i,graph:o.graph,anonymizePII:o.anonymizePII,...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{},...Q?{checkpoint:Q}:{},...n.readBack!==void 0?{readBack:n.readBack}:{},...e.mute!==void 0?{mute:e.mute}:{},...e.deliverability!==void 0?{deliverability:e.deliverability}:{},...B?{sentBefore:()=>({target:B()})}:{},target:{org:e.org,limits:cr(this.limitsTransportOf(e.targetOrgId,()=>Un(e.lookup)),e.targetOrgId)},source:{org:o.source,limits:this.limitsTransportOf(o.sourceOrgId,()=>{e.lookup.requests++})},...a?{sample:a}:{},...e.automationRoom?{automation:e.automationRoom()}:{}});if(!a&&K.storage.verdict==="exceeds"){let ae=Ja({storage:K.storage});ae&&e.onSampleOffer?.(ae.budget)}throw oe.info("Forge write gate: the dry run of a clone of the whole org",{records:K.totalRows,objects:K.wouldInsert.length,targetRequests:K.targetRequests.estimate,sourceRequests:K.sourceRequests.estimate,...K.bulkBatches?{bulkBatches:K.bulkBatches.estimate}:{},wouldBeRefused:K.wouldBeRefused.map(ae=>ae.code)}),new JR(K)}if(n.dryRun){let B=Dl(n.objects);e.onSimulated?.(B);let N=r(B);return t&&N&&this.beforeRunCheckpoints&&B.totalRows>0&&await this.beforeRunCheckpoints.scope(N,t.own).then(t.onEstimate,L=>{oe.warn(`Forge simulation: ${Sr(L)}`)}),{}}let d=i?Xb(i.readWholeOver):void 0;if(d)throw pt.of(d);let c=i?Nl(n.objects,i):Dl(n.objects);if(c.totalRows===0)return{};Un(e.lookup);let u=await this.readTargetDataStorage(e.targetOrgId),l=Or(c,u,e.automationRoom?Zb(c,e.automationRoom()):0);if(a){let B=rR({sample:a,storage:u,target:e.org});if(B)throw pt.of(B)}let g=this.confirmAboveRecords(),p=g>0&&c.totalRows>g?g:void 0,f=rb(e.orgTier),h=f!==void 0&&c.totalRows>f?f:void 0;oe.info("Forge write gate",{records:c.totalRows,objects:Object.fromEntries(c.objects.slice(0,20).map(B=>[B.objectApiName,B.rows])),storageEstimateMB:Ws(l.estimateMB),...l.verdict==="unread"?{storageUnread:l.unread}:{storageRemainingMB:l.remainingMB,storageMaxMB:l.maxMB},storage:l.verdict});let m=hR(l,e.org);if(m&&l.verdict==="exceeds"){if(o&&!a&&!("unread"in u)){let N=Ja({storage:u});N&&e.onSampleOffer?.(N.budget)}let B=n.roots&&!o?Pb(l,e.org,n.roots):void 0;throw B?pt.of(B):new pt("STORAGE_EXCEEDED",`${m} Nothing was written.`,{estimateMB:Number(Ws(l.estimateMB)),remainingMB:l.remainingMB,...Ir(l)})}l.verdict==="near"?oe.warn("Forge write gate: the records take more than 80 % of the data storage the target has left"):l.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?Yb(i.files,u,e.org):void 0;if(y?.stop)throw pt.of(y.stop);let R;"unread"in u?(Un(e.lookup),R=await this.readTargetApiBudget(e.targetOrgId)):R=u.dailyApiRequests;let S=r(c),b;if(t&&S){let B=this.beforeRunCheckpoints;if(!B)throw new pt(Pn,Sr(new Error("SandForge's checkpoints are not set up in this window")));b=await B.scope(S,t.own).catch(N=>{throw new pt(Pn,Sr(N))})}let O=o?await this.readSourceApiBudget(o,e.lookup):void 0,P=Qb({plan:c,...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{},...n.readBack!==void 0?{readBack:n.readBack}:{},...b?{checkpoint:b}:{},...e.mute!==void 0?{mute:e.mute}:{},...e.deliverability!==void 0?{deliverability:e.deliverability}:{},...e.sentBefore?{sentBefore:e.sentBefore()}:{},budget:R,target:e.org,...o&&i?{wholeOrg:{measures:i,bulkBatches:"unread"in u?u:u.dailyBulkApiBatches,sourceBudget:O,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 pt.of(P.stop);let v=ya(P.api),w=o&&i&&P.wholeOrg?XR({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;w&&oe.info("Forge write gate: a clone of the whole org",{sourceRequests:P.wholeOrg?.source.estimate,sourceApi:P.wholeOrg?.source.verdict,jobs:w.bulk?.jobs??0,...P.wholeOrg?.bulkBatches?{bulkBatches:P.wholeOrg.bulkBatches.estimate}:{},durationSeconds:Math.round(w.durationSeconds),managedPackages:w.managedPackages?.length??0,personalAsIs:w.personalAsIs?.length??0});let C=async()=>{let B=this.beforeRunCheckpoints;if(!t||!S||!b||!B)return;let N=b,L=await Ha(()=>B.take(S,t.own,{planned:N,signal:t.signal,onProgress:({percentage:Q})=>t.onProgress?.(Q)}));if("stop"in L)throw L.stop.code===Pn?pt.of({...L.stop,code:Pn}):Object.assign(new Error(L.stop.message),{name:"ForgeAbortedError"});t.onTaken(L.checkpoint)},k=[],E=[];if(e.emailsPerInsert.length>0){Un(e.lookup);for(let B of oR(c,e.emailsPerInsert,await this.readTargetEmailLimits(e.targetOrgId)))B.verdict==="exceeds"?k.push(aR(B)):B.verdict==="unread"&&E.push(dR(B));E.length>0&&oe.warn("Forge write gate: a daily email limit of the target could not be read",{limits:E.map(({limit:B,emails:N})=>({limit:B,emails:N}))}),k.length>0&&oe.warn("Forge write gate: the records take the target past a daily email limit",{limits:k.map(({limit:B,emails:N,remaining:L})=>({limit:B,emails:N,remaining:L}))})}let x=e.automation===void 0?void 0:"automation"in e.automation?iR(e.automation.automation,sR(c)):`the target's automation: ${e.automation.unread}`;x!==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 V=(e.mayBeInTarget??[]).filter(({rows:B})=>B>0),H=e.simulated?Jb(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&&l.verdict==="fits"&&k.length===0&&E.length===0&&x===void 0&&V.length===0&&H?.farAbove!==!0&&!P.asks)return await C(),v;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:B,rows:N})=>({objectApiName:B,rows:N})),total:c.totalRows,...p!==void 0?{aboveRecords:p}:{},...h!==void 0?{largeVolume:h}:{},storage:xn(l),...c.leftOut?{leftOut:c.leftOut}:{},...n.objects.some(B=>B.counted)?{counted:!0}:{},...k.length>0?{emails:k}:{},...E.length>0?{emailsUnread:E}:{},...x!==void 0?{emailsUncounted:x}:{},...Vb(c),...Kb(c),...V.length>0?{mayBeInTarget:V.map(({objectApiName:B,rows:N})=>({objectApiName:B,rows:N}))}:{},...V.length>0&&e.jobsUnderway&&e.jobsUnderway.length>0?{jobsUnderway:P0(e.jobsUnderway)}:{},...n.capped?{capped:n.capped}:{},...H?{simulated:H}:{},...w?{wholeOrg:w,...P.confirmation.checkpoint?{checkpoint:P.confirmation.checkpoint}:{}}:P.confirmation});if(Y==="confirmed")return e.onConfirmed(),await C(),v;throw Y==="declined"?new pt("WRITE_DECLINED","Forge execution was cancelled before it wrote the records it had read. Nothing was written."):new pt("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(I0).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 (${I(i)}); cloned records keep their source RecordTypeId.`);return}finally{t.removeEventListener("abort",n)}}async readRecordTypeMappings(e,t){let[r,n]=await Promise.all([e.sourceOrgId,e.targetOrgId].map(async o=>{let i=await q(o,this.deps.orgRegistry,this.deps.orgManager),a=()=>{o===e.targetOrgId?Un(t):t.requests++},{records:d}=await nr({query:async c=>(a(),i.query(c)),queryMore:async c=>(a(),i.queryMore(c))},bR);return RR(d)}));for(let o of vR(r,n))oe.warn(`[forge] ${SR(o)}`);return new kR().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=>qu.safeParse(o).success),...r===void 0?{}:{importNotMerged:r}});this.deps.broker.postToWebview(n)}async handleSaveTemplate(e){let t=it(_j,e,"forge:templates:save:error",this.deps);if(!t)return;let{template:r}=t;try{let o=[r,...(await this.loadTemplates()).templates.filter(i=>i.id!==r.id)];await this.saveTemplates(o)}catch(o){T(this.deps,"forge:templates:save","forge:templates:save:error",e,o);return}let n=A(this.deps,e,"forge:templates:save:response",{success:!0});this.deps.broker.postToWebview(n)}async handleDeleteTemplate(e){let t=it(Jj,e,"forge:templates:delete:error",this.deps);if(!t)return;let{templateId:r}=t;try{let o=(await this.loadTemplates()).templates.filter(i=>i.id!==r);await this.saveTemplates(o)}catch(o){T(this.deps,"forge:templates:delete","forge:templates:delete:error",e,o);return}let n=A(this.deps,e,"forge:templates:delete:response",{success:!0});this.deps.broker.postToWebview(n)}async handleHistoryList(e){await this.keepRunsLeftOver();let t=this.loadHistory(),r=await this.resumableRuns(t),n=[];try{n=await this.removalPlans?.list()??[]}catch(u){oe.warn(`Forge removal plans could not be read: ${I(u)}`)}let o=await this.journalsPresent([...t.flatMap(u=>u.remapInJournal&&u.journalId?[u.journalId]:[]),...n.flatMap(u=>u.inJournal?[u.inJournal.journalId]:[])]),i=t.map(u=>({...u,...r.has(u.forgeId)?{resumable:!0}:{},...u.remapInJournal&&!(u.journalId&&o.has(u.journalId))?{journalGone:!0}:{}})),a=new Set(i.map(u=>u.forgeId)),d=n.filter(u=>!a.has(u.forgeId)&&zr(u).length>0).map(u=>u.inJournal&&!o.has(u.inJournal.journalId)?{...u,journalGone:!0}:u);await this.dropJournalsNoLongerNamed(t,n);let c=A(this.deps,e,"forge:history:list:response",{history:i,...d.length>0?{olderRuns:d}:{}});this.deps.broker.postToWebview(c)}async handleUndo(e){let t={};try{await this.undoUnderItsLock(e,t)}finally{t.lock?.release()}}async undoUnderItsLock(e,t){let r=it(Uj,e,"forge:undo:error",this.deps);if(!r)return;let{forgeId:n}=r,o=r.includeChanged===!0,i=r.sweep===!0,a=r.again===!0,d=r.muteAutomation===!0,c=i&&r.sweepLate===!0,u=i&&r.sweepUntied===!0,l=(O,P)=>this.refuseUndo(e,O,P),g=this.loadHistory().find(O=>O.forgeId===n),p=g?void 0:await this.keptRemovalPlan(n),f,h={},m=g?.targetOrgId??p?.targetOrgId,y=g?g.journalId:p?.inJournal?.journalId;if(y){let O=this.journalBusy(y,"remove");if(O){l(O,vi);return}if(this.removing.has(n)){l("The records of this run are being removed already: its result shows under the run once it ends.",Fg);return}let P=this.lockToRemove(y,m);if(P&&"busy"in P){l(P.busy,vi);return}P&&(t.lock=P)}if(m&&y&&(!g||g.idRemapCreated)){if(this.removing.has(n)){l("The records of this run are being removed already: its result shows under the run once it ends.",Fg);return}this.removing.add(n);try{let O=await this.callsLookedForBeforeRemoval({forgeId:n,targetOrgId:m,journalId:y,removedBefore:(g??p)?.undo!==void 0});if("unread"in O){l(O.unread,"IN_FLIGHT_UNREAD");return}f=O.reconciled,h=O,f&&f.found.length>0&&(g?g=await this.withRowsFoundAfterStop(g,f.found):p&&(p=await this.planWithRowsFoundAfterStop(p,f.found)))}finally{this.removing.delete(n)}}let R,S,b=()=>{};if(g){let O=Date.parse(g.timestamp);if(!g.idRemapCreated||!g.targetOrgId||Number.isNaN(O)){l(`This run was recorded before Forge kept what a run created: its records cannot be removed from the history. ${Gc}`,"NOT_RECORDED");return}let P=g.remapInJournal&&g.journalId&&g.journalPart!==void 0?{journalId:g.journalId,part:g.journalPart}:void 0,v=x0(g.mayHaveBeenWritten,{...h,reconciled:f});if(R={...g,targetOrgId:g.targetOrgId,unreachable:$0(g.mayHaveBeenWritten,f),...v?{notLookedFor:v}:{},...P?{inJournal:P}:{}},g.remapInJournal){if(S=[],a||yn(g).length>0){let w=await this.journalRecordsOf(P,g.undo,a);if("gone"in w){l(w.gone,ds);return}S=w.records,b=w.close}}else S=a?Wr(g):bs(g)}else if(p){if(i){l(JA,"SWEEP_UNAVAILABLE");return}R={...p,unreachable:f&&f.calls>0?Wl(f):p.mayHaveBeenWritten??0,...h.callsNotLookedFor?{notLookedFor:{callsAfterRemoval:h.callsNotLookedFor}}:{}};let{inJournal:O}=p;if(O&&(a||zr(p).length>0)){let P=await this.journalRecordsOf(O,p.undo,a);if("gone"in P){l(P.gone,ds);return}S=P.records,b=P.close}else S=a?p.objects.map(({objectApiName:P,ids:v})=>({objectApiName:P,ids:[...v]})):Zu(p)}else{l("This run is no longer in the Forge history.",cs);return}try{let O=kl(S),P=i&&R.undo!==void 0,v=O===0&&XA(R),w=v&&o;if(O===0&&!P&&!w){R.undo?l(`The records this run created were already removed, on ${R.undo.removedAt}.`+(v?" What that removal kept as changed since the run, the duplicate record sets the target's rules made of them, goes once the records changed since are included.":""),"ALREADY_REMOVED"):l("This run created no record to remove.","NOTHING_TO_REMOVE");return}if(this.removing.has(n)){l("The records of this run are being removed already: its result shows under the run once it ends.",Fg);return}this.removing.add(n);let C=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(e.id);try{await this.removeRun(e,R,S,{includeChanged:o,again:a,muteAutomation:d,sweepLate:c,sweepUntied:u,...w?{setsAgain:!0}:{},...!i&&g?.config?.inputMode==="org"?{wholeOrgNotSwept:!0}:{}},i?g:void 0,C)}finally{this.removing.delete(n),C?.release()}}finally{b()}}async journalRecordsOf(e,t,r=!1){let n=this.runJournal;if(!n||!e)return{gone:Fn};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: ${I(o)}`),{gone:Fn}}}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: ${I(r)}`),new Set(e)}}async dropJournalsNoLongerNamed(e,t){let r=this.runJournal;if(r)try{let n=new Set([...e.map(o=>o.journalId),...t.map(o=>o.inJournal?.journalId),...this.journalsRunning].filter(o=>o!==void 0).map(o=>r.fileNameOf(o)));for(let o of await r.endedFiles())n.has(o)||await r.forgetFile(o)}catch(n){oe.warn(`Forge run journals could not be dropped: ${I(n)}`)}}async withIdsOf(e,t=!1){if(!e.remapInJournal)return{entry:e};let r=this.runJournal;if(!r||!e.journalId||e.journalPart===void 0)return{gone:Fn};try{let n=await r.idsOf(e.journalId,e.journalPart);if(!n)return{gone:Fn};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: ${I(n)}`),{gone:Fn}}}async planRecordsOf(e,t=!1){let r=this.runJournal;if(!r)return{gone:Fn};try{let{journalId:n,part:o}=e.inJournal,i=await r.idsOf(n,o);if(!i)return{gone:Fn};let a={idRemapTable:i.table,idRemapExisting:i.existing,idRemapCreated:i.createdByObject};if(t)return{records:Wr(a)};let d=await r.leftOf(n,o);return{records:bs({...a,...e.undo?{undo:e.undo}:{},...d?{removalLeft:d}:{}})}}catch(n){return oe.warn(`Forge run journal could not be read: ${I(n)}`),{gone:Fn}}}async keptRemovalPlan(e){try{return await this.removalPlans?.get(e)}catch(t){oe.warn(`Forge removal plans could not be read: ${I(t)}`);return}}async callsLookedForBeforeRemoval(e){let t=this.runJournal,{forgeId:r,journalId:n}=e;if(!t||this.journalsRunning.has(n))return{};try{if((await t.lastEnd(n))?.forgeId!==r)return{};let a=t.callsInFlight(n);if(e.removedBefore)return a>0?{journalRead:!0,callsNotLookedFor:a}:{};if(a===0)return{journalRead:!0}}catch{return{}}let o=ye(this.deps.orgManager.getOrg(e.targetOrgId),e.targetOrgId);try{let i=await q(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=await t.reconcile(n,Bl(i));for(let d of ql(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 (${I(i)}): removed without them, the records those calls wrote would stay behind. Nothing was deleted. Reconnect ${o} on Organizations if its session expired, then remove the run again.`}}}async datedByItsJournal(e,t){let r=this.runJournal,{journalId:n,part:o,scope:i}=e;if(!(!r||!n))try{return(await r.present([n])).has(n)?await r.writtenBetween(n,t,o,i):void 0}catch(a){oe.warn(`Forge run not dated from its journal: ${I(a)}`);return}}async withRowsFoundAfterStop(e,t){let r=this.runJournal,{journalId:n,journalPart:o}=e;if(!r||!n||o===void 0)return e;let i=t.reduce((u,{rows:l})=>u+l,0),a=D0(e.idRemapByObject,t),d;if(e.remapInJournal)d={...e,idRemapCount:e.idRemapCount+i,createdCount:(e.createdCount??0)+i,...a?{idRemapByObject:a}:{}};else{let u=await r.idsOf(n,o).catch(()=>{});if(!u)return e;d={...e,idRemapTable:u.table,idRemapExisting:u.existing,idRemapCreated:u.createdByObject,idRemapCount:Object.keys(u.table).length,createdCount:u.createdByObject.reduce((l,{sourceIds:g})=>l+g.length,0),...a?{idRemapByObject:a}:{}}}this.saveHistory(this.loadHistory().map(u=>u.forgeId===d.forgeId?d:u));let c=zi(d);return c&&await this.removalPlans?.put(c).catch(u=>{oe.warn(`Forge removal plan not kept: ${I(u)}`)}),d}async planWithRowsFoundAfterStop(e,t){let{inJournal:r}=e;if(!r)return e;let n=r.left.map(i=>({...i}));for(let{objectApiName:i,rows:a}of t){let d=n.find(c=>c.objectApiName===i);d?d.count+=a:n.unshift({objectApiName:i,count:a})}let o={...e,inJournal:{...r,left:n}};return await this.removalPlans?.put(o).catch(i=>{oe.warn(`Forge removal plan not kept: ${I(i)}`)}),o}async keepRunsLeftOver(){let e=this.runJournal;if(e)try{let t=new Set(this.journalsRunning);for(let r of await e.leftOver(t)){if(this.journalBusy(r.journalId,"remove")!==void 0)continue;let n=r.resume?.startedWith;if(!n){let o=HR.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=h0(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: ${I(t)}`)}}async resumableRuns(e){let t=new Set,r=this.runJournal;if(!r)return t;for(let n of e)if(!(!n.journalId||this.journalsRunning.has(n.journalId))){try{let o=await r.lastEnd(n.journalId);if(o?.forgeId!==n.forgeId||!HA.has(o.status))continue}catch{continue}WA(n,e)===void 0&&t.add(n.forgeId)}return t}async runToResume(e){let t=this.loadHistory(),r=t.find(l=>l.forgeId===e);if(!r)return{refused:"The run to resume is no longer in the history: what it wrote and where it stopped are not known. Run the clone again from Review. Nothing was read or written."};let n=r.targetOrgId,o=this.runJournal;if(!r.journalId||!o)return{refused:`This run kept no journal to take it up from: ${_A}`,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||!HA.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=WA(r,t);if(d!==void 0)return{refused:`The records ${d===r?"this run created":"a part of this run created"} were removed on ${d.undo?.removedAt}: there is nothing to resume against.`,targetOrgId:n};let c=await o.head(r.journalId),u=c?.resume?.startedWith;return!c?.resume||!u||c.targetOrgId!==n?{refused:`The journal of this run does not say how it was set up: ${_A}`,targetOrgId:n}:{entry:r,journalId:r.journalId,head:{...c.resume,startedWith:u},targetOrgId:c.targetOrgId,end:a}}async handleResumeRun(e){let t=it(jj,e,"forge:execute:error",this.deps);if(!t)return;let r=(y,R,S)=>{S&&Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:S,outcome:"stopped",code:y}),T(this.deps,"forge:execute","forge:execute:error",e,new Error(R),{code:y})},n=await this.runToResume(t.forgeId);if("refused"in n){r(Nj,n.refused,n.targetOrgId);return}let{entry:o,journalId:i,head:a,targetOrgId:d,end:c}=n,u=this.deps.orgManager.getOrg(d);if(!u){r(UA,"The org this run wrote to is no longer registered in SandForge: add the same org again on Organizations, then resume \u2014 the run checks it is the org it wrote to. Refreshed since, it holds nothing the run wrote: run the clone again. Nothing was read or written.",d);return}if(a.targetSalesforceOrgId!==void 0&&u.orgId&&u.orgId.slice(0,15)!==a.targetSalesforceOrgId.slice(0,15)){r(UA,`${ye(u,d)} is no longer the org this run wrote to \u2014 refreshed or replaced since: what the run wrote is not there. Run the clone again from Review into it as it is now. Nothing was read or written.`,d);return}let{graph:l,config:g,anonymizationRules:p}=a.startedWith,f=Bu(g);if(f!==void 0){r(_g,`${f}. Nothing was read or written.`,d);return}let h=this.maxRecordsPerObject(),m=y=>zR(a.fingerprint,y.graph,this.runSetupOf(y.config,p,h,a.targetSalesforceOrgId));if(!m({graph:l,config:g})){r(_g,"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(_g,"The clone on this page is set up otherwise than the run to resume: its objects, filters or decisions changed since.",d);return}await this.handleExecute(e,{forgeId:o.forgeId,journalId:i,head:a,end:c,startedWith:{graph:l,config:g,...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&&Hg.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 WR(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=zi(e),o=[...n?[r.put(n)]:[],...t.flatMap(i=>{let a=zi(i);return a&&zr(a).length>0?[r.putIfAbsent(a)]:[]})];Promise.all(o).catch(i=>{oe.warn(`Forge removal plan not kept: ${I(i)}`)})}refuseUndo(e,t,r){T(this.deps,"forge:undo","forge:undo:error",e,new Error(t),{code:r})}async handleOpenRecord(e){let t=it(qj,e,"forge:open-record:error",this.deps);if(!t)return;let r=(u,l)=>{T(this.deps,"forge:open-record","forge:open-record:error",e,new Error(u),{code:l})},n=this.loadHistory().find(u=>u.forgeId===t.forgeId);if(!n){r("This run is no longer in the Forge history.",cs);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,ds);return}let i=t.recordId.slice(0,15),a;for(let{objectApiName:u,ids:l}of Wr(o.entry)){let g=l.find(p=>p.slice(0,15)===i);if(g){a={objectApiName:u,id:g};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(FA,"ORG_NOT_FOUND");return}let c=ac(d.instanceUrl,a.objectApiName,a.id);if(!c.ok){let u=c.reason==="not-https"?`its instance URL must use HTTPS, got "${c.protocol}"`:c.reason==="invalid"?"its instance URL is not a valid URL":"the record is not one an address can be built for";r(`Cannot open the record in "${ye(d)}": ${u}.`,c.reason==="not-a-record"?"NOT_CREATED":"INVALID_INSTANCE_URL");return}try{let u=await this.externalBrowser.open(c.url),l=A(this.deps,e,"forge:open-record:response",u);this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id} status=${u.status}`)}catch(u){T(this.deps,"forge:open-record","forge:open-record:error",e,u)}}async handleVerify(e){let t=it(Wj,e,"forge:verify:error",this.deps);if(!t)return;let{forgeId:r}=t,n=(u,l)=>{T(this.deps,"forge:verify:request","forge:verify:error",e,new Error(u),{code:l})},o=this.loadHistory().find(u=>u.forgeId===r);if(!o){n("This run is no longer in the Forge history.",cs);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. ${Gc}`,"NOT_RECORDED");return}let a=o;if(o.remapInJournal&&yn(o).length>0){let u=await this.withIdsOf(o,!0);if("gone"in u){n(u.gone,ds);return}a=u.entry}let d=o.remapInJournal&&a===o?[]:bs(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(FA,"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.",Dj);return}this.verifying.add(r);let c=`forge-verify-${this.deps.nextId()}`;try{let u=await q(i,this.deps.orgRegistry,this.deps.orgManager),l=new lv({target:Kl(u,"forge:verify"),source:await this.verificationSource(o.sourceOrgId)}),g=o.writtenBetween??await this.datedByItsJournal({journalId:o.journalId,part:o.journalPart,scope:"part"},u),p=await l.verify({records:d,remapTable:a.idRemapTable??{},...g?{runStartedAt:new Date(g.first),runEndedAt:new Date(g.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:fv(o.writtenWithoutFields??[]),...o.lookupsLeftEmptyByFilter?{leftEmptyByFilter:o.lookupsLeftEmptyByFilter}:{},leftEmptyByTheRun:gv(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,...pv(p)}});let f=A(this.deps,e,"forge:verify:response",{verification:p});this.deps.broker.postToWebview(f),this.deps.log(`[TX] ${f.type} id=${f.id} verdict=${p.verdict}`)}catch(u){Z(this.deps,{action:"forge_verify",module:"forge",operationId:c,orgId:i,outcome:"failure",details:{forgeId:r}}),T(this.deps,"forge:verify:request","forge:verify:error",e,u,{code:"VERIFY_ERROR",retryable:!0})}finally{this.verifying.delete(r)}}async handleExportIds(e){let t=it(zj,e,"forge:export-ids:error",this.deps);if(!t)return;let r=(c,u)=>{T(this.deps,"forge:export-ids:request","forge:export-ids:error",e,new Error(c),{code:u})},n=this.loadHistory().find(c=>c.forgeId===t.forgeId);if(!n){r("This run is no longer in the Forge history.",cs);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,ds);return}i=Bf(c.entry)}let d=new Date().toISOString().slice(0,10);try{let c=await this.saveDialog.saveStream(`sandforge-forge-id-map-${d}.csv`,async g=>{await g(qf([]));let p=0,f=[];for(let h of i)f.push(h),!(f.length<Gj)&&(await g(`
18
+ ${el(f)}`),p+=f.length,f=[]);return f.length>0&&await g(`
19
+ ${el(f)}`),p+f.length},["csv"]),u=c.status==="saved"?{status:"saved",path:c.path,rows:c.result}:c,l=A(this.deps,e,"forge:export-ids:response",u);this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id} status=${c.status}`)}finally{a()}}async idMapRowsInJournal(e){let t=this.runJournal;if(!(!t||!e.journalId||e.journalPart===void 0))try{return await t.idMapRowsOf(e.journalId,e.journalPart)}catch(r){oe.warn(`Forge run journal could not be read: ${I(r)}`);return}}async verificationSource(e){if(!e)return{unavailable:"This run was recorded before Forge kept the org it read from."};if(!this.deps.orgManager.getOrg(e))return{unavailable:"The org this run read from is no longer registered."};try{let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return Kl(t,"forge:verify source")}catch(t){return{unavailable:`The org this run read from could not be reached: ${I(t)}`}}}async removeRun(e,t,r,n,o,i){let{includeChanged:a,again:d}=n,{forgeId:c,targetOrgId:u}=t,l=kl(r),g=l>0||n.setsAgain===!0,p=(E,x)=>this.refuseUndo(e,E,x),f=this.deps.infraServices?.productionGuard;if(!f){Z(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:u,outcome:"stopped",code:Re.code}),p(Re.message,Re.code);return}let h=this.deps.orgManager.getOrg(u),m=Pe(h),{check:y,decision:R}=g?await et(f,{orgId:u,orgTier:m,operation:"delete",objectName:l>0?Ol(r).join(", "):Sa,recordCount:l>0?l:"unknown",module:"forge"}):{check:void 0,decision:"allowed"};if(y&&(R==="refused"||R==="declined")){Z(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:u,outcome:"stopped",guard:R}),R==="refused"?p(`Operation blocked by Production Guard: ${y.blockedReason??y.impactSummary}`,"GUARD_BLOCKED"):T(this.deps,"forge:undo","forge:undo:error",e,new Error("Operation cancelled by user (confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}if(i?.signal.aborted){Z(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:u,outcome:"stopped",guard:R,code:bt});let E={forgeId:c,status:"cancelled",includeChanged:a,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(A(this.deps,e,"forge:undo:response",{result:E,operationId:e.id}));return}let S=e.id,b=l>0?`Removing ${l} record(s) a Forge run created`:n.setsAgain?"Removing the duplicate record sets a Forge run\u2019s records went in":"Sweeping what the target\u2019s automation created during a Forge run",O=new AbortController;Je(this.deps,S,"forge",b);let P=this.trackRun(S,b,O);this.liveTracker?.register(S,"forge",b,l);let v,w,C,k;try{let E=await q(u,this.deps.orgRegistry,this.deps.orgManager),{inJournal:x}=t,V=t.writtenBetween??await this.datedByItsJournal({journalId:t.journalId??x?.journalId,part:t.journalPart??x?.part},E),H={...t.removalStamps,...x?await this.runJournal?.stampsOf(x.journalId,x.part).catch(F=>(oe.warn(`Forge removal stamps not read: ${I(F)}`),{})):{}};l>0&&(w=await this.otherPartsOf(c,u,E));let Y=Il(t.removalSpans,w?.spans);o&&(C=await this.sweepOfRemoval({conn:E,entry:o,includeChanged:a,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,removalSpans:Y,signal:O.signal,guard:f,orgTier:m,operationId:S,muted:()=>g?void 0:k}));let B=C;await B?.ask();let N=B?.takes??[],L=n.muteAutomation===!0&&(g||N.length>0)?await this.removalMute(u,Ol(r),n.setsAgain?[...N,Sa]:N,w?.parts.flatMap(F=>F.objects)??[],t.runUserId!==void 0&&l>0):void 0,Q;k=L?.muted;let K=async()=>{let F=L?.prepared;!F||O.signal.aborted||(Q=await F.acquire(S),k=Q.outcome)},U=await(g?Uw(ir(E,"forge:undo"),r,{...V?{runStartedAt:new Date(V.first),runEndedAt:new Date(V.last)}:{runDurationMs:t.duration,runRecordedAt:new Date(t.timestamp)},...Object.keys(H).length>0?{removalStamps:H}:{},...Y.length>0?{removalSpans:Y}:{},...w&&w.laterParts.length>0?{laterParts:w.laterParts}:{},...B?{sweep:F=>B.first(F),afterRemoval:F=>B.afterRemoval(F),automationMade:B.automationMade}:{},...t.runUserId?{runUserId:t.runUserId}:{},...w&&w.parts.length>0?{otherParts:w.parts.map(F=>F.alongside)}:{},includeChanged:a,onUndeletable:Vr(this.deps,u,"forge:undo"),beforeFirstWrite:K,signal:O.signal,onProgress:(F,ee,_)=>{let de=Math.min(100,Math.round(F/Math.max(ee,1)*100));Fe(this.deps,S,de,F,ee,_),O.signal.aborted||this.deps.infraServices?.backgroundRegistry?.updateProgress(S,de),this.liveTracker?.updateProgress(S,de,F,ee,_)}}):(async()=>(await K(),await B?.first(),await B?.afterRemoval(),_w))()).finally(async()=>{Q&&(k=await Q.release())});w&&await this.keepOtherPartStamps(w.parts,U.otherPartStamps??[]);let re=await C?.settle(),ne=d?void 0:t.undo?.removedAt,ue=t.unreachable,ce=w?E0(U.objects,w.parts):[],be=(w?.parts??[]).flatMap(F=>F.undo&&F.records>0?[{forgeId:F.forgeId,records:F.records}]:[]),Xe={forgeId:c,status:Hw(U.objects,U.cancelled),includeChanged:a,objects:U.objects,finishedAt:new Date().toISOString(),...ne?{leftBy:ne}:{},...ue>0?{mayHaveBeenWritten:ue}:{},...t.notLookedFor?{notLookedFor:t.notLookedFor}:{},...k?{mutedAutomation:k}:{},...ce.length>0?{heldByOtherParts:ce}:{},...be.length>0?{otherPartsLeft:be}:{}};g&&Z(this.deps,{action:"cleanup_delete",module:"forge",operationId:S,orgId:u,outcome:$o(Xe),guard:R,objects:In(Xe.objects),...ne?{leftBy:ne}:{},...k?{muted:ut(k)}:{}});let De={...Xe,status:Co(Xe.status,re),...re?{sweep:re}:{},...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 _e=Bw(De,l,t.undo,d)??(n.setsAgain&&t.undo&&De.status!=="cancelled"?qw(De,t.undo):void 0),z=re&&tv(re,new Date().toISOString(),o?.sweep),se=Object.keys(U.stamps).length>0,te=U.span,he,D;if(x)(U.objects.some(ee=>ee.deleted+ee.alreadyGone>0)||d&&_e!==void 0)&&(D=await this.runJournal?.keepLeftPages(x.journalId,x.part,U.left()).catch(ee=>{oe.warn(`Forge removal left not kept: ${I(ee)}`)})),se&&await this.runJournal?.keepStamps(x.journalId,x.part,U.stamps).catch(ee=>{oe.warn(`Forge removal stamps not kept: ${I(ee)}`)});else if((U.gone.length>0||d&&_e)&&!Fw(r)){let F=new Set(U.gone);he=r.flatMap(({ids:ee})=>ee.filter(_=>!F.has(_)))}if(_e||se||te||he||D||z){let F=ee=>({...ee,..._e?{undo:_e}:{},...z?{sweep:z}:{},...se&&!x?{removalStamps:{...ee.removalStamps,...U.stamps}}:{},...te?{removalSpans:[...ee.removalSpans??[],te]}:{},...he?{removalLeft:he}:{}});this.saveHistory(this.loadHistory().map(ee=>ee.forgeId===c?{...F(ee),...D?{removalLeftByObject:D}:{}}:ee)),await this.removalPlans?.update(c,ee=>{let _={...F(ee),...ee.inJournal&&D?{inJournal:{...ee.inJournal,left:D}}:{}};return zr(_).length>0?_:void 0}).catch(ee=>{oe.warn(`Forge removal plan not updated: ${I(ee)}`)})}let W=A(this.deps,e,"forge:undo:response",{result:De,operationId:S});this.deps.broker.postToWebview(W);let X=De.status==="failure"?"No record this run created could be removed.":!g&&re&&re.status!=="success"?re.refusal??"The sweep left records in the org.":void 0;De.status==="cancelled"||re?.status==="cancelled"?(ge(this.deps,S,{aborted:!0}),this.liveTracker?.cancel(S)):(ge(this.deps,S,{status:X&&!g?"failure":De.status}),X?(v=new Error(X),this.liveTracker?.fail(S,X)):De.status==="partial"?this.liveTracker?.partial(S):this.liveTracker?.complete(S))}catch(E){v=E,await C?.settle().catch(V=>{oe.warn(`Forge sweep not recorded: ${I(V)}`)});let x=Dt(E)?E:void 0;Z(this.deps,{action:"cleanup_delete",module:"forge",operationId:S,orgId:u,outcome:x?"stopped":"failure",guard:R,...x?{code:x.code}:{}}),T(this.deps,"forge:undo","forge:undo:error",e,E,{code:x?.code??"UNDO_ERROR",retryable:!0}),ge(this.deps,S,{status:"failure"}),this.liveTracker?.fail(S,I(E))}finally{w?.close(),P(v)}}async otherPartsOf(e,t,r){let n=[],o=[],i=this.loadHistory(),a=new Set(i.map(l=>l.forgeId)),d=(await this.keptRemovalPlans()).filter(l=>!a.has(l.forgeId)),c=l=>T0(l,i,d,t),u=[];for(let l of await this.runLineOf(e,i,d)){let g=i.find(h=>h.forgeId===l),p=g?void 0:d.find(h=>h.forgeId===l);(g??p)?.targetOrgId===t&&u.push((g??p)?.removalSpans??[]);let f=g?await this.otherPartFromEntry(g,t,r,c(l)):await this.otherPartFromPlan(p,t,r,c(l));f&&(f.close&&n.push(f.close),o.push(f.part))}return{parts:o,spans:Il(...u),laterParts:c(e),close:()=>n.forEach(l=>l())}}async otherPartObjectsOf(e,t){let r=this.loadHistory(),n=new Set(r.map(a=>a.forgeId)),o=(await this.keptRemovalPlans()).filter(a=>!n.has(a.forgeId)),i=new Set;for(let a of await this.runLineOf(e,r,o)){let d=r.find(l=>l.forgeId===a),c=d?void 0:o.find(l=>l.forgeId===a);if((d??c)?.targetOrgId!==t)continue;let u=d?yn(d):c?zr(c):[];for(let{objectApiName:l}of u)i.add(l)}return[...i]}async runLineOf(e,t,r){let n=[...t.map(a=>({forgeId:a.forgeId,...a.retryOf!==void 0?{retryOf:a.retryOf}:{},...a.journalId!==void 0?{journalId:a.journalId}:{}})),...r.map(a=>({forgeId:a.forgeId,...a.retryOf!==void 0?{retryOf:a.retryOf}:{},...a.inJournal?{journalId:a.inJournal.journalId}:{}}))],o=this.runJournal,i=new Map;for(;;){let{inLine:a,journals:d}=A0(e,n,i),c=o?[...d].filter(u=>!i.has(u)):[];if(!o||c.length===0)return[...a].filter(u=>u!==e);for(let u of c)i.set(u,await o.partsOf(u).catch(l=>(oe.warn(`Forge run journal parts not read: ${I(l)}`),[])))}}async keptRemovalPlans(){try{return await this.removalPlans?.list()??[]}catch(e){return oe.warn(`Forge removal plans could not be read: ${I(e)}`),[]}}async otherPartFromEntry(e,t,r,n){if(e.targetOrgId!==t||!e.idRemapCreated||this.removing.has(e.forgeId)||yn(e).length===0)return;let o=e.remapInJournal&&e.journalId&&e.journalPart!==void 0?{journalId:e.journalId,part:e.journalPart}:void 0,i,a;if(o){let c=await this.journalRecordsOf(o,e.undo);if("gone"in c)return;i=c.records,a=c.close}else i=bs(e);let d=e.writtenBetween??await this.datedByItsJournal({journalId:e.journalId,part:e.journalPart},r);return{part:{forgeId:e.forgeId,...o?{inJournal:o}:{},alongside:await this.alongside(i,d,e,e.removalStamps,o,n),...e.undo?{undo:e.undo}:{},objects:yn(e).map(c=>c.objectApiName),records:yn(e).reduce((c,u)=>c+u.count,0)},...a?{close:a}:{}}}async otherPartFromPlan(e,t,r,n){if(!e||e.targetOrgId!==t||this.removing.has(e.forgeId)||zr(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=Zu(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:zr(e).map(c=>c.objectApiName),records:zr(e).reduce((c,u)=>c+u.count,0)},...a?{close:a}:{}}}async alongside(e,t,r,n,o,i){let a={...n,...o?await this.runJournal?.stampsOf(o.journalId,o.part).catch(()=>({})):{}};return{plan:e,span:nT(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: ${I(a)}`)});continue}let i=a=>({...a,removalStamps:{...a.removalStamps,...o}});this.saveHistory(this.loadHistory().map(a=>a.forgeId===n.forgeId?i(a):a)),await this.removalPlans?.update(n.forgeId,a=>i(a)).catch(a=>{oe.warn(`Forge removal plan not updated: ${I(a)}`)})}}sweepOfRemoval(e){let{conn:t,entry:r}=e,n=r.targetOrgId??"";return zo({input:async()=>{let o=await this.sweepInputOf(r,t,e.signal);return"gone"in o?{refused:o.gone}:o},org:rn(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:Go(i)}:{},objects:Bo(o),details:qo(o,r.forgeId),...a?{muted:ut(a)}:{}})},keepMade:async(o,i,a)=>{await this.removalPlans?.keepMade(r.forgeId,o,i,a).catch(d=>{oe.warn(`Forge sweep finds not kept: ${I(d)}`)})}})}async sweepInputOf(e,t,r){let n=await this.withIdsOf(e);if("gone"in n)return n;let o=n.entry,i=Wr(o),a=await this.sweepPartsBeside(e),d=new Set(Object.values(o.idRemapTable??{}).map(g=>g.slice(0,15))),c=this.targetAutomation,u=e.targetOrgId??"",l;if(!c)l={error:"Target automation reader not configured"};else try{l=await new fe(ki).withTimeout("forge:undo-sweep automation",()=>c.read(u,i.map(g=>g.objectApiName)))}catch(g){l={error:I(g)}}return Wo({writtenBetween:e.writtenBetween,created:i,remap:d,automation:ev(l),...e.runUserId?{runUserId:e.runUserId}:{},ties:await this.tiesOf(e),...a.length>0?{otherParts:a}:{},...r?{signal:r}:{}},ir(t,"forge:undo-sweep copies"))}async sweepPartsBeside(e){let t=this.loadHistory(),r=new Set(t.map(a=>a.forgeId)),n=(await this.keptRemovalPlans()).filter(a=>!r.has(a.forgeId)),o=[],i=0;for(let a of await this.runLineOf(e.forgeId,t,n)){i++;let d=t.find(l=>l.forgeId===a),c=d?void 0:n.find(l=>l.forgeId===a);if((d??c)?.targetOrgId!==e.targetOrgId)continue;let u;if(d){let l=await this.withIdsOf(d);"gone"in l||(u=Wr(l.entry))}else if(c?.inJournal){let l=await this.planRecordsOf({...c,inJournal:c.inJournal},!0);"gone"in l||(u=l.records)}else c&&(u=c.objects);u&&o.push({part:d?.journalPart??c?.inJournal?.part??i,created:u})}return o}async tiesOf(e){let t=e.writtenBetween,r=await this.localRunsOn(e.targetOrgId,t,e.forgeId);e.targetOrgId!==void 0&&r.push(...await this.otherModuleRuns(e.targetOrgId,t).catch(()=>[]));let n=e.mutedAutomation,o=Sv(e.removalSpans),i=await this.removalPlans?.madeOf(e.forgeId).catch(()=>[]),a=await this.removalPlans?.lateOf(e.forgeId).catch(()=>[]);return{otherRuns:bv(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(!Rv(t,d))return{ids:[],...d};let u=await c();return u?{ids:u.flatMap(({ids:l})=>l),...d}:{ids:[],idsUntold:!0,...d}};for(let d of this.loadHistory()){if(o.add(d.forgeId),d.forgeId===r||d.targetOrgId!==e)continue;let c=GA(d);i.push(d.remapInJournal?await a(c,async()=>{let u=await this.withIdsOf(d);return"gone"in u?void 0:Wr(u.entry)}):{ids:Wr(d).flatMap(({ids:u})=>u),...c})}for(let d of n??[]){if(o.has(d.forgeId)||d.forgeId===r||d.targetOrgId!==e)continue;let c=GA(d),u=d.inJournal;i.push(u?await a(c,async()=>{let l=await this.planRecordsOf({...d,inJournal:u},!0);return"gone"in l?void 0:l.records}):{ids:d.objects.flatMap(({ids:l})=>l),...c})}return i}setOtherModuleRuns(e){this.otherModuleRuns=e}setJournalLocks(e){this.journalLocks=e}journalBusy(e,t){let r=t==="remove"?"Removing its records now would delete under it what it goes on writing; remove them once it has ended.":"Taken up now, two runs would write the same journal; resume it once it has ended.";if(this.journalsRunning.has(e))return`A run of this window still writes this run's journal \u2014 a part that resumes it. ${r} Stop it on the Forge page, or let it end. Nothing was read or written.`;let n=this.runJournal;if(!n)return;let o;try{o=this.journalLocks.holder(n.pathOf(e))}catch(i){return`The lock of this run's journal, in ${Mg(n.pathOf(e))}, could not be read (${I(i)}): whether a run still writes it is not known. Try again once the folder can be read. Nothing was read or written.`}if(o)return`${Si(Va(o))}. ${r} ${Si(Ka(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:ye(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 (${I(o)})`);return}return"busy"in n?{busy:`${Si(Va(n.busy))}. Removing its records now would delete under it what it goes on writing; remove them once it has ended. ${Si(Ka(n.busy))}. Nothing was read or written.`}:n}async handleUndoSweep(e){let t=it(Bj,e,"forge:undo-sweep:error",this.deps);if(!t)return;let r=(a,d)=>T(this.deps,"forge:undo-sweep","forge:undo-sweep:error",e,new Error(a),{code:d}),n=this.loadHistory().find(a=>a.forgeId===t.forgeId);if(!n){r(JA,cs);return}let o=n.journalId?this.journalBusy(n.journalId,"remove"):void 0;if(o){r(o,vi);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. "+Gc,"NOT_RECORDED");return}try{let a=await new fe(R0).withTimeout("forge:undo-sweep",async()=>{let d=await q(i,this.deps.orgRegistry,this.deps.orgManager),c=await this.sweepInputOf(n,d);return"gone"in c?c:Ho(rn(d,"forge:undo-sweep"),c,n.removalSpans??[])});if("gone"in a){r(a.gone,ds);return}this.deps.broker.postToWebview(A(this.deps,e,"forge:undo-sweep:response",{forgeId:t.forgeId,listing:a}))}catch(a){let d=a instanceof vr;T(this.deps,"forge:undo-sweep","forge:undo-sweep:error",e,a,{code:d?"TIMEOUT":"SWEEP_ERROR",retryable:!0})}}async handlePlanRequest(e){if(!this.planGenerator){T(this.deps,"forge:plan","forge:plan:error",e,new Error("Plan generator not configured"),{code:"NOT_INITIALIZED"});return}let t=it(Vj,e,"forge:plan:error",this.deps);if(!t)return;let{graph:r,config:n}=t,o=`forge-plan-${this.deps.nextId()}`;Je(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(zA).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),ge(this.deps,o,{waveCount:a.waves?.length??0})}catch(i){let a=i instanceof vr;T(this.deps,"forge:plan","forge:plan:error",e,i,{code:a?"TIMEOUT":"PLAN_ERROR",retryable:a}),ge(this.deps,o,{status:"failure"})}}async readPersonalFields(e,t){let r=this.orchestrator;if(!r)return e;try{return await new fe(zA).withTimeout("forge:plan:personal-fields",n=>r.readPersonalFields(e,t,n))}catch(n){return oe.warn(`Forge personal fields not read: ${I(n)}`),e}}async handleComplianceRequest(e){if(!this.complianceService){T(this.deps,"forge:compliance","forge:compliance:error",e,new Error("Compliance service not configured"),{code:"NOT_INITIALIZED"});return}let t=it(Kj,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()}`;Je(this.deps,a,"forge","Generating compliance report");try{oe.info("Forge compliance report generation started");let d=await new fe(w0).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),ge(this.deps,a,{framework:r})}catch(d){let c=d instanceof vr;T(this.deps,"forge:compliance","forge:compliance:error",e,d,{code:c?"TIMEOUT":"COMPLIANCE_ERROR",retryable:c}),ge(this.deps,a,{status:"failure"})}}async handleMetadataDiffRequest(e){if(!this.metadataDiff){T(this.deps,"forge:metadata-diff","forge:metadata-diff:error",e,new Error("Metadata diff service not configured"),{code:"NOT_INITIALIZED"});return}let t=it(Xj,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()}`;Je(this.deps,i,"forge","Comparing metadata schemas");try{oe.info("Forge metadata diff started");let a=await new fe(b0).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}),ge(this.deps,i,{objectCount:o.length})}catch(a){let d=a instanceof vr;T(this.deps,"forge:metadata-diff","forge:metadata-diff:error",e,a,{code:d?"TIMEOUT":"METADATA_DIFF_ERROR",retryable:d}),ge(this.deps,i,{status:"failure"})}}async handleRehearseRequest(e){let t=this.rehearser,r=(v,w,C=!1)=>T(this.deps,"forge:rehearse","forge:rehearse:error",e,v,{code:w,retryable:C});if(!t){r(new Error("Forge rehearsal is not initialized"),"NOT_INITIALIZED");return}let n=it(Yj,e,"forge:rehearse:error",this.deps);if(!n)return;let{graph:o,config:i,anonymizationRules:a}=n;if(i.inputMode==="org"){r(new Error(Pj),Ej);return}let d=(v,w,C={})=>Z(this.deps,{action:"forge_rehearse",module:"forge",operationId:v,orgId:i.targetOrgId,outcome:w,...C}),c=(v,w,C=!1)=>{d(e.id,"stopped",{code:w}),r(v,w,C)},u=this.deps.infraServices?.productionGuard;if(!u){c(new Error(Re.message),Re.code);return}let l=this.deps.orgManager.getOrg(i.targetOrgId),g=Pe(l),p=ye(l,i.targetOrgId);if(g==="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."),Ug,!0);return}let f=`forge-rehearse-${this.deps.nextId()}`,h="Rehearsing a forge run";this.rehearseOperationId=f,Je(this.deps,f,"forge",h);let m=new AbortController,y=this.trackRun(f,h,m);this.liveTracker?.register(f,"forge",h);let R,S=!1,b=v=>this.deps.broker.postToWebview(A(this.deps,e,"forge:rehearse:progress",{...v})),O=v=>{if(v.phase!=="rehearsing"||!v.call||!v.calls)return;let w=Math.min(100,Math.round((v.call-1)/v.calls*100));m.signal.aborted||this.deps.infraServices?.backgroundRegistry?.updateProgress(f,w),this.liveTracker?.updateProgress(f,w,v.call-1,v.calls,`call ${v.call} of ${v.calls}`)},P=zc(b,100);try{let v=await this.automationBeforeTheRun(i.targetOrgId,o),w="automation"in v?v.automation:void 0,C=await this.loadRecordTypeMappings(i,new AbortController().signal,{requests:0}),k=await t.rehearse(o,i,{recordTypeMappings:C,anonymizationRules:a,signal:m.signal,onProgress:E=>{if(E.phase==="reading"){P(E);return}P.flush(),b(E),O(E)},confirm:async E=>{let x=await u.confirmRun({stage:"rehearsal",org:p,orgTier:g,rows:E.rows,sampled:E.sampled,updates:E.updates.reduce((V,H)=>V+H.updates,0),calls:E.calls,maxCalls:E.maxCalls,fired:w?jl(w):[],firedOnUpdate:w?Ml(w,E.updates.map(V=>V.objectApiName)):[],unread:w?Fl(w):[{part:"automation",reason:"unread"in v?v.unread:""}]});if(x==="confirmed"){S=!0;return}throw new Jc(x==="declined"?"REHEARSAL_DECLINED":"CONFIRMATION_UNAVAILABLE",x==="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:k})),this.trials.note("rehearsal",Vl(o,i)),oe.info("Forge rehearsal",{rows:k.rows,sampled:k.sampled,judged:k.judged,passed:k.passed,notJudged:k.notJudged,calls:k.calls,plannedCalls:k.plannedCalls,codes:[...new Set(k.gaps.flatMap(E=>typeof E.detail?.statusCode=="string"?[E.detail.statusCode]:[]))]}),d(f,"success",{guard:S?"confirmed":"allowed",details:H0(k)}),ge(this.deps,f,{status:"success"}),this.liveTracker?.complete(f)}catch(v){let w=v instanceof Jc?v:void 0,C=v instanceof uv?v:void 0,k=v instanceof cv?v:void 0,E=I(v);if(r(v instanceof Error?v:new Error(E),w?.code??(C?"REHEARSAL_CANCELLED":"REHEARSAL_ERROR"),!0),w||C){let x=w?.code==="REHEARSAL_DECLINED"?"declined":S?"confirmed":void 0;d(f,"stopped",{code:w?.code??"REHEARSAL_CANCELLED",...x?{guard:x}:{},...C?{details:{calls:C.calls}}:{}}),ge(this.deps,f,{aborted:!0}),this.liveTracker?.cancel(f)}else R=v,d(f,"failure",{...S?{guard:"confirmed"}:{},...k?{code:"REHEARSAL_NOT_ROLLED_BACK",details:{recordsLeft:k.ids.length},objects:k.objects.map(({objectApiName:x,created:V})=>({objectApiName:x,created:V,updated:0,deleted:0,failed:0}))}:{}}),je(this.deps,f,E,!0),this.liveTracker?.fail(f,E)}finally{P.flush(),y(R),this.rehearseOperationId===f&&(this.rehearseOperationId=null)}}async handleAutomationRequest(e){if(!this.targetAutomation){T(this.deps,"forge:automation","forge:automation:error",e,new Error("Target automation reader not configured"),{code:"NOT_INITIALIZED"});return}let t=it(Qj,e,"forge:automation:error",this.deps);if(!t)return;let{targetOrgId:r,graph:n}=t,o=`forge-automation-${this.deps.nextId()}`;Je(this.deps,o,"forge","Reading the target org's automation");try{let i=new fe(ki).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}),ge(this.deps,o,{objectCount:a.objectsRead.length})}catch(i){let a=i instanceof vr;T(this.deps,"forge:automation","forge:automation:error",e,i,{code:a?"TIMEOUT":"AUTOMATION_ERROR",retryable:a}),ge(this.deps,o,{status:"failure"})}}async readDeliverability(e,t){let r=()=>{},n=new Promise((o,i)=>{r=()=>i(new Error(_n)),t?.addEventListener("abort",r,{once:!0})});try{return await Promise.race([new fe(mb).withTimeout("forge:deliverability",async()=>Gt(await q(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=Ll(t,{leftOut:new Set(t.nodes.filter(Gi).map(d=>d.objectApiName))}),i=new Set(o.map(d=>d.objectApiName)),{ofRun:a}=await dr({read:r,writes:(d,c)=>c==="insert"||c==="update"&&i.has(d),readDeliverability:()=>Pe(n)==="production"?Promise.resolve(zt):this.readDeliverability(e),accepted:!1,target:ye(n,e),run:"clone"});return a.read?{...r,deliverability:a.read.reading,requests:r.requests+a.read.requests}:r}async handleUndoAutomation(e){let t=it(Hj,e,"forge:undo-automation:error",this.deps);if(!t)return;let r=(c,u)=>T(this.deps,"forge:undo-automation","forge:undo-automation:error",e,c,{code:u}),n=this.targetAutomation;if(!n){r(new Error("Target automation reader not configured"),"NOT_INITIALIZED");return}let o=this.loadHistory().find(c=>c.forgeId===t.forgeId);if(!o?.targetOrgId){r(new Error("This run is no longer in the Forge history."),cs);return}let i=o.journalId?this.journalBusy(o.journalId,"remove"):void 0;if(i){r(new Error(i),vi);return}let a=(t.again===!0?Hf(o):yn(o)).map(c=>c.objectApiName),d=o.targetOrgId;try{let c=await this.otherPartObjectsOf(t.forgeId,d),u=[...new Set([...On(a,c,{userKept:o.runUserId!==void 0}),...a.length===0&&XA(o)?[Sa]:[],...t.sweptObjects??[]])],l=await new fe(ki).withTimeout("forge:undo-automation",()=>n.read(d,u));this.deps.broker.postToWebview(A(this.deps,e,"forge:undo-automation:response",{forgeId:t.forgeId,automation:l,drafted:sr(a)}))}catch(c){let u=c instanceof vr;T(this.deps,"forge:undo-automation","forge:undo-automation:error",e,c,{code:u?"TIMEOUT":"AUTOMATION_ERROR",retryable:u})}}async handleGapsRequest(e){if(!this.targetGaps){T(this.deps,"forge:gaps","forge:gaps:error",e,new Error("Target gap reader not configured"),{code:"NOT_INITIALIZED"});return}let t=it(Zj,e,"forge:gaps:error",this.deps);if(!t)return;let{graph:r,config:n}=t,o=this.targetGaps,i=`forge-gaps-${this.deps.nextId()}`;Je(this.deps,i,"forge","Reading what the target org holds against the rows");try{let a=await new fe(v0).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}),ge(this.deps,i,{objectCount:r.nodes.length})}catch(a){let d=a instanceof vr;T(this.deps,"forge:gaps","forge:gaps:error",e,a,{code:d?"TIMEOUT":"GAPS_ERROR",retryable:d}),ge(this.deps,i,{status:"failure"})}}async handleUsersRequest(e){let t=it(e0,e,"forge:users:error",this.deps);if(t)try{let r=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),n=await r.query(DA);xe(r.limitInfo,"forge:users query");let{users:o,truncated:i}=NA(n.records,n.done===!1);this.deps.broker.postToWebview(A(this.deps,e,"forge:users:response",{orgId:t.orgId,users:o,truncated:i}))}catch(r){T(this.deps,"forge:users","forge:users:error",e,r,{code:"USERS_ERROR"})}}async handleTargetRecordsRequest(e){let t=it(t0,e,"forge:target-records:error",this.deps);if(t)try{let r=await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await new fe(us).withTimeout("forge:target-records",()=>r.request(`/services/data/v${r.version}/limits/recordCount`)),o=jb(n);if(!o)throw new Error("The target org answered its record counts in no form known.");let i=[...new Set(t.objectApiNames)].map(a=>({objectApiName:a,records:o.get(a)??0})).filter(({records:a})=>a>0).sort((a,d)=>d.records-a.records||a.objectApiName.localeCompare(d.objectApiName));this.deps.broker.postToWebview(A(this.deps,e,"forge:target-records:response",{targetOrgId:t.targetOrgId,objects:i}))}catch(r){T(this.deps,"forge:target-records","forge:target-records:error",e,r,{code:"TARGET_RECORDS_ERROR"})}}async handleSampleBudgetRequest(e){let t=it(r0,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=ZR({graph:r,options:n.sample,...n.excludedObjects?{excludedObjects:n.excludedObjects}:{},storage:o,source:i,maxRecordsPerObject:this.maxRecordsPerObject()});this.deps.broker.postToWebview(A(this.deps,e,"forge:sample-budget:response",{targetOrgId:n.targetOrgId,budget:a}))}catch(o){T(this.deps,"forge:sample-budget","forge:sample-budget:error",e,o,{code:"SAMPLE_BUDGET_ERROR"})}}async handlePreviewRoots(e){let t=it(n0,e,"forge:previewRoots:error",this.deps);if(!t)return;let{sourceOrgId:r,soqlQuery:n}=t,o=t.maxRoots??this.maxRoots(),i=Tb(n);if("issue"in i){let c=$b(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 q(r,this.deps.orgRegistry,this.deps.orgManager),u=d.limit!==void 0&&d.limit<=o?d.limit:o+1,{records:l,pages:g}=await new fe(y0).withTimeout("forge:previewRoots",()=>nr({query:async p=>c.query(p),queryMore:async p=>c.queryMore(p)},Eb(a,d,void 0,o),u));xe(c.limitInfo,`forge:previewRoots ${a}`),this.deps.broker.postToWebview(A(this.deps,e,"forge:previewRoots:response",{sourceOrgId:r,soqlQuery:n,objectApiName:a,cap:o,chosen:Math.min(l.length,o),more:l.length>o,...d.limit!==void 0?{limit:d.limit}:{},...d.orderBy!==void 0?{orderBy:d.orderBy}:{},requests:g}))}catch(c){T(this.deps,"forge:previewRoots","forge:previewRoots:error",e,c,{code:"ROOTS_PREVIEW_ERROR",retryable:!0,extraPayload:{soqlQuery:n}})}}maxRoots(){let e=this.deps.services?.getSandforgeSetting?.("forge.maxRoots",Uu);return Ab(typeof e=="number"?e:void 0,Uu)}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(!Hu(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:l,ids:g,sha256:p,readAt:f,query:h}=e.retried;return{...o,plan:{version:1,sourceOrgId:t.sourceOrgId,fingerprint:"",objectApiName:l,...h?{query:h}:{},from:"query",readAt:f,ids:g,sha256:p},planOfTheRunRetried:!0}}let i=this.runJournal?.storagePath;if(i===void 0||e.resumes)return o;await Gl(i,new Date).catch(l=>{oe.warn(`Forge roots: the roots of past simulations were not swept (${I(l)})`)});let d=this.setupFingerprintOf(e.graph,t,e.anonymizationRules,e.readCeiling),c;try{c=BR(i,d)}catch(l){if(l instanceof zl)return o;throw l}if(e.dryRun)return{...o,keepAt:c,fingerprint:d};let u;try{u=await qR(c)}catch(l){if(!(l instanceof zl))throw l;l.fault==="changed"&&oe.warn(`Forge roots: the simulation's roots no longer read whole (${l.message})`)}return{...o,fingerprint:d,...u?{plan:u}:{}}}};import{randomUUID as B0}from"node:crypto";import*as iT from"node:os";import*as Fr from"node:path";var oT=50*1024*1024,q0=new Set(["migration:pick-file","migration:import-sfdmu","migration:save-sync-config"]),W0="Saved from the SandForge SFDMU Import page",z0=new Set([".json"]);function G0(s,e,t){if(typeof s!="string"||s.trim().length===0)throw new Error("Invalid import path: path is empty.");if(!Fr.isAbsolute(s))throw new Error(`Invalid import path: "${s}" is not absolute. Pick a file inside the workspace or your home directory.`);let r=Fr.resolve(s),n=Fr.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=Fr.resolve(i);if(process.platform==="win32"){let d=r.toLowerCase(),c=a.toLowerCase();return d===c||d.startsWith(c+Fr.sep)}return r===a||r.startsWith(a+Fr.sep)}))throw new Error("Invalid import path: the file must be inside an open workspace folder or your home directory.");return r}async function sT(s,e){let t=await s.statSize(e);if(t>oT){let r=(t/1048576).toFixed(1),n=oT/(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 Kc=class{constructor(e){this.deps=e}deps;fileReader;setFileReader(e){this.fileReader=e}async handle(e){if(!q0.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=$(My,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(oh(o.list(),n)){r({success:!1,code:"DUPLICATE_NAME"});return}let a=(Array.isArray(t.config.objects)?t.config.objects:[]).map(l=>typeof l=="object"&&l!==null?l.objectApiName:void 0).filter(l=>typeof l=="string").filter(l=>aa(l));if(a.length>0){r({success:!1,code:"SYNC_CANNOT_COPY",objects:a});return}let d=new Date().toISOString(),c=nm.safeParse({...t.config,id:B0(),name:n,description:W0,createdAt:d,updatedAt:d});if(!c.success){let[l]=c.error.issues;r({success:!1,code:"INVALID_CONFIG",reason:l?`${l.path.join(".")}: ${l.message}`:c.error.message});return}let u=c.data;o.save(u),this.deps.log(`[TX] migration:save-sync-config:response saved ${u.id}`),r({success:!0,id:u.id,name:u.name})}catch(n){T(this.deps,"migration:save-sync-config","migration:error",e,n)}}getAllowedBaseDirs(){return[...this.deps.services?.getWorkspaceFolders?.()??[],iT.homedir()]}async handlePickFile(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.fileReader;if(!t?.pickExportFile)throw new Error("Migration services not available.");let r=await t.pickExportFile();this.deps.broker.postToWebview(A(this.deps,e,"migration:pick-file:response",r===void 0?{}:{filePath:r}))}catch(t){T(this.deps,"migration:pick-file","migration:error",e,t)}}async handleImportSfdmu(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(jy,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=G0(r,z0,this.getAllowedBaseDirs());await sT(n,o);let{SfdmuImporter:i,SfdmuRefusal:a}=await import("./chunk-LNXBCE7E.mjs"),d=new i({readFile:async c=>(c!==o&&await sT(n,c),n.readFile(c))});try{let{config:c,notes:u}=await d.import(o),l=A(this.deps,e,"migration:import-sfdmu:response",{success:!0,config:c,notes:u});this.deps.broker.postToWebview(l)}catch(c){if(!(c instanceof a))throw c;this.deps.log(`[ERR] migration:import-sfdmu: ${c.message}`),this.deps.broker.postToWebview(A(this.deps,e,"migration:import-sfdmu:response",{success:!1,error:c.message,code:c.code,objects:[...c.objects]}))}}catch(n){this.deps.log(`[ERR] migration:import-sfdmu: ${I(n)}`);let o=A(this.deps,e,"migration:import-sfdmu:response",{success:!1,error:I(n)});this.deps.broker.postToWebview(o)}}};import*as ls from"node:fs/promises";var uT="settings",aT=J({version:j(),exportedAt:j(),exportedBy:j().optional(),categories:ve(We(["syncMappings","forgePlans","pipelines","anonymizationTemplates",uT])),data:Mi(j(),hn())});function dT(s){return s!==uT}var Bg={syncMappings:"sync:config:",forgePlans:"forge:templates",pipelines:"pipeline:saved:",anonymizationTemplates:"anonymization:"},cT={syncMappings:"syncConfigs",forgePlans:"forge",pipelines:"pipelines",anonymizationTemplates:"anonymizationTemplates"},Oi="forge:templates";function J0(s){return typeof s.name=="string"&&s.name.length>0?s.name:s.id}var Xc=class{constructor(e,t){this.configStore=e;this.workspace=t}configStore;workspace;async exportProfile(e,t){try{let r={},n=0;for(let i of e){if(i==="forgePlans"){let u=await this.heldTemplates();r[i]=u.length>0?{[Oi]:u}:{},n+=u.length;continue}let a=Bg[i],d=this.configStore.getKeysByPrefix(a),c={};for(let u of d){let l=this.configStore.get(u);l!==void 0&&(c[u]=l,n++)}r[i]=c}let o={version:"1.0.0",exportedAt:new Date().toISOString(),exportedBy:t,categories:e,data:r};return{success:!0,json:JSON.stringify(o,null,2),categoriesExported:e.length,entriesExported:n}}catch(r){return{success:!1,categoriesExported:0,entriesExported:0,error:r instanceof Error?r.message:String(r)}}}async importProfile(e,t=!0){let r=[];try{let n=JSON.parse(e),o=aT.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(dT),d=0;for(let c of a){let u=i.data[c];if(!u||typeof u!="object"){r.push(`Category "${c}" has no data, skipped.`);continue}if(c==="forgePlans"){d+=await this.importTemplates(u,t,r);continue}let l=Bg[c];for(let[g,p]of Object.entries(u)){if(!g.startsWith(l)){r.push(`Key "${g}" does not match expected prefix "${l}" for category "${c}", skipped.`);continue}if(!t&&this.configStore.has(g)){r.push(`Key "${g}" already exists, skipped.`);continue}if(this.configStore.set(g,p,cT[c]),d++,c==="pipelines"){let f=mS(this.configStore,g.slice(l.length));f.length>0&&r.push(`Pipeline "${g}" was written over: confirm its Rewind ${f.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=aT.safeParse(t);return r.success?{valid:!0,categories:r.data.categories.filter(dT)}:{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(Bg)){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(Oi);return Array.isArray(r)?r.filter(pn):[]}let e=await this.workspace.readTemplates(),t=Wc(this.configStore,this.workspace.folder);return t?Ri(e,t.templates,new Set(t.replacing)):[...e]}async importTemplates(e,t,r){let n=await this.heldTemplates(),o=new Set(n.map(c=>c.id)),i=new Set,a=[],d=[];for(let[c,u]of Object.entries(e)){if(c!==Oi){r.push(`Key "${c}" does not match expected prefix "${Oi}" for category "forgePlans", skipped.`);continue}if(!Array.isArray(u)){r.push(`Key "${c}" holds no list of templates, skipped.`);continue}for(let l of u){if(!pn(l)){r.push(`An entry of "${c}" has no id, skipped.`);continue}if(!i.has(l.id)){if(i.add(l.id),o.has(l.id)){if(!t){r.push(`Forge template "${J0(l)}" already exists, skipped.`);continue}d.push(l.id)}a.push(l)}}}return this.workspace?CA(this.configStore,this.workspace.folder,a,d):a.length>0&&this.configStore.set(Oi,Ri(n,a,new Set(d)),cT.forgePlans),a.length}};import*as qg from"node:path";var Yc=class{deps;filePath;constructor(e){this.deps=e,this.filePath=qg.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(pn):[]}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=Ri(r,e.filter(pn),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=qg.join(this.deps.workspacePath,".sandforge");await this.deps.mkdir(t).catch(()=>{}),await this.deps.writeFile(this.filePath,JSON.stringify(e,null,2))}};var V0=new Set(["config:export","config:import","config:categories","config:validate"]);function K0(s){let e=s.services?.getWorkspaceFolders?.()[0];if(!e)return;let t=new Yc({workspacePath:e,readFile:r=>ls.readFile(r,"utf-8"),writeFile:(r,n)=>ls.writeFile(r,n,"utf-8"),mkdir:r=>ls.mkdir(r,{recursive:!0}).then(()=>{})});return{folder:e,readTemplates:()=>t.list()}}var Qc=class{constructor(e){this.deps=e;this.profileManager=new Xc(e.configStore,K0(e))}deps;profileManager;async handle(e){if(!V0.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=$(qy,e,"config:error",this.deps);if(!t)return;let r=t;try{let n=await this.profileManager.exportProfile(r.categories),o=A(this.deps,e,"config:export:response",{success:n.success,json:n.json,categoriesExported:n.categoriesExported,entriesExported:n.entriesExported,error:n.error});this.deps.broker.postToWebview(o),this.deps.log(`[TX] config:export:response (${n.entriesExported} entries)`)}catch(n){T(this.deps,"config:export","config:error",e,n)}}async handleImport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Wy,e,"config:error",this.deps);if(!t)return;let r=t;try{let n=await this.profileManager.importProfile(r.json,r.overwrite),o=A(this.deps,e,"config:import:response",{success:n.success,categoriesImported:n.categoriesImported,entriesImported:n.entriesImported,warnings:n.warnings,error:n.error});this.deps.broker.postToWebview(o),this.deps.log(`[TX] config:import:response (${n.entriesImported} entries)`)}catch(n){T(this.deps,"config:import","config:error",e,n)}}async handleCategories(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=await this.profileManager.listCategories(),r=A(this.deps,e,"config:categories:response",{categories:t});this.deps.broker.postToWebview(r),this.deps.log("[TX] config:categories:response")}catch(t){T(this.deps,"config:categories","config:error",e,t)}}handleValidate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(zy,e,"config:error",this.deps);if(!t)return;let r=t;try{let n=this.profileManager.validateProfile(r.json),o=A(this.deps,e,"config:validate:response",{valid:n.valid,categories:n.categories,error:n.error});this.deps.broker.postToWebview(o),this.deps.log("[TX] config:validate:response")}catch(n){T(this.deps,"config:validate","config:error",e,n)}}};var X0=J({metric:j(),operator:We(["gt","gte","lt","lte","eq","neq"]),threshold:Te(),warningThreshold:Te().optional()}),Y0=J({id:j(),name:j(),description:j(),category:We(["security","performance","compliance","custom"]),condition:X0,remediation:j(),enabled:Ke()}),Ii=J({id:j(),name:j(),description:j(),rules:ve(Y0),createdAt:j(),updatedAt:j()});function lT(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 Zc=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";lT(a,n,o)?d="fail":i!==void 0&&lT(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 eu="governance:policy:",Q0="governance",Ai=class{constructor(e){this.configStore=e}configStore;getAll(){let e=this.configStore.getKeysByPrefix(eu),t=[];for(let r of e){let n=this.configStore.get(r);if(n){let o=Ii.safeParse(n);o.success&&t.push(o.data)}}return t}getById(e){let t=this.configStore.get(`${eu}${e}`);if(!t)return;let r=Ii.safeParse(t);return r.success?r.data:void 0}save(e){this.configStore.set(`${eu}${e.id}`,e,Q0)}delete(e){return this.configStore.delete(`${eu}${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 Z0={apiUsagePercent:"DailyApiRequests",storageUsagePercent:"DataStorageMB"},eM=new Set(["governance:policies:list","governance:policy:save","governance:policy:delete","governance:evaluate","governance:templates"]),tu=class{constructor(e,t){this.deps=e;this.store=new Ai(e.configStore),this.engine=new Zc,this.alertEngine=t}deps;store;engine;alertEngine;async handle(e){if(!eM.has(e.type))return!1;switch(e.type){case"governance:policies:list":return this.handlePoliciesList(e),!0;case"governance:policy:save":return this.handlePolicySave(e),!0;case"governance:policy:delete":return this.handlePolicyDelete(e),!0;case"governance:evaluate":return await this.handleEvaluate(e),!0;case"governance:templates":return this.handleTemplates(e),!0;default:return!1}}handlePoliciesList(e){try{let r=this.store.getAll().map(o=>({id:o.id,name:o.name,description:o.description,ruleCount:o.rules.length,createdAt:o.createdAt,updatedAt:o.updatedAt})),n=A(this.deps,e,"governance:policies:result",{policies:r});this.deps.broker.postToWebview(n),this.deps.log("[TX] governance:policies:result")}catch(t){T(this.deps,"governance:policies:list","governance:error",e,t)}}handlePolicySave(e){let t=$(_y,e,"governance:error",this.deps);if(t)try{let r=Ii.safeParse(t.policy);if(!r.success){T(this.deps,"governance:policy:save","governance:error",e,new Error(`Validation failed: ${r.error.message}`),{code:"VALIDATION_ERROR"});return}this.store.save(r.data);let n=A(this.deps,e,"governance:policy:save:response",{success:!0});this.deps.broker.postToWebview(n),this.deps.log("[TX] governance:policy:save:response")}catch(r){T(this.deps,"governance:policy:save","governance:error",e,r)}}handlePolicyDelete(e){let t=$(Fy,e,"governance:error",this.deps);if(t)try{let r=this.store.delete(t.policyId),n=A(this.deps,e,"governance:policy:delete:response",{success:r});this.deps.broker.postToWebview(n),this.deps.log("[TX] governance:policy:delete:response")}catch(r){T(this.deps,"governance:policy:delete","governance:error",e,r)}}async handleEvaluate(e){let t=$(Uy,e,"governance:error",this.deps);if(!t)return;let r=t;try{let n=this.store.getById(r.policyId);if(!n){T(this.deps,"governance:evaluate","governance:error",e,new Error(`Policy not found: ${r.policyId}`),{code:"NOT_FOUND"});return}let i=await(await q(r.orgId,this.deps.orgRegistry,this.deps.orgManager)).request(`/services/data/${Ro}/limits`),a={};for(let[u,{Max:l,Remaining:g}]of Object.entries(i))a[u]=l>0?Math.round((l-g)/l*100):0;for(let[u,l]of Object.entries(Z0))l in a&&(a[u]=a[l]);let d=this.engine.evaluatePolicy(n,a);if(this.alertEngine)for(let u of d.ruleResults)u.status==="fail"&&u.actualValue!==null&&this.alertEngine.evaluate(`governance:${u.ruleId}`,u.actualValue,r.orgId);let c=A(this.deps,e,"governance:evaluate:response",{success:!0,result:d});this.deps.broker.postToWebview(c),this.deps.log("[TX] governance:evaluate:response")}catch(n){T(this.deps,"governance:evaluate","governance:error",e,n)}}handleTemplates(e){try{let t=Ai.getDefaultTemplates(),r=A(this.deps,e,"governance:templates:response",{templates:t});this.deps.broker.postToWebview(r),this.deps.log("[TX] governance:templates:response")}catch(t){T(this.deps,"governance:templates","governance:error",e,t)}}};var ru=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 tM=new Set(["OpportunityId","CaseId","ContractId","OrderId"]),nu=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)||Ph(c))continue;let u=this.inferRelationshipType(d.name);a.push({childObject:e,parentObject:c,lookupField:d.name,relationshipType:u,suggestedInsertOrder:0})}return a}inferRelationshipType(e){return tM.has(e)?"masterDetail":"lookup"}};var ou=class{estimate(e,t=new Set,r=200){let n=r>0?r:200,o=e.map(c=>({objectApiName:c.objectApiName,recordCount:c.count,...c.heldInSource!==void 0?{heldInSource:c.heldInSource}:{},estimatedApiCalls:c.count>0?Math.ceil(c.count/n):0,isParentDependency:t.has(c.objectApiName)})),i=o.reduce((c,u)=>c+u.recordCount,0),a=o.reduce((c,u)=>c+u.estimatedApiCalls,0),d=a*2;return{objects:o,totalRecords:i,totalApiCalls:a,estimatedDurationSec:d}}};var su=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 Zp(e,t)}inferType(e,t){return e.apiName===t.apiName&&e.type===t.type?"direct":e.apiName!==t.apiName?"rename":"direct"}};var rM=new Set(["quicksync:suggest-objects","quicksync:detect-relationships","quicksync:preview","quicksync:execute"]),Ti={direction:"source_to_target",mode:"full",conflictStrategy:"source_wins",operation:"insert",batchSize:200},iu=class{constructor(e){this.deps=e}deps;suggester=new ru;relationshipDetector=new nu;previewEstimator=new ou;autoFieldMapper=new su;async handle(e){if(!rM.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=$(Sy,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let i=(await(await q(r.orgId??"",this.deps.orgRegistry,this.deps.orgManager)).describeGlobal()).sobjects.filter(c=>c.createable&&c.queryable).map(c=>c.name),a=this.suggester.suggest(i,r.alreadySelected??[]),d=A(this.deps,e,"quicksync:suggest-objects:response",{suggestions:a,availableObjects:[...i].sort((c,u)=>c.localeCompare(u))});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(n){T(this.deps,"quicksync:suggest-objects","quicksync:error",e,n)}}async handleDetectRelationships(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(ky,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let n=await q(r.orgId??"",this.deps.orgRegistry,this.deps.orgManager),i=(await n.describe(r.objectApiName??"")).fields.map(u=>({name:u.name,type:u.type,referenceTo:u.referenceTo??[],relationshipName:u.relationshipName??null})),a=r.availableObjects??(await n.describeGlobal()).sobjects.filter(u=>u.createable&&u.queryable).map(u=>u.name),d=this.relationshipDetector.detect(r.objectApiName??"",i,r.alreadySelected??[],a),c=A(this.deps,e,"quicksync:detect-relationships:response",{suggestions:d});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(n){T(this.deps,"quicksync:detect-relationships","quicksync:error",e,n)}}async handlePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Oy,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let n=await q(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=[...new Set([...r.selectedObjects,...r.parentObjects??[]])],i=[],a=id(this.deps.services?.getSandforgeSetting?.("sync.maxRecordsPerObject",void 0));for(let l of o){let p=(await n.query(`SELECT COUNT() FROM ${l}`)).totalSize??0;i.push({objectApiName:l,count:Math.min(p,a),...p>a?{heldInSource:p}:{}})}let d=new Set(r.parentObjects??[]),c={...this.previewEstimator.estimate(i,d),readCap:a},u=A(this.deps,e,"quicksync:preview:response",{preview:c});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`)}catch(n){T(this.deps,"quicksync:preview","quicksync:error",e,n)}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Iy,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let n=vf.parse(r.config),o=await q(n.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),i=await q(n.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=[...new Set([...n.selectedObjects,...n.parentObjects])],d=[];for(let l=0;l<a.length;l++){let g=a[l],p=n.parentObjects.includes(g),[f,h]=await Promise.all([Yt(n.sourceOrgId,g,()=>o.describe(g)),Yt(n.targetOrgId,g,()=>i.describe(g))]),m=f.fields.filter(b=>b.createable).map(b=>({apiName:b.name,label:b.label,type:b.type})),y=h.fields.filter(b=>b.createable).map(b=>({apiName:b.name,label:b.label,type:b.type})),R=this.autoFieldMapper.suggest(m,y),S=this.autoFieldMapper.toMappings(R);d.push({objectApiName:g,operation:Ti.operation,fieldMappings:S,transformRules:[],excludedFields:[],batchSize:Ti.batchSize,insertOrder:p?0:l+1})}let c={id:e.id,name:`Quick Sync ${new Date().toISOString()}`,description:"Auto-generated by Quick Sync",sourceOrgId:n.sourceOrgId,targetOrgId:n.targetOrgId,direction:Ti.direction,mode:Ti.mode,objects:d,conflictStrategy:Ti.conflictStrategy,enableRollback:!1};Ie(this.deps,"info","Quick Sync",`Starting sync of ${a.length} object(s)`);let u=A(this.deps,e,"quicksync:execute:response",{syncConfig:c,objectCount:a.length});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`)}catch(n){T(this.deps,"quicksync:execute","quicksync:error",e,n)}}};var pT=6e4,nM=2880*6e4,oM=60*6e4,au=class{deps;schedules=new Map;checkInterval;lastTickTime=0;claims;lastPrune=0;running=new Set;constructor(e){this.deps=e,this.claims=e.claims??ss()}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()},pT),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+dS)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*pT&&this.deps.log(`[SyncScheduleExecutor] sleep-wake detected (elapsed ${Math.round(t/1e3)}s)`),this.lastTickTime=e,e-this.lastPrune>=oM&&(this.lastPrune=e,this.claims.prune(nM));for(let r of this.schedules.values()){if(!r.enabled||!r.nextRunAt)continue;let n=new Date(r.nextRunAt).getTime();if(Number.isNaN(n)){let i=r.nextRunAt;r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),this.deps.scheduleStore.save(r),this.deps.log(`[SyncScheduleExecutor] ${r.id}: next run "${i}" cannot be read, replaced by ${r.nextRunAt||"none"}`);continue}if(n>e||this.running.has(r.id))continue;if(!this.claims.claim(`sync-schedule:${r.id}:${n}`)){this.deps.log(`[SyncScheduleExecutor] ${r.id} due at ${r.nextRunAt} is run by another window`),r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone);continue}let o=this.deps.configStore.load(r.configId);if(!o){this.deps.log(`[SyncScheduleExecutor] config not found for schedule ${r.id} (configId=${r.configId})`),r.lastRunAt=new Date(e).toISOString(),r.lastResult="failure",r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),r.updatedAt=new Date(e).toISOString(),this.deps.scheduleStore.save(r),r.notifyOnFailure&&this.deps.notificationCenter.notify("error","Sync schedule failed",`${r.name}: sync configuration "${r.configId}" no longer exists. Save the configuration again, or delete the schedule.`);continue}r.notifyOnComplete&&this.deps.notificationCenter.notify("info","Sync schedule started",r.name),this.running.add(r.id);try{let i=await this.deps.onExecute(o);if(r.lastRunAt=new Date(e).toISOString(),r.lastResult=i.cancelled?"cancelled":i.status,r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),r.updatedAt=new Date(e).toISOString(),this.deps.scheduleStore.save(r),i.cancelled)r.notifyOnComplete&&this.deps.notificationCenter.notify("info","Sync schedule cancelled",`${r.name}: ${i.error??"the run was cancelled."} Its entry in the sync history has what it wrote.`);else if(i.status==="failure"){if(r.notifyOnFailure){let a=i.objectResults.flatMap(d=>d.errors)[0];this.deps.notificationCenter.notify("error","Sync schedule failed",`${r.name}: ${a??"the run failed; its entry in the sync history has the details."}`)}}else if(i.status==="partial"&&r.notifyOnComplete){let a=i.objectResults.flatMap(u=>u.errors)[0],d=ad(i),c=[a,d].filter(u=>u!==void 0);this.deps.notificationCenter.notify("warning",a===void 0&&d!==void 0?"Sync schedule copied part of the source":"Sync schedule completed with errors",`${r.name}: ${c.length>0?c.join("; "):"some records failed; its entry in the sync history has the details."}`)}else r.notifyOnComplete&&this.deps.notificationCenter.notify("success","Sync schedule completed",r.name)}catch(i){if(r.lastRunAt=new Date(e).toISOString(),r.lastResult="failure",r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),r.updatedAt=new Date(e).toISOString(),this.deps.scheduleStore.save(r),r.notifyOnFailure){let a=i instanceof Error?i.message:String(i);this.deps.notificationCenter.notify("error","Sync schedule failed",`${r.name}: ${a}`)}}finally{this.running.delete(r.id)}}}upsert(e){let t=this.schedules.get(e.id),r={...e,nextRunAt:this.computeNextRunAt(e.cron,e.timezone),lastRunAt:t?.lastRunAt,lastResult:t?.lastResult};return this.schedules.set(r.id,r),this.deps.scheduleStore.save(r),this.deps.log(`[SyncScheduleExecutor] upserted schedule ${r.id}`),r}delete(e){let t=this.schedules.delete(e);return t&&(this.deps.scheduleStore.delete(e),this.deps.log(`[SyncScheduleExecutor] deleted schedule ${e}`)),t}toggle(e,t){let r=this.schedules.get(e);if(r)return r.enabled=t,t&&(r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone)),r.updatedAt=new Date(this.now()).toISOString(),this.deps.scheduleStore.save(r),this.deps.log(`[SyncScheduleExecutor] toggled ${e} -> ${t?"enabled":"disabled"}`),r}getSchedules(){return Array.from(this.schedules.values())}getSchedule(e){return this.schedules.get(e)}computeNextRunAt(e,t){let r=pd(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 Wg="schedule:sync:",gT="syncSchedules",du=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${Wg}${e.id}`,e,gT)}load(e){return this.configStore.get(`${Wg}${e}`)}list(){let e=this.configStore.getByCategory(gT);return Object.values(e).sort((r,n)=>n.createdAt.localeCompare(r.createdAt))}delete(e){return this.configStore.delete(`${Wg}${e}`)}loadAll(){return this.list()}};var sM=new Set(["sync:schedule:list","sync:schedule:upsert","sync:schedule:toggle","sync:schedule:delete"]),cu=class{constructor(e){this.deps=e}deps;executor;executeBridge;inFlight=0;claims=ss();async handle(e){if(!sM.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 au({scheduleStore:new du(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){T(this.deps,"sync:schedule:list","sync:schedule:error",e,t)}}handleUpsert(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(km,e,"sync:schedule:error",this.deps);if(!t)return;let r=t.schedule.configId;if(!new It(this.deps.configStore).load(r)){T(this.deps,"sync:schedule:upsert","sync:schedule:error",e,new Error(`Sync configuration not found: ${r}. Save it from the Sync tab first.`),{code:"NOT_FOUND"});return}let{cron:n,timezone:o}=t.schedule,i=pd(n,o,Date.now());if(typeof i!="number"){T(this.deps,"sync:schedule:upsert","sync:schedule:error",e,new Error(i.refused==="unreadable"?`The schedule was not saved: SandForge cannot read the cron expression "${n}" (${i.reason}).`:`The schedule was not saved. ${i.reason}`),{code:"INVALID_SCHEDULE"});return}try{let a=this.getExecutor().upsert(t.schedule),d=A(this.deps,e,"sync:schedule:upsert:response",{success:!0,schedule:a});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(a){T(this.deps,"sync:schedule:upsert","sync:schedule:error",e,a)}}handleToggle(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Om,e,"sync:schedule:error",this.deps);if(t)try{let r=this.getExecutor().toggle(t.scheduleId,t.enabled);if(!r){T(this.deps,"sync:schedule:toggle","sync:schedule:error",e,new Error(`Schedule not found: ${t.scheduleId}`),{code:"NOT_FOUND"});return}let n=A(this.deps,e,"sync:schedule:toggle:response",{success:!0,schedule:r,scheduleId:t.scheduleId,enabled:t.enabled});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){T(this.deps,"sync:schedule:toggle","sync:schedule:error",e,r)}}handleDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(Im,e,"sync:schedule:error",this.deps);if(t)try{let r=this.getExecutor().delete(t.scheduleId),n=A(this.deps,e,"sync:schedule:delete:response",{success:r,scheduleId:t.scheduleId});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){T(this.deps,"sync:schedule:delete","sync:schedule:error",e,r)}}};var iM=new Set(["direct","rename"]);function fT(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(g=>g.objectApiName===s.objectApiName);if(!a)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" does not carry it.`);let d=So([a]);if(d.length>0)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" cannot be applied. ${ko(d)}`);let c=Ff([a]);if(c.length>0)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" cannot be applied. ${_f(c)}`);let u=a.externalIdField?.trim()||"Id",l=a.fieldMappings.find(g=>g.targetField===u&&iM.has(g.type));return{...n,keyField:u,keySource:u==="Id"?"Id":l?.sourceField??u,fieldMappings:a.fieldMappings,...a.excludedFields?.length?{excludedFields:a.excludedFields}:{},addOnFields:a.addOnFields,transformRules:a.transformRules,...i.keepContactPoints===!0?{keepContactPoints:!0}:{}}}}}var aM=J({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(),dM=J({event:J({replayId:Te()}).loose(),payload:J({ChangeEventHeader:aM}).loose()}).loose(),uu="ChangeEvent";function mT(s){return`/data/${s.endsWith("__c")?s.slice(0,-1):s}${uu}`}function yT(s){if(!s.endsWith(uu)||s===uu)return null;let e=s.slice(0,-uu.length);return e.endsWith("__")?`${e}c`:e}function wT(s,e){return s.endsWith("__c")?`${s.slice(0,-3)}__${e}__s`:s.endsWith("Address")?`${s.slice(0,-7)}${e}`:e}function hT(s){let e=s.indexOf(".");return e<0?s:wT(s.slice(0,e),s.slice(e+1))}function cM(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function bT(s,e){let t=dM.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(cM(a))for(let[d,c]of Object.entries(a))o[wT(i,d)]=c;else o[i]=a;for(let i of r.nulledFields??[])o[hT(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(hT),values:o}}var zg="SandForgeRealtime";function RT(s){return s.changeOrigin.split(";").some(e=>e.trim()===`client=${zg}`)}var ps=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 uM(s){return s instanceof Error?s.message:typeof s=="object"&&s!==null&&"message"in s?String(s.message):String(s)}function vT(s){let e=new Map,t=new Map,r=[],n=!1,o={added(a){a.disable("websocket")},outgoing(a,d){if(a.channel==="/meta/subscribe"&&a.subscription){let c=e.get(a.subscription);c!==void 0&&(a.ext={...a.ext??{},replay:{[a.subscription]:c}})}d(a)},incoming(a,d){if(a.channel==="/meta/subscribe"&&a.successful===!1)t.set(a.subscription??"",a.error??"refused without a reason");else if((a.channel==="/meta/handshake"||a.channel==="/meta/connect")&&a.successful===!1&&a.advice?.reconnect==="none"){if(!n){n=!0;let c=a.error??`${a.channel} refused`;for(let u of r)u(c)}}else if(!a.channel.startsWith("/meta/")){let c=a.data?.event?.replayId;typeof c=="number"&&e.has(a.channel)&&e.set(a.channel,c)}d(a)}},i=s.createClient([o]);return{subscribe(a,d,c){return e.set(a,d),t.delete(a),new Promise((u,l)=>{i.subscribe(a,c).then(()=>u(),g=>{e.delete(a),l(new ps(a,t.get(a)??uM(g)))})})},onDown(a){r.push(a)},disconnect(){n=!0,i.disconnect()}}}var ST="SELECT EventChannel, SelectedEntity FROM PlatformEventChannelMember";function kT(s){let e=new Map;for(let t of s){let r=typeof t.SelectedEntity=="string"?t.SelectedEntity:"",n=yT(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 OT(s,e,t,r,n=()=>{}){let o=t.filter(i=>i.sourceOrgId===r.sourceOrgId&&i.targetOrgId===r.targetOrgId);return Promise.all(s.map(async({objectApiName:i,channel:a})=>{let d=!0,c=[];try{c=(await e(i)).fields.filter(l=>l.externalId===!0).map(l=>l.name).sort()}catch(u){d=!1,n(`[realtime] ${i} could not be described in the target: ${I(u)}`)}return{objectApiName:i,channel:a,inTarget:d,externalIdFields:c,syncConfigs:o.filter(u=>u.objects.some(l=>l.objectApiName===i)).map(u=>({id:u.id,name:u.name}))}}))}var pu=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}},Bn=200,IT=new Set(["int","double","currency","percent","long"]),lM="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 pM(s){return s==="DELETE"||s==="GAP_DELETE"}function AT(s){return s==="CREATE"||s==="UNDELETE"}function lu(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 TT(s){return Object.fromEntries(Object.entries(s).filter(([e])=>e!=="attributes"))}function ET(s){return s==null||s===""}function Gg(s){return String(s).toLowerCase()}var gu=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:Bn,insertOrder:0}}plan;deps;mapping=new Xh;transforms=new Kh;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:lM});return}if(i.recordIds.length===0){t[a].push({outcome:"failed",error:"The change named no record."});return}let d=pM(i.changeType)?"delete":"upsert";if(d==="delete"&&!this.plan.applyDeletes){t[a].push({outcome:"deletes-off"});return}let c=o[o.length-1];(!c||c.kind!==d)&&(c={kind:d,changes:new Map},o.push(c));for(let u of i.recordIds){let l=c.changes.get(u);l?(l.eventIndexes.push(a),l.values={...l.values,...i.values},l.full=l.full||AT(i.changeType),l.needsRead=l.needsRead||i.changeType.startsWith("GAP_"),l.commitTimestamp=Math.min(l.commitTimestamp,i.commitTimestamp),l.replayId=Math.max(l.replayId,i.replayId)):c.changes.set(u,{recordId:u,eventIndexes:[a],changeType:i.changeType,full:AT(i.changeType),needsRead:i.changeType.startsWith("GAP_")&&d==="upsert",values:{...i.values},commitTimestamp:i.commitTimestamp,replayId:i.replayId})}});for(let i of o){let a=[...i.changes.values()],d=(c,u)=>{for(let l of c.eventIndexes)t[l].push(u)};try{i.kind==="upsert"?await this.applyUpserts(a,d,r):await this.applyDeletes(a,d,r)}catch(c){let u=I(c);for(let l of a)d(l,{outcome:"failed",error:u})}}return{results:t.map(gM),held:r}}async resolve(e,t,r){let n=e.record[this.plan.keyField],o;if(e.kind==="delete"?o=t==="source_wins"?{}:null:o=this.resolvedValues(e,t,r),o===null)return{success:!0,resolvedValues:{}};try{if(e.kind==="delete"){let d=await this.writeOne("delete",{Id:e.targetId});return d.success?{success:!0,resolvedValues:{Id:e.targetId}}:{success:!1,resolvedValues:{},error:d.errors[0]??"Delete refused."}}let i=await this.coerced({...o,[this.plan.keyField]:n}),a=await this.writeOne(this.objectConfig.operation,i);return a.success?(await this.rememberWrites([a.id??e.targetId]),{success:!0,resolvedValues:i}):{success:!1,resolvedValues:{},error:a.errors[0]??"Write refused."}}catch(i){return{success:!1,resolvedValues:{},error:I(i)}}}resolvedValues(e,t,r){let n=Object.fromEntries(Object.entries(e.record).filter(([o])=>o!==this.plan.keyField));switch(t){case"source_wins":return n;case"merge":{let o=Object.fromEntries(Object.entries(n).filter(([,i])=>i!==null));return Object.keys(o).length>0?o:null}case"manual":{let o=Object.fromEntries(Object.entries(r??{}).filter(([i])=>i in n).map(([i,a])=>[i,a.value]));return Object.keys(o).length>0?o:null}case"target_wins":case"newest_wins":return null}}async coerced(e){let t=await this.deps.target.describe(this.plan.objectApiName),r=new Map(t.fields.map(o=>[o.name,o.type??""])),n={};for(let[o,i]of Object.entries(e)){let a=r.get(o)??"";if(typeof i=="string"&&a==="boolean")n[o]=i.trim().toLowerCase()==="true";else if(typeof i=="string"&&IT.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=[],u=[];for(let p of i){let f=a.get(p.recordId),h=d.get(Gg(f))??[];if(h.length>1){t(p,{outcome:"failed",error:`${h.length} records of ${n} in the target have ${this.plan.keyField} = ${String(f)}.`});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,f,o,!1)}):u.push(p);continue}let y=String(m.Id),R=this.recordFor(p,f,o,!0),S=lu(m.LastModifiedDate);if(!(S!==null&&S>p.commitTimestamp&&!this.deps.ownWrites.wrote(y,S))){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 O=Object.fromEntries(Object.entries(R).filter(([P,v])=>v!==null||P===this.plan.keyField));Object.keys(O).length>1?c.push({change:p,record:O,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(u.length>0){for(let p of u)p.needsRead=!0;await this.readWhole(u,t);for(let p of u.filter(f=>f.full))c.push({change:p,record:this.recordFor(p,a.get(p.recordId),o,!1)})}if(c.length===0)return;let{outcomes:l}=await this.deps.write(this.objectConfig,c.map(p=>p.record),this.contactPoints),g=[];c.forEach((p,f)=>{let h=l[f];if(h?.success){t(p.change,{outcome:"applied"});let m=h.id??p.targetId;m&&g.push(m)}else t(p.change,{outcome:"failed",error:h?.errors[0]??"The target answered nothing for this record."})}),await this.rememberWrites(g)}async applyDeletes(e,t,r){let n=this.plan.objectApiName,o=new Map((await this.deps.target.describe(n)).fields.map(l=>[l.name,l])),i=await this.keysOf(e,t,!0),a=e.filter(l=>i.has(l.recordId)),d=await this.readTarget([...new Set([...i.values()])],o,[]),c=[];for(let l of a){let g=i.get(l.recordId),p=d.get(Gg(g))??[];if(p.length>1){t(l,{outcome:"failed",error:`${p.length} records of ${n} in the target have ${this.plan.keyField} = ${String(g)}.`});continue}let f=p[0];if(!f){t(l,{outcome:"applied"});continue}let h=String(f.Id),m=lu(f.LastModifiedDate);!(m!==null&&m>l.commitTimestamp&&!this.deps.ownWrites.wrote(h,m))||this.deps.conflictStrategy==="source_wins"?c.push({change:l,targetId:h}):this.deps.conflictStrategy==="manual"?(r.push(this.held(l,"delete",{[this.plan.keyField]:g},f)),t(l,{outcome:"held"})):t(l,{outcome:"kept-target"})}if(c.length===0)return;let{outcomes:u}=await this.deps.write({...this.objectConfig,operation:"delete"},c.map(l=>({Id:l.targetId})));c.forEach((l,g)=>{let p=u[g];t(l.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(lu(n.LastModifiedDate)??0).toISOString()}}async keysOf(e,t,r){let{keySource:n}=this.plan,o=e.filter(a=>n!=="Id"&&ET(a.values[n])&&!(n in a.values&&a.full));if(o.length>0){let a=await this.readSource(o.map(d=>d.recordId),`Id, ${ze(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(ET(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?[]:ra(this.plan.objectApiName,o),a={};for(let[d,c]of Object.entries(o)){if(c===void 0||d==="Id"||d===this.plan.keyField||i.includes(d))continue;let u=r.get(d);u&&((n?u.updateable!==!0:u.createable!==!0)||(a[d]=c))}return a[this.plan.keyField]=t,a}writtenFieldsOf(e,t){let r=new Set;for(let n of e)if(t.has(n.recordId))for(let[o,i]of Object.entries(this.mapped(n)))i!==void 0&&r.add(o);return[...r]}async readWhole(e,t){if(e.length===0)return;let r=await this.readSource(e.map(n=>n.recordId),"FIELDS(ALL)",!1);for(let n of e){let o=r.get(n.recordId);if(!o){t(n,{outcome:"failed",error:"The source record could not be read back: it was deleted since."});continue}n.values={...TT(o),...n.values},n.full=!0}}async readSource(e,t,r){let n=wt(this.plan.objectApiName),o=new Map;for(let i=0;i<e.length;i+=Bn){let d=e.slice(i,i+Bn).map(l=>`'${tr(l)}'`).join(", "),c=t==="FIELDS(ALL)"?` LIMIT ${Bn}`:"",u=await this.deps.source.query(`SELECT ${t} FROM ${n} WHERE Id IN (${d})${c}`,{includeDeleted:r});for(let l of u)o.set(String(l.Id),l)}return o}async readTarget(e,t,r){let n=wt(this.plan.objectApiName),o=ze(this.plan.keyField),i=IT.has(t.get(this.plan.keyField)?.type??""),a=r.filter(u=>u!=="Id"&&u!==this.plan.keyField&&u!=="LastModifiedDate"&&t.has(u)),d=["Id",...o==="Id"?[]:[o],"LastModifiedDate",...a],c=new Map;for(let u=0;u<e.length;u+=Bn){let g=e.slice(u,u+Bn).map(h=>i?String(Number(h)):`'${tr(String(h))}'`).join(", "),p=`WHERE ${o} IN (${g})`,f;try{f=await this.deps.target.query(`SELECT ${d.map(ze).join(", ")} FROM ${n} ${p}`)}catch{f=await this.deps.target.query(`SELECT Id${o==="Id"?"":`, ${o}`}, LastModifiedDate FROM ${n} ${p}`)}for(let h of f){let m=Gg(h[this.plan.keyField]);c.set(m,[...c.get(m)??[],TT(h)])}}return c}async rememberWrites(e){if(e.length===0)return;let t=wt(this.plan.objectApiName);try{for(let r=0;r<e.length;r+=Bn){let n=e.slice(r,r+Bn).map(i=>`'${tr(i)}'`).join(", "),o=await this.deps.target.query(`SELECT Id, LastModifiedDate FROM ${t} WHERE Id IN (${n})`);for(let i of o){let a=lu(i.LastModifiedDate);a!==null&&this.deps.ownWrites.record(String(i.Id),a)}}}catch{}}};function gM(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 fu=class{constructor(e){this.deps=e}deps;async open(e){let t={subscribed:[],refused:[],notes:[]};for(let r of e){let n=mT(r),o=a=>{let d;try{d=bT(n,a)}catch(c){this.deps.onUnreadable(n,I(c));return}this.deps.onEvent(d)},i=this.deps.replayStore.get(n);try{await this.deps.transport.subscribe(n,i??-1,o),t.subscribed.push(r)}catch(a){if(i!==void 0&&a instanceof ps&&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:PT(d)})}else t.refused.push({objectApiName:r,reason:PT(a)})}}return t}close(){this.deps.transport.disconnect()}};function PT(s){return s instanceof ps?s.answer:I(s)}var mM=[2e3,1e4,3e4],yM=6e4,hu=class{constructor(e,t){this.config=e;this.deps=t}config;deps;state="disconnected";subscription;watched=[];refused=[];notes=[];error;stopped=!1;buffer=[];flushTimer;flushing=Promise.resolve();held=new Map;startedAt=0;lastEventAt;received=0;applied=0;failed=0;lagTotal=0;lagCount=0;currentLag=0;recentReceipts=[];now(){return(this.deps.now??Date.now)()}get sessionId(){return this.config.sessionId}get running(){return this.state==="syncing"||this.state==="connecting"}async start(){this.state="connecting",this.startedAt=this.now();let e;try{e=await this.open(this.config.watchedObjects)}catch(t){throw this.state="error",this.error=I(t),t}return this.watched=e.subscribed,this.refused=e.refused,this.notes=e.notes,e.subscribed.length===0?(this.state="error",this.error="The source org refused a subscription to every watched object.",this.closeSubscription()):this.state="syncing",e}async stop(){this.stopped=!0,this.state="disconnected",this.flushTimer&&clearTimeout(this.flushTimer),this.flushTimer=void 0,this.closeSubscription(),this.buffer=[],await this.flushing;let e=this.held.size;return this.held.clear(),e}snapshot(){return{status:this.state,sessionId:this.config.sessionId,watchedObjects:this.watched,refused:this.refused,notes:this.notes,...this.error?{error:this.error}:{}}}metrics(){let e=this.now();this.recentReceipts=this.recentReceipts.filter(r=>e-r<yM);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 fu({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 mM){if(await new Promise(r=>setTimeout(r,t)),this.stopped)return;try{let r=await this.open(this.watched);if(r.subscribed.length>0){this.watched=r.subscribed,this.notes=[...this.notes,...r.notes],this.state="syncing",this.error=void 0,this.deps.sink.status(this.snapshot());return}this.closeSubscription()}catch(r){this.deps.log(`[WARN] realtime reconnect failed: ${I(r)}`)}}this.stopped||(this.state="error",this.error=`The connection to the source org was closed (${e}) and could not be reopened.`,this.deps.sink.status(this.snapshot()))}}receive(e){if(this.stopped)return;let t=this.now();this.received++,this.lastEventAt=t,this.recentReceipts.push(t),this.buffer.push(e),this.scheduleFlush(this.buffer.length>=this.config.maxBatchSize?0:this.config.flushIntervalMs)}scheduleFlush(e){if(this.flushTimer!==void 0){if(e>0)return;clearTimeout(this.flushTimer)}this.flushTimer=setTimeout(()=>{this.flushTimer=void 0,this.flushing=this.flushing.then(()=>this.flush())},e)}async flush(){for(;this.buffer.length>0&&!this.stopped;){let e=this.buffer.splice(0,this.config.maxBatchSize);try{await this.process(e)}catch(t){this.deps.log(`[ERR] realtime batch: ${I(t)}`)}}}async process(e){let t=e.map(()=>({outcome:"watched"})),r=new Map;e.forEach((i,a)=>{RT(i)?t[a]={outcome:"own-write"}:this.config.appliers.has(i.objectApiName)&&r.set(i.objectApiName,[...r.get(i.objectApiName)??[],a])});for(let[i,a]of r){let d=this.config.appliers.get(i);if(d)try{let{results:c,held:u}=await d.apply(a.map(l=>e[l]));c.forEach((l,g)=>{t[a[g]]=l});for(let l of u)this.held.set(l.conflictId,{change:l,applier:d}),this.deps.sink.conflict(l)}catch(c){let u=I(c);for(let l of a)t[l]={outcome:"failed",error:u}}}let n=this.now(),o=new Map;e.forEach((i,a)=>{let d=t[a];d.outcome==="applied"&&this.applied++,d.outcome==="failed"&&this.failed++;let c=Math.max(0,n-i.commitTimestamp);this.lagTotal+=c,this.lagCount++,this.currentLag=c,o.set(i.channel,Math.max(o.get(i.channel)??0,i.replayId))}),this.deps.sink.events(e.map((i,a)=>wM(i,t[a]))),this.deps.replayStore.save(o)}};function wM(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 bM="realtime:replay:",RM="realtime",Ei=class{constructor(e,t){this.configStore=e;this.sourceOrgId=t}configStore;sourceOrgId;get key(){return`${bM}${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)},RM)}forget(){this.configStore.delete(this.key)}};function Jg(s){return s.eventsFailed===0?"success":s.eventsApplied>0?"partial":"failure"}function CT(s){return s.slice(0,15)}function $T(s){let e=s.store.recorder({runId:s.sessionId,configId:`realtime:${s.sessionId}`,configName:"",sourceOrgId:s.sourceOrgId,targetOrgId:s.targetOrgId,realtime:!0});s.identity&&Tr(e,s.identity,`realtime ${s.sessionId}`);let t=s.backups?od({runId:s.sessionId,orgId:s.targetOrgId,files:s.backups,meta:s.meta}):void 0,r=d=>s.target.query(d),n=t?sd({query:r,backup:t,recorder:e,describe:async d=>Er(await s.target.describe(d)),viewsEncrypted:Rr(r)}):void 0,o=new Set,i=(d,c,u,l)=>{if(c==="insert"||c==="upsert"){for(let p of dd(c,l))o.add(CT(p));return}if(c!=="delete")return;let g=u.flatMap((p,f)=>{let h=p.Id;return l[f]?.success===!0&&typeof h=="string"&&!o.has(CT(h))?[h]:[]});g.length>0&&e.deleted?.(d,g)},a;return{runId:s.sessionId,calls:cd(e,n),write:d=>{let c=Promise.resolve();return(u,l,g)=>{let p=c.then(async()=>{let f=await d(u,l,g);return i(u.objectApiName,u.operation,l,f.outcomes),f});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 vM=new Set(["realtime:start","realtime:stop","realtime:status","realtime:metrics","realtime:objects","realtime:resolve-conflict"]);function SM(s){let e=r=>q(r,s.orgRegistry,s.orgManager),t=lt(s);return{async openTransport(r){let{streaming:n}=await e(r);return vT({createClient(o){let i=n.createClient(o);return{subscribe:(a,d)=>i.subscribe(a,d),disconnect:()=>i.disconnect?.()}}})},async identity(r){return(await e(r)).identity()},reader(r){return{async query(n,o){let i=await e(r),a=o?.includeDeleted===!0,{records:d}=await nr({query:async c=>i.query(c,{scanAll:a}),queryMore:async c=>i.queryMore(c)},n);return d},async describe(n){let o=await e(r);return{fields:(await Yt(r,n,()=>o.describe(n))).fields}}}},writer(r,n){return async(o,i,a)=>{let d=await e(r),c=await hh(d,zg),u=new Dn({connection:c,bulkExecutor:new kn(t.bulk.threshold),bulkManager:br(s),retryConfig:t.retry,onProgress:()=>{},log:g=>s.log(g),...n?{calls:n}:{}});return new Av({upsert:(g,p,f,h)=>u.upsert(g,p,f,h),insert:(g,p,f)=>u.insert(g,p,f),update:(g,p,f)=>u.update(g,p,f),delete:(g,p,f)=>u.delete(g,p,f),describeTargetFields:async g=>Er(await Yt(r,g,()=>d.describe(g))),...a?{contactPoints:a}:{}}).write(o,i)}},async tooling(r,n){let o=await e(r),{records:i}=await nr({query:async a=>o.tooling.query(a),queryMore:async a=>o.tooling.queryMore(a)},n);return i}}}var mu=class{constructor(e,t){this.deps=e;this.syncConfigs=new It(e.configStore),this.access=t??SM(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(!vM.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 Ei(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:Jg(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=$(lm,e,"realtime:error",this.deps);if(t)try{let r=await this.access.tooling(t.sourceOrgId,ST),n=this.access.reader(t.targetOrgId),o=await OT(kT(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=ah(I(r));T(this.deps,"realtime:objects","realtime:error",e,r,n?{code:n}:void 0)}}async handleStart(e){let t=$(cm,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(k=>fT(k,E=>this.syncConfigs.load(E),t,{keepContactPoints:t.keepContactPoints===!0})),o=n.length>0?await this.passesProductionGuard(e,t.targetOrgId,n):void 0;if(n.length>0&&!o){r("The target org is protected by the Production Guard, which did not allow the writes.");return}let i=new AbortController,a=new pu,d=this.access.reader(t.sourceOrgId),c=this.access.reader(t.targetOrgId),u=crypto.randomUUID(),l=o&&this.runCreations?$T({sessionId:u,sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,store:this.runCreations,...this.backupRecords?{backups:this.backupRecords}:{},meta:this.deps.configStore,target:c,identity:async()=>await this.access.identity?.(t.targetOrgId)??{},log:k=>this.deps.log(k)}):void 0,g=l?l.write(this.access.writer(t.targetOrgId,l.calls)):this.access.writer(t.targetOrgId),p=new wR,f=Qn(Rr(k=>d.query(k)),k=>d.describe(k)),h=new Map(n.map(k=>[k.objectApiName,new gu(k,{source:d,target:c,write:g,conflictStrategy:t.conflictStrategy,ownWrites:a,contactPoints:p,maskedSourceFields:f})])),m,y=()=>{},R=new Promise((k,E)=>{y=x=>{x?m?.fail(x):i.signal.aborted?m?.cancel():m?.complete(),x?E(new Error(x)):k()}});R.catch(()=>{});let S=async()=>{if(!l)return;let k=await l.end({status:Jg(b.metrics()),cancelled:i.signal.aborted}).catch(E=>I(E));this.openRuns.delete(l.runId),k!==void 0&&Ie(this.deps,"warning","Real-time sync",`What the session wrote could not all be kept (${k}): removing it may leave some of it in the target.`)},b=new hu({sessionId:u,watchedObjects:t.watchedObjects,appliers:h,flushIntervalMs:t.flushIntervalMs,maxBatchSize:t.maxBatchSize},{openTransport:()=>this.access.openTransport(t.sourceOrgId),replayStore:new Ei(this.deps.configStore,t.sourceOrgId),sink:{events:k=>this.pushEvents(k),conflict:k=>this.pushConflict(k),status:k=>{if(k.status!=="error"){this.pushStatus(k);return}y(k.error),S().then(()=>this.pushStatus(k))}},log:k=>this.deps.log(k)}),O={session:b,abort:i,operationId:e.id,sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,guard:o,finish:k=>y(k),detach:()=>{},endRun:S};this.current=O,this.lastMetrics=null,l&&this.openRuns.add(l.runId);let P;try{P=await b.start()}catch(k){throw await S(),k}let v=b.snapshot();if(P.subscribed.length>0){let k=`Real-time sync of ${P.subscribed.length} object(s)`;this.registry?.register(b.sessionId,"sync",k,R,i),m=ar(this.liveTracker,b.sessionId,"realtime",k);let E=()=>{this.current?.session===b&&this.stopCurrent().then(x=>{x&&this.pushStopped(x,"cancelled")})};i.signal.addEventListener("abort",E,{once:!0}),O.detach=()=>i.signal.removeEventListener("abort",E)}else y(),await S();let w=new Set(P.subscribed),C=(await Promise.all(n.filter(k=>w.has(k.objectApiName)).map(async k=>({objectApiName:k.objectApiName,fields:[...await f(k.objectApiName)].sort()})))).filter(k=>k.fields.length>0);C.length>0&&(O.encryptedLeftOut=C),this.post(A(this.deps,e,"realtime:started",{success:P.subscribed.length>0,sessionId:b.sessionId,watchedObjects:P.subscribed,refused:P.refused,notes:P.notes,...C.length>0?{encryptedLeftOut:C}:{},...v.error?{error:v.error}:{}}))}catch(n){r(I(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:Re.code}),oa();let o={orgId:t,orgTier:Pe(this.deps.orgManager.getOrg(t)),operation:r.some(a=>a.applyDeletes)?"delete":"upsert",objectName:r.map(a=>a.objectApiName).join(", "),recordCount:"unknown",module:"sync"},{decision:i}=await et(n,o);if(i==="refused"||i==="declined"){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=$(um,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=$(pm,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 kM=new Set(["file:save"]),yu=class{constructor(e,t){this.deps=e;this.saveDialog=t??new An}deps;saveDialog;async handle(e){return kM.has(e.type)?(await this.handleSave(e),!0):!1}async handleSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=om.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 OM=new Set(["reports:list","reports:audit","reports:lineage"]),IM="forge:history",AM="sync:history:all",xT=50;function TM(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 EM(s){let e=s.graph?.nodes??[];return e.filter(t=>!Wf(t)).length+zf(s,e).length}var wu=class{constructor(e){this.deps=e}deps;async handle(e){if(!OM.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=$(Hy,e,"reports:error",this.deps);if(t===null)return;let r=new To(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=$(By,e,"reports:error",this.deps);if(t===null)return;let r=new Mh(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?xT:Math.min(Math.floor(t),500)}build(e=xT){let t=this.deps.configStore.get(IM)??[],r=this.deps.configStore.get(AM)??[],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:CM(n)}}forgeReport(e){let t=EM(e),r=TM(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 PM(s){let e=s.sections[0]?.content?.status;return e==="failure"||e==="failed"||e==="partial"}function CM(s){let e=s.length;if(e===0)return{totalOperations:0,successRate:0,avgDuration:0,errorRate:0};let t=s.filter(PM).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 DT(s){return Object.values(s).every(e=>e<50)}var bu=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(nf.map(async n=>{try{let o=await e.query(`SELECT COUNT() FROM ${n}`);return{objectName:n,count:o.totalSize}}catch{return{objectName:n,count:0}}})),r={};for(let{objectName:n,count:o}of t)r[n]=o;return r}decide(e,t,r,n){let o=Object.values(t).reduce((u,l)=>u+l,0),i=DT(t),a=n!==void 0&&!DT(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 xM(s,e){return`smart-action:${s}:${e??""}`}var DM=300*1e3,NM=new Set(["smart-action:analyze"]),Ru=class{constructor(e){this.deps=e;this.analyzer=new bu({getConnection:t=>q(t,e.orgRegistry,e.orgManager)})}deps;analyzer;cache=new Map;async handle(e){return NM.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=$(nw,e,"smart-action:error",this.deps);if(t)try{let r=t.targetOrgId,n=t.sourceOrgId,o=xM(r,n),i=this.cache.get(o);if(i&&Date.now()-i.fetchedAt<DM){this.deps.log(`[SmartAction] Cache hit for ${r}`);let c=A(this.deps,e,"smart-action:analyze:response",{recommendation:i.recommendation});this.deps.broker.postToWebview(c),this.deps.log("[TX] smart-action:analyze:response (cached)");return}this.deps.log(`[SmartAction] Analyzing org ${r}`);let a=await this.analyzer.analyzeOrg(r,n);this.cache.set(o,{recommendation:a,fetchedAt:Date.now(),orgIds:n?[r,n]:[r]});let d=A(this.deps,e,"smart-action:analyze:response",{recommendation:a});this.deps.broker.postToWebview(d),this.deps.log("[TX] smart-action:analyze:response")}catch(r){T(this.deps,"smart-action:analyze","smart-action:error",e,r)}}};var jM=new Set(["execution:abort"]),vu=class{constructor(e,t){this.deps=e;this.registry=t}deps;registry;async handle(e){return jM.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=$(Ly,e,"execution:error",this.deps);if(!t)return;let r=t.operationId??t.executionId??"",n=this.registry.get(r);if(!n&&this.registry.cancelBeforeStart(r)){let i=A(this.deps,e,"execution:abort:response",{success:!0,operationId:r});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} (before it started)`);return}if(!n){let i=A(this.deps,e,"execution:abort:response",{success:!1,error:`Operation not found: ${r}`});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} (not found)`);return}if(n.status!=="running"){let i=A(this.deps,e,"execution:abort:response",{success:!1,error:"Operation already finished",status:n.status});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} (already ${n.status})`);return}this.registry.abort(r);let o=A(this.deps,e,"execution:abort:response",{success:!0,operationId:r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(t){T(this.deps,"execution:abort","execution:error",e,t)}}};import{readFile as MM}from"node:fs/promises";import{join as LM}from"node:path";var Vg=new Map;function NT(s,e){let t=LM(s,`${e}.json`),r=Vg.get(t);if(r)return r;let n=MM(t,"utf-8").then(o=>JSON.parse(o));return Vg.set(t,n),n.catch(()=>Vg.delete(t)),n}var FM=new Set(["i18n:locale"]),Su=class{constructor(e,t){this.deps=e;this.localesDir=t}deps;localesDir;async handle(e){return FM.has(e.type)?(await this.handleLocaleRequest(e),!0):!1}async handleLocaleRequest(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=$(rw,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 NT(this.localesDir,r),o=A(this.deps,e,"i18n:locale:response",{lng:r,bundle:n});this.deps.broker.replyToRequester(o),this.deps.log(`[TX] i18n:locale:response (${r})`)}catch(n){this.deps.log(`[ERR] i18n:locale (${r}): ${I(n)}`);let o=A(this.deps,e,"i18n:locale:response",{lng:r,error:I(n)});this.deps.broker.replyToRequester(o)}}};import{AsyncLocalStorage as _M}from"node:async_hooks";function MT(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 jT=new _M;async function LT(s,e,t,r){let n=Symbol("pipeline sync"),o,i=s.registry?.onEvent((d,c,u)=>{c!=="started"||u.module!=="sync"||jT.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 jT.run(n,()=>Ea(t,()=>s.execute(e)));return o!==void 0?{...d,operationId:o}:d}finally{i?.(),r?.removeEventListener("abort",a)}}var UM=J({setting:j().regex(/^sandforge(?:\.[A-Za-z][A-Za-z0-9]*)+$/)}),ku=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 Id({configStore:e.configStore,orgManager:e.orgManager,log:e.log}),this.recoveryProgressSource=sS({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:Wu,bulkManager:new jh(Wu.bulk.maxConcurrentJobs),nextId:()=>this.nextId(),sandboxRefreshes:this.refreshDetector,recoveryProgress:this.recoveryProgressSource},this.orgHandler=new Pd(this.handlerDeps),this.recoveryHandler=new Ad(this.handlerDeps),this.settingsHandler=new Cd(this.handlerDeps),this.monitorHandler=new qd(this.handlerDeps),this.seedHandler=new Jd(this.handlerDeps),this.seedCloneHandler=new Yd(this.handlerDeps),this.seedCsvHandler=new tc(this.handlerDeps),this.seedRemovalHandler=new dc(this.handlerDeps,void 0,r=>this.seedHandler.isRunning(r)||this.seedCsvHandler.isRunning(r)||this.seedCloneHandler.isRunning(r)),this.syncHandler=new oc(this.handlerDeps),this.syncHistoryStore=new uc(e.configStore),this.syncHandler.setHistoryLogger(new lc(this.syncHistoryStore)),this.syncHistoryHandler=new sc(this.handlerDeps,this.syncHistoryStore,this.syncHandler),this.syncRemovalHandler=new ic(this.handlerDeps,this.syncHistoryStore,r=>this.syncHandler.isRunning(r)||this.realtimeHandler.isRunning(r)),this.compareHandler=new pc(this.handlerDeps),this.dataOpsHandler=new Lb(this.handlerDeps),this.complianceHandler=new mc(this.handlerDeps),this.cleanupHandler=new yc(this.handlerDeps),this.emptyHandler=new xc(this.handlerDeps),this.automationHandler=new jc(this.handlerDeps),this.aiHandler=new Uc(this.handlerDeps),this.autopilotHandler=new Bc(this.handlerDeps),this.forgeHandler=new Vc(this.handlerDeps),this.frozenHandler=new pS(this.handlerDeps),this.frozenHandler.setSaltKeeper(lS(e.secretVault));let t=()=>[this.forgeHandler,this.frozenHandler,this.dataOpsHandler,this.complianceHandler,this.emptyHandler,this.autopilotHandler,this.realtimeHandler];this.checkpointHandler=new vd(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 Kc(this.handlerDeps),this.configHandler=new Qc(this.handlerDeps),this.governanceHandler=new tu(this.handlerDeps,this.monitorHandler.getAlertEngine()),this.quickSyncHandler=new iu(this.handlerDeps),this.syncScheduleHandler=new cu(this.handlerDeps),this.realtimeHandler=new mu(this.handlerDeps),this.fileHandler=new yu(this.handlerDeps),this.reportsHandler=new wu(this.handlerDeps),this.smartActionHandler=new Ru(this.handlerDeps),this.i18nHandler=new Su(this.handlerDeps,e.localesDir),this.automationHandler.setStepRunners({orgName:r=>{let n=e.orgManager.getOrg(r);return n?ye(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=>MT(this.handlerDeps.infraServices?.productionGuard,ng(r,e.orgManager.getOrg(r.targetOrgId))),runSync:(r,n,o)=>LT({execute:i=>this.syncHandler.executeScheduled(i,"pipeline"),registry:this.backgroundRegistry},r,n,o),orgTier:r=>{let n=e.orgManager.getOrg(r);return n?Pe(n):void 0},organizationIdsOf:r=>[e.orgManager.getOrg(r)?.orgId,this.refreshDetector.organizationIdOf(r)].filter(n=>typeof n=="string"&&n!==""),savedSeedTemplate:r=>new cn(e.configStore).load(r),listSeedTemplates:()=>new cn(e.configStore).list(),seed:(r,n)=>this.seedHandler.seedForPipeline(r,n),maskingTemplates:()=>[...Fh.map(r=>({...r,builtIn:!0})),...new Ia(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(Sk),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){Io().remove(e),Ok(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(Ib(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 To(this.handlerDeps.configStore).list({orgId:r,limit:gf}).entries,a=[...e==="forge"?[]:await this.forgeHandler.localRunsOn(r,n),...e==="sync"?[]:await this.syncRemovalHandler.localRunsOn(r),...e==="seed"?[]:await this.seedRemovalHandler.localRunsOn(r),...vv(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-4CVUUVGJ.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 vu(this.handlerDeps,e)}async replayQueuedOperation(e){let t=Rn("offline-replay",e.id,`${e.type}:execute`);switch(e.type){case"sync":await this.syncHandler.rerunFromSnapshot(t,e.payload.config);return;case"seed":{let r={...t,payload:e.payload};await this.seedHandler.handle(r);return}default:throw new Error(`Unsupported queued operation type: ${e.type}`)}}startSyncScheduler(e){this.syncScheduleHandler.startScheduler(t=>this.syncHandler.executeScheduled(t),e)}stopSyncScheduler(){this.syncScheduleHandler.stopScheduler()}stopLiveOperationsPush(){this.monitorHandler.dispose()}async stopRealtime(){await this.realtimeHandler.dispose()}startPipelineTriggers(e){this.automationHandler.startTriggers(e)}stopPipelineTriggers(){this.automationHandler.stopTriggers()}setAIModules(e){this.aiHandler.setAIModules(e),this.handlerDeps.errorResolver=e?.errorResolver}setRuleModules(e){this.aiHandler.setRuleModules(e)}setMigrationServices(e){this.migrationHandler.setFileReader(e)}setPipelineMarketplace(e){this.automationHandler.setPipelineMarketplace(e)}setAutopilotOrchestrator(e){this.autopilotHandler.setOrchestrator(e)}sweepForgePlans(){return this.forgeHandler.sweepSimulationPlans()}setForgeOrchestrator(e,t){this.forgeHandler.setForgeOrchestrator(e,t)}registerAll(e){let t=(r,n)=>{for(let o of r)e.route(o,async i=>{await n.handle(i)})};t(["org:list","org:connect","org:connect:cancel","org:disconnect","org:select","org:update","org:open-in-browser","org:cli-status"],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: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=UM.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 Ou=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 HM=100,BM=1e3,qM=3,WM=1e3;function zM(s){return typeof s=="object"&&s!==null&&"protocolVersion"in s&&"payload"in s&&typeof s.payload=="object"}var FT=500;function GM(s){let e=s.map(t=>`${t.path.map(String).join(".")}: ${t.message}`).join("; ");return e.length<=FT?e:`${e.slice(0,FT)}\u2026(+${s.length} issues)`}var Au=class{handlers=new Map;panels=new Set;rateLimiter;telemetry;fixSuggestionNotifier;mismatchCount=0;webviewSeen=!1;firstWebviewCallbacks=[];senders=new Map;constructor(e){this.rateLimiter=new Ou(e?.rateLimitMax??HM,e?.rateLimitWindowMs??BM),this.telemetry=e?.telemetry,this.fixSuggestionNotifier=e?.showFixSuggestion}registerPanel(e,{inbound:t=!0}={}){this.panels.add(e);let r=t?e.webview.onDidReceiveMessage(n=>{this.dispatch(n,e)}):void 0;if(!this.webviewSeen){this.webviewSeen=!0;for(let n of this.firstWebviewCallbacks.splice(0))this.runFirstWebview(n)}return{dispose:()=>{this.panels.delete(e),r?.dispose();for(let[n,o]of this.senders)o===e&&this.senders.delete(n)}}}onFirstWebview(e){if(this.webviewSeen){this.runFirstWebview(e);return}this.firstWebviewCallbacks.push(e)}runFirstWebview(e){try{e()}catch(t){this.logError("first webview",t)}}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>{this.handlers.get(e)?.delete(t)}}postToWebview(e){for(let t of this.panels)t.webview.postMessage(e)}replyToRequester(e){let t=typeof e.correlationId=="string"?this.senders.get(e.correlationId):void 0;if(t&&this.panels.has(t)){t.webview.postMessage(e);return}this.postToWebview(e)}get panelCount(){return this.panels.size}showFixSuggestion(e){this.fixSuggestionNotifier?.(e)}dispose(){this.handlers.clear(),this.panels.clear(),this.firstWebviewCallbacks=[],this.senders.clear()}logFn;setLogFunction(e){this.logFn=e}logError(e,t){let r=I(t);this.logFn?.(`[MessageBroker] Handler error for "${e}": ${r}`)}warn(e,t){try{this.telemetry?.addBreadcrumb(e,"bridge","warning"),this.telemetry?.getLogger?.()?.warn?.(t??{},e)}catch{}}dispatch(e,t){if(!zM(e)){this.logFn?.("[MessageBroker] Received malformed message: not an envelope");return}let r=uf.safeParse(e);if(!r.success){let o=GM(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;of(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>=qM&&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>WM){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 Tu=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 Eu=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 Pu=class{storage;prefix;logWarning;constructor(e,t="sandforge",r){this.storage=e,this.prefix=t,this.logWarning=r}async storeSecret(e,t){await this.storage.store(this.prefixKey(e),t)}async getSecret(e){return this.storage.get(this.prefixKey(e))}async deleteSecret(e){await this.storage.delete(this.prefixKey(e))}async storeObject(e,t){await this.storeSecret(e,JSON.stringify(t))}async getObject(e){let t=await this.getSecret(e);if(t)try{return JSON.parse(t)}catch(r){let n=I(r);this.logWarning?.(`[SecretVault] Failed to parse JSON for key "${e}": ${n}`);return}}async hasSecret(e){return await this.storage.get(this.prefixKey(e))!==void 0}prefixKey(e){return`${this.prefix}.${e}`}};var Cu=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:I(r)})}}addOrg(e){let t=this.orgs.has(e.id);this.orgs.set(e.id,e),this.emit({type:t?"updated":"added",orgId:e.id,org:e})}removeOrg(e){let t=this.orgs.delete(e);return t&&this.emit({type:"removed",orgId:e}),t}getOrg(e){return this.orgs.get(e)}getAllOrgs(){return Array.from(this.orgs.values())}updateStatus(e,t){let r=this.orgs.get(e);if(!r)return!1;let n={...r,status:t};return this.orgs.set(e,n),this.emit({type:"statusChanged",orgId:e,org:n}),!0}findByTag(e){return this.getAllOrgs().filter(t=>t.tags.includes(e))}get connectedCount(){return this.getAllOrgs().filter(e=>e.status==="connected").length}clear(){let e=Array.from(this.orgs.keys());this.orgs.clear();for(let t of e)this.emit({type:"removed",orgId:t})}dispose(){this.listeners.clear(),this.orgs.clear()}};var gs="org.",$u="org-cred.",Kg="orgs",_T=1e4;function JM(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 VM(e)}function VM(s){if(s.orgType===qi(s.orgType,s.metadata?.edition))return s;let{safetyTier:e,color:t}=qr("Developer");return{...s,orgType:"Developer",safetyTier:e,appearance:{...s.appearance,color:s.appearance.color===Xu?t:s.appearance.color}}}var xu=class{constructor(e,t,r){this.configStore=e;this.secretVault=t;this.orgManager=r}configStore;secretVault;orgManager;loadAll(){let e=this.configStore.getByCategory(Kg),t=new Map,r=[];for(let[n,o]of Object.entries(e)){if(!n.startsWith(gs))continue;let i=JM(o),a=i.orgId??i.id,d=n.slice(gs.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(gs.length);this.secretVault.deleteSecret(`${$u}${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=`${gs}${e.id}`,n=this.configStore.get(r),i=n!==void 0&&Pe(n)==="production"&&vo(e)&&n.appearance?.color===Xu?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,Kg),this.orgManager.addOrg(a),t&&await this.secretVault.storeObject(`${$u}${e.id}`,t)}async removeOrg(e){this.configStore.delete(`${gs}${e}`),await this.secretVault.deleteSecret(`${$u}${e}`),this.orgManager.removeOrg(e)}async getCredentials(e){let t=this.secretVault.getObject(`${$u}${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 ${_T} ms for org "${e}" \u2014 the OS keyring may be locked or unavailable.`))},_T)})])}finally{r!==void 0&&clearTimeout(r)}}updateOrgMetadata(e){this.configStore.set(`${gs}${e.id}`,e,Kg),this.orgManager.addOrg(e)}};import{mkdtemp as KM,readFile as XM,rm as YM}from"node:fs/promises";import{tmpdir as QM}from"node:os";import{join as Xg}from"node:path";async function UT(s){let e=await KM(Xg(QM(),"sandforge-sf-"));try{let t={stdout:Xg(e,"stdout.json"),stderr:Xg(e,"stderr.txt")},r;try{await s(t)}catch(o){r=o}let n=o=>XM(o,"utf8").catch(()=>"");return{stdout:await n(t.stdout),stderr:await n(t.stderr),...r!==void 0?{failure:r}:{}}}finally{await YM(e,{recursive:!0,force:!0}).catch(()=>{})}}var WT=10*1024*1024,ZM=3e4,Du=3e4,ef=6e4,HT=12e4,BT=3e4,eL=4,tL=2e3,rL=/["%!\u0000-\u001f\u007f]/,qT=/^[A-Za-z0-9._-]+={0,2}$/;async function tf(s,e){let{exec:t}=await import("child_process"),{promisify:r}=await import("util"),n=await r(t)(s,{maxBuffer:WT,windowsHide:!0,env:il(),...e});return{stdout:String(n.stdout),stderr:String(n.stderr)}}function zT(s,e){if(rL.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 Nu(s,e){let{exec:t,execFile:r}=await import("child_process");return new Promise(n=>{let o={encoding:"utf8",maxBuffer:WT,windowsHide:!0,timeout:e.timeoutMs,env:il()},i={},a=!1,d=l=>{a||(a=!0,clearTimeout(i.timer),n(l))},c=(l,g,p)=>{d({stdout:String(g),stderr:String(p),...l?{failure:{message:l.message,killed:l.killed}}:{}})},u=process.platform==="win32"?t(["sf",...s.map(l=>zT(l.value,l.role))].join(" "),o,c):r("sf",s.map(l=>l.value),o,c);i.timer=setTimeout(()=>{d({stdout:"",stderr:"",failure:{message:`sf did not finish within ${Math.round(e.timeoutMs/1e3)} s`,killed:!0}}),process.platform==="win32"&&u.pid!==void 0&&r("taskkill",["/pid",String(u.pid),"/T","/F"],{windowsHide:!0},()=>{})},e.timeoutMs+tL),u.stdin?.once("error",()=>{}),u.stdin?.end(e.input??"")})}var nL=J({status:Te().optional(),result:hn().optional(),message:j().optional(),name:j().optional()}).loose();function GT(s){try{let e=nL.safeParse(JSON.parse(VT(s.stdout)));return e.success?e.data:void 0}catch{return}}function JT(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 oL=J({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(),sL=J({username:j().min(1),orgId:j().min(1),instanceUrl:j().min(1)}).loose();function Yg(s,e,t=ef){let r=GT(s);if(s.failure||r?.status!==0)throw JT(s,r,e,t);let n=sL.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 Qg(s){let e=Xi(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 VT(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 iL(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 aL(s,e){let t=s;return t.killed===!0?`its ${e/1e3} s limit`:typeof t.code=="number"?`exit code ${t.code}`:al(I(s))??"an error that says nothing"}async function dL(s,e){let t=Date.now(),r=o=>process.platform==="win32"?zT(o,"temporary folder path"):iL(o),n=!1;try{let o=await UT(async a=>{let d=`${s} > ${r(a.stdout)} 2> ${r(a.stderr)}`;n=!0,await tf(d,{timeout:e})}),i=o.failure===void 0?void 0:n?aL(o.failure,e):I(o.failure);return{ran:n,stdout:o.stdout,stderr:o.stderr,ms:Date.now()-t,...i?{failure:Is(i)}:{}}}catch(o){return{ran:n,stdout:"",stderr:"",ms:Date.now()-t,failure:Is(I(o))}}}function KT(s){if(!s.ran)return`could not be made (${(s.failure??"").slice(0,200)})`;let e=Mu(s.stderr);return`ended with ${s.failure??"exit code 0"} after ${rf(s.ms)} s, with ${s.stdout.length} chars in its stdout file and ${s.stderr.length} in its stderr file${e?` ("${e}")`:""}`}function Mu(s){let e=al(s);return e===void 0?void 0:Is(e).slice(0,200)}function rf(s){return(s/1e3).toFixed(1)}function XT(s,e){return s.ms>=e-500}function cL(s,e,t,r,n){let o=Mu(s.stderr),i=a=>a.length>0?a.join(" | "):"none";return[`first run: ${rf(s.ms)} s of the ${n/1e3} s allowed`+(XT(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: ${KT(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: ${Is(process.cwd())}`,`variables ${ch()}`].join("; ")}function uL(s,e,t,r,n){let o=Mu(s.stderr),i=process.platform==="win32"?"where.exe sf":"which -a sf",a=new Set(t.sf.map(u=>u.replace(/[\\/][^\\/]*$/,""))).size,d=t.runs?`This window runs ${t.runs}${a>1?` (sf is found in ${a} folders of its PATH)`:""}`:t.failure?`${i} could not run in this window (${t.failure.slice(0,200)})`:`${i} finds no sf this window can run`,c=r===void 0?"":r===""?", and its sf --version printed nothing either":`, and its sf --version says ${r}`;return`sf org list --json ended without an error and printed nothing${o?` (it said: ${o})`:""}, so there are no orgs to read. It ran ${rf(s.ms)} s${XT(s,n)?`, its ${n/1e3} s limit,`:""} and exited with code 0. Run again with its output sent to a file, it ${KT(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 Zg(s){return s.connectedStatus!==void 0?s.connectedStatus==="Connected":s.isScratch===!0&&s.status==="Active"&&s.isExpired!==!0}function lL(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 pL(s){let e=await lh({instanceUrl:s.instanceUrl,accessToken:s.accessToken,...s.apiVersion?{version:s.apiVersion}:{}});return Yi(e)}async function gL(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 ju=class{constructor(e=fh,t=pL){this.readToken=e;this.readKind=t}readToken;readKind;versionAnswer;async isCliAvailable(){try{let{stdout:e}=await tf("sf --version",{timeout:ZM});return this.versionAnswer=Mu(e)??"",!0}catch{return!1}}async listOrgs(e){let t=await this.readOrgEntries(),r=this.dedupeByOrgId(t.filter(a=>Zg(a))),n=new Set(r.map(a=>a.orgId));for(let a of this.dedupeByOrgId(t.filter(d=>!Zg(d))))n.has(a.orgId)||e?.({username:a.username,...a.alias?{alias:a.alias}:{},orgId:a.orgId,reason:lL(a),why:"notConnected"});let o=await gL(r.map(a=>async()=>{try{return{entry:await this.withUsableToken(a)}}catch(d){return{entry:a,reason:I(d)}}}),eL),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||!Zg(t))return;let r;try{r=await this.withUsableToken(t)}catch(n){throw new Error(`The Salesforce CLI gave no access token for ${t.username}: ${I(n)}`)}return this.mapToSalesforceOrg(await this.typedByTheOrg(r))}async displayOrg(e){if(!/^[\w.@+-]+$/.test(e)||e.startsWith("-"))throw new Error(`Invalid username format: "${e}"`);let t=await Nu([{value:"org",role:"command"},{value:"display",role:"command"},{value:"--target-org",role:"flag"},{value:e,role:"username"},{value:"--json",role:"flag"}],{timeoutMs:BT}),r=GT(t);if(r?.name==="NamedOrgNotFoundError")return;if(t.failure||r?.status!==0)throw JT(t,r,"sf org display",BT);let n=oL.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:Qg(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"}),Yg(await Nu(t,{timeoutMs:ef}),"sf org login jwt")}async loginWithRefreshToken(e){if(!qT.test(e.clientId))throw new Error("The consumer key holds characters the Salesforce CLI does not accept.");if(!qT.test(e.refreshToken))throw new Error("Salesforce issued a refresh token the Salesforce CLI cannot store (unexpected characters).");let t=new URL(Qg(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 Yg(await Nu(r,{timeoutMs:ef,input:n}),"sf org login sfdx-url")}async readOrgEntries(){let e="sf org list --json",t=Date.now(),r,n="";try{let a=await tf(e,{timeout:Du});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=VT(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 dL(e,Du),n=await uh(),o=cL(t,r,n,this.versionAnswer,Du);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(uL(t,r,n,this.versionAnswer,Du))}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:Qg(t),role:"login URL"}];return e&&r.push({value:"--alias",role:"flag"},{value:e,role:"alias"}),r.push({value:"--json",role:"flag"}),Yg(await Nu(r,{timeoutMs:HT}),"sf org login web",HT)}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(dl(e.accessToken))return e;let t=await this.readToken(e.username);if(!dl(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=Kn({isScratch:e.isScratch,isSandbox:e.isSandbox,edition:e.orgEdition}),{safetyTier:r,color:n}=qr(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??bo.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 fL(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 Lu=class{deps;results=new Map;constructor(e){this.deps=e}async execute(e,t){let r=Date.now(),{items:n,managedLeftOut:o}=await fL(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 hL(){return globalThis.crypto.randomUUID()}function YT(s){return{stepId:s.id,stepName:s.name,stepType:s.type,status:"skipped"}}function mL(s,e){let t={};for(let r of s.variables)r.defaultValue!==void 0&&(t[r.name]=r.defaultValue);return{...t,...e}}function yL(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 QT(s){return`Validation failed: ${s.join(", ")}`}function wL(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 Fu=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=QT(o),h.endTime=new Date().toISOString(),this.emit("failed",{runId:h.id,error:h.error}),h}let i=this.refuseUnrunnable(e,t,r);if(i)return i;let a=this.createRun(e,t,r);a.status="running",this.activeRuns.set(a.id,a);let d=new AbortController,c=()=>d.abort();n?.aborted&&d.abort(),n?.addEventListener("abort",c,{once:!0}),this.aborters.set(a.id,d),this.emit("started",{runId:a.id,pipelineId:e.id});let u=mL(e,t),{steps:l}=e,g=this.deps.conditionalRouter,p=!1,f=0;for(;f<l.length;){if(this.cancelledRuns.has(a.id)||d.signal.aborted){a.status="cancelled";break}let h=l[f],m=await this.runStep(h,a,u,d.signal);if(a.stepResults.push(m),m.status==="skipped"){this.emit("stepSkipped",{runId:a.id,stepResult:m}),f+=1;continue}if(this.emit("stepCompleted",{runId:a.id,stepResult:m}),Object.assign(u,yL(m)),u[Vf]=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=f+1;if(g.endsRun(h,m))y=l.length;else{let R=g.getNextStep(h,m),S=R?l.findIndex((b,O)=>O>f&&b.id===R):-1;S!==-1&&(y=S)}for(let R of l.slice(f+1,y)){let S=YT(R);a.stepResults.push(S),this.emit("stepSkipped",{runId:a.id,stepResult:S})}f=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 ${I(i)}.`}}if(!o)return YT(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?[QT(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)??wL(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:hL(),pipelineId:e.id,pipelineName:e.name,status:"queued",triggeredBy:r,stepResults:[],variables:t,startTime:new Date().toISOString()}}};var _u=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 vL=3e4;function SL(s,e,t={}){let r=Kn({isSandbox:e.isSandbox,edition:e.orgType,...t.typeScratch===!0&&s.scratch===!0?{isScratch:!0}:{}}),{safetyTier:n,color:o}=qr(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:bo.DEFAULT_API_VERSION,edition:e.orgType,features:[]},status:"connected",lastConnected:new Date().toISOString(),tags:[]}}function kL(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 OL(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 IL(s,e,t={}){return{compareOrchestrator:n=>new Lu(n),automationOrchestrator:n=>new Fu(n),seedOrchestrator:n=>new Nv(n),syncOrchestrator:n=>new Dv(n),getSandforgeSetting:(n,o)=>o,isAIEnabled:()=>!1,configStore:s,showNotification:n=>e(` notification: ${n}`),runsFrom:"commandLine",...t}}function IQ(s){let{log:e}=s,t=s.waitMs??5*6e4,r=sl();gh("command line");let n=CR(RL(s.storeDir,"configStore.json")),o=new Map,i=new Pu({get:S=>Promise.resolve(o.get(S)),store:(S,b)=>(o.set(S,b),Promise.resolve()),delete:S=>(o.delete(S),Promise.resolve())}),a=new Cu,d=new xu(n,i,a),c=new ju,u=new oS;u.setSfdxBridge(c);let l=new Au;l.setLogFunction(e);let g=new Tu(l),p=IL(n,e,s.services),f=new ku({log:e,broker:l,stateSync:new Eu(l),orgManager:a,orgRegistry:d,configStore:n,secretVault:i,authProvider:u,sfdxBridge:c,services:p});f.setLiveOperationTracker(new _u),s.compose?.({handlers:f,configStore:n,orgRegistry:d,orgManager:a,services:p,log:e}),f.registerAll(g);let h=[],m=new Set,y,R={webview:{postMessage:S=>{h.push(S);let b=OL(S);b&&e(` ${b}`),s.onPost?.(S);for(let O of[...m])O(S);return Promise.resolve(!0)},onDidReceiveMessage:S=>(y=S,{dispose:()=>{y=void 0}})}};return l.registerPanel(R),{posted:h,async connect(S){let b=await yh(S),O=await u.validateConnection(b.accessToken,b.instanceUrl),P=SL(b,O,{typeScratch:s.typeScratchOrgs===!0});return await d.saveOrg(P,{loginUrl:b.instanceUrl,instanceUrl:b.instanceUrl,accessToken:b.accessToken,username:b.username}),P},connectingRequests:()=>sl()-r,request(S){let b=y;if(!b)return Promise.reject(new Error("No panel is registered with the broker."));let O=S.responseType??`${S.type}:response`,P=S.timeoutMs??vL,v={id:S.id??`wv-${bL()}`,type:S.type,timestamp:Date.now(),...S.payload!==void 0?{payload:S.payload}:{}},w=Date.now();return new Promise(C=>{let k=V=>{m.delete(E),clearTimeout(x),C(V)},E=V=>{let H=kL(V,v.id,O);if(!H)return;let Y=Date.now()-w;k({outcome:H,message:V,elapsedMs:Y,late:Y>P})},x=setTimeout(()=>k({outcome:"unanswered",elapsedMs:Date.now()-w,late:!0}),Math.max(t,P));m.add(E),b({protocolVersion:1,payload:v})})}}}export{Nn as a,ZT as b,cn as c,ap as d,cp as e,hd as f,ES as g,yd as h,CS as i,zL as j,pp as k,xS as l,YL as m,LS as n,QL as o,WE as p,IQ as q};