sandforge 1.81.0 → 1.82.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 (208) hide show
  1. package/README.md +48 -0
  2. package/bin/sandforge-users.mjs +12 -0
  3. package/lib/{chunk-C4YGSK6W.mjs → chunk-27Z76O2O.mjs} +1 -1
  4. package/lib/{chunk-TKQQVB2D.mjs → chunk-2JZGCCPG.mjs} +1 -1
  5. package/lib/{chunk-TPHXRHOA.mjs → chunk-2UU42PTD.mjs} +1 -1
  6. package/lib/{chunk-ZWZXQTAK.mjs → chunk-32EUNQT6.mjs} +14 -14
  7. package/lib/{chunk-HYOOJVR6.mjs → chunk-3C2ZZIFN.mjs} +1 -1
  8. package/lib/{chunk-AELFEK3G.mjs → chunk-3CX7GPCR.mjs} +1 -1
  9. package/lib/{chunk-YJEXE6HZ.mjs → chunk-3HEMJTAP.mjs} +2 -2
  10. package/lib/{chunk-DQR5NDMI.mjs → chunk-3HROD5RE.mjs} +1 -1
  11. package/lib/{chunk-D7P7DTWL.mjs → chunk-3MGMNK3Q.mjs} +1 -1
  12. package/lib/{chunk-MNITSYI2.mjs → chunk-3SKLBRPL.mjs} +1 -1
  13. package/lib/{chunk-MAHZMPMZ.mjs → chunk-3XG25GTF.mjs} +1 -1
  14. package/lib/{chunk-N7J6NJQ6.mjs → chunk-42BFLWHR.mjs} +1 -1
  15. package/lib/chunk-466F37VD.mjs +7 -0
  16. package/lib/chunk-47UHTN3Q.mjs +7 -0
  17. package/lib/{chunk-DHGPDSXS.mjs → chunk-52EXDVPN.mjs} +1 -1
  18. package/lib/{chunk-5344TZBT.mjs → chunk-5K2I2DMP.mjs} +1 -1
  19. package/lib/{chunk-2OZG6GRW.mjs → chunk-6GQUZ4IP.mjs} +1 -1
  20. package/lib/{chunk-SW2NUKQL.mjs → chunk-6KP6WETK.mjs} +1 -1
  21. package/lib/{chunk-FSZTXLNW.mjs → chunk-6VSZNZHH.mjs} +1 -1
  22. package/lib/{chunk-6NADW3OI.mjs → chunk-7CVDVBEE.mjs} +1 -1
  23. package/lib/{chunk-67CC7RAE.mjs → chunk-7EYQYZJP.mjs} +1 -1
  24. package/lib/{chunk-IBURU7T7.mjs → chunk-7LKI7OAS.mjs} +1 -1
  25. package/lib/{chunk-CULAOP3U.mjs → chunk-7PY3VQP3.mjs} +1 -1
  26. package/lib/chunk-7SDZR6SR.mjs +7 -0
  27. package/lib/{chunk-V4RKM4QZ.mjs → chunk-7WSLT5VX.mjs} +1 -1
  28. package/lib/chunk-A32ISQ6M.mjs +28 -0
  29. package/lib/{chunk-K77NR3UK.mjs → chunk-A65ADTCR.mjs} +1 -1
  30. package/lib/chunk-A7JJWOLT.mjs +7 -0
  31. package/lib/{chunk-MWLFFVQV.mjs → chunk-AUS6NFLZ.mjs} +1 -1
  32. package/lib/{chunk-NWPQF5XR.mjs → chunk-BMTNTBBM.mjs} +1 -1
  33. package/lib/{chunk-FTA5LOVX.mjs → chunk-BN33LVPQ.mjs} +1 -1
  34. package/lib/chunk-BNKT3R3F.mjs +7 -0
  35. package/lib/{chunk-WM5JI4JI.mjs → chunk-C2N2TNEU.mjs} +1 -1
  36. package/lib/{chunk-5UT2ZBGF.mjs → chunk-C3LNYAVJ.mjs} +1 -1
  37. package/lib/{chunk-GYKNCYES.mjs → chunk-CBL42DUU.mjs} +1 -1
  38. package/lib/{chunk-W2AAGIZF.mjs → chunk-CCEH7L53.mjs} +1 -1
  39. package/lib/{chunk-WWTXRWNZ.mjs → chunk-CELEBWEZ.mjs} +1 -1
  40. package/lib/{chunk-D62KWDDT.mjs → chunk-CV47FDQW.mjs} +1 -1
  41. package/lib/{chunk-AJPSGVMD.mjs → chunk-CZLJZQCS.mjs} +1 -1
  42. package/lib/{chunk-YIGFYZQY.mjs → chunk-DBBPDSFN.mjs} +1 -1
  43. package/lib/{chunk-T5VAULLQ.mjs → chunk-DIL62SUN.mjs} +1 -1
  44. package/lib/chunk-DIS254AN.mjs +7 -0
  45. package/lib/{chunk-GK7VEYFM.mjs → chunk-DJCGURW7.mjs} +1 -1
  46. package/lib/{chunk-MHW6DV6T.mjs → chunk-DT3T7FRD.mjs} +1 -1
  47. package/lib/{chunk-PYUEHBA6.mjs → chunk-DWMRIWV5.mjs} +1 -1
  48. package/lib/{chunk-E2OBAWSH.mjs → chunk-EEFUE2ES.mjs} +1 -1
  49. package/lib/{chunk-MKNAZPOT.mjs → chunk-EOFO3PHS.mjs} +1 -1
  50. package/lib/{chunk-UUSLTW5V.mjs → chunk-FA4ZKDCU.mjs} +1 -1
  51. package/lib/{chunk-DHIW4IO5.mjs → chunk-FKK5YBGZ.mjs} +1 -1
  52. package/lib/{chunk-BZFIOZS3.mjs → chunk-FOIWWK7G.mjs} +1 -1
  53. package/lib/chunk-FZF23M6R.mjs +7 -0
  54. package/lib/{chunk-XIZ5LMQM.mjs → chunk-G2JR3F63.mjs} +1 -1
  55. package/lib/{chunk-2Z54GB6X.mjs → chunk-GBGHJTPC.mjs} +1 -1
  56. package/lib/{chunk-2NAIUKVL.mjs → chunk-GCGHHN4K.mjs} +1 -1
  57. package/lib/{chunk-TQM2XJ27.mjs → chunk-GGNUACTY.mjs} +1 -1
  58. package/lib/{chunk-2IB7I3IQ.mjs → chunk-GGUOIDWP.mjs} +1 -1
  59. package/lib/chunk-GHPR5UVV.mjs +7 -0
  60. package/lib/{chunk-YHIOS2PU.mjs → chunk-GJ6SZVHT.mjs} +1 -1
  61. package/lib/{chunk-WI4HYWV6.mjs → chunk-H4JUYUSL.mjs} +1 -1
  62. package/lib/{chunk-5WGA5CZB.mjs → chunk-H4OBZIX3.mjs} +1 -1
  63. package/lib/{chunk-KRNFVAGC.mjs → chunk-HFUDCNU5.mjs} +1 -1
  64. package/lib/{chunk-OIIL4NVI.mjs → chunk-HIHCYMSL.mjs} +1 -1
  65. package/lib/chunk-HKUWHVI7.mjs +9 -0
  66. package/lib/chunk-HQQVANWQ.mjs +20 -0
  67. package/lib/{chunk-V2QO6KOE.mjs → chunk-IRZJU2PG.mjs} +14 -11
  68. package/lib/{chunk-CAFUNR6D.mjs → chunk-ISSP2FZ5.mjs} +1 -1
  69. package/lib/{chunk-OEHVAJAB.mjs → chunk-IVZJSDJD.mjs} +1 -1
  70. package/lib/{chunk-E2YJVSX6.mjs → chunk-J24TIGSI.mjs} +1 -1
  71. package/lib/{chunk-YCSFP6ER.mjs → chunk-JESRFE2Z.mjs} +1 -1
  72. package/lib/{chunk-KOQV4WXC.mjs → chunk-JFNLKHY6.mjs} +2 -2
  73. package/lib/{chunk-NJ3EOEHS.mjs → chunk-JH27IKCO.mjs} +1 -1
  74. package/lib/{chunk-DXOXLUZA.mjs → chunk-JJITOWZK.mjs} +1 -1
  75. package/lib/{chunk-KNIRA333.mjs → chunk-JKT5YAQ2.mjs} +1 -1
  76. package/lib/{chunk-J6G23RUI.mjs → chunk-JLZRZL5E.mjs} +1 -1
  77. package/lib/{chunk-6FMLW7PH.mjs → chunk-JPEVIXNH.mjs} +1 -1
  78. package/lib/{chunk-6IGEASOF.mjs → chunk-JQZTMFO7.mjs} +1 -1
  79. package/lib/{chunk-55LQD3Y3.mjs → chunk-KIMQQ6JQ.mjs} +1 -1
  80. package/lib/{chunk-EH5YUA5W.mjs → chunk-KJYEQHYP.mjs} +1 -1
  81. package/lib/chunk-KKOA62S4.mjs +474 -0
  82. package/lib/{chunk-56MPPWLA.mjs → chunk-KP5G6FUC.mjs} +1 -1
  83. package/lib/{chunk-EAFLDSQ2.mjs → chunk-L4INJ5TZ.mjs} +1 -1
  84. package/lib/{chunk-MO3N5XVV.mjs → chunk-LAUOSXMN.mjs} +2 -2
  85. package/lib/{chunk-HVC5CYIB.mjs → chunk-LHU6CPGE.mjs} +1 -1
  86. package/lib/{chunk-7PK5QDQI.mjs → chunk-LXDSRP2W.mjs} +1 -1
  87. package/lib/{chunk-YOGMP72T.mjs → chunk-MKTXJCXN.mjs} +1 -1
  88. package/lib/{chunk-VSU74RQ3.mjs → chunk-MUEQRIK7.mjs} +1 -1
  89. package/lib/{chunk-UCHAZ4ZU.mjs → chunk-NLB3RGIY.mjs} +1 -1
  90. package/lib/{chunk-OVOLG3AL.mjs → chunk-NWOI25WY.mjs} +1 -1
  91. package/lib/{chunk-6SEDOIO3.mjs → chunk-O2PUGRNW.mjs} +1 -1
  92. package/lib/chunk-O4BROUGM.mjs +7 -0
  93. package/lib/{chunk-KGYXLSQ5.mjs → chunk-P55MKIZX.mjs} +1 -1
  94. package/lib/{chunk-KE2PGD6C.mjs → chunk-P63WJMXQ.mjs} +1 -1
  95. package/lib/chunk-PBE44M2Y.mjs +7 -0
  96. package/lib/{chunk-OMZJ37JI.mjs → chunk-PE435FVH.mjs} +2 -2
  97. package/lib/{chunk-GR3NGDVM.mjs → chunk-PPHVWUFY.mjs} +1 -1
  98. package/lib/{chunk-ZUA5BNAO.mjs → chunk-PR74GYVI.mjs} +1 -1
  99. package/lib/{chunk-43K2C6H2.mjs → chunk-PWVDNN2C.mjs} +1 -1
  100. package/lib/{chunk-DMBR24CK.mjs → chunk-PYRZFUVU.mjs} +1 -1
  101. package/lib/{chunk-OXKZ4Y3B.mjs → chunk-Q3DY7TO2.mjs} +1 -1
  102. package/lib/{chunk-EOSEMFPU.mjs → chunk-Q6SXNKV2.mjs} +1 -1
  103. package/lib/chunk-QAPVKPEC.mjs +7 -0
  104. package/lib/chunk-QROPNEGY.mjs +14 -0
  105. package/lib/{chunk-6CDIIFNX.mjs → chunk-RCYEBY42.mjs} +1 -1
  106. package/lib/chunk-RLWB7F26.mjs +7 -0
  107. package/lib/{chunk-X2ZVSQ54.mjs → chunk-RTWYLOCA.mjs} +1 -1
  108. package/lib/chunk-RYRMUPMY.mjs +7 -0
  109. package/lib/{chunk-ETT5GP4P.mjs → chunk-SAMWHL22.mjs} +1 -1
  110. package/lib/{chunk-LO527YLT.mjs → chunk-SFGZFB4F.mjs} +1 -1
  111. package/lib/{chunk-33ZX3A56.mjs → chunk-SNEOKYV7.mjs} +1 -1
  112. package/lib/{chunk-GTIXJCGS.mjs → chunk-STRMWSIQ.mjs} +1 -1
  113. package/lib/{chunk-OQQHNYR7.mjs → chunk-SZGGFST2.mjs} +2 -2
  114. package/lib/{chunk-OU5W7SCB.mjs → chunk-T7WREYA5.mjs} +1 -1
  115. package/lib/{chunk-FLNLG43R.mjs → chunk-TCBAE65A.mjs} +1 -1
  116. package/lib/{chunk-RKALOKAU.mjs → chunk-TMA34QMA.mjs} +1 -1
  117. package/lib/{chunk-WEZLXE34.mjs → chunk-TWV4A5RK.mjs} +1 -1
  118. package/lib/{chunk-ONMBSACW.mjs → chunk-UHFLKP26.mjs} +1 -1
  119. package/lib/chunk-UV74P4H2.mjs +7 -0
  120. package/lib/{chunk-HYBH5PFM.mjs → chunk-V3R45ZWT.mjs} +1 -1
  121. package/lib/{chunk-BNO5GIJ6.mjs → chunk-VPDEJGPS.mjs} +1 -1
  122. package/lib/{chunk-3AOKLIVE.mjs → chunk-VQJMP3DC.mjs} +1 -1
  123. package/lib/{chunk-742SSN7I.mjs → chunk-VYOYXTCU.mjs} +1 -1
  124. package/lib/{chunk-GWRKS3AL.mjs → chunk-VZT4E2OJ.mjs} +1 -1
  125. package/lib/{chunk-2OIRJEYE.mjs → chunk-VZVICK7Q.mjs} +1 -1
  126. package/lib/chunk-WEMLDUQA.mjs +7 -0
  127. package/lib/{chunk-FDGFUEK3.mjs → chunk-WOOUISSO.mjs} +1 -1
  128. package/lib/{chunk-UIUPPEFB.mjs → chunk-WSUKC2U3.mjs} +1 -1
  129. package/lib/{chunk-XC2QKQT5.mjs → chunk-WT3SCUHS.mjs} +1 -1
  130. package/lib/{chunk-UT27HXE7.mjs → chunk-XFU3HRUV.mjs} +1 -1
  131. package/lib/{chunk-5VQNKDFU.mjs → chunk-XK5W7BVE.mjs} +1 -1
  132. package/lib/{chunk-OZNLOV4U.mjs → chunk-XO5FBOQF.mjs} +1 -1
  133. package/lib/{chunk-FSDO4DJA.mjs → chunk-XSKPYGMT.mjs} +1 -1
  134. package/lib/{chunk-AITNZWLB.mjs → chunk-XU25YA46.mjs} +1 -1
  135. package/lib/{chunk-XEB6HZ34.mjs → chunk-XZISAZA6.mjs} +1 -1
  136. package/lib/chunk-Y4TDVDP2.mjs +13 -0
  137. package/lib/{chunk-4L7FBOJS.mjs → chunk-YAIIRFKJ.mjs} +1 -1
  138. package/lib/{chunk-T3PLRQ2T.mjs → chunk-YAJQS3OL.mjs} +1 -1
  139. package/lib/{chunk-Y5ZCPY36.mjs → chunk-YGJF55VJ.mjs} +1 -1
  140. package/lib/chunk-YH4DYI6D.mjs +7 -0
  141. package/lib/{chunk-R6TF26V4.mjs → chunk-YMDFF657.mjs} +1 -1
  142. package/lib/{chunk-JU2XEKEO.mjs → chunk-YT22LMF7.mjs} +1 -1
  143. package/lib/{chunk-NWVVCZUK.mjs → chunk-Z42PHCVZ.mjs} +1 -1
  144. package/lib/{chunk-O6ADMP36.mjs → chunk-ZHIZY3ZC.mjs} +1 -1
  145. package/lib/chunk-ZQO5PDX5.mjs +48 -0
  146. package/lib/{chunk-QXLZINZB.mjs → chunk-ZUBBEP75.mjs} +1 -1
  147. package/lib/{chunk-SQGP46QS.mjs → chunk-ZUOPC4W2.mjs} +1 -1
  148. package/lib/{chunk-3B5H24ZG.mjs → chunk-ZUTUYBNW.mjs} +1 -1
  149. package/lib/{chunk-K55LH4ZQ.mjs → chunk-ZXFL2MSN.mjs} +1 -1
  150. package/lib/sandforge-autopilot.mjs +1 -1
  151. package/lib/sandforge-backup.mjs +1 -1
  152. package/lib/sandforge-checkpoint.mjs +1 -1
  153. package/lib/sandforge-cleanup.mjs +1 -1
  154. package/lib/sandforge-clone.mjs +1 -1
  155. package/lib/sandforge-compare.mjs +1 -1
  156. package/lib/sandforge-dataops.mjs +1 -1
  157. package/lib/sandforge-empty.mjs +1 -1
  158. package/lib/sandforge-env.mjs +185 -139
  159. package/lib/sandforge-frozen.mjs +1 -1
  160. package/lib/sandforge-mcp.mjs +14 -14
  161. package/lib/sandforge-monitor.mjs +1 -1
  162. package/lib/sandforge-pipeline.mjs +1 -1
  163. package/lib/sandforge-seed.mjs +1 -1
  164. package/lib/sandforge-sync.mjs +1 -1
  165. package/lib/sandforge-users.mjs +157 -0
  166. package/lib/sandforge.mjs +1 -22
  167. package/lib/sf/sandforge/autopilot.mjs +20 -0
  168. package/lib/sf/sandforge/backup.mjs +20 -0
  169. package/lib/sf/sandforge/checkpoint.mjs +20 -0
  170. package/lib/sf/sandforge/cleanup.mjs +20 -0
  171. package/lib/sf/sandforge/clone.mjs +20 -0
  172. package/lib/sf/sandforge/compare.mjs +20 -0
  173. package/lib/sf/sandforge/dataops.mjs +20 -0
  174. package/lib/sf/sandforge/empty.mjs +20 -0
  175. package/lib/sf/sandforge/env.mjs +20 -0
  176. package/lib/sf/sandforge/frozen.mjs +20 -0
  177. package/lib/sf/sandforge/hardis-commands.mjs +20 -0
  178. package/lib/sf/sandforge/index.mjs +20 -0
  179. package/lib/sf/sandforge/mcp.mjs +20 -0
  180. package/lib/sf/sandforge/monitor.mjs +20 -0
  181. package/lib/sf/sandforge/pipeline.mjs +20 -0
  182. package/lib/sf/sandforge/seed.mjs +20 -0
  183. package/lib/sf/sandforge/sync.mjs +20 -0
  184. package/lib/sf/sandforge/users.mjs +20 -0
  185. package/lib/sfHelpHook.mjs +7 -0
  186. package/lib/sfPlugin.mjs +11 -0
  187. package/oclif.manifest.json +1 -0
  188. package/package.json +17 -3
  189. package/lib/chunk-2ZMGVBLW.mjs +0 -7
  190. package/lib/chunk-5C5XEVZN.mjs +0 -11
  191. package/lib/chunk-5CKWGZX4.mjs +0 -9
  192. package/lib/chunk-5ZKCLBTN.mjs +0 -474
  193. package/lib/chunk-7DALDJMO.mjs +0 -7
  194. package/lib/chunk-DPYTG6DM.mjs +0 -48
  195. package/lib/chunk-G4VXPS3A.mjs +0 -7
  196. package/lib/chunk-GF247DA7.mjs +0 -7
  197. package/lib/chunk-IKGHRYCN.mjs +0 -7
  198. package/lib/chunk-IM2XA6JI.mjs +0 -7
  199. package/lib/chunk-K5HV4YRO.mjs +0 -7
  200. package/lib/chunk-N6HHNR6J.mjs +0 -7
  201. package/lib/chunk-O7DAFE6M.mjs +0 -14
  202. package/lib/chunk-R2BJWO5N.mjs +0 -20
  203. package/lib/chunk-T26C576X.mjs +0 -9
  204. package/lib/chunk-V473C7LY.mjs +0 -7
  205. package/lib/chunk-WD47PGUS.mjs +0 -10
  206. package/lib/chunk-XC54KKKC.mjs +0 -7
  207. package/lib/chunk-XGKSSCW7.mjs +0 -7
  208. package/lib/chunk-ZWCRWF7E.mjs +0 -7
@@ -0,0 +1,20 @@
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 FS,b as nd,c as _S,d as HS}from"./chunk-BXZ73A5M.mjs";import{a as Sb}from"./chunk-DBBPDSFN.mjs";import{c as bb,d as Rb}from"./chunk-GBGHJTPC.mjs";import{b as hb}from"./chunk-ZRUDYB7O.mjs";import{a as MS,b as Qn,c as qs,d as Hu,e as Uu,f as Bu,g as LS,h as qu,l as US,y as BS}from"./chunk-IRZJU2PG.mjs";import{a as wu,b as yb,c as wb,d as Ca,f as _s}from"./chunk-YT22LMF7.mjs";import{a as Xb,d as rR,e as nR,f as Us,g as Do,h as Tu,i as ja,j as oR,k as sR,l as iR,m as aR}from"./chunk-G2JR3F63.mjs";import{a as GR,b as Lu,c as AS,d as TS,e as ES,h as PS,i as CS,j as $S,k as xS,n as DS,o as NS,p as td,q as Fu,r as rd,s as _u}from"./chunk-3CX7GPCR.mjs";import{b as OS,e as IS}from"./chunk-NWOI25WY.mjs";import{A as Ya,B as dS,C as cS,D as Qa,E as Za,F as ed,G as Pn,H as lS,I as uS,L as pS,M as gS,N as fS,O as hS,P as mS,R as yS,S as Mu,T as wS,U as bS,V as RS,_ as SS,a as Ua,aa as vS,ba as kS,c as Ba,d as qa,e as JR,f as VR,g as XR,h as Ot,j as Wa,k as za,l as Qr,m as Fo,n as _o,o as Ho,p as KR,q as YR,r as QR,s as Ga,t as Ja,u as Va,v as ZR,w as oS,x as sS,y as iS,z as aS}from"./chunk-A7JJWOLT.mjs";import{b as Xa,g as Ka}from"./chunk-ZXFL2MSN.mjs";import{e as kr,g as eS,i as tS,k as rS,l as Uo,m as nS}from"./chunk-52EXDVPN.mjs";import{a as jS}from"./chunk-EEFUE2ES.mjs";import{a as yh,b as ea,e as ya,g as vn,h as sr,i as eb,l as ob,p as mb}from"./chunk-PE435FVH.mjs";import{a as Rt,b as Tw}from"./chunk-PWVDNN2C.mjs";import{a as Hw,b as Uw}from"./chunk-XCA5AONB.mjs";import{a as wa,b as Ew,c as Pw,d as Cw,e as js,f as $w,g as xw,h as Dw,j as Nw}from"./chunk-WB2RIVO3.mjs";import{$ as sm,$b as Ty,A as Lh,Ab as ty,B as yn,Bb as ry,C as tu,Ca as wm,Cb as ny,D as Fh,Da as bm,Db as oy,Dc as Ze,E as _h,Ea as Rm,Eb as sy,Ec as Ms,F as ra,Fa as Sm,Fb as iy,Fc as Bw,G as Hh,Ga as vm,Gb as oa,Gc as qw,H as Uh,Ha as km,Hb as ay,I as Bh,Ia as Om,Ib as dy,J as qh,Ja as Im,Jb as cy,K as Wh,Ka as Am,Kb as ly,L as zh,La as Tm,Lb as uy,M as ru,Ma as Em,Mb as py,N as Gh,Na as Pm,Nb as gy,O as Jh,Oa as Cm,Ob as fy,P as Vh,Pa as Gr,Pb as hy,Q as Xh,Qa as $m,Qb as my,R as Kh,Ra as iu,Rb as yy,S as Yh,Sa as na,Sb as wy,T as Qh,Ta as Es,Tb as by,U as Zh,Ua as xm,Ub as Ry,V as em,Va as Dm,Vb as Sy,W as tm,Wb as vy,X as rm,Xb as ky,Y as nm,Yb as Oy,Z as om,Zb as Iy,_ as ko,_b as Ay,a as Wr,aa as im,ac as Ey,b as Se,ba as am,bc as Py,c as Qi,ca as dm,cc as Cy,d as Ct,da as nu,dc as $y,e as hn,ea as cm,ec as xy,f as vo,fa as lm,fb as Nm,fc as Dy,g as ct,ga as um,gb as jm,gc as Ny,h as hr,ha as pm,hb as Mm,hc as jy,i as mn,ia as gm,ib as Lm,ic as My,j as T,ja as fm,jb as Fm,jc as Ly,k as Ie,ka as hm,kb as _m,kc as Fy,l as ze,la as mm,lb as Hm,lc as sa,m as Le,ma as ym,mb as Um,mc as _y,n as pe,na as ou,nb as Bm,nc as Hy,o as E,oa as su,ob as qm,oc as Uy,p as Zi,pa as Ts,pb as Wm,pc as By,q as vs,qb as zm,qc as qy,r as zr,rb as Gm,rc as Wy,s as De,sb as Jm,sc as zy,t as xh,tb as Vm,tc as Gy,u as Dh,ub as Xm,uc as Jy,v as Nh,vb as Km,vc as au,w as jh,wb as Ym,wc as x,x as ta,xb as Qm,yb as Zm,yc as ma,z as Mh,zb as ey}from"./chunk-ISSP2FZ5.mjs";import{g as ha}from"./chunk-XU25YA46.mjs";import{a as Nt,b as Is,c as Sh,d as vh}from"./chunk-CE6ZDGBB.mjs";import{a as Ww,b as zw,c as Gw,e as Jw,f as Vw,g as Sa,h as Eo,i as Xn,j as Xr,k as kn,l as va}from"./chunk-IVZJSDJD.mjs";import{b as Vn,c as Zw}from"./chunk-BOGNK4LV.mjs";import{Aa as TR,Ba as ER,D as lR,Da as PR,Ea as CR,Fa as Du,Ha as No,Ja as $R,Ka as Fa,La as xR,S as uR,Ua as DR,Wa as jo,Ya as NR,Za as Mo,_a as Lo,a as Ji,b as Yf,ca as Pu,cb as jR,da as Cu,db as vr,eb as Nu,fa as $u,fb as MR,g as Vb,gb as LR,h as Au,hb as FR,ib as _R,ja as La,jb as _a,kb as Ha,la as bR,m as dR,na as xu,nb as HR,ob as UR,pa as RR,qb as ju,ra as SR,rb as BR,sb as qR,ta as vR,tb as WR,ua as Bs,ub as zR,va as kR,xa as OR,ya as IR,z as cR,za as AR}from"./chunk-P55MKIZX.mjs";import{a as Sw,b as Oo,c as Io,d as Sn,e as vw,f as pu,i as jw,j as Mw,k as Ra,l as Lw,m as Fw,p as mu,q as Fs,r as Kn,s as Ea}from"./chunk-O2PUGRNW.mjs";import{B as yw,C as nr,D as pa,E as ga,F as fa,K as ww,L as lu,M as uu,N as or,O as bw,P as Rw,Q as Rn,a as fh,b as Vy,c as Xy,d as Ky,e as rr,f as Yy,g as du,h as Qy,i as Zy,j as ew,k as tw,m as zn,o as $s,p as cw,q as lw,s as uw,t as pw,u as xs,w as gw,x as fw,y as hw,z as mw}from"./chunk-7SDZR6SR.mjs";import{h as Kb}from"./chunk-TEIBWMJM.mjs";import{a as Yb,b as Qb,f as Zb,g as eR,h as tR}from"./chunk-BWWQXU2B.mjs";import{d as ba}from"./chunk-T63U4OZJ.mjs";import{a as ub,b as Pa,c as pb,k as gb,p as fb}from"./chunk-YAIIRFKJ.mjs";import{a as _w}from"./chunk-YYZL7UGV.mjs";import{a as la,c as ua}from"./chunk-54HYHHVL.mjs";import{b as kw,f as Ow,p as jt,q as Ds,r as gu,s as To,t as fu,u as Ns,x as Iw,y as Aw}from"./chunk-3SKLBRPL.mjs";import{b as pR,c as gR,d as Ma,e as Eu,g as fR,h as hR,i as mR,j as yR,m as wR}from"./chunk-JH27IKCO.mjs";import{c as mr,d as Jn}from"./chunk-SAMWHL22.mjs";import{b as Aa,f as Ta}from"./chunk-6KP6WETK.mjs";import{L as nb,d as ka,h as Oa,i as tb,k as rb,z as Ia}from"./chunk-J24TIGSI.mjs";import{a as Mt,b as $t,d as hu,e as Vr,f as Qw,h as kt,i as Ls,j as Vt}from"./chunk-HKUWHVI7.mjs";import{a as ia,b as Ut,c as Jr,d as Ps,e as aa,f as Cs,g as da,h as wn,i as rw,j as ca,k as cu}from"./chunk-VPDEJGPS.mjs";import{a as $e}from"./chunk-5LFSFYFJ.mjs";import{b as Kf}from"./chunk-LHU6CPGE.mjs";import{a as Jl,c as wo,d as Vl,e as Bf,f as Rs,g as Xl,h as qf,j as Wf,k as zf,l as bo,m as Gf,n as Kl,o as Jf,p as Vf,q as Xf,r as q}from"./chunk-PBE44M2Y.mjs";import{a as zi,f as Gi}from"./chunk-ZUOPC4W2.mjs";import{a as Xw,b as Bt,c as qt,g as ir}from"./chunk-JQZTMFO7.mjs";import{$a as ar,$b as Ub,Ab as $b,Ac as Jb,B as sb,Cb as Su,D as ib,F as ab,Gb as xb,I as db,J as cb,K as yu,La as Yr,Mb as Db,N as lb,Na as bu,Nb,Oa as vb,Ob as jb,Pb as Sr,Ra as Yn,Sa as Ru,Ta as kb,Ua as Ob,Vb as Mb,Wa as Ib,Xa as Ab,Xb as Lb,Ya as Tb,Yb as Fb,Zb as _b,_a as br,_b as Hb,a as hh,b as So,c as bt,cc as Bb,d as mh,db as On,e as Z,eb as Co,ec as An,f as ft,fb as $a,fc as Tn,gb as $o,h as wh,hb as In,i as rt,ib as xo,j as bh,jb as xa,k as Zl,l as Rh,lb as Da,lc as En,m as ks,mc as Hs,n as eu,oc as vu,pc as ku,qc as Ou,rc as qb,sc as Wb,tc as zb,uc as Iu,wb as Eb,xb as Pb,xc as lt,yb as Cb,yc as Na,zb as Rr,zc as Gb}from"./chunk-JFNLKHY6.mjs";import{q as wr,r as Kr,s as Po}from"./chunk-VZVICK7Q.mjs";import{a as Uf}from"./chunk-PPGDAUEQ.mjs";import{a as yr,b as ge}from"./chunk-VV3B6IC3.mjs";import{a as oe}from"./chunk-4TLYUZD5.mjs";import{i as Os}from"./chunk-INIT2UKJ.mjs";import{a as bs,b as Gl}from"./chunk-SU65Z2BA.mjs";import{e as sw,h as bn,k as iw,l as aw,m as dw}from"./chunk-HFUDCNU5.mjs";import{D as As,F as $h,p as Th}from"./chunk-XZISAZA6.mjs";import{b as kh,e as Oh,k as Ih,m as Ah}from"./chunk-HFSBDM7B.mjs";import{a as Kw,b as Yw}from"./chunk-PC247GKX.mjs";import{a as tr}from"./chunk-EADHKH3A.mjs";import{c as dh,f as Yi,g as ch,j as lh,l as uh,r as ph,s as gh}from"./chunk-L4INJ5TZ.mjs";import{$ as ah,F as fr,G as Ss,N as nh,P as oh,Y as sh,Z as ih,a as Vi,b as er,c as Xi,f as Zf,j as eh,m as Ki,n as Ql,o as th,p as rh,q as Ro,r as gr}from"./chunk-KIMQQ6JQ.mjs";import{a as Zt,d as Yl,f as Qf,h as qe}from"./chunk-TZE3Y7IQ.mjs";import{a as Hf,b as I}from"./chunk-CA5NAXSU.mjs";import{f as nw,j as ow}from"./chunk-ZUTUYBNW.mjs";import{a as Ph,d as Ch}from"./chunk-PR74GYVI.mjs";import{a as Eh}from"./chunk-TMA34QMA.mjs";import{a as Ao,d as Gn}from"./chunk-TUACWKIH.mjs";import{$b as Ll,$c as yo,$d as Tf,A as ps,Aa as Fr,Ae as qi,Ba as $i,Be as Lf,Ca as nf,Cd as If,Ce as Ff,Da as Nl,De as _f,Ea as jl,Ee as Wi,Fa as of,Ga as Ml,Hb as df,Hc as wt,I as Qg,Jc as Wn,Jd as hs,Kb as cf,Kc as Mi,Lb as lf,Ld as Br,Ma as sf,Mb as uf,Mc as Ce,Na as af,Nb as xi,Nc as Li,Ob as pf,Oc as Fl,Pb as gf,Pc as _r,Pd as Af,Qb as Di,Rc as _l,Sb as ff,Sc as me,Tb as hf,Td as qr,Ub as mf,Ud as dt,Y as Ci,Z as $l,Zc as Fi,_ as Zg,_b as yf,_c as mo,ae as Ef,b as Ug,bd as wf,be as ms,c as Bg,cd as bf,d as Jg,fe as Pf,gd as Hl,ge as Cf,hd as Hr,he as $f,ic as Ni,ie as xf,ja as xl,je as Df,k as fo,kc as ji,kd as fs,l as ho,la as ef,ld as _i,mc as gs,md as Ul,me as fn,nd as gn,ne as Pt,o as pn,od as Rf,oe as Ui,p as us,pd as Ur,pe as ys,q as Vg,qd as Sf,qe as ws,r as Xg,rd as Bl,re as Bi,s as Kg,sd as vf,se as ql,td as kf,te as Nf,ud as Hi,ue as Wl,va as tf,vd as Of,wa as Dl,we as jf,xa as rf,ye as Mf,z as Yg,ze as zl}from"./chunk-ZQO5PDX5.mjs";import{a as qg,b as j,e as Te,f as Ge,i as un,k as Re,l as G,o as Wg,p as Ei,s as Pi,u as _e,v as yt,x as zg,y as Gg,z as qn}from"./chunk-WZQEK4WT.mjs";var qS="pipeline-rewind-grants",zS="pipeline:rewind-grant:",WS="pipeline:saved:",Wu=G({pipelineId:j().min(1).max(200),stepId:j().min(1).max(200),organizationId:j().min(1).max(18),checkpointId:j().min(1).max(200),digest:j().regex(/^sha256:[0-9a-f]{64}$/),grantedAt:qn.datetime(),grantedBy:j().max(80).optional(),takenBackAt:qn.datetime().optional()}).strict();function Cn(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 zu(s,e){return`${zS}${s}:${e}`}var Ws=class{constructor(e){this.store=e}store;all(){return Object.values(this.store.getByCategory(qS)).flatMap(e=>{let t=Wu.safeParse(e);return t.success?[t.data]:[]})}get(e,t){let r=Wu.safeParse(this.store.get(zu(e,t)));return r.success?r.data:void 0}write(e){this.store.set(zu(e.pipelineId,e.stepId),Wu.parse(e),qS)}revoke(e,t){return this.store.delete(zu(e,t))}revokePipeline(e){let t=`${zS}${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&&zs(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(`${WS}${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(`${WS}${e}`)?{refusal:"never"}:r.takenBackAt!==void 0||zs(t.config)!==r.digest?{refusal:"changed"}:{grant:{organizationId:r.organizationId,checkpointId:r.checkpointId,digest:r.digest,grantedAt:r.grantedAt}}}};function zs(s){let e=Pt.safeParse(s??{});return e.success?ws(e.data):void 0}function GS(s,e){return new Ws(s).revokePipeline(e)}function $n(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 AT="/lightning/setup/AsyncApexJobs/home";function JS(s){let e=$n(s);return e.ok?{ok:!0,url:new URL(AT,e.url.origin).toString()}:e}import{randomBytes as TT}from"node:crypto";import{createReadStream as ET}from"node:fs";import{open as PT,readdir as CT,rm as $T,stat as xT}from"node:fs/promises";import{homedir as DT}from"node:os";import{join as dr,resolve as NT}from"node:path";import{createInterface as jT}from"node:readline";var Gu="journal.ndjson",od=2e3,QS=/^em-\d{8}-\d{6}-[a-z0-9]{4}$/,VS="abcdefghijklmnopqrstuvwxyz0123456789";function Vu(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(TT(4),o=>VS[o%VS.length]).join("");return`em-${t}-${r}-${n}`}function Ju(s){return QS.test(s)}function Xu(s=process.env){let e=s.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?NT(e):dr(DT(),".sandforge");return dr(t,"empty")}var MT=j().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),Zr=j().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Not an API name").max(80),Gs=qn.datetime({offset:!0}),XS=Re(MT).max(od),ZS=_e(["success","partial","failure","cancelled"]),ev=G({v:yt(1),kind:yt("head"),runId:j().regex(QS),organizationId:j().min(15).max(18),orgName:j(),startedAt:Gs,readAt:Gs,previewId:j(),mode:_e(["objects","org"]),deleteMode:_e(["recycle","hard"]),request:G({mode:_e(["objects","org"]),objects:Re(j()).optional(),excluded:Re(j()).optional(),customSettings:Ge().optional(),files:Ge().optional(),managedPackages:Ge().optional(),unrestorable:Ge().optional()}).strict(),passes:Re(G({objectApiName:Zr,records:Te().int().nonnegative().optional(),sent:Te().int().nonnegative().optional(),rows:j().max(200).optional()})),toDraftAlong:Re(G({objectApiName:Zr,condition:j().optional()})),beforeParent:Re(G({objectApiName:Zr,field:j(),parent:Zr,reason:_e(["restricted","customPrices"])})),undoLost:Re(G({objectApiName:Zr,field:j().optional(),parent:Zr.optional(),reason:_e(["restricted","unordered","notRestorable"]),records:Te().int().nonnegative().optional(),atLeast:yt(!0).optional()})).optional()}),LT=G({kind:yt("attempt"),at:Gs,resumed:Ge()}),tv=G({kind:yt("spooled"),objectApiName:Zr,place:Te().int().nonnegative(),count:Te().int().nonnegative(),sinceRead:Ge()}),FT=G({kind:yt("settled"),objectApiName:Zr,deleted:XS,gone:XS}),_T=G({objectApiName:Zr,planned:Te().int().nonnegative(),deleted:Te().int().nonnegative(),gone:Te().int().nonnegative(),refused:Te().int().nonnegative(),notReached:Te().int().nonnegative().optional(),madeSince:Te().int().nonnegative().optional(),reasons:Re(j())}),rv=G({kind:yt("end"),at:Gs,status:ZS,hardRefused:j().optional(),passes:Re(_T)}),HT=G({kind:yt("undo"),at:Gs,status:ZS}),KS=Ei("kind",[ev,LT,tv,FT,rv,HT]),Or=class extends Error{constructor(e){super(e),this.name="EmptyJournalDamaged"}};function UT(s){return s==="success"||s==="partial"}var sd=class s{constructor(e,t){this.dir=e;this.head=t}dir;head;static async begin(e,t){let r=ev.parse({v:1,kind:"head",...t});await Ia(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 YS(dr(e,Gu))){r.kind==="head"&&(t=r);break}if(t===void 0)throw new Or("The journal of this emptying names nothing it was to do.");return new s(e,t)}idsDirOf(e,t){return dr(this.dir,"ids",`${e}-${wt(t)}`)}async write(e,t="a"){let r=dr(this.dir,Gu),n=await PT(r,t,ka);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(tv.parse({kind:"spooled",...e}))}async settled(e,t,r){for(let n=0;n<Math.max(t.length,r.length);n+=od)await this.write({kind:"settled",objectApiName:e,deleted:t.slice(n,n+od),gone:r.slice(n,n+od)})}ended(e,t,r,n){return this.write(rv.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 YS(dr(this.dir,Gu))}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":UT(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*YS(s){let e=ET(s,{encoding:"utf8"}),t=jT({input:e,crlfDelay:1/0}),r,n=0,o=(i,a)=>{try{return KS.parse(JSON.parse(i))}catch{throw new Or(`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 Or("The journal of this emptying is not on this machine."):i}finally{t.close(),e.destroy()}if(r)try{yield KS.parse(JSON.parse(r.raw))}catch{return}}var id=class{constructor(e){this.root=e}root;orgDir(e){return dr(this.root,rb(e))}begin(e,t){return sd.begin(dr(this.orgDir(e),t.runId),{...t,organizationId:e})}async runsOf(e){let t=this.orgDir(e),r;try{r=await CT(t)}catch(n){if(n.code==="ENOENT")return[];throw n}return r.filter(Ju).sort().map(n=>({runId:n,dir:dr(t,n)}))}async lastOf(e){return(await this.runsOf(e)).at(-1)}async open(e,t){if(!Ju(t))throw new Or(`Not an emptying's id: ${t}`);let r=dr(this.orgDir(e),t);try{await xT(r)}catch{throw new Or(`No journal of the emptying ${t} is on this machine.`)}return sd.open(r)}async remove(e,t){Ju(t)&&await $T(dr(this.orgDir(e),t),{recursive:!0,force:!0})}};import{createHash as BT}from"node:crypto";import{readFileSync as qT}from"node:fs";import{homedir as WT}from"node:os";import{join as ad,resolve as zT}from"node:path";var nv=G({...Kw,pipelineId:j().min(1).max(200),pipelineName:j().max(200).optional(),ranFrom:_e(["editor","commandLine"]),triggeredBy:_e(["manual","schedule","event","webhook","sandbox_refresh","deployment_complete"]),dryRun:Ge().optional()}),Ku=Yw(s=>{let e=nv.safeParse(s);return e.success?e.data:void 0}),GT="run.lock",JT=/^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/;function ov(s=process.env){let e=s.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?zT(e):ad(WT(),".sandforge");return ad(t,"pipelines")}function Js(s){return JT.test(s)&&!s.includes("..")?s:`p-${BT("sha256").update(s).digest("hex").slice(0,32)}`}function dd(s,e){return ad(s,Js(e))}function sv(s,e){return ad(dd(s,e),GT)}function VT(s){try{let e=nv.safeParse(JSON.parse(qT(s,"utf8")));return e.success?e.data:void 0}catch{return}}function Yu({version:s,token:e,...t}){return t}function iv(s,e,t,r={}){let n=sv(s,e),o=VT(n),i=o!==void 0&&Ku.holder(n,r)===void 0,a=Ku.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:Yu(a.busy)}:{lock:{pipelineId:e,release:a.lock.release},...i&&o!==void 0?{tookOver:Yu(o)}:{}}}function dL(s,e,t={}){let r=Ku.holder(sv(s,e),t);return r!==void 0?Yu(r):void 0}function av(s){let e=s.dryRun?"a dry run":"a run";return s.ranFrom==="commandLine"?`${e} from the command line (sandforge pipeline run)`:`${e} in VS Code`}function Qu(s,e){return`Pipeline "${e}" is already running on this machine: ${av(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 dv(s){return`The run lock of pipeline "${s.pipelineName??s.pipelineId}" was left by ${av(s)} started at ${s.acquiredAt} (process ${s.pid} on ${s.host}), whose process has ended: taken over.`}import{randomBytes as XT}from"node:crypto";import{mkdirSync as KT,readFileSync as uv,readdirSync as YT,renameSync as cv,statSync as QT,unlinkSync as ZT,writeFileSync as eE}from"node:fs";import{join as ep}from"node:path";var tp=50,rp="history.json",np=1,lv=4*1024*1024,tE=448,rE=384,nE=G({decision:_e(["approved","rejected","timedOut","cancelled"]),via:_e(["notification","page","terminal","commandLine"]).optional(),at:j().max(64),by:j().max(64).optional()}),oE=G({stepName:j().max(200),stepType:j().max(80),status:_e(["pending","running","completed","failed","skipped","stopped"]),duration:Te().nonnegative().optional(),summary:j().max(8e3).optional(),error:j().max(8e3).optional(),approval:nE.optional()}),Zu=G({runId:j().min(1).max(200),pipelineId:j().min(1).max(200),pipelineName:j().max(200),status:_e(["idle","queued","running","completed","completed_with_warnings","failed","cancelled"]),triggeredBy:_e(["manual","schedule","event","webhook","sandbox_refresh","deployment_complete"]),startTime:qn.datetime({offset:!0}),duration:Te().nonnegative(),stepCount:Te().int().nonnegative(),errorCount:Te().int().nonnegative(),steps:Re(oE).max(200).optional()}),sE=G({sandforgePipelineHistory:yt(np),entries:Re(un()).max(tp*4)});function fL(s,e){return ep(dd(s,e),rp)}function iE(s){let e=Date.parse(s.startTime);return{...s,ranFrom:"commandLine",timestamp:Number.isNaN(e)?0:e}}function pv(s){let e;try{e=JSON.parse(s)}catch{return{why:"it is not JSON"}}let t=sE.safeParse(e);if(!t.success){let o=e?.sandforgePipelineHistory;return{why:typeof o=="number"&&o>np?`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=Zu.safeParse(o);i.success?r.push(iE(i.data)):n+=1}return{entries:r,skipped:n}}function gv(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=YT(s,{withFileTypes:!0}).filter(i=>i.isDirectory()).map(i=>i.name)}catch{return[]}let o=[];for(let i of n.sort()){let a=ep(s,i,rp),d,c;try{let u=QT(a);if(d=`${u.size}:${u.mtimeMs}`,u.size>lv){r(a,d,`[WARN] pipeline history ${a} is not listed: at ${u.size} bytes it is past the ${lv} a history of ${tp} runs takes.`);continue}c=uv(a,"utf8")}catch{continue}let l=pv(c);if("why"in l){r(a,d,`[WARN] pipeline history ${a} is not listed: ${l.why}. The runs it held are not shown in History; the next run from the command line starts it again.`);continue}l.skipped>0&&r(a,d,`[WARN] pipeline history ${a}: ${l.skipped} of its runs do not read and are not listed.`),o.push(...l.entries)}return o.sort((i,a)=>a.timestamp-i.timestamp)}}}function hL(s,e,t){let r=Zu.safeParse(t);if(!r.success)throw new Error(`The run was not recorded: ${r.error.issues.slice(0,3).map(u=>`${u.path.join(".")||"(entry)"}: ${u.message}`).join("; ")}`);let n=dd(s,e);KT(n,{recursive:!0,mode:tE});let o=ep(n,rp),i=[],a,d;try{d=uv(o,"utf8")}catch{d=void 0}if(d!==void 0){let u=pv(d);"why"in u?(a=`${o}.unreadable-${Date.now()}`,cv(o,a)):i=u.entries.map(({ranFrom:p,timestamp:g,...h})=>Zu.parse(h))}let c=[r.data,...i.filter(u=>u.runId!==r.data.runId)].sort((u,p)=>Date.parse(p.startTime)-Date.parse(u.startTime)).slice(0,tp),l=`${o}.${process.pid}-${XT(4).toString("hex")}.tmp`;eE(l,`${JSON.stringify({sandforgePipelineHistory:np,entries:c},null,2)}
9
+ `,{encoding:"utf8",mode:rE,flag:"wx"});try{cv(l,o)}catch(u){try{ZT(l)}catch{}throw u}return{kept:c.length,...a!==void 0?{setAside:a}:{}}}var Ft={major:20,minor:19},fv=5,aE=12,dE=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function ut(s){return s.replace(/\s*[\r\n\u2028\u2029]+\s*/g," ").trim()}function Lt(s){return`'${s.replace(/'/g,"'\\''")}'`}function Xt(s){return`'${s.replace(/['\u2018\u2019\u201a\u201b]/g,e=>e+e)}'`}function Bo(s){return JSON.stringify(s)}function op(s){return s.endsWith(ql)?s.slice(0,-ql.length):s.replace(/\.json$/,"")}function cE(s){return`SFDX_AUTH_URL_${s.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"")}`}function sp(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 hv(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 ip(s,e){return[`SandForge pipeline "${ut(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 ap(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} "${ut(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} "${ut(n.name)}" rewinds an org with no alias: confirm it with pipeline confirm.`)}return r}function qo(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 uE({alias:s,...e}){return e}function dp(s){if(!qo(s.fileName))throw new Error("A pipeline file name is one line of text.");let e=[],t=s.orgs.flatMap(i=>qo(i.key)?i.alias===void 0||qo(i.alias)?[i]:(e.push(`The alias of org "${ut(i.label)}" holds a line break: it is asked below as an alias of this machine.`),[uE(i)]):(e.push(`Org "${ut(i.label)}" is named by a key no line can hold: run it from a terminal.`),[])),r=s.variables.filter(i=>qo(i.name)?!0:(e.push(`Variable "${ut(i.name)}" holds a line break in its name, which no line gives: rename it.`),!1)),n=s.approvals.filter(i=>qo(i.name)?!0:(e.push(`Approval step "${ut(i.name)}" holds a line break in its name: only a terminal answers it.`),!1)),o=s.rewinds.map(i=>i.alias===void 0||qo(i.alias)?i:{name:i.name});return{input:{...s,orgs:t,variables:r,approvals:n,rewinds:o},leftOut:e}}function mv(s){return s.orgs.filter(e=>e.alias===void 0).map((e,t)=>({...e,slot:`org_alias_${t+1}`}))}function pE(s){let{input:e,leftOut:t}=dp(s),n=`${op(e.fileName)}.sh`,o=Js(e.pipelineId),i=e.schedule===null?void 0:sp(qi(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.`]:[],...hv(i)]:["Its schedule cannot be written as a line of this machine's crontab:",ut(i.reason)],d=[`Keep it beside ${e.fileName}. It needs Node.js ${Ft.major}.${Ft.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=mv(e),l=["#!/usr/bin/env bash",...ip(e,d).map(u=>u===""?"#":`# ${u}`),"set -u","",'here="$(cd "$(dirname "$0")" && pwd)"',`file="$here/"${Lt(e.fileName)}`,`store="\${SANDFORGE_JOURNAL_DIR:-$HOME/.sandforge}/pipelines/"${Lt(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 > ${Ft.major} || (a === ${Ft.major} && b >= ${Ft.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 ${Ft.major}.${Ft.minor} or later is not found on this PATH ($PATH), nor through nvm: nothing ran. Install it, or add its folder to PATH at the top of this script."`," exit 127","fi","if ! command -v sf >/dev/null 2>&1; then",' say "The Salesforce CLI (sf) is not found on this PATH ($PATH): nothing ran. Install it (npm install -g @salesforce/cli), or add its folder to PATH at the top of this script."'," exit 127","fi",""];if(c.length>0||e.variables.length>0){l.push("# What the pipeline file does not hold, read from here or from the environment.",'# cron gives a script no environment of yours: set values in "$store/env",',"# one `export NAME='value'` a line, in a file only you can read (chmod 600).",'if [ -f "$store/env" ]; then . "$store/env"; fi');for(let u of c)l.push(`# The alias, on this machine, of org "${ut(u.label)}", which has none of its own`,"# (sf alias set <alias>=<its username>).",`${u.slot}="\${${u.slot.toUpperCase()}:-}"`);l.push("missing=()");for(let u of c)l.push(`[ -n "$${u.slot}" ] || missing+=(${Lt(`${u.slot} (the alias of org "${ut(u.label)}")`)})`);for(let u of e.variables)l.push(`[ -n "\${${u.env}:-}" ] || missing+=(${Lt(`${u.env} (variable "${ut(u.name)}"${u.secret?", a secret":""})`)})`);l.push('if [ "${#missing[@]}" -gt 0 ]; then',' say "Not set, so nothing ran: ${missing[*]}. Set each in this script or in $store/env."'," exit 2","fi","")}return l.push('args=(pipeline run --file "$file" --triggered-by schedule --fail-on-partial)',...c.map(u=>`args+=(--org ${Lt(`${u.key}=`)}"$${u.slot}")`),...e.variables.map(u=>`args+=(--var-env ${Lt(`${u.name}=${u.env}`)})`),...ap(e,"#",(u,p)=>`args+=(${u} ${Lt(p)})`),"",'say "start"',`npx -y ${Lt(`sandforge@${e.sandforgeVersion}`)} "\${args[@]}" >>"$log" 2>&1`,"code=$?",'say "exit $code"','exit "$code"',""),{runner:"cron",fileName:n,text:l.join(`
10
+ `),...i!==void 0?{schedule:i.kind==="line"?{...i,text:`${i.text} /bin/bash /path/to/${n}`}:i}:{}}}function gE(s){let e=zl(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>aE)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=>dE[n]).join(",");return t.map(n=>r===void 0?`New-ScheduledTaskTrigger -Daily -At ${Xt(n)}`:`New-ScheduledTaskTrigger -Weekly -DaysOfWeek ${r} -At ${Xt(n)}`)}function fE(s){let{input:e,leftOut:t}=dp(s),r=op(e.fileName),n=`${r}.ps1`,o=Js(e.pipelineId),i;if(e.schedule!==null){let u=sp(qi(e.schedule.cron,e.schedule.timezone,e.machineTimezone,e.now));if(u.kind!=="line")i=u;else{let p=gE(u.text);i=typeof p=="string"?{kind:"manual",reason:p}:{...u,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 = @(",...p.map(g=>` ${g}`),")",`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(u=>` ${u}`),...hv(i)]:i.kind==="manual"?[`Its schedule, ${e.schedule?.cron} in ${e.schedule?.timezone}, as Task Scheduler reads it:`,ut(i.reason)]:["Its schedule cannot be written for this machine's clock:",ut(i.reason)],d=[`Keep it beside ${e.fileName}. It needs PowerShell 7 (pwsh), Node.js`,`${Ft.major}.${Ft.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=mv(e),l=[...ip(e,d).map(u=>u===""?"#":`# ${u}`),"$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)","}","","$node = Get-Command node -ErrorAction SilentlyContinue","$nodeOk = $false","if ($node) {",` & node -e 'const [a, b] = process.versions.node.split(".").map(Number); process.exit(a > ${Ft.major} || (a === ${Ft.major} && b >= ${Ft.minor}) ? 0 : 1)'`," $nodeOk = ($LASTEXITCODE -eq 0)","}","if (-not $nodeOk) {",` Say "Node.js ${Ft.major}.${Ft.minor} or later is not found on this PATH: nothing ran. Install it, or add its folder to PATH."`," exit 127","}","if (-not (Get-Command sf -ErrorAction SilentlyContinue)) {",' Say "The Salesforce CLI (sf) is not found on this PATH: nothing ran. Install it (npm install -g @salesforce/cli), or add its folder to PATH."'," exit 127","}",""];if(c.length>0||e.variables.length>0){l.push("# What the pipeline file does not hold, set here or in the environment.");for(let u of c)l.push(`# The alias, on this machine, of org "${ut(u.label)}", which has none of its own.`,`$${u.slot} = $env:${u.slot.toUpperCase()}`);l.push("$missing = @()");for(let u of c)l.push(`if (-not $${u.slot}) { $missing += ${Xt(`${u.slot} (the alias of org "${ut(u.label)}")`)} }`);for(let u of e.variables)l.push(`if (-not $env:${u.env}) { $missing += ${Xt(`${u.env} (variable "${ut(u.name)}"${u.secret?", a secret":""})`)} }`);l.push("if ($missing.Count -gt 0) {"," Say ('Not set, so nothing ran: {0}. Set each in this script or in the environment.' -f ($missing -join ', '))"," exit 2","}","")}return l.push("$runArgs = @('pipeline', 'run', '--file', $file, '--triggered-by', 'schedule', '--fail-on-partial')",...c.map(u=>`$runArgs += @('--org', (${Xt(`${u.key}={0}`)} -f $${u.slot}))`),...e.variables.map(u=>`$runArgs += @('--var-env', ${Xt(`${u.name}=${u.env}`)})`),...ap(e,"#",(u,p)=>`$runArgs += @('${u}', ${Xt(p)})`),"","Say 'start'",`& npx -y ${Xt(`sandforge@${e.sandforgeVersion}`)} @runArgs *>> $log`,"$code = $LASTEXITCODE",'Say "exit $code"',"exit $code",""),{runner:"taskScheduler",fileName:n,text:l.join(`
13
+ `),...i!==void 0?{schedule:i}:{}}}function hE(s){let e=zl(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]<fv)return!0;return!1}function mE(s){let{input:e,leftOut:t}=dp(s),n=`${op(e.fileName)}.yml`,o=Js(e.pipelineId),i=e.schedule===null?void 0:sp(qi(e.schedule.cron,e.schedule.timezone,e.schedule.timezone,e.now)),a=e.orgs.map((u,p)=>{let g=u.alias??`pipeline-org-${p+1}`;return{...u,ciAlias:g,secret:cE(g)}}),d=u=>u===""?"#":`# ${u}`,c=[...ip(e,[`Save it as .github/workflows/${n} of a private repository, and commit`,`${e.fileName} at the repository's root. Each org signs in from a repository secret:`,...a.map(u=>` ${u.secret}: the sfdx auth URL of "${ut(u.label)}" (sf org auth show-sfdx-auth-url --target-org ${u.alias??"<its username>"} --json, its result.sfdxAuthUrl)`),...e.variables.map(u=>` ${u.env}: variable "${ut(u.name)}"${u.secret?" (a secret)":""}`),"","GitHub starts a schedule late when its runners are busy, the start of each hour most of","all, and may drop it under heavy load; it disables the schedules of a public repository",'after 60 days without activity (docs.github.com, "Events that trigger workflows").',...i?.kind==="refused"?["","The pipeline's schedule cannot be written for GitHub:",ut(i.reason)]:[],...i?.kind==="line"&&hE(i.text)?["",`GitHub starts a schedule every ${fv} minutes at most, whatever its line says.`]:[],...t.length>0?["",...t]:[]]).map(d),`name: ${Bo(`SandForge pipeline: ${ut(e.pipelineName)}`)}`,"","on:"];i?.kind==="line"&&c.push(" schedule:",` - cron: ${Bo(i.text)}`,` timezone: ${Bo(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: ${Bo(`sandforge-pipeline-${o}`)}`," cancel-in-progress: false","","permissions:"," contents: read","","jobs:"," run:"," runs-on: ubuntu-latest"," steps:"," - uses: actions/checkout@v4"," - uses: actions/setup-node@v4"," with:"," node-version: 22"," - name: Install the Salesforce CLI"," run: npm install -g @salesforce/cli"),a.length>0&&c.push(" - name: Sign in to the pipeline's orgs"," env:",...a.map(u=>` ${u.secret}: \${{ secrets.${u.secret} }}`)," # The URLs go to a private folder removed when this shell exits, a failed sign-in too."," run: |"," umask 077"," auth_dir=$(mktemp -d)",` trap 'rm -rf "$auth_dir"' EXIT`,...a.flatMap((u,p)=>[` printf '%s' "$${u.secret}" > "$auth_dir/org-${p+1}.txt"`,` sf org login sfdx-url --sfdx-url-file "$auth_dir/org-${p+1}.txt" --alias ${Lt(u.ciAlias)}`])),c.push(" # The Sync watermarks, the confirmations and the history of earlier runs."," - uses: actions/cache@v4"," with:"," path: .sandforge",` key: ${Bo(`sandforge-pipeline-${o}-\${{ github.run_id }}`)}`,` restore-keys: ${Bo(`sandforge-pipeline-${o}-`)}`),e.rewinds.length>0&&c.push(" # A Rewind step rewinds to a checkpoint kept on the machine of the run: import it"," # here first (sandforge checkpoint import), from a file you keep apart, with its key."," # - name: Import the checkpoint a Rewind step names",` # run: npx -y sandforge@${e.sandforgeVersion} checkpoint import --file <checkpoint file>`);let l=[`args=(pipeline run --file ${Lt(e.fileName)} --triggered-by "$TRIGGERED_BY" --fail-on-partial)`,...a.filter(u=>u.alias===void 0).map(u=>`args+=(--org ${Lt(`${u.key}=${u.ciAlias}`)})`),...e.variables.map(u=>`args+=(--var-env ${Lt(`${u.name}=${u.env}`)})`),...ap(e,"#",(u,p)=>`args+=(${u} ${Lt(p)})`),`npx -y ${Lt(`sandforge@${e.sandforgeVersion}`)} "\${args[@]}"`];return c.push(" - name: Run the pipeline"," env:"," SANDFORGE_JOURNAL_DIR: ${{ github.workspace }}/.sandforge"," TRIGGERED_BY: ${{ github.event_name == 'schedule' && 'schedule' || 'manual' }}",...e.variables.map(u=>` ${u.env}: \${{ secrets.${u.env} }}`)," run: |",...l.map(u=>` ${u}`),""),{runner:"githubActions",fileName:n,text:c.join(`
14
+ `),...i!==void 0?{schedule:i}:{}}}function yv(s){return{cron:pE(s),taskScheduler:fE(s),githubActions:mE(s)}}var yE={"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},wE=new Set(["seed","anonymize","rewind","restore","delete"]),bE={sandbox_refresh:"sandbox refresh",event:"event",webhook:"webhook",deployment_complete:"deployment"},RE="prebuilt-",SE="tpl-";function Xs(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)?s:void 0}function Ir(s){return typeof s=="string"&&s.trim()!==""?s:void 0}function ld(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Ks(s,e){return ld(s,e)?s[e]:void 0}function Vs(s){return JSON.parse(JSON.stringify(s))}function vE(s){switch(Mi(s.orgType??"",s.metadata?.edition)){case"Sandbox":return"sandbox";case"Scratch":return"scratch";case"Developer":return"developer";default:return"production"}}function kE(s){let e=vE(s),t=_l(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&&_l(r,s.username)?{name:r}:{}}}function cp(s,e){return e.alias??e.name??s}function cd(s,e,t,r){return{exported:!1,pipelineId:s,code:e,message:t,...r?{issues:r}:{}}}function OE(s,e){let t=[];return s.forEach((r,n)=>{let o=Xs(r.config)??{};if(r.type==="sync"){let a=e.get(Ir(o.configId)??""),d=Ir(a?.sourceOrgId),c=Ir(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=ld(Wl,r.type)?Wl[r.type]??[]:[];for(let a of i){let d=Ir(o[a]);d!==void 0&&t.push({orgId:d,stepIndex:n,stepName:r.name,writes:wE.has(r.type)})}}),t}function IE({defaultValue:s,...e}){return e}function AE(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 TE(s,e){let t=(s.triggers??[]).filter(n=>n.type==="schedule"&&(n.enabled||s.runsOutside!==void 0)&&Ir(n.config?.cron)!==void 0);if(t.length>1)return{many:t.length};let[r]=t;return r?{cron:(r.config.cron??"").trim(),timezone:Ir(r.config.timezone)?.trim()??e}:null}function EE(s){let e={};for(let t of Object.keys(Nf)){let r=yE[t],n=s.setting(t,r);n===r||n===void 0||n===null||(e[t]=n)}return e}function Ys(s,e,t={}){return{code:s,text:e,...t}}function wv(s){let{pipeline:e}=s,t=e.id,r=Vs(e.steps??[]).map(g=>({...g,config:Xs(g.config)??{}})),n=TE(e,s.machineTimezone);if(n!==null&&"many"in n)return cd(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 g of r){let h=g.config;if(g.type==="sync"){let m=Ir(h.configId);if(m===void 0||ld(o,m))continue;let y=Xs(s.syncConfig(m));if(!y)return cd(t,"SYNC_CONFIG_UNKNOWN",`Sync step "${g.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]={...Vs(y),id:m}}let f=Ir(h.templateId);if(g.type==="seed"&&f&&!f.startsWith(RE)){let m=Xs(s.seedTemplate(f));m&&(i[f]={...Vs(m),id:f})}if(g.type==="anonymize"&&f&&!f.startsWith(SE)){let m=Xs(s.maskingTemplate(f));m&&(a[f]={...Vs(m),id:f})}}let d=OE(r,new Map(Object.entries(o))),c={},l=new Map;for(let g of d){if(ld(c,g.orgId))continue;let h=s.org(g.orgId);if(!h)return cd(t,"ORG_UNKNOWN",`Step "${g.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[g.orgId]=kE(h),l.set(g.orgId,h.authMethod!=="usernamePassword")}let u=AE(e.variables??[]),p=Vs(e.variables??[]).map(g=>g.type==="secret"?IE(g):g);return{pipelineId:t,fileName:Mf(e.name),schedule:n,orgs:c,cliHolds:l,uses:d,syncConfigs:o,seedTemplates:i,maskingTemplates:a,settings:EE(s),steps:r,variables:p,envs:u}}function bv(s,e,t){return s.checkedWhereItRuns!==!0&&e.type==="rewind"&&t!==void 0&&(t===Cn(e.name,"never")||t===Cn(e.name,"changed"))}function PE(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=(h,f)=>{a.push(h),t.push(Ys(h,f,{step:o.name}))},c=s.stepRefusal?.(o,i),l=bv(s,o,c)?void 0:c,u=n(i).find(h=>Ks(e.orgs,h)?.kind==="production"),p="runs",g;if(l!==void 0)p="refused",g=l,d("STEP_REFUSED",l);else if(u!==void 0){p="refused";let h=Ks(e.orgs,u);g=`Step "${o.name}" writes to "${h?cp(u,h):u}", a production org: the command line never writes to a production org, whatever an Approval answers.`,d("STEP_REFUSED",g)}else if(o.type==="approval")p="asks",e.uses.some(f=>f.stepIndex>i&&f.writes&&Ks(e.orgs,f.orgId)?.staging===!0)?d("STAGING_NEEDS_PERSON",`Approval step "${o.name}" stands before a write to a sandbox marked Staging: only a person at a terminal answers it, never --approve.`):d("APPROVAL_NEEDS_PERSON",`Approval step "${o.name}" asks a person: at the terminal of the run, or answered ahead with --approve "${o.name}" for a run with no one at a terminal.`);else if(o.type==="rewind"){p="asks";let h=Ir(o.config.orgId),f=h!==void 0?Ks(e.orgs,h):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 ${f?.alias??"<alias>"}.`),d("REWIND_CHECKPOINT_ELSEWHERE",`Rewind step "${o.name}" rewinds to a checkpoint kept on this machine: on another, import it first (sandforge checkpoint import).`)}else o.type==="notification"&&d("NOTIFICATION_PRINTED",`Notification step "${o.name}" prints its message in the run's output: there is no VS Code window to show it in.`);r.push({stepId:o.id,name:o.name,type:o.type,fate:p,notes:a,...g!==void 0?{refusal:g}:{}})}),{steps:r,notes:t}}function CE(s,e){let t=[];for(let[r,n]of Object.entries(e.orgs))if(n.alias===void 0&&t.push(Ys("ORG_NO_ALIAS",`Org "${cp(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(Ys("ORG_NOT_SIGNED_IN",`The Salesforce CLI of this machine does not hold org "${cp(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(Ys("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=bE[r.type];!r.enabled||n===void 0||t.push(Ys("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 $E(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 xE(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 Rv(s,e,t){let{pipeline:r}=s;return jf({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 Sv(s){let e=s.pipeline.id,t=wv(s);if("exported"in t)return t;let{steps:r,notes:n}=PE(s,t),o=[...n,...CE(s,t)],i=Rv(s,t,o);if(!i.ok)return cd(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=$E(t),d=xE(t),c=a.map(p=>({key:p.key,...p.alias!==void 0?{alias:p.alias}:{},label:p.alias??p.name??p.key})),l=d.flatMap(p=>p.env!==void 0?[{name:p.name,env:p.env,secret:p.type==="secret"}]:[]),u={fileName:t.fileName,text:i.text,digest:i.file.digest,schedule:t.schedule,steps:r,orgs:a,variables:d,launchers:yv({pipelineId:e,pipelineName:s.pipeline.name,fileName:t.fileName,sandforgeVersion:s.sandforgeVersion,exportedAt:s.exportedAt,schedule:t.schedule,machineTimezone:s.machineTimezone,now:s.now,orgs:c,variables:l,approvals:r.filter(p=>p.type==="approval"&&p.fate==="asks").map(p=>({name:p.name,staging:p.notes.includes("STAGING_NEEDS_PERSON")})),rewinds:t.steps.filter(p=>p.type==="rewind").map(p=>{let g=Ir(p.config.orgId),h=g!==void 0?Ks(t.orgs,g)?.alias:void 0;return{name:p.name,...h!==void 0?{alias:h}:{}}})}),notes:o,problems:(s.problems??[]).filter(p=>!t.steps.some(g=>bv(s,g,p)))};return{exported:!0,pipelineId:e,...u}}function vv(s){let e=wv(s);if("exported"in e)return;let t=Rv(s,e,[]);return t.ok?t.file.digest:void 0}import{randomUUID as MM}from"node:crypto";import{join as LM}from"node:path";import{randomBytes as DE,randomUUID as Wo}from"node:crypto";import{lstat as NE,rename as jE,rm as ME,stat as LE}from"node:fs/promises";import{hostname as FE}from"node:os";import{basename as Zs,dirname as Av,join as _E,sep as HE}from"node:path";var UE=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"]),Ar="checkpoint",BE=8,qE=6e4,cr="CANCELLED",WE={success:"success",partial:"partial",unstable:"partial",failure:"failure",cancelled:"cancelled"},zE={preview:"previewed",rewind:"rewound to",undo:"used",export:"exported"};function lp(s){let{result:e,notes:t,deliverability:r}=s;return{done:!0,result:e,notes:t,...r!==void 0?{deliverability:r}:{}}}var GE=/\s*\b(?:No record was (?:read or )?written|Nothing was written)\./g;function up(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:Tv([n,...o])},alsoRefused:o}:{done:!1,refusal:n,alsoRefused:o}}function Tv(s){let e=!1;return s.map(({message:t})=>{let r=t.replace(GE,"").trim();return e?r:(e=r!==t.trim(),t)}).join(" ")}var JE=new Set(["RUN_WRITING","API_BUDGET","EMAILS"]),Tr=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 kv(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 VE(){let[s,e,t,r,n,o,i,a,d,c,l,u,p]=await Promise.all([import("./chunk-XK5W7BVE.mjs"),import("./chunk-FZF23M6R.mjs"),import("./chunk-466F37VD.mjs"),import("./chunk-WEMLDUQA.mjs"),import("./chunk-O4BROUGM.mjs"),import("./chunk-CV47FDQW.mjs"),import("./chunk-47UHTN3Q.mjs"),import("./chunk-GHPR5UVV.mjs"),import("./chunk-RLWB7F26.mjs"),import("./chunk-NLB3RGIY.mjs"),import("./chunk-BMTNTBBM.mjs"),import("./chunk-CELEBWEZ.mjs"),import("./chunk-3C2ZZIFN.mjs")]);return{pageEmailsRefusal:l.pageEmailsRefusal,planSelection:a.planSelection,snapshotRowsOf:a.snapshotRowsOf,rewindWriters:a.rewindWriters,boundsRefusals:d.boundsRefusals,selectionDiff:d.selectionDiff,rewindStepsOf:d.rewindStepsOf,notConfirmedRefusal:d.notConfirmedRefusal,undeletableUnattendedRefusal:d.undeletableUnattendedRefusal,REWIND_STEP_WORDS:d.REWIND_STEP_WORDS,REWIND_MUTING_STEP_WORDS:d.REWIND_MUTING_STEP_WORDS,guardCheckpoint:o.guardCheckpoint,newArchiveKey:i.newArchiveKey,archiveKeyText:i.archiveKeyText,parseArchiveKey:i.parseArchiveKey,ARCHIVE_EXTENSION:i.ARCHIVE_EXTENSION,exportCheckpointArchive:i.exportCheckpointArchive,CheckpointExportError:i.CheckpointExportError,readArchiveHeader:i.readArchiveHeader,importCheckpointArchive:i.importCheckpointArchive,DEFAULT_KEEP_DAYS:s.DEFAULT_KEEP_DAYS,openCheckpointStore:s.openCheckpointStore,defaultCheckpointStoreRoot:s.defaultCheckpointStoreRoot,scratchOrgExpired:s.scratchOrgExpired,previewDirOf:s.previewDirOf,CheckpointStoreError:s.CheckpointStoreError,takeCheckpoint:e.takeCheckpoint,scopeCheckpoint:e.scopeCheckpoint,takeOrgOf:e.takeOrgOf,CheckpointTakeStopped:e.CheckpointTakeStopped,previewCheckpoint:t.previewCheckpoint,rewindOrg:r.rewindOrg,rewindOrgOf:r.rewindOrgOf,RewindStopped:r.RewindStopped,undoCheckpoint:n.undoCheckpoint,UndoStopped:n.UndoStopped,beforeRunScopeOf:c.beforeRunScopeOf,beforeRunAskedOf:c.beforeRunAskedOf,beforeRunKeepDaysOf:c.beforeRunKeepDaysOf,beforeRunDiskRefusal:c.beforeRunDiskRefusal,beforeRunOutcomeOf:c.beforeRunOutcomeOf,freeBytesOf:c.freeBytesOf,scopeBeforeRun:c.scopeBeforeRun,settleBeforeRun:c.settleBeforeRun,ReplayStore:u.ReplayStore,defaultReplayStoreRoot:u.defaultReplayStoreRoot,loadToRemove:p.loadToRemove,loadRecordsInfo:p.loadRecordsInfo}}var ke=class extends Error{constructor(t,r,n=!1,o,i,a=[]){super(r);this.code=t;this.retryable=n;this.result=o;this.refusal=i;this.alsoRefused=a;this.name="Refused"}code;retryable;result;refusal;alsoRefused};function ud(s){return s instanceof Rt?s:s instanceof ke?s.code===cr?new Rt(s.message):new Tr(s.code,s.alsoRefused.length>0?Tv([s,...s.alsoRefused]):s.message,s.result,s.alsoRefused):s}async function Ov(s){try{return(await LE(s)).isDirectory()}catch{return!1}}function xt(s,e){return s!==void 0&&e!==void 0&&s.length>=15&&s.slice(0,15)===e.slice(0,15)}var Iv=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function Qs(s,e){if(e===void 0)return;let t=new Map(s.objects.map(({objectApiName:n})=>[n.toLowerCase(),n])),r=e.filter(n=>!t.has(n.toLowerCase()));if(r.length>0)throw new ke("NOT_HELD",`The checkpoint '${s.name}' holds no ${r.join(", ")}: a rewind is limited to objects it holds. No record was read or written.`);return[...new Set(e.flatMap(n=>t.get(n.toLowerCase())??[]))]}function pt(s){return me(s)}function XE(s,e){let t=[...e].sort((n,o)=>o.length-n.length),r=s;for(let n of t)r=r.replaceAll(n,Zs(n));for(let n of t){let o=Av(n);o===n||o.length<=1||(r=r.replaceAll(`${o}${HE}`,"").replaceAll(o,Zs(o)))}return r}function KE(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 YE(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 pp(s){return`${s.operation==="take"?"a checkpoint is being taken":s.operation==="rewind"?"a rewind is writing":s.operation==="undo"?"an undo is writing":s.operation==="empty"?"an emptying of its objects is writing":"SandForge is deleting checkpoints"} (process ${s.pid} on ${s.host})`}var pd=class{constructor(e,t={},r=Ao){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(!UE.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||!Iv.test(t)?0:(await(await this.openedStore()).list({organizationId:t})).length}async latestUsableOf(e){let t=this.deps.orgManager.getOrg(e);if(!t||!Li(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:${Wo()}`,o=this.registeredOrg(e.orgId),i=await this.modules(),a=await this.openedStore(),d=this.beforeRunRequestOf(i,e),c=i.beforeRunScopeOf(d),l=(h,f={})=>{let{taken:m}=f;Z(this.deps,{action:"checkpoint_take",module:Ar,operationId:n,orgId:o.id,outcome:h,beforeRun:{module:e.module,operationId:e.operationId},...f.code!==void 0?{code:f.code}:{},details:m?{checkpointId:m.checkpointId,records:m.records,objects:m.objects.length,bytes:m.bytes}:{}})};if(r.planned!==void 0){let h=i.beforeRunDiskRefusal(r.planned.estimate.bytes,await(this.freeBytes??i.freeBytesOf)(a.root));if(h!==void 0)return l("stopped",{code:h.code}),{taken:!1,refusal:h}}let u=await this.connect(o);if(r.signal?.aborted)return l("cancelled"),{taken:!1,stopped:!0};let p;try{p=await this.take(n,i,a,u,o,i.beforeRunAskedOf(c,d),{description:`Checkpoint first: taking a checkpoint of ${pt(o)} before the run`,runWriting:this.beforeRunWriting(o,t),...r.signal?{signal:r.signal}:{},...r.onProgress?{onProgress:r.onProgress}:{}})}catch(h){if(h instanceof ke&&h.code===cr)return l("cancelled"),{taken:!1,stopped:!0};if(h instanceof ke&&h.refusal!==void 0)return l("stopped",{code:h.refusal.code}),{taken:!1,refusal:h.refusal};throw l("failure"),h}let g=await i.beforeRunOutcomeOf(a,c,p);return g.taken?l("success",{taken:g.checkpoint}):(this.checkpointsChanged(),l("stopped",{..."refusal"in g?{code:g.refusal.code}:{}})),g}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",Yg.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,pt(e),"start this run","No record was read.",t)}async takeForPipeline(e,t){let r=`checkpoint:pipeline:${Wo()}`;try{let n=fn.safeParse(e.config);if(!n.success)throw new ke("CONFIG_INVALID",`The Checkpoint step "${e.origin.step}" does not read: ${n.error.issues[0]?.message??"its configuration is not one"}. Nothing was read.`);let o=n.data,i=this.registeredOrg(o.orgId),a=await this.modules(),d=await this.openedStore(),c=await this.connect(i);if(t?.aborted)throw new ke(cr,new a.CheckpointTakeStopped().message);let{checkpoint:l}=await this.take(r,a,d,c,i,{...o.name!==void 0?{nameWithDate:o.name}:{},mode:o.mode,...o.objects!==void 0?{objects:o.objects}:{},...o.excluded!==void 0?{excluded:o.excluded}:{},...o.maxTotal!==void 0?{maxTotal:o.maxTotal}:{},keepDays:o.keepDays,...o.ignoredFields!==void 0?{ignoredFields:o.ignoredFields}:{}},{description:`Pipeline '${e.origin.pipeline}': taking a checkpoint of ${pt(i)}`,...t?{signal:t}:{}});return{operationId:r,checkpointId:l.checkpointId,name:l.name,records:l.objects.reduce((u,p)=>u+p.records,0),objects:l.objects.length,bytes:l.bytes,movedWhileTaken:l.movedWhileTaken}}catch(n){throw ud(n)}}async rewindForPipeline(e,t){let r=`checkpoint:pipeline:${Wo()}`,{grant:n,origin:o}=e;try{let i=await this.modules(),a=Pt.safeParse(e.config);if(!a.success)throw new ke("CONFIG_INVALID",`The Rewind step "${o.step}" does not read: ${a.error.issues[0]?.message??"its configuration is not one"}. No record was read or written.`);let d=a.data;if(n.digest!==ws(d)||n.checkpointId!==d.checkpointId)throw this.refusalOf(i.notConfirmedRefusal(o.step,!0));let c=await this.openedStore(),{folder:l,checkpoint:u}=await this.checkpointOf(c,d.checkpointId);if(!xt(n.organizationId,u.org.organizationId))throw this.refusalOf(i.notConfirmedRefusal(o.step,!0));this.usable(i,u,"rewind");let p=this.registeredOrg(d.orgId);if(!xt(p.orgId,u.org.organizationId)&&!xt(this.deps.sandboxRefreshes?.organizationIdOf(p.id),u.org.organizationId))throw new ke("OTHER_ORG",`The checkpoint '${u.name}' is not of ${pt(p)}, the org the Rewind step "${o.step}" names. No record was read or written.`);let g=Qs(u,d.objects),h=await this.connect(p),f=pt(p),m={operationId:r,pipeline:{origin:o,grantedAt:n.grantedAt}},y=()=>(this.audit(m,"rewind",p,u,"stopped",{code:bt}),new Rt(new i.RewindStopped().message)),R=(D,z=[])=>(this.audit(m,"rewind",p,u,"stopped",{code:D.code}),this.refusalOf(D,z));if(t?.aborted)throw y();let k;try{k=await i.previewCheckpoint({org:i.takeOrgOf(h),store:c,readAutomation:D=>this.readAutomation(p.id,D),runWriting:this.runWriting(p.id,f,"rewind","No record would be read or written."),...t?{signal:t}:{}},{checkpoint:u,folder:l,orgName:f,registered:p,username:p.username,...g!==void 0?{objects:g}:{},reusesPreview:!0,...d.muteAutomation?{muteAutomation:!0}:{},acceptOutside:d.acceptOutside})}catch(D){throw t?.aborted?y():D}if(!k.previewed)throw R(k.refusal);let w=g!==void 0?i.selectionDiff(k.diff,await i.planSelection({checkpoint:u,previewDir:i.previewDirOf(l,k.diff.previewId),readAt:k.diff.readAt,objects:new Set(g),acceptOutside:d.acceptOutside,heldRows:i.snapshotRowsOf(u,l),...t?{signal:t}:{}})):k.diff,O=d.muteAutomation&&k.automation?hu(k.automation,Br(i.rewindStepsOf(w))).automation:k.automation,P=await i.boundsRefusals({orgName:f,preview:{diff:w,...O?{automation:O}:{},...k.emails?{emails:k.emails}:{},...k.emailsUncounted!==void 0?{emailsUncounted:k.emailsUncounted}:{},...k.deliverability?{deliverability:k.deliverability}:{}},bounds:{maxRecords:d.maxRecords,refuseWhenActive:d.refuseWhenActive},accepted:d,writers:async()=>i.rewindWriters(u.takenBy,await i.takeOrgOf(h).userId()),words:d.muteAutomation?i.REWIND_MUTING_STEP_WORDS:i.REWIND_STEP_WORDS,user:p.username}),[b,...v]=[...k.refusal!==void 0?[k.refusal]:[],...P.filter(D=>D.code!==k.refusal?.code)];if(b!==void 0)throw R(b,v);if(t?.aborted)throw y();let C=[],S=[],A=await this.writeAct(m,"rewind",p,u,`Pipeline '${o.pipeline}': rewinding ${f} to '${u.name}'`,async(D,z)=>{let U=await i.rewindOrg({org:i.rewindOrgOf(h),undelete:Y=>h.soap.undelete(Y),store:c,readAutomation:Y=>this.readAutomation(p.id,Y),runWriting:this.runWriting(p.id,f,"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(H=>`${H.objectApiName} (${H.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:H})=>z(Y,H),signal:D,...d.muteAutomation?{mute:this.muteOf(h)}:{}},{checkpoint:u,folder:l,orgName:f,registered:p,username:p.username,previewId:k.diff.previewId,reusesPreview:k.diff,...g!==void 0?{objects:g}:{},acceptAutomation:d.acceptAutomation,acceptEmails:d.acceptEmails,acceptNoUndo:d.acceptNoUndo,acceptRecreate:d.acceptRecreate,acceptOutside:d.acceptOutside,acceptUnseen:d.acceptUnseen});return U.rewound?(S=U.notes,lp(U)):up(U.refusal,U.alsoRefused,Y=>Y,!1)},D=>D instanceof i.RewindStopped,{...t?{signal:t}:{},acceptEmails:d.acceptEmails,refusalOf:D=>C.length>0?i.undeletableUnattendedRefusal(f,C,kv(D)):void 0});return{operationId:r,checkpointId:u.checkpointId,result:A,notes:S,estimate:k.estimate}}catch(i){throw ud(i)}}async estimateTakeForPipeline(e,t){try{let r=fn.safeParse(e.config);if(!r.success)throw new ke("CONFIG_INVALID",`The Checkpoint step "${e.origin.step}" does not read: ${r.error.issues[0]?.message??"its configuration is not one"}. Nothing was read.`);let n=r.data,o=this.registeredOrg(n.orgId),i=await this.modules(),a=await this.openedStore(),d=await this.connect(o);if(t?.aborted)throw new ke(cr,new i.CheckpointTakeStopped().message);let c=await i.scopeCheckpoint({org:i.takeOrgOf(d),store:a,handler:this.deps,runWriting:this.runWriting(o.id,pt(o),"take the checkpoint","No record was read."),...t?{signal:t}:{}},this.takeRequestOf(o,{mode:n.mode,...n.objects!==void 0?{objects:n.objects}:{},...n.excluded!==void 0?{excluded:n.excluded}:{},...n.maxTotal!==void 0?{maxTotal:n.maxTotal}:{}}));if(c.refusal)throw this.refusalOf(c.refusal);return{objects:c.objects.length,records:c.objects.reduce((l,u)=>l+u.records,0),leftOut:c.leftOut.length,estimate:c.estimate}}catch(r){throw ud(r)}}async previewRewindForPipeline(e,t){let{grant:r,origin:n}=e;try{let o=await this.modules(),i=Pt.safeParse(e.config);if(!i.success)throw new ke("CONFIG_INVALID",`The Rewind step "${n.step}" does not read: ${i.error.issues[0]?.message??"its configuration is not one"}. No record was read or written.`);let a=i.data;if(r.digest!==ws(a)||r.checkpointId!==a.checkpointId)throw this.refusalOf(o.notConfirmedRefusal(n.step,!0));let d=await this.openedStore(),{folder:c,checkpoint:l}=await this.checkpointOf(d,a.checkpointId);if(!xt(r.organizationId,l.org.organizationId))throw this.refusalOf(o.notConfirmedRefusal(n.step,!0));this.usable(o,l,"rewind");let u=this.registeredOrg(a.orgId);if(!xt(u.orgId,l.org.organizationId)&&!xt(this.deps.sandboxRefreshes?.organizationIdOf(u.id),l.org.organizationId))throw new ke("OTHER_ORG",`The checkpoint '${l.name}' is not of ${pt(u)}, the org the Rewind step "${n.step}" names. No record was read or written.`);let p=Qs(l,a.objects),g=await this.connect(u),h=pt(u);if(t?.aborted)throw new ke(cr,new o.RewindStopped().message);let f=await o.previewCheckpoint({org:o.takeOrgOf(g),store:d,readAutomation:P=>this.readAutomation(u.id,P),runWriting:this.runWriting(u.id,h,"rewind","No record would be read or written."),...t?{signal:t}:{}},{checkpoint:l,folder:c,orgName:h,registered:u,username:u.username,...p!==void 0?{objects:p}:{},reusesPreview:!0,...a.muteAutomation?{muteAutomation:!0}:{},acceptOutside:a.acceptOutside});if(!f.previewed)throw this.refusalOf(f.refusal);let m=p!==void 0?o.selectionDiff(f.diff,await o.planSelection({checkpoint:l,previewDir:o.previewDirOf(c,f.diff.previewId),readAt:f.diff.readAt,objects:new Set(p),acceptOutside:a.acceptOutside,heldRows:o.snapshotRowsOf(l,c),...t?{signal:t}:{}})):f.diff,y=a.muteAutomation&&f.automation?hu(f.automation,Br(o.rewindStepsOf(m))).automation:f.automation,R=await o.boundsRefusals({orgName:h,preview:{diff:m,...y?{automation:y}:{},...f.emails?{emails:f.emails}:{},...f.emailsUncounted!==void 0?{emailsUncounted:f.emailsUncounted}:{},...f.deliverability?{deliverability:f.deliverability}:{}},bounds:{maxRecords:a.maxRecords,refuseWhenActive:a.refuseWhenActive},accepted:a,writers:async()=>o.rewindWriters(l.takenBy,await o.takeOrgOf(g).userId()),words:a.muteAutomation?o.REWIND_MUTING_STEP_WORDS:o.REWIND_STEP_WORDS,user:u.username}),[k,...w]=[...f.refusal!==void 0?[f.refusal]:[],...R.filter(P=>P.code!==f.refusal?.code)];if(k!==void 0)throw this.refusalOf(k,w);let O=P=>m.objects.reduce((b,v)=>b+P(v),0);return{checkpointId:l.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:f.estimate}}catch(o){throw ud(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:Ar,operationId:Wo(),orgId:this.orgOfCheckpoint(o)?.id??o.org.organizationId,outcome:"success",details:{checkpointId:o.checkpointId,records:d.records,objects:d.objects,files:d.files,bytes:a.bytes}}),{exported:!0,checkpoint:o,header:d,bytes:a.bytes,sha256:a.sha256,...e.key===void 0?{key:t.archiveKeyText(i)}:{}}}catch(t){return{exported:!1,refusal:await this.transferRefusalOf(t,"EXPORT_ERROR")}}}async readImport(e){let t=await this.importChecked(e);return"refusal"in t?{allowed:!1,...t}:{allowed:!0,header:t.read.header}}async importCheckpoint(e){let t=await this.importChecked(e),r=(d,c,l,u={})=>{Z(this.deps,{action:"checkpoint_import",module:Ar,operationId:Wo(),orgId:d,outcome:c,...u.code!==void 0?{code:u.code}:{},details:{...l?{checkpointId:l.checkpointId,records:l.records,objects:l.objects}:{},...u.alreadyKept?{alreadyKept:!0}:{}}})};if("refusal"in t)return t.orgId!==void 0&&r(t.orgId,"stopped",t.header,{code:t.refusal.code}),{imported:!1,refusal:t.refusal,...t.header?{header:t.header}:{}};let{m:n,store:o,org:i,read:a}=t;try{let d=await n.importCheckpointArchive({store:o,file:e.file,read:a,key:e.key,...i.alias?{alias:i.alias}:{},keepDays:e.keepDays??n.DEFAULT_KEEP_DAYS,takenOn:{host:FE(),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=pt(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:pt(i),registered:i,username:i.username,organizationId:t.organizationId});if(!c.allowed){let l=c.refusal.code==="OTHER_ORG"?this.refreshedAt(t.organizationId):void 0;return{refusal:l!==void 0?{code:"OTHER_ORG",message:`The sandbox this file's checkpoint was taken of was refreshed on ${l.slice(0,10)}: ${pt(i)} is another org now, and the checkpoint can no longer be rewound to. ${ps} Nothing was imported.`}:c.refusal,header:t,orgId:r}}return{m:n,store:o,org:i,read:a.read}}catch(n){return{refusal:await this.transferRefusalOf(n,"IMPORT_ERROR"),...t?{header:t}:{},...r!==void 0?{orgId:r}:{}}}}async transferRefusalOf(e,t){if(e instanceof ke)return{code:e.code,message:e.message};let r=await this.modules().catch(()=>{});return r!==void 0&&e instanceof r.CheckpointExportError?{code:e.code,message:e.message}:{code:t,message:I(e)}}async handleExport(e){let t=x(Hm,e,"checkpoint:error",this.deps);if(!t)return;let r=[];try{let n=this.fileDialogs("export"),o=await this.modules(),i=await this.openedStore();r.push(i.root);let{checkpoint:a}=await this.checkpointOf(i,t.checkpointId);this.usable(o,a,"export");let{checkpointId:d}=a,c=await n.pickExportFile(`${d}${o.ARCHIVE_EXTENSION}`);if(c===void 0){this.respond(e,"checkpoint:export:response",{status:"cancelled",checkpointId:d});return}r.push(c);let l=await NE(c).then(()=>!0,()=>!1),u=l?_E(Av(c),`.${Zs(c)}.${DE(4).toString("hex")}.export`):c;r.push(u);let p=await this.exportCheckpoint({checkpointId:d,out:u,sandforgeVersion:n.sandforgeVersion});if(!p.exported)throw new ke(p.refusal.code,p.refusal.message);if(l)try{await jE(u,c)}catch(g){throw await ME(u,{force:!0}),g}this.respond(e,"checkpoint:export:response",{status:"saved",checkpointId:d,fileName:Zs(c),key:p.key,records:p.header.records,objects:p.header.objects,bytes:p.bytes})}catch(n){this.fail(e,this.pathless(n,r,"EXPORT_ERROR"),"EXPORT_ERROR")}}async handleImportRead(e){let t=[];try{let r=this.fileDialogs("import"),n=await this.modules(),o=await this.openedStore();t.push(o.root);let i=await r.pickImportFile();if(i===void 0){this.respond(e,"checkpoint:import-read:response",{status:"cancelled"});return}t.push(i);let a=await n.readArchiveHeader(i);if("refusal"in a)throw this.refusalOf(a.refusal);let{header:d}=a.read,c=[],l;for(let p of this.deps.orgManager.getAllOrgs()){if(!this.organizationIdsOf(p.id).some(f=>xt(f,d.organizationId)))continue;let h=await this.readImport({orgId:p.id,file:i});h.allowed?c.push(p.id):l??=h.refusal}if(c.length===0&&l!==void 0)throw new ke(l.code,l.message);let u=await o.read(d.checkpointId)!==void 0;this.respond(e,"checkpoint:import-read:response",{status:"read",token:this.keepImportFile(i),fileName:Zs(i),summary:KE(d),orgIds:c,...u?{keptHere:!0}:{}})}catch(r){this.fail(e,this.pathless(r,t,"IMPORT_ERROR"),"IMPORT_ERROR")}}async handleImport(e){let t=x(Um,e,"checkpoint:error",this.deps);if(!t)return;let r=this.importFiles.get(t.token),n=r!==void 0?[r]:[];try{if(r===void 0)throw new ke("IMPORT_FILE_GONE","This window no longer knows the file to import: choose it again with Import\u2026. Nothing was imported.");let o=await this.modules();n.push((await this.openedStore()).root);let i=o.parseArchiveKey(t.key);if(i===void 0){let d=await this.readImport({orgId:t.orgId,file:r});throw d.allowed?new ke("IMPORT_KEY","That is not a key SandForge draws: 52 letters and digits, in groups of four as the export showed it. Nothing was imported."):new ke(d.refusal.code,d.refusal.message)}let a=await this.importCheckpoint({orgId:t.orgId,file:r,key:i,keepDays:t.keepDays});if(!a.imported)throw new ke(a.refusal.code,a.refusal.message);this.importFiles.delete(t.token),this.respond(e,"checkpoint:import:response",{checkpoint:a.checkpoint,outcome:a.outcome})}catch(o){this.fail(e,this.pathless(o,n,"IMPORT_ERROR"),"IMPORT_ERROR")}}fileDialogs(e){let t=this.deps.infraServices?.checkpointFiles;if(!t)throw new ke("NO_FILE_DIALOG",e==="export"?"This window has no dialog to ask where the file goes: export the checkpoint with npx sandforge checkpoint export. Nothing was written.":"This window has no dialog to ask which file to read: import it with npx sandforge checkpoint import. Nothing was imported.");return t}keepImportFile(e){let t=Wo();this.importFiles.set(t,e);for(let r of this.importFiles.keys()){if(this.importFiles.size<=BE)break;this.importFiles.delete(r)}return t}pathless(e,t,r){let n=e instanceof ke?e:new ke(r,I(e));return new ke(n.code,XE(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??=VE(),this.loaded}async openedStore(){this.store??=this.modules().then(t=>{let r=t.openCheckpointStore({root:t.defaultCheckpointStoreRoot()});return"store"in r?r.store:r.refusal});let e=await this.store;if("reason"in e)throw this.store=void 0,new ke("STORE_REFUSED",YE(e));return e}respond(e,t,r){let n=T(this.deps,e,t,r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}fail(e,t,r,n=!0){if(t instanceof ke){let o=t.refusal?.holdingLimit,i={...t.alsoRefused.length>0?{alsoRefused:[...t.alsoRefused]}:{},...o!==void 0?{holdingLimit:o}:{}};E(this.deps,e.type,"checkpoint:error",e,t,{code:t.code,retryable:t.retryable,...Object.keys(i).length>0?{extraPayload:i}:{}});return}E(this.deps,e.type,"checkpoint:error",e,t,{code:r,retryable:n})}refusalOf(e,t=[]){return new ke(e.code,e.message,JE.has(e.code),void 0,e,t)}registeredOrg(e){let t=this.deps.orgManager.getOrg(e);if(!t)throw new ke("ORG_NOT_FOUND","SandForge has no connected org of this id: connect it first.");return t}async connect(e){try{return await q(e.id,this.deps.orgRegistry,this.deps.orgManager)}catch(t){throw t instanceof wo&&t.code==="SCRATCH_ORG_EXPIRED"?new ke("SCRATCH_EXPIRED",`${pt(e)} is a scratch org that has expired: its checkpoints no longer rewind it. `+ps):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:pt(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||Gn(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||xt(e.targetOrganizationId,r)||xt(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(xt(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||!Iv.test(o)||n.some(i=>xt(i,o))||n.push(o);return n}async listOfOrg(e,t){let r=o=>this.refreshedAt(o);return(await Promise.all(this.organizationIdsOf(t).map(o=>e.list({organizationId:o,refreshedAt:r})))).flat().sort((o,i)=>o.checkpointId<i.checkpointId?1:o.checkpointId>i.checkpointId?-1:0)}async withReplays(e){if(e.length===0)return e;try{let t=await this.modules();this.replays??=new t.ReplayStore({root:t.defaultReplayStoreRoot()});let r=this.replays,n=this.deps.orgManager.getAllOrgs(),o=new Map;for(let a of e)o.has(a.organizationId)||o.set(a.organizationId,await r.list({sourceOrganizationId:a.organizationId}));let i=[];for(let a of e){let d=(o.get(a.organizationId)??[]).filter(l=>l.checkpointId===a.checkpointId),c=[];for(let l of d){let u=n.find(h=>xt(h.orgId,l.target.organizationId)),p=await r.mappingStoreOf(r.folderOf(l.sourceOrganizationId,l.checkpointId),l.target.organizationId).recordedLoads(),g=t.loadToRemove(p);c.push({target:{organizationId:l.target.organizationId,...l.target.name!==void 0?{name:l.target.name}:{},...u?{orgId:u.id}:{}},...l.replayedAt!==void 0?{replayedAt:l.replayedAt}:{},inPlace:l.inPlace,...l.removed?{removed:!0}:{},...l.choices?{choices:l.choices}:{},...u&&g?{records:{...t.loadRecordsInfo(g),orgId:u.id}}:{}})}i.push(c.length>0?{...a,replays:c}:a)}return i}catch(t){return this.deps.log(`[WARN] The replays of the checkpoints could not be read: ${I(t)}`),e}}orgOfCheckpoint(e){let t=e.org.organizationId,r=this.deps.orgManager.getAllOrgs(),n=r.filter(a=>xt(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=>xt(i?.organizationIdOf(a.id),t))}async checkpointOf(e,t){let r=await e.read(t);if(r===void 0)throw new ke("NOT_FOUND",`No checkpoint ${t} is kept on this machine.`,!1);if(r.checkpoint===void 0)throw new ke("DAMAGED",`The file of checkpoint ${t} cannot be read: it can only be deleted.`);return{folder:r.folder,checkpoint:r.checkpoint}}usable(e,t,r){let n=me(t.org);if(t.status!=="ready")throw new ke(t.status==="taking"?"TAKING":"FAILED",t.status==="taking"?`The checkpoint '${t.name}' is being taken, or its take never ended: it can be ${zE[r]} once taken, or deleted.`:`The take of checkpoint '${t.name}' failed: it can only be deleted.`);if(r==="export")return;let o=this.refreshedAt(t.org.organizationId);if(o!==void 0)throw new ke("OTHER_ORG",`This sandbox was refreshed on ${o.slice(0,10)}: ${n} is another org now, and this checkpoint is of the org before it, which it no longer rewinds. `+ps);if(e.scratchOrgExpired(t.org,Date.now()))throw new ke("SCRATCH_EXPIRED",`${n} is a scratch org that has expired: its checkpoints no longer rewind it. `+ps)}connectedOrgOf(e,t){let r=this.orgOfCheckpoint(e);if(!r){let n=me(e.org);throw new ke("ORG_NOT_FOUND",`${n} is not connected in SandForge: connect it to ${t}.`)}return r}async undoOffered(e,t,r,n){if((await e.list({organizationId:t.organizationId,refreshedAt:d=>this.refreshedAt(d)})).find(d=>d.checkpointId===r.checkpointId)?.undo?.rewindId===n)return;let i=r.lastRewind,a=i?.rewindId!==n?`the rewind ${n} is not the last rewind to '${r.name}'`:i.undoneAt!==void 0?`it was undone on ${i.undoneAt.slice(0,10)}, and there is nothing left to undo`:i.undoUntil!==void 0&&Date.parse(i.undoUntil)<=Date.now()?`its 15 days ended on ${i.undoUntil.slice(0,10)}, and what it deleted may have left the recycle bin`:"Undo is offered for the last rewind of an org only, while its journal is kept on this machine";throw new ke("UNDO_CLOSED",`This rewind can no longer be undone: ${a}. No record was read or written.`)}audit(e,t,r,n,o,i={}){let{result:a,code:d,deliverability:c}=i,l=a?.mutedAutomation??i.muted,u=a?.rewindId??i.rewindId,p=e.pipeline;Z(this.deps,{action:t==="rewind"?"checkpoint_rewind":"checkpoint_undo",module:Ar,operationId:e.operationId,orgId:r.id,outcome:o,...a?{objects:ha(Sn(a.deleted),a.restored,a.undeleted)}:{},...d!==void 0?{code:d}:{},...l?{muted:dt(l)}:{},details:{checkpointId:n.checkpointId,...u!==void 0?{rewindId:u}:{},...a?{status:a.status,passes:a.passes}:{},...a?.scope?{limitedTo:a.scope.objects.join(", ")}:{},...c!==void 0?{deliverability:c}:{},...c!==void 0&&c!=="withheld"&&i.acceptEmails===!0?{confirmed:"emails"}:{},...p?{pipeline:p.origin.pipeline,step:p.origin.step,trigger:p.origin.trigger,grantedAt:p.grantedAt}:{}}})}async handleList(e){let t=x(Nm,e,"checkpoint:error",this.deps);if(t!==null)try{let r=await this.openedStore(),n=t?.orgId===void 0?await r.list({refreshedAt:i=>this.refreshedAt(i)}):await this.listOfOrg(r,t.orgId),o=await this.withReplays(n);this.respond(e,"checkpoint:list:response",{checkpoints:o})}catch(r){this.fail(e,r,"LIST_ERROR")}}async handleScope(e){let t=x(jm,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,pt(r),"take the checkpoint","No record was read.")},this.takeRequestOf(r,t));this.respond(e,"checkpoint:scope:response",{orgId:t.orgId,mode:a.mode,objects:a.objects,leftOut:a.leftOut,estimate:a.estimate,...a.refusal?{refusal:a.refusal}:{},...a.files?{files:a.files}:{},...a.customSettings?{customSettings:a.customSettings}:{}})}catch(r){this.fail(e,r,"SCOPE_ERROR")}}async handleTake(e){let t=x(Mm,e,"checkpoint:error",this.deps);if(!t)return;let r=e.id,o=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(r);try{let i=this.registeredOrg(t.orgId),a=await this.modules(),d=await this.openedStore(),c=await this.connect(i);if(o?.signal.aborted)throw new ke(cr,new a.CheckpointTakeStopped().message,!0);await this.take(e.id,a,d,c,i,t,{kept:({checkpoint:l,requests:u,estimate:p})=>this.respond(e,"checkpoint:take:response",{checkpoint:l,operationId:e.id,...u?{requests:u}:{},estimate:p})})}catch(i){this.fail(e,i,"TAKE_ERROR")}finally{o?.release()}}async take(e,t,r,n,o,i,a={}){let d=pt(o),c=a.description??`Taking a checkpoint of ${d}`,l=this.deps.infraServices?.backgroundRegistry,u=new AbortController,p=()=>{},g=new Promise((y,R)=>{p=k=>k===void 0?y():R(k)});g.catch(()=>{}),ze(this.deps,e,Ar,c),l?.register(e,Ar,c,g,u);let h=sr(this.liveTracker,e,Ar,c),f=y=>{let{percentage:R,processedObjects:k,totalObjects:w,step:O}=y;Le(this.deps,e,R,k,w,O),u.signal.aborted||l?.updateProgress(e,R),h.progress(R,k,w,O),a.onProgress?.(y)},m=()=>{l?l.abort(e):u.abort()};a.signal?.addEventListener("abort",m,{once:!0}),a.signal?.aborted&&m();try{let y=await t.takeCheckpoint({org:t.takeOrgOf(n),store:r,handler:this.deps,signal:u.signal,onProgress:f,runWriting:a.runWriting??this.runWriting(o.id,d,"take the checkpoint","No record was read.")},{...this.takeRequestOf(o,i),...i.name!==void 0?{name:i.name}:{},...i.nameWithDate!==void 0?{nameWithDate:i.nameWithDate}:{},keepDays:i.keepDays,...i.ignoredFields?{ignoredFields:i.ignoredFields}:{},...i.unprovenLeftOut===!0?{unprovenLeftOut:!0}:{},...i.beforeRun!==void 0?{beforeRun:i.beforeRun}:{}});if(!y.taken)throw pe(this.deps,e,{status:"refused",code:y.refusal.code}),h.fail(y.refusal.message),p(new Error(y.refusal.message)),this.refusalOf(y.refusal);for(let{objectApiName:w,reason:O}of y.notChecked)this.deps.log(`[WARN] checkpoint:take ${e}: what moved in ${w} while it was read was not checked: ${O}`);let{checkpoint:R}=y,k={checkpoint:R,...y.requests?{requests:y.requests}:{},estimate:y.estimate};return a.kept?.(k),this.checkpointsChanged(),pe(this.deps,e,{status:"success",objects:R.objects.length,records:R.objects.reduce((w,O)=>w+O.records,0)}),h.complete(),p(),k}catch(y){throw y instanceof ke?y:y instanceof t.CheckpointTakeStopped?(l?.abort(e),pe(this.deps,e,{aborted:!0}),h.cancel(),p(),new ke(cr,y.message,!0)):(pe(this.deps,e,{status:"failure"}),h.fail(I(y)),p(y),y)}finally{a.signal?.removeEventListener("abort",m)}}async handlePreview(e){let t=x(Lm,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=Qs(i,t.objects),d=this.connectedOrgOf(i,`preview the checkpoint '${i.name}'`),c=await this.connect(d),l=await r.previewCheckpoint({org:r.takeOrgOf(c),store:n,readAutomation:u=>this.readAutomation(d.id,u),runWriting:this.runWriting(d.id,pt(d),"rewind","No record would be read or written."),...t.muteAutomation===!0?{mute:this.muteOf(c)}:{}},{checkpoint:i,folder:o,orgName:pt(d),registered:d,username:d.username,...a!==void 0?{objects:a}:{},...this.previewsAnswered!==void 0?{reusesPreview:!0}:{},...t.muteAutomation===!0?{muteAutomation:!0}:{},...t.acceptOutside!==void 0?{acceptOutside:t.acceptOutside}:{}});if(!l.previewed)throw this.refusalOf(l.refusal);this.previewsAnswered?.set(l.diff.previewId,l.diff),this.previewReads.set(l.diff.previewId,{checkpointId:i.checkpointId,readAt:l.diff.readAt}),this.respond(e,"checkpoint:preview:response",{diff:l.diff,...l.automation?{automation:l.automation}:{},...l.emails?{emails:l.emails}:{},...l.emailsKeepingOutside?{emailsKeepingOutside:l.emailsKeepingOutside}:{},...l.emailsUncounted!==void 0?{emailsUncounted:l.emailsUncounted}:{},...l.deliverability?{deliverability:l.deliverability}:{},estimate:l.estimate,...l.refusal?{refusal:l.refusal}:{}})}catch(r){this.fail(e,r,"PREVIEW_ERROR")}}async handlePlanSelection(e){let t=x(_m,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=Qs(i,t.objects)??[],d=r.previewDirOf(o,t.previewId),c=this.previewReads.get(t.previewId);if(c?.checkpointId!==i.checkpointId||!await Ov(d))throw new ke("PREVIEW_GONE",`The preview to plan this selection from is no longer kept on this machine: preview the rewind to '${i.name}' again. No record was read or written.`);let l=await r.planSelection({checkpoint:i,previewDir:d,readAt:c.readAt,objects:new Set(a),acceptOutside:t.acceptOutside,heldRows:r.snapshotRowsOf(i,o)});this.respond(e,"checkpoint:plan-selection:response",{checkpointId:i.checkpointId,previewId:t.previewId,plan:l})}catch(r){this.fail(e,r,"PLAN_SELECTION_ERROR")}}async handleRewind(e){let t=x(Fm,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=Qs(d,t.objects);if(!await Ov(o.previewDirOf(a,t.previewId)))throw new ke("PREVIEW_GONE",`The preview this rewind was confirmed on is no longer kept on this machine: preview the rewind to '${d.name}' again, then rewind. No record was read or written.`);let l=this.connectedOrgOf(d,`rewind it to the checkpoint '${d.name}'`),u=await this.connect(l),p=this.pageAt(e);if(n?.signal.aborted)throw this.audit(p,"rewind",l,d,"stopped",{code:bt}),new ke(cr,new o.RewindStopped().message,!0);let g=this.previewsAnswered?.get(t.previewId);this.previewsAnswered?.delete(t.previewId);let h=g?.checkpointId===d.checkpointId?g:void 0,f=pt(l);await this.writeAct(p,"rewind",l,d,`Rewinding ${f} to '${d.name}'`,async(m,y)=>{let R=await o.rewindOrg({org:o.rewindOrgOf(u),undelete:w=>u.soap.undelete(w),store:i,readAutomation:w=>this.readAutomation(l.id,w),runWriting:this.runWriting(l.id,f,"rewind","No record was read or written."),onUndeletable:Wr(this.deps,l.id,"checkpoint:rewind"),onProgress:({percentage:w,step:O})=>y(w,O),signal:m,...t.muteAutomation===!0?{mute:this.muteOf(u)}:{}},{checkpoint:d,folder:a,orgName:f,registered:l,username:l.username,previewId:t.previewId,...h?{reusesPreview:h}:{},...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 lp(R);let k=t.fromPage===!0;return up(R.refusal,R.alsoRefused,w=>k?o.pageEmailsRefusal(w,"rewind",f):w,k)},m=>m instanceof o.RewindStopped,{acceptEmails:t.acceptEmails===!0})}catch(o){this.fail(e,o,"REWIND_ERROR")}finally{n?.release()}}async handleUndo(e){let t=x(Bm,e,"checkpoint:error",this.deps);if(!t)return;let n=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(e.id);try{let o=await this.modules(),i=await this.openedStore(),{folder:a,checkpoint:d}=await this.checkpointOf(i,t.checkpointId);this.usable(o,d,"undo"),await this.undoOffered(i,a,d,t.rewindId);let c=this.connectedOrgOf(d,`undo its rewind to '${d.name}'`),l=await this.connect(c),u=this.pageAt(e);if(n?.signal.aborted)throw this.audit(u,"undo",c,d,"stopped",{code:bt,rewindId:t.rewindId}),new ke(cr,new o.UndoStopped().message,!0);let p=pt(c);await this.writeAct(u,"undo",c,d,`Undoing the rewind of ${p} to '${d.name}'`,async(g,h)=>{let f=await o.undoCheckpoint({org:o.rewindOrgOf(l),undelete:y=>l.soap.undelete(y),store:i,readAutomation:y=>this.readAutomation(c.id,y),runWriting:this.runWriting(c.id,p,"undo the rewind","No record was read or written."),onUndeletable:Wr(this.deps,c.id,"checkpoint:undo"),onProgress:({percentage:y,step:R})=>h(y,R),signal:g,...t.muteAutomation===!0?{mute:this.muteOf(l)}:{}},{checkpoint:d,folder:a,orgName:p,registered:c,username:c.username,rewindId:t.rewindId,acceptAutomation:t.acceptAutomation,acceptEmails:t.acceptEmails===!0,canMute:!0});if(f.undone)return lp(f);let m=t.fromPage===!0;return up(f.refusal,f.alsoRefused,y=>m?o.pageEmailsRefusal(y,"undo",p):y,m)},g=>g 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)=>kt(async()=>Mt(e),t,{...this.muteLeases,writes:r})}pageAt(e){return{operationId:e.id,respond:(t,r)=>this.respond(e,t,r)}}async writeAct(e,t,r,n,o,i,a,d={}){let{operationId:c}=e,{rewindId:l}=d,u=this.deps.infraServices?.backgroundRegistry,p=new AbortController,g=()=>{},h=new Promise((k,w)=>{g=O=>O===void 0?k():w(O)});h.catch(()=>{}),ze(this.deps,c,Ar,o),u?.register(c,Ar,o,h,p);let f=sr(this.liveTracker,c,Ar,o),m=l!==void 0?{rewindId:l}:{},y=(k,w)=>{Le(this.deps,c,k,0,0,w),p.signal.aborted||u?.updateProgress(c,k),f.progress(k,0,0,w)},R=()=>{u?u.abort(c):p.abort()};d.signal?.addEventListener("abort",R,{once:!0}),d.signal?.aborted&&R();try{let k=await i(p.signal,y);if(!k.done)throw this.audit(e,t,r,n,"stopped",{code:k.refusal.code,...m}),pe(this.deps,c,{status:"refused",code:k.refusal.code}),f.fail(k.refusal.message),g(new Error(k.refusal.message)),this.refusalOf(k.refusal,k.alsoRefused);let{result:w,notes:O,deliverability:P}=k,b={...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 w.removedJournals??[])this.deps.log(`[INFO] Removed the journal of rewind ${C.rewindId} of checkpoint '${C.name}': Undo reaches the last rewind of the org alone`);let v=d.refusalOf?.(w);if(v!==void 0)throw this.audit(e,t,r,n,kv(w)?"partial":"stopped",{result:w,code:v.code,...b}),pe(this.deps,c,{status:"refused",code:v.code}),f.fail(v.message),g(new Error(v.message)),new ke(v.code,v.message,!1,w);if(this.audit(e,t,r,n,WE[w.status],{result:w,...b}),e.respond?.(`checkpoint:${t}:response`,{result:w,operationId:c}),w.status==="cancelled")u?.abort(c),pe(this.deps,c,{aborted:!0}),f.cancel(),g();else if(w.status==="failure"){let C=`Nothing the ${t} set out to write went through: its result says why.`;pe(this.deps,c,{status:w.status}),f.fail(C),g(new Error(C))}else pe(this.deps,c,{status:w.status}),w.status==="success"?f.complete():f.partial(),g();return w}catch(k){if(k instanceof ke)throw k;if(a(k))throw u?.abort(c),pe(this.deps,c,{aborted:!0}),f.cancel(),g(),this.audit(e,t,r,n,"stopped",{code:cr,...m}),new ke(cr,I(k),!0);let w=Ls(k);throw this.audit(e,t,r,n,"failure",{...m,...w?{muted:w}:{}}),this.unreleased(e,t,r,w),pe(this.deps,c,{status:"failure"}),f.fail(I(k)),g(k),k}finally{d.signal?.removeEventListener("abort",R)}}unreleased(e,t,r,n){n?.released===!1&&this.deps.log(`[WARN] checkpoint:${t} ${e.operationId}: `+Vt(n,pt(r)).map(o=>o.trim()).join("; "))}readAutomation(e,t){let r=this.targetAutomation;return new ge(qE).withTimeout("checkpoint:preview automation",()=>r.read(e,t,{undeletes:!0}))}ownReader(){return this.reader??=import("./chunk-DIL62SUN.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=x(qm,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 ${pp(i)}`);if(n.length===0&&o.length>0)throw new ke("RUN_WRITING",`The checkpoint was not deleted: ${pp(o[0])}. Delete it once that has ended.`,!0);this.respond(e,"checkpoint:delete:response",{deleted:n}),n.length>0&&this.checkpointsChanged()}catch(r){this.fail(e,r,"DELETE_ERROR")}}async handleKeep(e){let t=x(Wm,e,"checkpoint:error",this.deps);t&&await this.change(e,t.checkpointId,"keep",r=>r.keep(t.checkpointId,t.keep))}async handleRename(e){let t=x(zm,e,"checkpoint:error",this.deps);t&&await this.change(e,t.checkpointId,"rename",r=>r.update(t.checkpointId,n=>({...n,name:t.name})))}async handleIgnoreFields(e){let t=x(Gm,e,"checkpoint:error",this.deps);t&&await this.change(e,t.checkpointId,"ignore-fields",r=>r.update(t.checkpointId,n=>({...n,ignoredFields:t.fields})))}async handleRewinds(e){let t=x(Jm,e,"checkpoint:error",this.deps);if(t!==null)try{let r=await this.openedStore(),{readRewindLedgers:n}=await import("./chunk-DWMRIWV5.mjs"),i=(t?.orgIds??this.deps.orgManager.getAllOrgs().map(c=>c.id)).map(c=>({orgId:c,ids:this.organizationIdsOf(c)})),a=await n(r.root,i.flatMap(({ids:c})=>c)),d=[];for(let[c,l]of a){for(let u of l.unreadable)this.deps.log(`[WARN] Line ${u} of the rewind ledger of ${c} does not parse: left out`);for(let u of l.records){let p=i.filter(({ids:g})=>g.some(h=>xt(h,u.organizationId)));d.push({...u,orgIds:p.map(({orgId:g})=>g)})}}this.respond(e,"checkpoint:rewinds:response",{rewinds:d})}catch(r){this.fail(e,r,"REWINDS_ERROR")}}async change(e,t,r,n){try{let o=await this.modules(),i=await this.openedStore(),{folder:a}=await this.checkpointOf(i,t),d=i.heldBy(a.organizationId);if(d!==void 0&&(d.checkpointId===void 0||d.checkpointId===t))throw new ke("RUN_WRITING",`The checkpoint was not changed: ${pp(d)}. Change it once that has ended.`,!0);let c;try{c=await n(i)}catch(l){throw l instanceof o.CheckpointStoreError?new ke(l.code==="notFound"?"NOT_FOUND":l.code==="damaged"?"DAMAGED":"INVALID",l.message):l}this.respond(e,`checkpoint:${r}:response`,{checkpoint:c}),this.checkpointsChanged()}catch(o){this.fail(e,o,"CHANGE_ERROR")}}};var St={orgUnknown:"ORG_NOT_FOUND",production:"PIPELINE_WRITE_REFUSED",needsApproval:"PIPELINE_WRITE_NEEDS_APPROVAL",templateMissing:"SEED_TEMPLATE_MISSING",templateInvalid:"SEED_TEMPLATE_INVALID",templateUsesAi:"SEED_TEMPLATE_USES_AI",unanswered:"SEED_CONFIRMATION_UNAVAILABLE"};function lr(s,e){return Object.assign(new Error(e),{code:s})}function Ev(s,e,t){let r=Bi(s);if(r==="refused")return lr(St.production,`${t} is a production org, or one SandForge cannot tell is not: a pipeline never seeds one, whatever an Approval step answers. Seed a sandbox, a scratch org or a Developer Edition org. Nothing was written.`);if(r==="needsApproval"&&!e.approved)return lr(St.needsApproval,`${t} is a sandbox marked Staging, which a pipeline seeds only once an Approval step before the seed has approved the run, and none did: put an Approval step before it. Nothing was written.`)}function gp(s){return s.objects.flatMap(e=>e.fieldRules.filter(t=>t.ruleType==="ai_generate").map(t=>`${e.objectApiName}.${t.fieldApiName}`))}function zo(s,e,t){let r=t(e)??Di.find(d=>d.id===e);if(r==null)return{refusal:lr(St.templateMissing,`No Seed template is saved under ${e}, and SandForge ships none: it was deleted on the Seed page. Choose another. Nothing was written.`)};let n=r.name,o=typeof n=="string"&&n!==""?n:e,i=ko.safeParse(r);if(!i.success){let d=i.error.issues[0];return{refusal:lr(St.templateInvalid,`The Seed template "${o}" no longer validates (${d.path.join(".")}: ${d.message}): open it on the Seed page and save it again. Nothing was written.`)}}let a=gp(i.data);return a.length>0?{refusal:lr(St.templateUsesAi,`The Seed template "${o}" fills ${a.join(", ")} with AI rules: a pipeline runs where nobody watches, and an AI rule sends field names to Anthropic on each run. Give ${a.length===1?"it a Faker rule":"them Faker rules"} on the Seed page. Nothing was written.`)}:{asked:{orgId:s,template:i.data}}}var Nv={apiLimits:"apiLimits",storage:"storage",recentErrors:"recentErrors",failedJobs:"activeJobs"},fp=Object.keys(Nv),Pv={apiLimits:{variable:ms.apiLimits,read:s=>s.percent},storage:{variable:ms.storage,read:s=>s.percent},recentErrors:{variable:ms.recentErrors,read:s=>s.count},failedJobs:{variable:ms.failedJobs,read:s=>s.count}},jv=500,Mv=G({orgId:xh,checks:Re(_e(["apiLimits","storage","recentErrors","failedJobs"])).min(1).refine(s=>new Set(s).size===s.length)}),Lv=G({message:j().trim().min(1).max(jv)});function It(s,e){return`${s} ${e}${s===1?"":"s"}`}function Pr(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 At(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 Er(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 wp(s){return Array.isArray(s)&&s.length>0?s:void 0}function QE(s){return e=>{let t=`Backup step "${e.name}"`,r=e.config??{},n=Er(s,t,r.orgId,"the org it backs up");if(n)return n;let o=wp(r.objects);if(!o)return`${t} names no object: list the API names of the objects it backs up.`;let i=o.filter(a=>!Dh.safeParse(a).success);if(i.length>0)return`${t} names what is not an object API name: ${i.map(String).join(", ")}.`;if(!Ts.safeParse({orgId:r.orgId,objects:o}).success)return`${t} backs up more objects than one backup takes: at most 100.`}}function ZE(s){return e=>{let t=`Compare step "${e.name}"`,r=e.config??{},n=Er(s,t,r.sourceOrgId,"the org it compares from")??Er(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=wp(r.types);if(!o)return`${t} names no component type: choose what it compares.`;if(!Es.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 eP(s){return e=>{let t=`Pre-check step "${e.name}"`,r=e.config??{},n=Er(s,t,r.orgId,"the org it checks");if(n)return n;let o=wp(r.checks);if(!o)return`${t} names no check: choose what it checks (${fp.join(", ")}).`;let i=o.filter(a=>typeof a!="string"||!fp.includes(a));if(i.length>0)return`${t} names checks SandForge does not have: ${i.map(String).join(", ")}. It can check ${fp.join(", ")}.`;if(!Mv.safeParse({orgId:r.orgId,checks:o}).success)return`${t} names the same check twice.`}}function tP(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(!Lv.safeParse({message:r}).success)return`${t} has a message longer than ${jv} characters.`}}function rP(s){return async(e,t)=>{let r=new Date().toISOString(),{orgId:n,objects:o}=Ts.parse({orgId:e.config.orgId,objects:e.config.objects}),i=await s.backup({operationId:s.newId(),orgId:n,objects:o},t.signal),a=s.orgName(n)??n,d=i.objects.filter(l=>l.truncated).map(l=>l.objectApiName),c=`Backed up ${It(i.totalRecords,"record")} of ${It(i.objects.length,"object")} from ${a}`+(d.length>0?`; only part of ${d.join(", ")}: the org holds more rows than one backup reads.`:".");return Pr(e,r,{operationId:i.operationId,orgId:n,objects:i.objects,totalRecords:i.totalRecords,partial:i.partial},c)}}function nP(s){return async(e,t)=>{let r=new Date().toISOString(),{sourceOrgId:n,targetOrgId:o,types:i}=Es.parse({sourceOrgId:e.config.sourceOrgId,targetOrgId:e.config.targetOrgId,types:e.config.types}),a=await s.compare({sourceOrgId:n,targetOrgId:o,types:i},t.signal),{added:d,removed:c,modified:l,unchanged:u,notCompared:p}=a.summary,g=s.orgName(n)??n,h=s.orgName(o)??o;return Pr(e,r,{sourceOrgId:n,targetOrgId:o,types:i,summary:a.summary,content:a.content,variables:{[Ef]:String(d+c+l)}},`Compared ${It(i.length,"component type")} of ${g} with ${h}: ${c} only in ${g}, ${d} only in ${h}, ${l} modified, ${u} unchanged, ${p} not compared.`)}}function Cv(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 oP(s){return async e=>{let t=new Date().toISOString(),{orgId:r,checks:n}=Mv.parse({orgId:e.config.orgId,checks:e.config.checks}),o=s.orgName(r)??r,i=await s.readOrgHealth(r,n.map(u=>Nv[u])),a=n.map((u,p)=>({check:u,signal:i[p]})),d={};for(let{check:u,signal:p}of a){let g=p?Pv[u].read(p):void 0;g!==void 0&&p.status!=="unknown"&&(d[Pv[u].variable]=String(g))}let c={orgId:r,checks:a.map(({check:u,signal:p})=>({check:u,status:p?.status??"unknown",message:p?.message??"Not read"})),variables:d},l=a.filter(({signal:u})=>!u||u.status==="critical"||u.status==="unknown");return l.length>0?At(e,t,c,`Pre-check "${e.name}" failed on ${o}: ${l.map(({check:u,signal:p})=>p?Cv(p):`${u} was not read`).join("; ")}.`):Pr(e,t,c,`${a.length===1?"The check":`${a.length} checks`} passed on ${o}: ${a.map(({signal:u})=>Cv(u)).join("; ")}.`)}}function sP(s){return async(e,t)=>{let r=new Date().toISOString(),{message:n}=Lv.parse({message:e.config.message});return s.notify?(s.notify(t.pipelineName?`${t.pipelineName}: ${n}`:n),Pr(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.")):At(e,r,{},`Notification step "${e.name}" cannot show a notification: there is no VS Code window to show it in.`)}}function Fv(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=iP(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 iP(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=ei(s,t);r="problem"in n?void 0:n.config.targetOrgId}else(t.type==="seed"||t.type==="anonymize")&&(r=en((t.config??{}).orgId));if(r!==void 0&&s.orgTier?.(r)==="staging")return s.orgName(r)??r}}function aP(s){return(e,t)=>{let r=`Approval step "${e.name}"`;if(!s.askApproval)return Fv(s,e,t);switch(Df(e.config)){case"timeout":return`${r} waits for a time it cannot keep: set a whole number of minutes from 1 to ${Cf} (a day).`;case"message":return`${r} has a message that is not text, or is longer than ${$f} characters.`;default:return}}}function $v(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 dP(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Approval step "${e.name}"`;if(!s.askApproval)return At(e,r,{},Fv(s,e,void 0));let o=xf(e.config)??Pf,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{...Pr(e,r,c,`Approved${$v(d)} at ${d.at}.`),approval:d};case"rejected":return{...At(e,r,c,`${n} was rejected${$v(d)} at ${d.at}.`),approval:d};case"timedOut":return{...At(e,r,c,`${n} was not approved in time: nobody answered within ${It(o,"minute")}.`),approval:d};case"cancelled":return{...At(e,r,c,`${n} was stopped before anyone answered.`),approval:d}}}}function ei(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=yn.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 _v(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(!yn.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 Hv(s){return s===void 0||s.steps.slice(0,s.index).some(e=>e.type==="approval")}function cP(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=ei(s,e);if("problem"in n)return n.problem;let{config:o}=n,i=Er(s,r,o.sourceOrgId,"the source org of its configuration")??Er(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"&&!Hv(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 bp(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 Rp(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 xv=3;function lP(s){let e=s.filter(r=>r.failed>0).flatMap(r=>Hl(r.errors).map(n=>`${r.objectApiName}, ${n.count} \xD7 ${n.example}`));if(e.length===0)return"";let t=e.length-xv;return`; refused: ${e.slice(0,xv).join("; ")}`+(t>0?`; and ${It(t,"other reason")}`:"")}function uP(s){return async(e,t)=>{let r=new Date().toISOString(),n=ei(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,bp(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,l={configId:o.id,configName:i,operationId:a.operationId,status:a.status,totalProcessed:a.totalProcessed,totalSuccess:a.totalSuccess,totalFailed:a.totalFailed,totalSkipped:a.totalSkipped,objects:a.objectResults.map(g=>{let h=g.failed>0?Hl(g.errors):[];return{objectApiName:g.objectApiName,operation:g.operation,processed:g.processed,success:g.success,failed:g.failed,skipped:g.skipped,...h.length>0?{refusals:h}:{},...g.delta?{delta:g.delta}:{}}}),...typeof c=="object"&&c!==null?{summary:c}:{}},u=Rp(a.objectResults,!0).map(g=>`; ${g}`).join(""),p=`${It(a.totalSuccess,"record")} written, ${a.totalFailed} failed and ${a.totalSkipped} skipped of ${a.totalProcessed} read${u}`;if(a.status!=="success"){let g=[a.error,Qa(a)].filter(h=>h!==void 0&&h!=="");return At(e,r,l,`Sync step "${e.name}" ran "${i}" into ${d} and did not complete: ${p}`+lP(a.objectResults)+(g.length>0?`; ${g.join("; ")}`:"."))}return Pr(e,r,l,`Synced "${i}" into ${d}: ${p}.`)}}function en(s){return typeof s=="string"&&s.trim()!==""?s.trim():void 0}function Sp(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 pP(s,e){return s!==void 0&&e!==void 0&&s.length>=15&&s.slice(0,15)===e.slice(0,15)}function gd(s){return s.pipelineName??s.pipelineId}function Uv(s,e,t,r,n){let o=s.orgName(t)??t,i=Bi(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"&&!Hv(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 Bv(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 qv(s){if(s instanceof Rt)return;let e=s?.code;return typeof e=="string"?e:void 0}function gP(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=Er(s,r,n.orgId,"the org it seeds");if(o)return o;let i=en(n.templateId);if(i===void 0)return`${r} names no Seed template: choose the one it seeds with.`;let a=String(n.orgId),d=zo(a,i,c=>s.savedSeedTemplate?.(c));return"refusal"in d?`${r}: ${d.refusal.message}`:Bv(e,r,"a second try would write a second set of records")??Uv(s,r,a,"seeds",t)}}function fP(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}=Ui.parse({orgId:e.config.orgId,templateId:en(e.config.templateId)}),a=s.orgName(o)??o,d;try{d=await s.seed({orgId:o,templateId:i,pipeline:{name:gd(t)},answer:bp(t)},t.signal)}catch(g){let h=qv(g);if(h===void 0)throw g;return At(e,r,{orgId:o,templateId:i,code:h},`${n}: ${g.message}`)}let{result:c}=d,l={orgId:o,templateId:i,operationId:d.operationId,runId:d.runId,status:c.status,totalRecordsCreated:c.totalRecordsCreated,totalRecordsFailed:c.totalRecordsFailed,objects:c.objectResults.map(g=>({objectApiName:g.objectApiName,recordsCreated:g.recordsCreated,recordsFailed:g.recordsFailed})),...d.automation.length>0?{automation:d.automation}:{}},u=It(c.totalRecordsCreated,"record"),p="take them back from Seed's Recent runs";if(c.cancelled)throw new Rt(`${n} was cancelled: it had created ${u} in ${a}, which stay there; ${p}.`);return c.status!=="success"?At(e,r,l,`${n} seeded ${a} and did not complete: ${u} created, ${c.totalRecordsFailed} refused; ${p}.`):Pr(e,r,l,`Seeded ${u} into ${a}: ${p}.`)}}function Wv(s){let e=(s.listSeedTemplates?.()??[]).map(n=>({raw:n,builtIn:!1})),t=Di.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=ko.safeParse(n);return[{id:i,name:d,builtIn:o,valid:c.success,usesAi:c.success&&gp(c.data).length>0}]})}function hP(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 zv(s){return(s.maskingTemplates?.()??[]).map(e=>({id:e.id,name:e.name,builtIn:e.builtIn,objects:hP(e)}))}function mP(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=Er(s,r,n.orgId,"the org it masks");if(o)return o;let i=en(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=en(n.object),l=en(n.where),u=eb({orgId:a,templateId:i,...c!==void 0?{object:c}:{},...l!==void 0?{where:l}:{},...e.retries!==void 0?{retries:e.retries}:{}},g=>d.some(h=>h.id===g));if("refusal"in u)return`${r}: ${u.refusal.message}`;let p=ys.safeParse({orgId:a,templateId:i,...fd(n)});return p.success?Uv(s,r,a,"masks",t):`${r} does not read (${Sp(p.error)}).`}}function fd(s){return Object.fromEntries(["acceptAutomation","acceptEmails","muteAutomation"].flatMap(e=>s[e]===void 0?[]:[[e,s[e]]]))}var Dv=3;function yP(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-Dv;return`, refused by the org: ${e.slice(0,Dv).join("; ")}`+(t>0?`; and ${It(t,"other reason")}`:"")}function wP(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=en(e.config.object),i=en(e.config.where),{orgId:a,templateId:d,acceptAutomation:c,acceptEmails:l,muteAutomation:u}=ys.parse({orgId:e.config.orgId,templateId:en(e.config.templateId),...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...fd(e.config)}),p=s.orgName(a)??a,g=O=>O?` ${Vt(O,p).map(P=>P.trim()).join("; ")}.`:"",h;try{h=await s.anonymize({orgId:a,templateId:d,...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...e.retries!==void 0?{retries:e.retries}:{},accord:{acceptAutomation:c,acceptEmails:l,muteAutomation:u},pipeline:{name:gd(t)},answer:bp(t)},t.signal)}catch(O){let P=qv(O);if(P===void 0)throw O;let b=O.snapshot,v=Ls(O);return At(e,r,{orgId:a,templateId:d,code:P,...b!==void 0?{snapshot:b}:{},...v?{mutedAutomation:v}:{}},`${n}: ${O.message}`+(typeof b?.operationId=="string"?` The snapshot ${b.operationId} it took keeps the values it wrote over, in clear, until it is deleted on the DataOps page.`:"")+g(v))}let{result:f}=h,m=f.snapshot?`the snapshot ${f.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:h.operationId,status:f.status,recordsProcessed:f.recordsProcessed,recordsFailed:f.recordsFailed,recordsNotMasked:f.recordsNotMasked,objects:f.objects,message:f.message,errors:f.errors,...f.snapshot?{snapshot:f.snapshot}:{},...f.mutedAutomation?{mutedAutomation:f.mutedAutomation}:{}},R=g(f.mutedAutomation);if(f.cancelled)throw new Rt(`${n} was cancelled: it masked ${It(f.recordsProcessed,"record")} in ${p} before the stop, and ${f.recordsNotMasked} still hold their values; ${m}.`+R);let k=f.objects.filter(O=>O.notMasked>0);if(f.recordsNotMasked>0){let O=`${k.map(P=>`${P.notMasked} of ${P.objectApiName}`).join(", ")} still hold their values${yP(f)}`;return At(e,r,y,`${n} masked ${p} and did not complete: ${O}; ${m}.${R}`)}let w=o!==void 0?i!==void 0?`the ${o} rows where ${i}`:`every ${o} row`:`every row of ${f.objects.map(O=>O.objectApiName).join(", ")}`;return Pr(e,r,y,`Masked ${It(f.recordsProcessed,"record")} in ${p}, ${w}; ${m}.${R}`)}}function bP(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=Er(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=fn.safeParse(r);if(!i.success)return`${t} does not read (${Sp(i.error)}).`}}function RP(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 SP(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=fn.parse(e.config),i=s.orgName(o.orgId)??o.orgId,a;try{a=await s.takeCheckpoint({config:o,origin:{pipeline:gd(t),step:e.name,trigger:s.trigger??"manual"}},t.signal)}catch(l){if(!(l instanceof Tr))throw l;return At(e,r,{orgId:o.orgId,code:l.code},l.message)}let d=a.movedWhileTaken,c=d.changed+d.deleted+d.created;return Pr(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}: ${It(a.records,"record")} of ${It(a.objects,"object")}, ${RP(a.bytes)} on this machine, `+(o.keepDays===0?"kept until it is deleted":`kept ${It(o.keepDays,"day")}`)+(c>0?`; ${It(c,"record")} changed while it was taken.`:"."))}}var vP={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 Gv(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}, ${vP[a]}.`}}let i=s.organizationIdsOf?.(t)??[];if(n.organizationId!==void 0&&!i.some(a=>pP(a,n.organizationId)))return{why:"otherOrg",problem:`${e} rewinds ${s.orgName(t)??t} to the checkpoint ${o}, which was taken of another org.`}}function kP(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=Er(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=Pt.safeParse(r);if(!i.success)return`${t} does not read (${Sp(i.error)}).`;let a=Bv(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?Cn(e.name,d.refusal):Gv(s,t,o,i.data.checkpointId)?.problem}}function yp(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 hp(s){let e=yp(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 mp(s){return s.undo?`Undo on the Checkpoints page takes it back until ${s.undo.until}`:"it wrote nothing Undo would take back"}function OP(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=Pt.parse(e.config),i=s.rewindGrant(t.pipelineId,e);if("refusal"in i)return At(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:"NOT_CONFIRMED"},Cn(e.name,i.refusal));let a=s.orgName(o.orgId)??o.orgId,d=h=>h?` ${Vt(h,a).map(f=>f.trim()).join("; ")}.`:"",c;try{c=await s.rewind({config:o,grant:i.grant,origin:{pipeline:gd(t),step:e.name,trigger:s.trigger??"manual"}},t.signal)}catch(h){let f=(h instanceof Tr?h.result?.mutedAutomation:void 0)??Ls(h);if(!(h instanceof Tr)){if(!f||h instanceof Rt)throw h;return At(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,mutedAutomation:f},`${I(h)}${d(f)}`)}return At(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:h.code,...h.alsoRefused.length>0?{alsoRefused:[...h.alsoRefused]}:{},...h.result?{status:h.result.status,...yp(h.result)}:{},...f?{mutedAutomation:f}:{}},`${h.message}${d(f)}`)}let{result:l}=c,u=l.residual.reduce((h,f)=>h+f.count,0),p={orgId:o.orgId,checkpointId:c.checkpointId,operationId:c.operationId,rewindId:l.rewindId,status:l.status,...yp(l),residual:u,...l.undo?{undoUntil:l.undo.until}:{},apiRequests:l.apiRequests.used,...l.mutedAutomation?{mutedAutomation:l.mutedAutomation}:{}},g=d(l.mutedAutomation);if(l.status==="cancelled")throw new Rt(`${n} was stopped part way in ${a}: ${hp(l)}; ${mp(l)}.${g}`);return l.status!=="success"?At(e,r,p,`${n} rewound ${a} and did not complete (${l.status}): ${hp(l)}; ${It(u,"record")} still ${u===1?"differs":"differ"} from the checkpoint`+(l.unread&&l.unread.length>0?`, and ${l.unread.map(h=>h.objectApiName).join(", ")} could not be read`:"")+`; ${mp(l)}.${g}`):Pr(e,r,p,`Rewound ${a} to the checkpoint ${c.checkpointId}: ${hp(l)}, with ${It(l.apiRequests.used,"API request")}; ${mp(l)}.${g}`)}}function Jv(s,e,t,r){let n=r?{granted:{at:r.grantedAt,digestMatches:r.matches}}:{},o=Pt.safeParse(e.config??{});if(!o.success)return{stepId:e.id,valid:!1,why:"config",...n};let{orgId:i,checkpointId:a}=o.data,d=Gv({...s,checkpointKept:()=>t},"The step",i,a);return{stepId:e.id,checkpointId:a,valid:d===void 0,...d?{why:d.why}:{},...n}}function Vv(s,e){s.registerHandler("backup",rP(e),QE(e)),s.registerHandler("compare",nP(e),ZE(e)),s.registerHandler("precheck",oP(e),eP(e)),s.registerHandler("notification",sP(e),tP(e)),s.registerHandler("approval",dP(e),aP(e)),s.registerHandler("sync",uP(e),cP(e)),s.registerHandler("seed",fP(e),gP(e)),s.registerHandler("anonymize",wP(e),mP(e)),s.registerHandler("checkpoint",SP(e),bP(e)),s.registerHandler("rewind",OP(e),kP(e))}function nn(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 tn(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 rn(s,e){return`${s} ${e}${s===1?"":"s"}`}function ti(s){return typeof s=="string"&&s.trim()!==""?s.trim():void 0}function hd(s){return s.pipelineName??s.pipelineId}function vp(s){if(s instanceof Rt)return;let e=s?.code;return typeof e=="string"?e:void 0}function Go(s){return new Error(`${s} cannot be dry-run here: nothing can read what it would do. Nothing was written.`)}function IP(s){return s<6e4?`${s/1e3} s`:s<36e5?`${Math.round(s/6e4)} min`:`${(s/36e5).toFixed(1)} h`}function Yv(s){return`about ${rn(s.apiRequests,"API request")} of the ${s.apiRequestsLeft} the org has left today, about ${s.seconds} s`}function AP(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 Xv(s){let e=Rp(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 Kv=3;function TP(s){let e=s.flatMap(r=>(r.refusedFor??[]).map(({note:n})=>`${r.objectApiName}, ${n.replace(/\.$/,"")}`));if(e.length===0)return"";let t=e.length-Kv;return`; refused: ${e.slice(0,Kv).join("; ")}`+(t>0?`; and ${rn(t,"other reason")}`:"")}function EP(s){let e=new Date().toISOString(),t=Tw(s.config)??0;return Promise.resolve(nn(s,e,{wouldWait:t},`Would wait ${IP(t)}: a dry run does not wait.`))}function PP(s){let e=new Date().toISOString();return Promise.resolve(nn(s,e,{asked:!1},"Not asked in a dry run: the route goes on as if it were approved."))}function CP(s){return e=>{let t=new Date().toISOString(),r=ti(e.config.message)??"",n=s.ranFrom==="commandLine"?"Not printed in a dry run; the run would print":"Not shown in a dry run; the run would show in VS Code";return Promise.resolve(nn(e,t,{message:r},`${n}: "${r}"`))}}function $P(s){return e=>{let t=new Date().toISOString(),{orgId:r,objects:n}=Ts.parse({orgId:e.config.orgId,objects:e.config.objects}),o=s.orgName(r)??r;return Promise.resolve(nn(e,t,{orgId:r,objects:n},`Would take a snapshot of ${rn(n.length,"object")} of ${o} (${n.join(", ")}): a dry run takes none.`))}}function xP(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Sync step "${e.name}"`,o=ei(s,e);if("problem"in o)throw new Error(o.problem);if(!s.simulateSync)throw Go(n);let{config:i,name:a}=o,d=s.orgName(i.targetOrgId)??i.targetOrgId,c;try{c=await s.simulateSync(i,t.signal)}catch(g){let h=vp(g);if(h===void 0)throw g;return tn(e,r,{configId:i.id,code:h},`${n} would be refused: ${g.message}`)}if(c.cancelled)throw new Rt(`${n} was stopped before its simulation read every object. Nothing was written.`);let l={configId:i.id,configName:a,operationId:c.operationId,objects:c.objects.map(g=>({objectApiName:g.objectApiName,operation:g.operation,read:g.read,insert:g.insert,update:g.update,delete:g.delete,skipped:g.skipped,refused:g.refused,...g.refusedFor?{refusedFor:g.refusedFor}:{},...g.delta?{delta:g.delta}:{}})),...c.readCap!==void 0?{readCap:c.readCap}:{},...c.cutAtReadCap?{cutAtReadCap:c.cutAtReadCap}:{}},u=AP(c.objects);return c.error?tn(e,r,l,`${n} would stop on ${c.failedObject??"an object"}: ${c.error}`):c.objects.reduce((g,h)=>g+h.refused,0)>0?tn(e,r,l,`${n} would run "${a}" into ${d} and not complete: ${u}${Xv(c)}${TP(c.objects)}. Nothing was written.`):nn(e,r,l,`Would sync "${a}" into ${d}: ${u}${Xv(c)}. Nothing was written.`)}}function DP(s){let e=s.previousResults.filter(t=>t.stepType==="approval");return{approved:e[e.length-1]?.status==="completed"}}function NP(s,e){return yS(s,e)}function jP(s,e){let t=`about ${rn(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 MP(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Seed step "${e.name}"`,{orgId:o,templateId:i}=Ui.parse({orgId:e.config.orgId,templateId:ti(e.config.templateId)}),a=s.orgName(o)??o,d=zo(o,i,u=>s.savedSeedTemplate?.(u));if("refusal"in d)return tn(e,r,{orgId:o,templateId:i,code:d.refusal.code},`${n} would be refused: ${d.refusal.message}`);if(!s.previewSeed)throw Go(n);let{template:c}=d.asked,l;try{l=await s.previewSeed({orgId:o,templateId:i,pipeline:{name:hd(t)},answer:DP(t)},t.signal)}catch(u){let p=vp(u);if(p===void 0)throw u;return tn(e,r,{orgId:o,templateId:i,code:p},`${n} would be refused: ${u.message}`)}return nn(e,r,{orgId:o,templateId:i,records:l.records,objects:l.objects,storage:l.storage,apiRequests:l.apiRequests,...l.automation.length>0?{automation:l.automation}:{}},`Would seed "${c.name}" into ${a}: ${rn(l.records,"record")} of ${rn(l.objects,"object")}, as its template asks; ${NP(l.storage,a)}; ${jP(l.apiRequests,a)}. Nothing was written.`)}}function LP(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Anonymize step "${e.name}"`;if(!s.previewMasking)throw Go(n);let o=ti(e.config.object),i=ti(e.config.where),{orgId:a,templateId:d,acceptAutomation:c,acceptEmails:l,muteAutomation:u}=ys.parse({orgId:e.config.orgId,templateId:ti(e.config.templateId),...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...fd(e.config)}),p=s.orgName(a)??a;try{let g=await s.previewMasking({orgId:a,templateId:d,...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...e.retries!==void 0?{retries:e.retries}:{},accord:{acceptAutomation:c,acceptEmails:l,muteAutomation:u},pipeline:{name:hd(t)},answer:{approved:!0}},t.signal),h=g.objects.filter(f=>f.records>0).map(f=>`${f.records} of ${f.objectApiName} (${f.fields.join(", ")})`);return nn(e,r,{orgId:a,templateId:d,records:g.records,objects:g.objects},g.records===0?`Would mask nothing in ${p}: no row of ${g.objects.map(f=>f.objectApiName).join(", ")} holds anything to mask. Nothing was written.`:`Would mask ${rn(g.records,"record")} in ${p}: ${h.join("; ")}, after a snapshot of them. Nothing was written.`)}catch(g){let h=vp(g);if(h===void 0)throw g;return tn(e,r,{orgId:a,templateId:d,code:h},`${n} would be refused: ${g.message}`)}}}function FP(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Checkpoint step "${e.name}"`;if(!s.estimateTake)throw Go(n);let o=fn.parse(e.config),i=s.orgName(o.orgId)??o.orgId;try{let a=await s.estimateTake({config:o,origin:{pipeline:hd(t),step:e.name,trigger:s.trigger??"manual"}},t.signal);return nn(e,r,{orgId:o.orgId,objects:a.objects,records:a.records,leftOut:a.leftOut,estimate:a.estimate},`Would take a checkpoint of ${i}: ${rn(a.records,"record")} of ${rn(a.objects,"object")} now, ${Yv(a.estimate)}. Nothing was taken.`)}catch(a){if(!(a instanceof Tr))throw a;return tn(e,r,{orgId:o.orgId,code:a.code},`${n} would be refused: ${a.message}`)}}}function _P(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Rewind step "${e.name}"`;if(!s.rewindGrant||!s.previewRewind)throw Go(n);let o=Pt.parse(e.config),i=s.rewindGrant(t.pipelineId,e);if("refusal"in i)return tn(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:"NOT_CONFIRMED"},Cn(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:hd(t),step:e.name,trigger:s.trigger??"manual"}},t.signal);return nn(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`:"")+`, ${Yv(d.estimate)}. Nothing was written.`)}catch(d){if(!(d instanceof Tr))throw d;return tn(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 Qv(s,e){s.wrapHandler("delay",()=>EP),s.wrapHandler("approval",()=>PP),s.wrapHandler("notification",()=>CP(e)),s.wrapHandler("backup",()=>$P(e)),s.wrapHandler("sync",()=>xP(e)),s.wrapHandler("seed",()=>MP(e)),s.wrapHandler("anonymize",()=>LP(e)),s.wrapHandler("checkpoint",()=>FP(e)),s.wrapHandler("rewind",()=>_P(e))}var Jo=new Map,Zv=(s,e)=>`${s}::${e}`;async function Kt(s,e,t,r=Date.now){let n=Zv(s,e),o=Jo.get(n);if(o&&r()-o.at<3e5)return o.value;let i=t();Jo.set(n,{at:r(),value:i});try{return await i}catch(a){throw Jo.get(n)?.value===i&&Jo.delete(n),a}}function ek(s){let e=Zv(s,"");for(let t of Jo.keys())t.startsWith(e)&&Jo.delete(t)}var HP=G({orgId:j(),detectedAt:j(),evidence:_e(["connection","monitor","production"]),previousOrganizationId:j().optional(),organizationId:j().optional(),previousInstanceName:j().optional(),instanceName:j().optional(),sandboxName:j().optional(),reportedBy:j().optional()}),UP=G({organizationId:j(),instanceName:j().optional(),formerOrganizationIds:Re(j()),refreshes:Re(HP)}),tk="sandbox-refresh:",BP="sandbox-refresh",rk=10,qP=20,WP=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function kp(s){return s!==void 0&&WP.test(s)?s.slice(0,15):void 0}function nk(s){try{return new URL(s).hostname.toLowerCase()}catch{return}}function zP(s){let e=nk(s.instanceUrl),t=".my.salesforce.com";return e?.endsWith(t)?e.slice(0,-t.length):void 0}function GP(s,e,t){let r=t.toLowerCase(),n=zP(s);return n&&nk(e.instanceUrl)?.startsWith(`${n}--${r}.`)?!0:e.username.toLowerCase()===`${s.username.toLowerCase()}.${r}`}var md=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=kp(t.organizationId);if(!o)return;let i=this.read(e),a=i??this.baselineOf(n);if(!a){this.write(e,{organizationId:o,instanceName:t.instanceName,formerOrganizationIds:[],refreshes:[]});return}if(o===a.organizationId){let p=t.instanceName!==void 0&&t.instanceName!==a.instanceName;(!i||p)&&this.write(e,{...a,instanceName:t.instanceName??a.instanceName});return}if(a.formerOrganizationIds.includes(o))return;let[d,...c]=a.refreshes,l=d?.evidence==="production"&&d.organizationId===void 0?d:void 0,u={...l??{orgId:e,detectedAt:this.now().toISOString(),evidence:r},previousOrganizationId:a.organizationId,organizationId:o,previousInstanceName:a.instanceName,instanceName:t.instanceName};return this.write(e,{organizationId:o,instanceName:t.instanceName,formerOrganizationIds:[a.organizationId,...a.formerOrganizationIds].slice(0,qP),refreshes:(l?[u,...c]:[u,...a.refreshes]).slice(0,rk)}),this.deps.log?.(`[sandbox-refresh] ${n.alias}: org ${a.organizationId} is now ${o} (${r})`),l||this.emit(u),u}noteCompletedRefresh(e){let t=this.deps.orgManager.getOrg(e.orgId);if(!t)return[];let r=[];for(let n of this.deps.orgManager.getAllOrgs()){if(n.orgType!=="Sandbox"||n.id===t.id||!GP(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,rk)}),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=kp(t);return r!==void 0&&this.refreshesOf(e).some(n=>n.organizationId===r)}baselineOf(e){let t=kp(e.orgId);return t===void 0?void 0:{organizationId:t,formerOrganizationIds:[],refreshes:[]}}read(e){let t=this.deps.configStore.get(`${tk}${e}`);if(t===void 0)return;let r=UP.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(`${tk}${e}`,t,BP)}emit(e){for(let t of this.listeners)try{t(e)}catch(r){this.deps.log?.(`[sandbox-refresh] a listener failed: ${String(r)}`)}}};var JP=5,VP=5e3,XP=3e4,KP=G({device_code:j().min(1).max(4096),user_code:j().regex(/^[A-Za-z0-9-]{4,32}$/),verification_uri:j().min(1).max(2048),interval:Te().int().positive().max(300).optional(),expires_in:Te().int().positive().optional()}),YP=G({access_token:j().min(1),refresh_token:j().min(1).optional(),instance_url:j().min(1).max(2048)}),ok=G({error:j().min(1),error_description:j().optional()}),Zn=class extends Error{constructor(){super("Sign-in cancelled."),this.name="DeviceLoginCancelledError"}},yd=class extends Error{constructor(e){super(e),this.name="RefusedByHostError"}};function QP(s,e){return new Promise((t,r)=>{if(e?.aborted){r(new Zn);return}let n=()=>{clearTimeout(o),r(new Zn)},o=setTimeout(()=>{e?.removeEventListener("abort",n),t()},s);e?.addEventListener("abort",n,{once:!0})})}function ik(s){let e=$n(s);if(!(!e.ok||e.url.username!==""||e.url.password!=="")&&!(e.url.port!==""||!_f(e.url.hostname)))return e.url}function sk(s){return`Salesforce refused the device sign-in: ${s.error_description?`${s.error_description} (${s.error})`:s.error}`}var wd=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??QP}async authorize(e,t,r){let n=await this.post(e,{response_type:"device_code",client_id:t},r),o=ok.safeParse(n);if(o.success)throw new Error(sk(o.data));let i=KP.safeParse(n);if(!i.success)throw new Error("Salesforce answered the device sign-in without a usable code.");let a=ik(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,Xg);return{deviceCode:i.data.device_code,userCode:i.data.user_code,verificationUri:a.href,intervalMs:(i.data.interval??JP)*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 Zn;if(c instanceof yd)throw c;continue}let d=ok.safeParse(a);if(d.success){if(d.data.error==="authorization_pending")continue;if(d.data.error==="slow_down"){o+=VP;continue}throw new Error(sk(d.data))}return ZP(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 Zn;let n=AbortSignal.timeout(XP),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 Zn:a}let i=await o.text();try{return JSON.parse(i)}catch{throw new yd(`Salesforce answered HTTP ${o.status} with a page instead of JSON. Check the login URL.`)}}};function ZP(s){let e=YP.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=ik(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 Cr=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 eC,readdir as tC}from"node:fs/promises";import{join as ak}from"node:path";var rC=/^[^.][^@/\\]*@[^/\\]+\.json$/;async function dk(s,e=Date.now()){let t=ak(s,".sfdx"),r;try{r=await tC(t)}catch{return 0}let n=new Set;return await Promise.all(r.filter(o=>rC.test(o)&&!o.endsWith(".partial.json")).map(async o=>{let i=await nC(ak(t,o),e);i&&n.add(i)})),n.size}async function nC(s,e){try{let t=JSON.parse(await eC(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 oC}from"node:os";var sC=new Set(["org:list","org:connect","org:connect:cancel","org:disconnect","org:select","org:update","org:open-in-browser","org:cli-status"]),ck=15e3,lk="The Salesforce CLI holds no connected org yet. Use Log in with your browser on the Organizations page: it opens the Salesforce login page.",bd=class{constructor(e,t={}){this.deps=e;this.browser=t.browser??new Cr,this.deviceLogin=t.deviceLogin??new wd,this.countCliOrgs=t.countCliOrgs??(()=>dk(oC())),this.connectTo=t.connectTo??(r=>Xf(r))}deps;browser;deviceLogin;countCliOrgs;connectTo;pendingSignIns=new Map;async handle(e){if(!sC.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=T(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=T(this.deps,e,"org:list:response",{orgs:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id}`)}async handleOrgConnect(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Iy,e,"org:error",this.deps);if(!t)return;let r=t;switch(r.authMethod){case"sfdx_import":await this.handleSfdxImport(e);break;case"usernamePassword":await this.handleUsernamePassword(e,r);break;case"oauth_web":await this.handleOAuthWeb(e,r);break;case"jwt":await this.handleJwt(e);break;case"oauth_device":await this.handleOAuthDevice(e);break;default:Ie(this.deps,"warning","Auth Method",`${r.authMethod} is not yet supported.`),this.failConnect(e,`${r.authMethod} is not yet supported.`,"UNSUPPORTED_AUTH");break}this.syncOrgState()}failConnect(e,t,r){E(this.deps,"org:connect","org:error",e,new Error(t),{code:r,retryable:!1})}notifyCliMissing(e){Ie(this.deps,"error","Salesforce CLI",`${us} ${e}`,{actions:[{label:"Install the CLI",command:"sf-cli-install",url:Vg}]})}ackConnect(e,t){let r=T(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,us,"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",lk,{autoDismissMs:null,code:"NO_CLI_ORGS"}),this.failConnect(e,lk,"NO_CLI_ORGS");return}let o=await this.saveImported(n),i=this.deps.orgManager.getAllOrgs(),a=T(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=>`${me(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 zf(this.connectTo({instanceUrl:o,accessToken:n,version:t.metadata.apiVersion}).then(l=>zi(l)),ck,`the org did not answer within ${ck/1e3} s`),a=Wn({isSandbox:i.sandbox,edition:i.edition}),{safetyTier:d,color:c}=_r(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=Wn({isSandbox:o.isSandbox,edition:o.orgType}),{safetyTier:a,color:d}=_r(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:fo.DEFAULT_API_VERSION,edition:o.orgType,features:[]},status:"connected",lastConnected:new Date().toISOString(),tags:[]},l=this.deps.authProvider.buildConnectionConfig({method:"usernamePassword",loginUrl:r,username:t.username,password:t.password,securityToken:t.securityToken},n);await this.deps.orgRegistry.saveOrg(c,l);let u=T(this.deps,e,"org:statusChanged",{orgId:c.id,status:"connected"});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`),Ie(this.deps,"success","Connected",`${me(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=Wi(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,us,"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=x(Ay,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=x(Ty,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=T(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=x(Ey,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,us,"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,`${me(n.org)} connected.`),this.ackConnect(e,o??n.org.id)}async handleOrgDisconnect(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Py,e,"org:error",this.deps);if(!t)return;let r=t;bo().remove(r.orgId),await this.deps.orgRegistry.removeOrg(r.orgId);let n=T(this.deps,e,"org:statusChanged",{orgId:r.orgId,status:"disconnected"});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`),this.syncOrgState()}handleOrgSelect(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Cy,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=T(this.deps,e,"org:selected",{orgId:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleOrgUpdate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(xy,e,"org:error",this.deps);if(!t)return;let r=this.deps.orgManager.getOrg(t.orgId);if(!r){E(this.deps,"org:update","org:error",e,new Error(`Unknown org: ${t.orgId}`),{code:"ORG_NOT_FOUND",retryable:!1});return}try{this.deps.orgRegistry.updateOrgMetadata({...r,alias:t.alias,appearance:{...r.appearance,color:t.color},tags:t.tags,...t.staging!==void 0?{staging:t.staging}:{}})}catch(o){E(this.deps,"org:update","org:error",e,o,{code:"ORG_UPDATE_FAILED",retryable:!0});return}let n=T(this.deps,e,"org:list:response",{orgs:this.deps.orgManager.getAllOrgs()});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`),this.syncOrgState()}async handleOpenInBrowser(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x($y,e,"org:error",this.deps);if(!t)return;let r=this.deps.orgManager.getOrg(t.orgId);if(!r){E(this.deps,"org:open-in-browser","org:error",e,new Error(`No registered org has the id "${t.orgId}".`),{code:"ORG_NOT_FOUND",retryable:!1});return}let n=$n(r.instanceUrl);if(!n.ok){let a=n.reason==="not-https"?`its instance URL must use HTTPS, got "${n.protocol}"`:"its instance URL is not a valid URL";E(this.deps,"org:open-in-browser","org:error",e,new Error(`Cannot open "${me(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=T(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 iC(s){let e=ef.safeParse(s.services?.getSandforgeSetting?.("forge.graphView","auto"));return e.success?e.data:"auto"}function aC(s){return s.services?.getSandforgeSetting?.("grappe.enabled",!1)===!0}var dC=new Set(["settings:get","settings:update","telemetry:status","telemetry:toggle"]),Rd=class{constructor(e){this.deps=e}deps;async handle(e){if(!dC.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:iC(this.deps),grappeEnabled:aC(this.deps)}}handleSettingsGet(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=T(this.deps,e,"settings:response",this.settingsPayload());this.deps.broker.postToWebview(t),this.deps.log(`[TX] ${t.type} id=${t.id}`)}handleSettingsUpdate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Dy,e,"settings:error",this.deps);if(!t)return;let r=t;this.deps.configStore.set(r.key,r.value,"settings");let n=T(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=T(this.deps,e,"telemetry:status:response",{enabled:t,eventCount:r});this.deps.broker.postToWebview(n)}async handleTelemetryToggle(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Ny,e,"settings:error",this.deps);if(!t)return;let{enabled:r}=t;if(!this.deps.services?.setSandforgeSetting){let n=T(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=T(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=T(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 Op={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"}},Ip=1,uk=.15,cC=.55;function pk(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 lC(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 Ap(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 gk(s){switch(s){case"up":return"degrading";case"down":return"improving";case"stable":return"stable"}}function fk(s){return s.direction!=="up"?0:Math.min(15,Math.max(0,Math.abs(s.changePercent)*.5))}function ri(s){return s>=70?"healthy":s>=40?"warning":"critical"}function hk(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 mk(s){let e=s.max-s.remaining;return`${s.usedPercent}% used (${e.toLocaleString()} / ${s.max.toLocaleString()})`}var Sd=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((g,h)=>({weightedSum:g.weightedSum+h.score*h.weight,totalWeight:g.totalWeight+h.weight}),{weightedSum:0,totalWeight:0}),d=a>0?Math.round(i/a):100,c=this.scoreToOverallStatus(d),u=[...t].sort((g,h)=>g.score-h.score).filter(g=>g.status!=="healthy").slice(0,3),p=this.buildSummary(c,u);return{overallScore:d,overallStatus:c,factors:t,summary:p,topRisks:u}}countOptionalDimensions(e){let t=0;return(e.metadataCounts!==void 0||e.orgInfo!==void 0)&&t++,e.codeCoverage!==void 0&&t++,e.securitySettings!==void 0&&t++,t}computeLimitsWeightMultiplier(e){if(e===0)return Ip;let t=e*uk;return Math.max(cC,Ip-t)}computeOptionalDimensionWeight(e){return e===0?0:uk}addCoreLimitFactors(e,t,r){for(let[n,o]of Object.entries(Op)){let i=e.limits.find(p=>p.name===n);if(!i)continue;let a=pk(i.usedPercent),d=this.fetchTrendData(e,n),c=d?gk(d.direction):"stable",l=d?fk(d):0,u=Math.max(0,Math.round(a-l));t.push({name:i.name,category:o.category,score:u,weight:o.weight*r,status:ri(u),detail:mk(i),recommendation:hk(i.name,i.usedPercent),trend:c})}}addRemainingLimitFactors(e,t,r){let n=new Set(Object.keys(Op)),o=e.limits.filter(c=>!n.has(c.name)&&c.usedPercent>0);if(o.length===0)return;let i=Object.values(Op).reduce((c,l)=>c+l.weight,0),d=Math.max(0,(Ip-i)*r)/o.length;for(let c of o){let l=pk(c.usedPercent),u=this.fetchTrendData(e,c.name),p=u?gk(u.direction):"stable",g=u?fk(u):0,h=Math.max(0,Math.round(l-g));t.push({name:c.name,category:"limits",score:h,weight:d,status:ri(h),detail:mk(c),recommendation:hk(c.name,c.usedPercent),trend:p})}}addMetadataDimension(e,t,r){if(e.metadataCounts===void 0&&e.orgInfo===void 0)return;let n=e.metadataCounts?.customObjectCount??e.orgInfo?.customObjectCount??0,o=e.metadataCounts?.customFieldCount??0,i=e.metadataCounts?.apexClassCount??e.orgInfo?.apexClassCount??0,a=Math.round(Ap(n,50,500)*.4+Ap(o,200,2e3)*.3+Ap(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:ri(a),detail:d,recommendation:c,trend:"stable"})}addCoverageDimension(e,t,r){if(e.codeCoverage===void 0)return;let n=lC(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:ri(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:ri(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 uC=Re(G({version:j()}));function yk(s){let e=uC.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 pC(s){if(!s)return;let e=new Date(s);return Number.isNaN(e.getTime())?void 0:e.toISOString()}var vd=class{cache=new Map;cacheTtlMs;constructor(e=300*1e3){this.cacheTtlMs=e}async fetch(e,t){let r=this.cache.get(e);if(r&&Date.now()-r.fetchedAt<this.cacheTtlMs)return r.data;let[n,o,i,a,d,c]=await Promise.all([t.latestApiVersion(),t.queryOrg(),t.queryCount("SELECT COUNT() FROM User WHERE IsActive = true"),t.queryCount("SELECT COUNT() FROM EntityDefinition WHERE DeploymentStatus != null AND QualifiedApiName LIKE '%__c'"),t.queryCount("SELECT COUNT() FROM ApexClass"),t.queryCount("SELECT COUNT() FROM FlowDefinitionView WHERE IsActive = true")]),l=o.namespacePrefix||void 0,u=pC(o.createdDate),p={name:o.name,orgId:o.orgId,type:o.type,edition:o.edition,instanceName:o.instanceName,apiVersion:n,userCount:i,customObjectCount:a,apexClassCount:d,flowCount:c,...l!==void 0?{namespacePrefix:l}:{},...u!==void 0?{createdDate:u}:{}};return this.cache.set(e,{data:p,fetchedAt:Date.now()}),p}clearCache(e){e?this.cache.delete(e):this.cache.clear()}};function wk(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 Tp=1440*60*1e3,bk=7*Tp,gC=500*1024,fC=900*1e3,hC=2,mC="trends",yC=new Set(xi),wC=Tp,Od=class{configStore;lastSaveTimestamps=new Map;constructor(e){this.configStore=e}trendKey(e){return`trend:${e}`}record(e,t){let r=Date.now();this.isRateLimited(e,r)||this.append(e,this.read(e),t,r)}recordAndGetTrends(e,t,r){let n=Date.now(),o=this.read(e),a=(this.isRateLimited(e,n)?o:this.append(e,o,t,n)).filter(l=>l.timestamp>=kd(n-bk)),d=a.filter(l=>l.timestamp>=kd(n-wC)),c={};for(let l of r)c[l]=this.computeTrend(l,a,d);return c}getHistory(e,t=Tp){let r=kd(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)<fC}append(e,t,r,n){let o=kd(n-bk),i=[...t,r].filter(d=>d.timestamp>=o).map(d=>({...d,limits:d.limits.filter(c=>yC.has(c.name))})),a=this.trimToSizeLimit(i);return this.configStore.set(this.trendKey(e),a,mC),this.lastSaveTimestamps.set(e,n),a}computeTrend(e,t,r){let{values:n,timestamps:o}=Rk(e,t),{values:i}=Rk(e,r);if(i.length<2)return{limitName:e,direction:"stable",changePercent:0,sparklineData:n,timestamps:o};let a=i[0],d=i[i.length-1],c=d-a,l;Math.abs(c)<=hC?l="stable":c>0?l="up":l="down";let u;if(l==="up"&&d<100){let p=this.getTimeSpanMs(r);if(p>0){let g=c/p;if(g>0){let f=(100-d)/g;u=Math.round(f/(3600*1e3)*10)/10}}}return{limitName:e,direction:l,changePercent:Math.round(c*10)/10,predictedTimeToLimit:u,sparklineData:n,timestamps:o}}getTimeSpanMs(e){if(e.length<2)return 0;let t=new Date(e[0].timestamp).getTime();return new Date(e[e.length-1].timestamp).getTime()-t}trimToSizeLimit(e){let t=[...e];for(;t.length>0&&!(new TextEncoder().encode(JSON.stringify(t)).length<=gC);)t.shift();return t}};function kd(s){return new Date(s).toISOString()}function Rk(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 Id=class{onNotify;definitions=new Map;activeAlerts=new Map;lastTriggered=new Map;constructor(e){this.onNotify=e}addDefinition(e){this.definitions.set(e.id,e)}removeDefinition(e){this.definitions.delete(e)}getDefinitions(){return[...this.definitions.values()]}evaluate(e,t,r){for(let n of this.definitions.values()){if(!n.enabled||n.metric!==e||!bC(n.condition,t))continue;let o=`${n.id}:${r}`;if(this.isInCooldown(n,o))continue;let i=this.createAlert(n,t,r);return this.activeAlerts.set(i.id,i),this.lastTriggered.set(o,Date.now()),this.onNotify(i),i}return null}getActiveAlerts(){return[...this.activeAlerts.values()].filter(e=>e.status==="active"||e.status==="acknowledged")}acknowledgeAlert(e){let t=this.activeAlerts.get(e);t&&(t.status="acknowledged",t.acknowledgedAt=new Date().toISOString())}resolveAlert(e){let t=this.activeAlerts.get(e);t&&(t.status="resolved",t.resolvedAt=new Date().toISOString())}restoreAlerts(e){for(let t of e)if(t.status==="active"||t.status==="acknowledged"){this.activeAlerts.set(t.id,t);let r=`${t.definitionId}:${t.orgId}`,n=Date.parse(t.triggeredAt);!Number.isNaN(n)&&n>(this.lastTriggered.get(r)??0)&&this.lastTriggered.set(r,n)}}dismissAlert(e){let t=this.activeAlerts.get(e);t&&(t.status="dismissed")}isInCooldown(e,t){let r=this.lastTriggered.get(t);if(r===void 0)return!1;let n=e.cooldownMinutes*60*1e3;return Date.now()-r<n}createAlert(e,t,r){return{id:`alert-${globalThis.crypto.randomUUID()}`,definitionId:e.id,severity:e.severity,status:"active",message:`${e.name}: ${e.metric} is ${t} (threshold: ${e.condition.threshold})`,currentValue:t,threshold:e.condition.threshold,orgId:r,triggeredAt:new Date().toISOString()}}};function bC(s,e){switch(s.operator){case"gt":return e>s.threshold;case"gte":return e>=s.threshold;case"lt":return e<s.threshold;case"lte":return e<=s.threshold;case"eq":return e===s.threshold;case"neq":return e!==s.threshold}}var Vo="alert:state:",Ep="alerts";var Ad=class{constructor(e){this.configStore=e}configStore;saveAlerts(e){this.configStore.set(`${Vo}active`,e,Ep)}loadAlerts(){let e=this.configStore.get(`${Vo}active`);return Array.isArray(e)?e:[]}saveDefinitions(e){this.configStore.set(`${Vo}definitions`,e,Ep)}loadDefinitions(){let e=this.configStore.get(`${Vo}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(`${Vo}history`,i,Ep)}loadHistory(){let e=this.configStore.get(`${Vo}history`);return Array.isArray(e)?e:[]}};var Pp=[{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 Td=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 Ed=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 Pd=class{fetchLogs;analyses=new Map;truncatedCache=new Map;constructor(e){this.fetchLogs=e}analyze(e){let t=RC(e),r=SC(e),n=vC(e),o=e.durationMs,i=kC(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 RC(s){return Math.min(Math.floor(s.logSize/500),100)}function SC(s){return Math.min(Math.floor(s.logSize/1e3),150)}function vC(s){return Math.min(s.logSize*10,6e6)}function kC(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 OC=new Set(pf);function vk(s){return typeof s=="string"&&OC.has(s)?s:"Unknown"}function IC(){let s=new Map;return{load:e=>s.get(e),save:(e,t)=>{s.set(e,t)}}}function Sk(s){return`${s.sandboxName}:${s.refreshDate}`}var Cd=class{querySandboxes;onRefreshDetected;seen;refreshCache=new Map;supportedCache=new Map;truncatedCache=new Map;constructor(e,t,r=IC()){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(Sk(c))||this.onRefreshDetected?.(c)}let a=o.map(Sk);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=>gf(r.status))}};var $d=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 kk=new Set(["Queued","Processing"]),xd=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=>kk.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=>kk.has(r.status)).length,completed:t.filter(r=>r.status==="Completed").length,failed:t.filter(r=>r.status==="Failed").length}}};var AC=3e4,TC=1440*60*1e3,Ok=100,Ik=50,Ak=20,Tk="sandbox-process-seen:";function EC(s){return{load:e=>{let t=s.get(`${Tk}${e}`);return Array.isArray(t)?t.filter(r=>typeof r=="string"):void 0},save:(e,t)=>{s.set(`${Tk}${e}`,t,"sandbox-refresh")}}}function PC(s){return s instanceof wo?s.code==="ORG_AUTH_EXPIRED":Uf(s)||Gl(s)!==void 0}function ni(s){let e=Gl(s);return e!==void 0&&!(s instanceof wo)?`the org could not be reached (${e})`:I(s)}function Ek(s){let e=new Od(s.configStore),t=async(b,v,C)=>{try{return await C(await s.getConnection(b))}catch(S){if(!PC(S))throw S;s.log(`[WARN] monitor:${v} ${b}: ${ni(S)}; read again on a new connection`);try{return await C(await s.getConnection(b,{again:!0}))}catch(A){throw A instanceof wo&&A.code==="ORG_TEMPORARILY_UNREACHABLE"?S:A}}},r=new Ad(s.configStore),n=new Id(b=>{s.log(`[ALERT] ${b.severity}: ${b.message}`);let v=b.severity==="critical"?"error":"warning";s.notify(v,b.message),r.saveAlerts(n.getActiveAlerts())}),o=r.loadDefinitions(),i=o.length>0?o:Pp;for(let b of i)n.addDefinition(b);o.length===0&&r.saveDefinitions(Pp);let a=r.loadAlerts();n.restoreAlerts(a);let d=new Td(async(b,v)=>{let C=await s.getConnection(b),{records:S,truncated:A}=await Is(C,`SELECT Id, Operation, Status, DurationMilliseconds, LogLength, StartTime, LogUser.Username FROM ApexLog WHERE Status != 'Success' AND StartTime > ${v} ORDER BY StartTime DESC LIMIT ${Ik}`,Ik);return $e(C.limitInfo,"monitor:error-logs apexLog"),{records:S.map(D=>({id:D.Id,errorType:D.Status,message:`${D.Operation} - ${D.Status}`,timestamp:D.StartTime,user:D.LogUser?.Username??void 0,context:D.Operation})),truncated:A}}),c=async(b,v)=>{let C=await b.query(`SELECT COUNT() FROM ApexLog WHERE Status != 'Success' AND StartTime > ${v}`);return $e(b.limitInfo,"monitor:refresh apexLogCount"),C.totalSize},l=new Ed(async b=>{let v=await s.getConnection(b),{records:C,truncated:S}=await Is(v,`SELECT Id, UsersId, Users.Username, LoginType, SessionType, CreatedDate, SourceIp FROM AuthSession ORDER BY CreatedDate DESC LIMIT ${Ok}`,Ok);return $e(v.limitInfo,"monitor:sessions authSession"),{records:C.map(A=>({sessionId:A.Id,userId:A.UsersId,username:A.Users?.Username??A.UsersId,sessionType:A.SessionType??A.LoginType??"Unknown",loginTime:A.CreatedDate,sourceIp:A.SourceIp??""})),truncated:S}}),u=new Pd(async(b,v)=>{let C=await s.getConnection(b),{records:S,truncated:A}=await Is(C,`SELECT Id, Operation, Status, DurationMilliseconds, LogLength, StartTime, LogUser.Username FROM ApexLog ORDER BY StartTime DESC LIMIT ${v}`,v);return $e(C.limitInfo,"monitor:apex-insights apexLog"),{records:S.map(D=>({id:D.Id,operation:D.Operation??"Unknown",status:D.Status,durationMs:D.DurationMilliseconds??0,logSize:D.LogLength??0,startTime:D.StartTime,user:D.LogUser?.Username??"Unknown"})),truncated:A}}),p=new Set,g=new Cd(async b=>{if(p.has(b))return{supported:!1,events:[],truncated:!1};let v=await s.getConnection(b),C;try{C=await Is(v,`SELECT Id, SandboxName, Status, CreatedDate, Description FROM SandboxProcess ORDER BY CreatedDate DESC LIMIT ${Ak}`,Ak)}catch(S){let A=S instanceof Error?S.message:String(S);if(A.includes("SandboxProcess")&&A.includes("not supported"))return p.add(b),{supported:!1,events:[],truncated:!1};throw S}return $e(v.limitInfo,"monitor:sandbox-refresh sandboxProcess"),{supported:!0,events:C.records.map(S=>({orgId:b,sandboxName:S.SandboxName??"Unknown",refreshDate:S.CreatedDate,status:vk(S.Status),sourceOrg:S.Description??void 0})),truncated:C.truncated}},b=>s.onSandboxRefreshCompleted?.(b),EC(s.configStore)),h=new Map,f=async(b,v)=>{let C=h.get(b);if(C&&Date.now()-C.fetchedAt<AC)return C.data;let S=await v.request(`/services/data/${ho}/limits`);return h.set(b,{data:S,fetchedAt:Date.now()}),S},m=async b=>{try{let C=(await t(b,"apiLimits",D=>f(b,D))).DailyApiRequests;if(!C||!C.Max)return{name:"apiLimits",status:"unknown",score:0,message:"No API limit reported"};let S=Math.round((C.Max-C.Remaining)/C.Max*100);return{name:"apiLimits",status:S>80?"critical":S>60?"warning":"ok",score:100-S,message:`API usage at ${S}%`,percent:S}}catch(v){return{name:"apiLimits",status:"unknown",score:0,message:`Unable to fetch limits: ${ni(v)}`}}},y=async b=>{try{let C=(await t(b,"storage",D=>f(b,D))).DataStorageMB;if(!C||!C.Max)return{name:"storage",status:"unknown",score:0,message:"No storage limit reported"};let S=Math.round((C.Max-C.Remaining)/C.Max*100);return{name:"storage",status:S>85?"critical":S>70?"warning":"ok",score:100-S,message:`Storage usage at ${S}%`,percent:S}}catch(v){return{name:"storage",status:"unknown",score:0,message:`Unable to fetch storage: ${ni(v)}`}}},R=async b=>{let v;try{let A=new Date(Date.now()-TC).toISOString();v=await t(b,"recentErrors",D=>c(D,A))}catch(A){return{name:"recentErrors",status:"unknown",score:0,message:`Unable to fetch error logs: ${ni(A)}`}}let C=Math.max(0,100-v*5);return{name:"recentErrors",status:v>10?"critical":v>3?"warning":"ok",score:C,count:v,message:`${v} recent errors`}},k=async b=>{let v=await Nt(b,`SELECT Id, JobType, Status, NumberOfErrors, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${pn.monitorJobs}`);return $e(b.limitInfo,"monitor:refresh asyncJobs"),v.map(C=>({id:C.Id,jobType:C.JobType??"Batch",status:C.Status,createdBy:C.CreatedById,createdDate:C.CreatedDate,failedRecords:C.NumberOfErrors}))},w=new xd(b=>t(b,"activeJobs",k)),O=async b=>{try{await w.fetch(b);let v=w.getJobStats(b),C=Math.max(0,100-v.failed*10);return{name:"activeJobs",status:v.failed>5?"critical":v.failed>0?"warning":"ok",score:C,count:v.failed,outOf:v.total,message:`${v.active} active, ${v.failed} failed of ${v.total} recent jobs`}}catch(v){return{name:"activeJobs",status:"unknown",score:0,message:`Unable to fetch jobs: ${ni(v)}`}}},P=new $d([m,y,R,O]);return{trendStorage:e,alertStateStore:r,alertEngine:n,errorLogMonitor:d,userSessionMonitor:l,apexLogAnalyzer:u,sandboxRefreshTracker:g,healthCheck:P,healthSignals:{apiLimits:m,storage:y,recentErrors:R,activeJobs:O},getOrFetchLimits:f,forgetOrg:b=>{h.delete(b)}}}var Pk=25e3,Ck=20,CC=20,$C=20,xC=500,Dk=`SELECT Id, JobType, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${pn.monitorJobs}`,DC=`SELECT Id, JobType, Status, NumberOfErrors, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${pn.monitorJobs}`,NC=new Set([Dk,DC]),jC=new Set(["Queued","Preparing","Processing"]),MC=new Set(["BatchApex","Queueable","Future"]),oi=3600*1e3,$k=oi,xk=3;function Cp(s){let e=Math.floor(s/60),t=s%60;return e>0?`${e}h${String(t).padStart(2,"0")}m`:`${t}m`}function LC(s,e){return s.status===e.status&&s.batchesProcessed===e.batchesProcessed&&s.totalBatches===e.totalBatches}function FC(s,e,t){let r=new Map;for(let n of e){let o=s?.get(n.id);if(o!==void 0&&LC(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 _C(s,e,t){let r=[],n=[],o=[];for(let a of s){if(!jC.has(a.status)||!MC.has(a.jobType))continue;let d=e.get(a.id),c=d===void 0?null:t-d.unchangedSinceMs,l=a.batchesProcessed,u=a.totalBatches;if(a.status==="Processing"&&l!==null&&u!==null&&l<u&&c!==null&&c>=oi){n.push({job:a,stillMs:c,done:l,total:u});continue}if(d?.movedWhileWatched===!0&&c!==null&&c<oi)continue;let p=t-Date.parse(a.createdDate);p>=$k&&o.push({job:a,ageMs:p,stillMs:c})}n.sort((a,d)=>d.stillMs-a.stillMs);for(let{job:a,stillMs:d,done:c,total:l}of n){let u=Cp(Math.floor(d/6e4));r.push({type:"stuck",severity:"critical",title:`${a.jobType} ${a.id}: no batch completed in ${u}`,detail:`${c} of ${l} batches processed, unchanged across ${u} of observation by this dashboard while ${a.status} (stall bound ${oi/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<xk)continue;let c=d.reduce((l,u)=>l+(u.failedRecords||0),0);r.push({type:"frequent_failures",severity:"critical",title:`${d.length} ${a} jobs failed`,detail:`${d.length} of the last ${s.length} jobs are ${a} failures (${c} failed batch execution(s) reported) \u2014 at or above the ${xk}-failure pattern threshold.`,affectedJobs:d.map(l=>l.id),recommendation:`Open the most recent ${a} failure and read its extended status: a repeat at this rate is a defect or a data problem, not contention.`})}if(o.length>0){o.sort((p,g)=>g.ageMs-p.ageMs);let a=o[0],d=Cp(Math.floor(a.ageMs/6e4)),{batchesProcessed:c,totalBatches:l}=a.job,u=c===null||l===null||l<=0?"it reports no batch counter, so its progress cannot be observed":a.stillMs===null||a.stillMs<6e4?`${c} of ${l} batches processed, first seen at these values on this refresh`:`${c} of ${l} batches processed, unchanged over the ${Cp(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 ${$k/6e4}m or more after submission`,detail:`${a.job.jobType} ${a.job.id} is ${a.job.status}, submitted ${d} ago; ${u}. Time since submission includes time spent queued: it is not evidence of a stall.`,affectedJobs:o.map(({job:p})=>p.id),recommendation:`Keep this dashboard refreshing to measure progress, or check the job in Setup > Apex Jobs. A batch is called stuck only once its batch counter stays unchanged for ${oi/6e4}m of watching; a job without batch counters never is.`})}return r}var HC=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"]),Dd=class{constructor(e,t){this.deps=e;this.externalBrowser=t??new Cr;let r=Ek({configStore:e.configStore,log:n=>e.log(n),notify:(n,o)=>Ie(e,n,"Alert",o),getConnection:async(n,o)=>(o?.again===!0&&bo().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 vd;healthCalculator=new Sd;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)},xC),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(!HC.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&&NC.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 ${Pk}ms bound; skipping ${t}`),!0):!1}async handleRefresh(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Gr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{await new ge(Pk).withTimeout("monitor:refresh",n=>this.executeRefresh(e,r,n))}catch(n){E(this.deps,"monitor:refresh","monitor:error",e,n)}}async executeRefresh(e,t,r){try{let n=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),[o,i]=await Promise.allSettled([this.getOrFetchLimits(t.orgId,n),Nt(n,Dk)]);if(o.status==="rejected")throw o.reason;let a=wk(o.value);$e(n.limitInfo,"monitor:refresh limits");let d=[];for(let b of a){let v=this.alertEngine.evaluate(b.name,b.usedPercent,t.orgId);v&&d.push(v)}if(this.alertStateStore.saveAlerts(this.alertEngine.getActiveAlerts()),d.length>0&&this.alertStateStore.saveHistory(d),i.status==="rejected")throw i.reason;let c=i.value;if($e(n.limitInfo,"monitor:refresh asyncJobs"),this.inFlightJobRecords.set(t.orgId,c),this.pastDeadline(r,"org info and health check"))return;let l=Date.now(),u=c.map(b=>({id:b.Id,jobType:b.JobType??"Unknown",status:b.Status,createdBy:b.CreatedById,createdDate:b.CreatedDate,failedRecords:b.NumberOfErrors,batchesProcessed:b.JobItemsProcessed??null,totalBatches:b.TotalJobItems??null})),p=c.length>=pn.monitorJobs,g=u.map(({id:b,jobType:v,status:C,createdBy:S,createdDate:A,failedRecords:D})=>({id:b,jobType:v,status:C,createdBy:S,createdDate:A,failedRecords:D})),h=FC(this.jobProgress.get(t.orgId),u,l);this.jobProgress.set(t.orgId,h);let f=_C(u,h,l),m={orgId:t.orgId,limits:a,timestamp:new Date().toISOString()},y=this.trendStorage.recordAndGetTrends(t.orgId,m,xi),[R,k]=await Promise.all([this.fetchOrgInfo(t.orgId,n),this.computeOrgHealth(t.orgId)]);R&&this.deps.sandboxRefreshes?.observe(t.orgId,{organizationId:R.orgId,instanceName:R.instanceName||void 0},"monitor");let w=this.healthCalculator.calculate({limits:a,orgId:t.orgId,trends:y,orgInfo:R}),O=w.overallScore;if(this.pastDeadline(r,"the monitor:data reply"))return;let P=T(this.deps,e,"monitor:data",{limits:a,jobs:g,jobsTruncated:p,healthScore:O,healthReport:w,trends:y,jobInsights:f,orgInfo:R,orgHealthStatus:k,lastUpdated:new Date().toISOString()});this.deps.broker.postToWebview(P),this.deps.log(`[TX] ${P.type} id=${P.id}`)}catch(n){if(this.pastDeadline(r,`the failure "${I(n)}"`))return;E(this.deps,"monitor:refresh","monitor:error",e,n)}finally{this.inFlightJobRecords.delete(t.orgId)}}async computeOrgHealth(e){try{return await this.healthCheck.computeHealth(e)}catch(t){this.deps.log(`[WARN] HealthCheck failed: ${String(t)}`);return}}async fetchOrgInfo(e,t){try{let r={latestApiVersion:async()=>yk(await t.request("/services/data")),queryOrg:async()=>{let n=this.deps.orgManager.getOrg(e),o=await Nt(t,"SELECT Name, Id, OrganizationType, InstanceName, NamespacePrefix, CreatedDate FROM Organization LIMIT 1");$e(t.limitInfo,"monitor:refresh orgInfo");let i=o[0];return{name:i?.Name??n?.alias??"",orgId:i?.Id??e,type:n?.orgType??"Production",edition:i?.OrganizationType??n?.metadata.edition??"",instanceName:i?.InstanceName??"",namespacePrefix:i?.NamespacePrefix,createdDate:i?.CreatedDate}},queryCount:async n=>(await t.query(n)).totalSize};return await this.orgInfoFetcher.fetch(e,r)}catch(r){this.deps.log(`[WARN] OrgInfo fetch failed: ${String(r)}`);return}}handleLiveOperations(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.liveOperationTracker?.getAll()??[],r=T(this.deps,e,"monitor:live-operations:response",{operations:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id}`)}async handleStorage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Gr,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/${ho}/limits/recordCount`);$e(n.limitInfo,"monitor:storage recordCount");let i=(o.sObjects??[]).filter(g=>g.count>0).sort((g,h)=>h.count-g.count),a=i.slice(0,$C),d=a.map(g=>g.name).filter(g=>/^[A-Za-z][A-Za-z0-9_]*$/.test(g)),c=new Map;if(d.length>0){let g=await Nt(n,`SELECT QualifiedApiName, Label FROM EntityDefinition WHERE QualifiedApiName IN (${d.map(h=>`'${h}'`).join(", ")})`);$e(n.limitInfo,"monitor:storage entityDefinition");for(let h of g)h.Label&&c.set(h.QualifiedApiName,h.Label)}let l=a.map(g=>({objectName:g.name,label:c.get(g.name)??g.name,recordCount:g.count})),u=i.reduce((g,h)=>g+h.count,0),p=T(this.deps,e,"monitor:storage:response",{success:!0,objects:l,totalRecords:u,objectCount:i.length});this.deps.broker.postToWebview(p),this.deps.log(`[TX] ${p.type} id=${p.id}`)}catch(n){E(this.deps,"monitor:storage","monitor:error",e,n)}}async handleDeployments(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Gr,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 ${Ck}`)).records;$e(n.limitInfo,"monitor:deployments deployRequest");let a=i.map(c=>({id:c.Id,status:c.Status,startDate:c.StartDate,completedDate:c.CompletedDate??void 0,createdBy:c.CreatedBy?.Name??"Unknown",componentCount:c.NumberComponentsTotal??0,errorCount:c.NumberComponentErrors??0})),d=T(this.deps,e,"monitor:deployments:response",{success:!0,deployments:a,truncated:i.length>=Ck});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(n){E(this.deps,"monitor:deployments","monitor:error",e,n)}}async handleApiUsage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Gr,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);$e(n.limitInfo,"monitor:api-usage limits");let i=["DailyApiRequests","DailyBulkApiBatches","DailyBulkV2QueryJobs","DailyBulkV2QueryFileStorageMB","DailyStreamingApiEvents","DailyGenericStreamingApiEvents","DailyDurableStreamingApiEvents","DailyAsyncApexExecutions","HourlyAsyncReportRuns","HourlyTimeBasedWorkflow","DailyWorkflowEmails","MassEmail","SingleEmail","HourlyPublishedPlatformEvents","DailyStandardVolumePlatformEvents"],a=[];for(let c of i){let l=o[c];if(l&&typeof l.Max=="number"){let u=l.Max-l.Remaining,p=l.Max>0?Math.round(u/l.Max*100):0;a.push({category:c,used:u,max:l.Max,usedPercent:p})}}a.sort((c,l)=>l.usedPercent-c.usedPercent);let d=T(this.deps,e,"monitor:api-usage:response",{success:!0,categories:a});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(n){E(this.deps,"monitor:api-usage","monitor:error",e,n)}}async handleOpenApexJobs(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x($m,e,"monitor:error",this.deps);if(!t)return;let r=this.deps.orgManager.getOrg(t.orgId);if(!r){E(this.deps,"monitor:open-apex-jobs","monitor:error",e,new Error(`No registered org has the id "${t.orgId}".`),{code:"ORG_NOT_FOUND"});return}let n=JS(r.instanceUrl);if(!n.ok){let o=n.reason==="not-https"?`its instance URL must use HTTPS, got "${n.protocol}"`:"its instance URL is not a valid URL";E(this.deps,"monitor:open-apex-jobs","monitor:error",e,new Error(`Cannot open Apex Jobs for "${me(r)}": ${o}.`),{code:"INVALID_INSTANCE_URL"});return}try{let o=await this.externalBrowser.open(n.url),i=T(this.deps,e,"monitor:open-apex-jobs:response",o);this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} status=${o.status}`)}catch(o){E(this.deps,"monitor:open-apex-jobs","monitor:error",e,o)}}async handleErrorLogs(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Gr,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=T(this.deps,e,"monitor:error-logs:response",{success:!0,errors:n,errorsByType:i,totalCount:n.length,truncated:this.errorLogMonitor.isTruncated(r.orgId)});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id}`)}catch(n){E(this.deps,"monitor:error-logs","monitor:error",e,n)}}async handleSessions(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Gr,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=T(this.deps,e,"monitor:sessions:response",{success:!0,sessions:n,activeUserCount:o,truncated:this.userSessionMonitor.isTruncated(r.orgId)});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(n){E(this.deps,"monitor:sessions","monitor:error",e,n)}}async handleApexInsights(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Gr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await this.apexLogAnalyzer.fetchAndAnalyze(r.orgId,CC),o=this.apexLogAnalyzer.getTopIssues(r.orgId),i=T(this.deps,e,"monitor:apex-insights:response",{success:!0,analyses:n,topIssues:o,truncated:this.apexLogAnalyzer.isTruncated(r.orgId)});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(n){E(this.deps,"monitor:apex-insights","monitor:error",e,n)}}async checkSandboxIdentity(e){let t=this.deps.sandboxRefreshes;if(!(!t||this.deps.orgManager.getOrg(e)?.orgType!=="Sandbox"))try{let r=await q(e,this.deps.orgRegistry,this.deps.orgManager),[n]=await Nt(r,"SELECT Id, InstanceName FROM Organization");$e(r.limitInfo,"monitor:sandbox-refresh organization"),n&&t.observe(e,{organizationId:n.Id,instanceName:n.InstanceName??void 0},"monitor")}catch(r){this.deps.log(`[WARN] monitor:sandbox-refresh identity check: ${I(r)}`)}}async handleSandboxRefresh(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Gr,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=T(this.deps,e,"monitor:sandbox-refresh:response",{success:!0,supported:this.sandboxRefreshTracker.isSupported(r.orgId),refreshes:n,inProgress:o,truncated:this.sandboxRefreshTracker.isTruncated(r.orgId),detected:this.deps.sandboxRefreshes?.refreshesOf(r.orgId)??[]});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(n){E(this.deps,"monitor:sandbox-refresh","monitor:error",e,n)}}handleAlerts(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.alertEngine.getActiveAlerts(),r=this.alertStateStore.loadHistory(),n=T(this.deps,e,"monitor:alerts:result",{alerts:t,history:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleAlertAcknowledge(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(iu,e,"monitor:error",this.deps);if(!t)return;let r=t;this.alertEngine.acknowledgeAlert(r.alertId),this.alertStateStore.saveAlerts(this.alertEngine.getActiveAlerts());let n=T(this.deps,e,"monitor:alert:acknowledge:response",{success:!0});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}handleAlertDismiss(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(iu,e,"monitor:error",this.deps);if(!t)return;let r=t;this.alertEngine.dismissAlert(r.alertId),this.alertStateStore.saveAlerts(this.alertEngine.getActiveAlerts());let n=T(this.deps,e,"monitor:alert:dismiss:response",{success:!0});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}};var $p="seed:template:",Nk="seedTemplates",on=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${$p}${e.id}`,e,Nk)}load(e){return this.configStore.get(`${$p}${e}`)}list(){let e=this.configStore.getByCategory(Nk);return Object.values(e).sort((r,n)=>n.updatedAt.localeCompare(r.updatedAt))}delete(e){return this.configStore.delete(`${$p}${e}`)}};var Nd=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 jk=[{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"]}}}],jd=class{customPersonas=new Map;customCounter=0;getBuiltInPersonas(){return[...jk]}getPersona(e){let t=jk.find(r=>r.id===e);return t||this.customPersonas.get(e)}async createCustomPersona(e,t){let r=BC(e),n=await t(r),o=WC(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())}},Mk=zg(s=>typeof s=="string"&&s.trim().length>0?Number(s):s,Te().finite()),eo=Mk.optional().catch(void 0),xp=j().min(1).optional().catch(void 0),Dp={faker:G({method:j().transform((s,e)=>{let t=hf(s);return t||(e.addIssue({code:Gg.custom,message:`unknown faker method ${s}`}),qg)}),locale:xp}),random_pick:G({values:Re(Wg([j(),Te(),Ge()]).transform(String)).min(1)}),weighted_pick:G({values:Pi(j(),Mk).refine(s=>Object.keys(s).length>0)}),range:G({min:eo,max:eo,currency:xp}),sequence:G({prefix:xp,start:eo,step:eo,padLength:eo}),pattern:G({pattern:j().min(1)}),ai_generate:G({prompt:j().min(1)}),relative_date:G({minDaysFromNow:eo,maxDaysFromNow:eo})},UC={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 BC(s){let e=Object.keys(Dp);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}: ${UC[r]}`),"",`Faker methods: ${ff.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(`
15
+ `)}function qC(s){let e=s.generator;if(typeof e!="string"||!Object.hasOwn(Dp,e))return null;let r=Dp[e].safeParse(s.params??{});if(!r.success)return null;let n=typeof s.fieldType=="string"?s.fieldType:"string";return e==="ai_generate"&&!df(n)?null:{fieldType:n,generator:e,params:r.data,examples:Array.isArray(s.examples)?s.examples.filter(o=>typeof o=="string"):[]}}function WC(s){let e;try{e=sf(af,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=qC(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 Xo="SEED_WRITE_DECLINED",Lk=6e4;function sn(s){let e=s?.read.gate.audit;return e===void 0?{}:{details:{deliverability:e,...s?.accepted===!0?{confirmed:"emails"}:{}}}}var Bk="the checkpoints of this window are not open to the Seed page",Wt=class extends Error{constructor(t,r,n){super(r);this.code=t;this.refusal=n;this.name="SeedCheckpointStopped"}code;refusal};async function si(s,e){try{if(!s)throw new Error(Bk);return{ask:e,planned:await s.scope(e,{})}}catch(t){throw new Wt(In,wr(t))}}async function ii(s,e,t,r,n){let o=await Da(async()=>{if(!s)throw new Error(Bk);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,Po(i))})});if("stop"in o)throw new Wt(o.stop.code,o.stop.message,o.stop.refusal);return o.checkpoint}async function xn(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 ai(s,e){let t=new Set(s);return(r,n)=>t.has(r)&&(n==="insert"||e&&n==="update")}function Fd(s,e){return typeof s.unread=="string"?{firing:[]}:qr(s,void 0,e)}function Fk(s,e,t){return t==="refuse"?{code:St.unanswered,message:`The seed needed an answer before it wrote \u2014 ${e} delivers the emails what still runs sends, or would not say whether it does \u2014 and no Approval step before it approved the run: put one before it. Nothing was written.`}:{code:Bb,message:s.gate.stop?.message??"The seed was refused for its emails. Nothing was written."}}var zC={ask:(s,e)=>s.confirmRun(e),unanswered:"goOn"};function GC(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 _k(s,e){return`The seed needed an answer before it wrote \u2014 ${GC(s,e)} \u2014 and no Approval step before it approved the run: put one before it. Nothing was written.`}function Hk(s,e,t){if(bs(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 Md=1e3;function JC(s){return Array.isArray(s.objectResults)?{...s,objectResults:s.objectResults.map(e=>{let t=e.createdIds.length>Md||e.errors.length>Md;return t?{...e,createdIds:e.createdIds.slice(0,Md),errors:e.errors.slice(0,Md),truncated:t}:e})}:s}function Uk(s){return{query:async e=>s.tooling.query(e),queryMore:async e=>s.tooling.queryMore(e)}}function VC(s){return s.objectResults.flatMap(t=>t.errors)[0]??"The seed wrote no records."}var XC=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"]),Ld=class{constructor(e){this.deps=e;this.seedTemplateStore=new on(e.configStore),this.templateManager=new Nd(()=>crypto.randomUUID(),()=>new Date().toISOString(),this.seedTemplateStore),this.personaManager=new jd}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-DIL62SUN.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 td({org:n,objects:r,writes:o,readAutomation:c=>i===void 0?new ge(Lk).withTimeout("seed automation",()=>d.read(e,c)):typeof i.unread=="string"?Promise.reject(new Error(i.unread)):Promise.resolve(i),readLimits:()=>Sr(t),...a?{deliverability:a}:{},...i===void 0?{readDeliverability:()=>Ce(this.deps.orgManager.getOrg(e))==="production"?Promise.resolve(Bt):qt(t)}:{}})}setMuteLeases(e){this.muteLeases=e}muteLeases={};setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}beforeRunCheckpoints;checkpointProgress(e){return(t,r,n,o)=>{Le(this.deps,e,t,r,n,o),this.liveTracker?.updateProgress(e,t,r,n,o)}}async handleAutomation(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(am,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,me(n,t.orgId),CS(t.objects,t.publishes===!0));if("error"in o)throw new Error(o.error);let i=T(this.deps,e,"seed:automation:response",{orgId:t.orgId,objects:t.objects,preview:o.preview});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(r){E(this.deps,"seed:automation","seed:automation:error",e,r,{retryable:!0})}}async handle(e){if(!XC.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=T(this.deps,e,t,r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}async handleScenarioPacks(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!!x(um,e,"seed:error",this.deps))try{let{listScenarioPacks:t,nodeScenarioPackFiles:r}=await import("./chunk-7LKI7OAS.mjs"),n=this.workspaceFolders(),o=await t(r(),n);this.answerScenario(e,"seed:scenario:packs:response",{packs:o,workspace:n.length>0})}catch(t){E(this.deps,"seed:scenario:packs","seed:error",e,t)}}async handleScenarioPrepare(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(pm,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-PPHVWUFY.mjs"),{seedObjectAccess:a}=await import("./chunk-SNEOKYV7.mjs"),d=await o(async u=>(await r.query(u)).records),c=await i(a(r),u=>r.describe(u)),l=n(t.pack,{caseStatus:d,knowledge:c,...t.seed!==void 0?{seed:t.seed}:{},...t.articleBodyField!==void 0?{articleBodyField:t.articleBodyField}:{}});this.answerScenario(e,"seed:scenario:prepare:response",{...l})}catch(r){E(this.deps,"seed:scenario:prepare","seed:error",e,r,{retryable:!0})}}async handleScenarioExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(gm,e,"seed:error",this.deps);if(!t)return;let{compileScenario:r,ScenarioCompileError:n}=await import("./chunk-TWV4A5RK.mjs"),o;try{o=r(t.pack,t.options)}catch(a){if(!(a instanceof n))throw a;E(this.deps,"seed:scenario:execute","seed:error",e,a,{code:"SCENARIO_INVALID",retryable:!1});return}let i=ko.safeParse(o.template);if(!i.success){E(this.deps,"seed:scenario:execute","seed:error",e,new Error(`The scenario compiled to a template the seed refuses: ${i.error.issues[0]?.message??"invalid"}`),{code:"SCENARIO_INVALID",retryable:!1});return}await this.runAsked(e,{orgId:t.orgId,template:i.data,...t.locale!==void 0?{locale:t.locale}:{},...t.muteAutomation!==void 0?{muteAutomation:t.muteAutomation}:{},...t.checkpointFirst?{checkpointFirst:t.checkpointFirst}:{}},{pack:t.pack,options:t.options,compiled:o})}async keepScenario(e,t,r){let{compiled:n,pack:o}=t,i=n.tests.filter(u=>u.openCase!==void 0),a=new Set(i.map(u=>u.openCase?.caseKey)),d=Object.keys(r).filter(u=>a.has(u)).length,c={packId:o.id,packName:o.name,tests:n.tests.length,openCasesWritten:d,openCases:a.size};if(d===0)return{...c,companion:{kind:"none"}};let l=this.runCreations;if(!l)return{...c,companion:{kind:"failed",message:"The runs are not kept in this window."}};try{let{nodeScenarioSidecarFiles:u,scenarioRunSidecar:p,writeScenarioRunSidecar:g}=await import("./chunk-7CVDVBEE.mjs");return await g(u(),l.storagePath,p({runId:e.operationId,pack:o,compiled:n,options:t.options,caseIds:r})),{...c,companion:{kind:"kept"}}}catch(u){let p=I(u);return this.deps.log(`[WARN] seed:scenario:execute ${e.operationId}: the companion file could not be written, so its test file cannot be: ${p}`),{...c,companion:{kind:"failed",message:p}}}}async handleScenarioAgents(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(fm,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-PPHVWUFY.mjs"),{scenarioProjectOf:a}=await import("./chunk-RYRMUPMY.mjs"),d=await n(i(Uk(r))),c=await o(l=>r.describe(l));this.answerScenario(e,"seed:scenario:agents:response",{orgId:t.orgId,agents:d.kind==="agents"?{kind:"agents",agents:d.catalog.agents}:d,project:await a(this.workspaceFolders()),...c?{casePicklists:c}:{}})}catch(r){E(this.deps,"seed:scenario:agents","seed:error",e,r,{retryable:!0})}}async handleScenarioSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(hm,e,"seed:error",this.deps);if(t)try{let{nodeScenarioPackFiles:r,saveScenarioPack:n}=await import("./chunk-7LKI7OAS.mjs"),o=await n(r(),this.workspaceFolders(),t.pack,t.overwrite===!0);this.answerScenario(e,"seed:scenario:save:response",{outcome:o})}catch(r){E(this.deps,"seed:scenario:save","seed:error",e,r)}}async handleScenarioTestFile(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(mm,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-TCBAE65A.mjs"),{toolingQueryAll:l}=await import("./chunk-PPHVWUFY.mjs"),{findScenarioPack:u,nodeScenarioPackFiles:p}=await import("./chunk-7LKI7OAS.mjs"),{nodeScenarioSidecarFiles:g}=await import("./chunk-7CVDVBEE.mjs"),{scenarioProjectOf:h,writeRunTestFile:f}=await import("./chunk-RYRMUPMY.mjs"),m=this.workspaceFolders(),y=await f({sidecar:g(),spec:c()},{runId:t.runId,storagePath:n.storagePath,project:await h(m),alias:me(i,o.targetOrgId),choice:t.choice,...t.overwrite!==void 0?{overwrite:t.overwrite}:{},readCatalog:()=>d(l(Uk(a))),findPack:(R,k)=>u(p(),m,R,k)});r(y)}catch(n){E(this.deps,"seed:scenario:test-file","seed:error",e,n,{retryable:!0})}}async handleTemplateSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(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=T(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=T(this.deps,e,"seed:template:save:response",{success:!0,id:n.id});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}}catch(r){E(this.deps,"seed:template:save","seed:error",e,r)}}async handleTemplateLoad(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(nu,e,"seed:error",this.deps);if(t)try{let r=this.seedTemplateStore.load(t.id),n=T(this.deps,e,"seed:template:load:response",{template:r??null});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){E(this.deps,"seed:template:load","seed:error",e,r)}}async handleTemplateList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let r=this.seedTemplateStore.list().map(o=>({id:o.id,name:o.name,description:o.description,tags:o.tags,updatedAt:o.updatedAt,objectCount:o.objects.length,totalRecords:o.objects.reduce((i,a)=>i+a.recordCount,0)})),n=T(this.deps,e,"seed:template:list:response",{templates:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(t){E(this.deps,"seed:template:list","seed:error",e,t)}}async handleTemplateDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(nu,e,"seed:error",this.deps);if(t)try{let r=this.seedTemplateStore.delete(t.id),n=T(this.deps,e,"seed:template:delete:response",{success:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){E(this.deps,"seed:template:delete","seed:error",e,r)}}async handleListPersonas(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.personaManager.getBuiltInPersonas(),r=this.personaManager.getCustomPersonas(),n=[...t,...r].map(i=>({id:i.id,name:i.name,description:i.description,industry:i.industry,locale:i.locale,dataPatterns:i.dataPatterns})),o=T(this.deps,e,"seed:list-personas:response",{personas:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(t){E(this.deps,"seed:list-personas","seed:error",e,t)}}async handleCreatePersona(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(lm,e,"seed:error",this.deps);if(t)try{let r=t;if(!r.description||r.description.trim().length===0){let c=T(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=T(this.deps,e,"seed:create-persona:response",{persona:a,success:!0});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(r){E(this.deps,"seed:create-persona","seed:error",e,r)}}buildSeedCallAI(){let e=this.deps.services;return e?.isAIEnabled()?async t=>{try{return(await e.aiClient().chat({messages:[{role:"user",content:t}]})).text}catch(r){return this.deps.log(`[AI] seed data generation failed, falling back to faker: ${I(r)}`),"[]"}}:async()=>"[]"}async handleDescribeGlobal(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(im,e,"seed:error",this.deps);if(!t)return;let r=t,n=ct(this.deps);try{let o=await q(r.orgId,this.deps.orgRegistry,this.deps.orgManager),d=(await new ge(n.timeouts.describeGlobal).withTimeout("describe-global",()=>o.describeGlobal())).sobjects.filter(l=>l.createable).filter(l=>!ji(l.name)).map(l=>({apiName:l.name,label:l.label,recordCount:0,dependencies:[]})),c=T(this.deps,e,"seed:describe-global:response",{objects:d});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(o){E(this.deps,"seed:describe-global","seed:error",e,o)}}async handleDescribeObject(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(dm,e,"seed:error",this.deps);if(!t)return;let r=t,n=ct(this.deps);try{let o=await q(r.orgId,this.deps.orgRegistry,this.deps.orgManager),i=wt(r.objectApiName),d=await new ge(n.timeouts.describe).withTimeout("describe-object",()=>o.describe(i)),c=d.fields.filter(p=>p.createable).map(p=>({fieldApiName:p.name,label:p.label,type:p.type,required:!p.nillable&&!p.defaultedOnCreate,picklistValues:p.picklistValues?.map(g=>g.value)??[],referenceTo:p.referenceTo??[],length:p.length,integerDigits:mf(p),objectApiName:r.objectApiName})),l=AS(i,d.recordTypeInfos,i===Ro?await Lu(o):[]),u=T(this.deps,e,"seed:describe-object:response",{objectApiName:r.objectApiName,objectLabel:d.label,fields:c,recordTypes:l});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`)}catch(o){E(this.deps,"seed:describe-object","seed:error",e,o)}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(sm,e,"seed:error",this.deps);if(!t)return;let r=t;if(r.dryRun===!0){E(this.deps,"seed:execute","seed:error",e,new Error('Seed has no dry run: remove "dryRun" from this request to run the seed.'),{code:"DRY_RUN_UNSUPPORTED",retryable:!1});return}await this.runAsked(e,r)}async runAsked(e,t,r){let n=e.id,o={module:"seed",operation:e.type};try{let i=await this.clearSeed(t,n,o,zC,r!==void 0);if("refusal"in i){let{refusal:l}=i;E(this.deps,"seed:execute","seed:error",e,new Error(l.message),{code:l.code,retryable:!1,...l.extraPayload?{extraPayload:l.extraPayload}:{}}),l.failed&&De(this.deps,n,l.message,!1,{context:o,...l.failed.authored?{authored:!0}:{}});return}let a=r?`Seed of the scenario ${r.pack.name}`:"Seed data generation",{abortController:d,execution:c}=this.beginSeed(e,i,n,o,a,void 0,r);this.registry?this.registry.register(n,"seed",a,c,d):await c}catch(i){this.deps.infraServices?.performanceTracker?.complete(n),this.liveTracker?.fail(n,I(i));let a=Hk(i,n,this.deps.log);E(this.deps,"seed:execute","seed:error",e,i,{code:vo(i),retryable:!0,extraPayload:a}),De(this.deps,n,I(i),!0,{extraPayload:a,context:o})}}async clearSeed(e,t,r,n,o=!1,i=!1){let a=W=>{i||Z(this.deps,W)},d=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200,c=e.template.objects.map(W=>({...W,batchSize:W.batchSize??d}));Object.assign(r,zr(c));let l=await q(e.orgId,this.deps.orgRegistry,this.deps.orgManager),u={...e.template,objects:c},p=u.objects.some(W=>W.objectApiName===Ro)?TS(u,await Lu(l)):{template:u,personObjects:[]};if("refusal"in p)return{refusal:{code:"RECORD_TYPES_MIXED",message:p.refusal}};let g={orgId:e.orgId,template:p.template,personObjects:p.personObjects,locale:await ES(e.locale,l)},h=e.template.objects.reduce((W,se)=>W+se.recordCount,0),f=[],m=W=>{f.push(W),this.deps.log(`[WARN] seed:execute ${t}: ${W}`)},y=this.deps.orgManager.getOrg(g.orgId),R=me(y,g.orgId),k=p.template.objects.map(W=>({objectApiName:W.objectApiName,recordCount:W.recordCount})),w=this.targetAutomation,O=await new ge(Lk).withTimeout("seed automation",()=>w.read(g.orgId,k.map(W=>W.objectApiName))).catch(W=>({unread:I(W)})),P=PS(p.template,o),b;if("muteAutomation"in e&&e.muteAutomation===!0)try{b=await kt(async()=>Mt(l),O,{...this.muteLeases,writes:P})}catch(W){if(!$t(W))throw W;return a({action:"seed_execute",module:"seed",operationId:t,orgId:g.orgId,outcome:"stopped",code:W.code}),{refusal:{code:W.code,message:W.message,extraPayload:{},failed:{authored:!0}}}}b&&(g.mute=b);let v=NS(e.fit,h);v&&(g.fit=v);let{describedFieldsOf:C,requiredForAccountKinds:S}=await import("./chunk-27Z76O2O.mjs"),A=0,D=C(async W=>(A++,l.describe(W))),z=$S(O,b?.plan,P,await xS(p.template,O,D.unset)),U=await ir({read:O,...b?.plan?{plan:b.plan}:{},writes:P,readDeliverability:()=>Ce(y)==="production"?Promise.resolve(Bt):qt(l),accepted:!1,target:R,run:"seed",keepsAddresses:!0}),Y={read:U,accepted:!1};g.emails=Y;let H=U.gate.verdict==="asks",M;if(e.checkpointFirst!==void 0){let W={module:"seed",orgId:g.orgId,operationId:t,written:k.filter(se=>se.recordCount>0).map(se=>se.objectApiName),running:z.running??{firing:[]},request:e.checkpointFirst};try{M=await si(this.beforeRunCheckpoints,W)}catch(se){if(!(se instanceof Wt))throw se;return a({action:"seed_execute",module:"seed",operationId:t,orgId:g.orgId,outcome:"stopped",code:se.code}),{refusal:{code:se.code,message:se.message,extraPayload:{},failed:{authored:!0}}}}}let{seedObjectAccess:L,templateTheOrgTakes:ee}=await import("./chunk-SNEOKYV7.mjs"),Q=await ee(p.template,L(l)),B=gS(vs(this.deps.services),p.template),V=await pS(Q,{describeCreateableFields:D.createable,describeRequiredFields:S(D,p.personObjects)},B),we={duplicateRules:No(O),partition:B,slices:V,slicesRead:A,bulkThreshold:ct(this.deps).bulk.threshold,automationRead:An(O)},ie=await wS(l,Q,p.personObjects,me(y,g.orgId),M?.planned,{...Tn(U.ofRun),...Qw(b?.plan)},we,z.room);if(ie.check.verdict==="unread"&&m(`the data storage the org has left could not be read (${ie.check.unread}): whether the records fit is not known`),ie.refusal){let W=ie.refusedFor==="checkpoint",se=W?In:ie.refusedFor==="apiRequests"?Co:Mu,te=W?ie.checkpointRefusal?.code:void 0;a({action:"seed_execute",module:"seed",operationId:t,orgId:g.orgId,outcome:"stopped",code:se,...te!==void 0?{details:{checkpointRefusal:te}}:{}});let ue=ie.check,$=W?void 0:DS(bS(ie),Q,p.personObjects,z.room,we);return{refusal:{code:se,message:ie.refusal,extraPayload:{...ue.verdict==="unread"||se!==Mu?{}:{estimateMB:Number(Hs(ue.estimateMB)),remainingMB:ue.remainingMB,maxMB:ue.maxMB,org:me(y,g.orgId)},...te!==void 0?{checkpointRefusal:te}:{},...$?{fit:$}:{}},failed:{authored:!0}}}}let re=await this.readAutomation(g.orgId,l,k.map(W=>W.objectApiName),R,P,b?.automation??O,U.gate.deliverability),Ae=rd(re,k,R);for(let W of Ae.unknown??[])m(W);if(Ae.refusal)return a({action:"seed_execute",module:"seed",operationId:t,orgId:g.orgId,outcome:"stopped",code:Fu}),{refusal:{code:Fu,message:Ae.refusal,extraPayload:{...Ae.figures?{...Ae.figures}:{},...o?{scenario:!0}:{}},failed:{authored:!0}}};if(i)return{preview:{records:Q.objects.reduce((W,se)=>W+se.recordCount,0),objects:Q.objects.length,storage:ie.check,apiRequests:ie.api,automation:_u(re,R),warnings:f},storage:ie,asks:ie.check.verdict==="unread"||ie.api.verdict==="near"||M!==void 0||H,emailsAsked:H,emails:U};let he=this.deps.infraServices?.productionGuard;if(!he)return Z(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:g.orgId,outcome:"stopped",code:Se.code}),{refusal:{code:Se.code,message:Se.message,failed:{authored:!1}}};let Je={orgId:g.orgId,orgTier:Ce(y),operation:"insert",objectName:"SeedData",recordCount:h,module:"seed"},{check:Ne,decision:Fe}=await Ze(he,Je);if((Fe==="refused"||Fe==="declined")&&Z(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:g.orgId,outcome:"stopped",guard:Fe}),Fe==="refused")throw hn(Ne.blockedReason??Ne.impactSummary);if(Fe==="declined")return{refusal:{code:Ct.declined,message:"Operation cancelled by user (confirmation declined).",failed:{authored:!1}}};if(ie.check.verdict==="unread"||ie.api.verdict==="near"||M!==void 0||H){let W=await n.ask(he,{stage:"write",module:"seed",org:R,orgTier:Ce(y),objects:p.template.objects.map(se=>({objectApiName:se.objectApiName,rows:se.recordCount})).sort((se,te)=>te.rows-se.rows),total:h,storage:En(ie.check),counted:!0,...$o(ie.api),...M?{checkpoint:M.planned}:{},...U.gate.confirmation});if(W==="confirmed"&&H&&(Y.accepted=!0),W==="declined")return Z(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:g.orgId,outcome:"stopped",guard:Fe,code:Xo,...sn(Y)}),{refusal:{code:Xo,message:"The seed was cancelled before it wrote anything. Nothing was written.",failed:{authored:!0}}};if(W==="unavailable"&&H){let se=Fk(U,R,n.unanswered);return Z(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:g.orgId,outcome:"stopped",guard:Fe,code:se.code,...sn(Y)}),{refusal:{...se,failed:{authored:!0}}}}if(W==="unavailable"&&M!==void 0)return Z(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:g.orgId,outcome:"stopped",guard:Fe,code:St.unanswered}),{refusal:{code:St.unanswered,message:`The seed needed an answer before it wrote \u2014 the checkpoint it takes first reads whole tables of ${R} \u2014 and there was no one to ask. Nothing was written.`,failed:{authored:!0}}};if(W==="unavailable"&&n.unanswered==="refuse")return Z(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:g.orgId,outcome:"stopped",guard:Fe,code:St.unanswered}),{refusal:{code:St.unanswered,message:_k(ie,R),failed:{authored:!0}}};W==="unavailable"&&this.deps.log(`[WARN] seed:execute ${t}: nobody could be asked about the storage or the API requests the org has left; the seed goes on`)}return{conn:l,run:g,plannedRecords:h,guardDecision:Fe,automation:re,orgName:R,warnings:f,...M?{checkpoint:M}:{}}}beginSeed(e,t,r,n,o,i,a){this.deps.infraServices?.performanceTracker?.start(r,"seed"),ze(this.deps,r,"seed",o),this.liveTracker?.register(r,"seed",o,t.plannedRecords);let d=new AbortController,c=this.executeSeed(e,t.conn,t.run,r,d,n,t.guardDecision,i,a,t.checkpoint);return{abortController:d,execution:c}}pipelineSeedOf(e){let t=this.deps.orgManager.getOrg(e.orgId);if(!t)throw lr(St.orgUnknown,`The org the seed writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was written.`);let r=Ev(Ce(t),e.answer,me(t,e.orgId));if(r)throw r;let n=zo(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 lr(i.refusal.code,i.refusal.message);if(t?.aborted)throw new Rt("The dry run of the seed was stopped before it said what the seed would meet. Nothing was written.");if(i.asks&&!e.answer.approved){let a=me(this.deps.orgManager.getOrg(e.orgId),e.orgId);if(i.emailsAsked){let d=Fk(i.emails,a,o.unanswered);throw lr(d.code,d.message)}throw lr(St.unanswered,_k(i.storage,a))}return i.preview}async seedForPipeline(e,t){let r=this.pipelineSeedOf(e),n=mn("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 Ra(e.answer,async()=>{let d=await this.clearSeed(r,o,i,a);if("refusal"in d)throw lr(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=_u(d.automation,d.orgName);for(let m of c)this.deps.log(`[INFO] seed:execute ${o}: ${m}`);let l,u=`Pipeline seed of ${r.template.name}`,{abortController:p,execution:g}=this.beginSeed(n,d,o,i,u,{pipeline:e.pipeline,ended:m=>{l=m}});this.registry?.register(o,"seed",u,g,p);let h=()=>{this.registry?this.registry.abort(o):p.abort()};t?.addEventListener("abort",h,{once:!0});try{await g}finally{t?.removeEventListener("abort",h)}let f=l;if(f===void 0)throw new Error("The seed ended without a result.");if("error"in f)throw f.error instanceof Error?f.error:new Error(I(f.error));return{operationId:o,runId:f.result.operationId,result:f.result,automation:c,warnings:d.warnings}})}async executeSeed(e,t,r,n,o,i,a,d,c,l){let u=ct(this.deps),p=new Date().toISOString(),g,h=!1,f={},m=r.template.name,y={origin:"generator",...typeof m=="string"?{label:m}:{}};try{let R=hr(this.deps),k=new Ua({retryConfig:u.retry,signal:o.signal,onRetry:(ae,be,He)=>{this.deps.log(`[RETRY] seed insert attempt=${ae} code=${be.originalError.statusCode} delay=${He}ms`)}}),w=this.deps,O=crypto.randomUUID(),P=d?this.deps.orgManager.getOrg(r.orgId)?.orgId:void 0,b=this.runCreations?.recorder({runId:O,targetOrgId:r.orgId,startedAt:p,...d?{pipeline:d.pipeline}:{},...P?{targetOrganizationId:P}:{}});vr(b,()=>t.identity(),`seed:execute ${n}`);let v={base:0,total:0},C=(ae,be,He)=>{let Ue=v.base+ae,ot=Math.max(v.total,Ue,be,1),Ve=Math.round(Ue/ot*100);Le(w,n,Ve,Ue,ot,He),this.liveTracker?.updateProgress(n,Ve,Ue,ot,He)},S=GR({conn:t,bulkThreshold:u.bulk.threshold,bulkManager:R,retry:k,signal:o.signal,label:`seed:execute ${n}`,log:ae=>this.deps.log(ae),onProgress:C,...b?{calls:{sending:(ae,be,He)=>b.sending(ae,be,He),answered:(ae,be)=>b.answered(ae,be)}}:{}}),A=async(ae,be,He,Ue)=>{He.length>0&&(h=!0);let ot=await S(ae,be,He,Ue);return b?.note(be,ot.successIds),ot},D=ae=>this.deps.log(`[WARN] seed:execute ${n}: what the run created could not all be kept, so removing it may leave some of it in the org: ${I(ae)}`),{SeedValidator:z}=await import("./chunk-GGUOIDWP.mjs"),{DataPlanBuilder:U}=await import("./chunk-FA4ZKDCU.mjs"),{FieldMapper:Y}=await import("./chunk-ZHIZY3ZC.mjs"),{ReferenceLinker:H}=await import("./chunk-UHFLKP26.mjs"),{AIDataGenerator:M}=await import("./chunk-KJYEQHYP.mjs"),{FakerFallback:L}=await import("./chunk-WOOUISSO.mjs"),{readExistingParentIds:ee,readPresentParentIds:Q}=await import("./chunk-JLZRZL5E.mjs"),{seedObjectAccess:B}=await import("./chunk-SNEOKYV7.mjs"),{describedFieldsOf:V,requiredForAccountKinds:we}=await import("./chunk-27Z76O2O.mjs"),{seedTargetOf:ie}=await import("./chunk-XFU3HRUV.mjs"),re=c?(await import("./chunk-3MGMNK3Q.mjs")).seedKnowledge:void 0,Ae=new M(this.buildSeedCallAI()),he=new L(r.locale),Je=new Y({aiGenerator:Ae,fakerFallback:he}),Ne=new H,Fe=new z,W=new U,{SeedGrappeAdapter:se}=await import("./chunk-PTTHSSQO.mjs"),te=vs(this.deps.services),ue=V(ae=>t.describe(ae)),$={validator:Fe,describeCreateableFields:ue.createable,describeVisibleFields:ue.visible,describeComputedFields:ue.computed,describePicklistValues:ue.picklistValues,describeFieldLengths:ue.lengths,describeRequiredFields:we(ue,r.personObjects),objectAccess:B(t),readExistingParentIds:(ae,be,He)=>ee(t,ae,be,He),readPresentParentIds:(ae,be)=>Q(t,ae,be),describeKeyPrefix:ue.keyPrefix,...ie(t),planBuilder:W,fieldMapper:Je,referenceLinker:Ne,insert:A,generateId:()=>crypto.randomUUID(),now:()=>new Date().toISOString(),services:this.deps.services,grappeAdapter:new se(()=>crypto.randomUUID(),te?.grappeSize),grappeConfig:te,onGrappeEvent:ae=>Zi(this.deps,ae),onProgress:ae=>{v.base=ae.processedRecords,v.total=ae.totalRecords,C(0,ae.totalRecords,`Insert ${ae.objectApiName}`)},signal:o.signal,...c&&re?{onRowIds:(ae,be)=>{ae==="Case"&&Object.assign(f,be)},knowledge:re({org:t,plan:{publish:!0,links:c.compiled.closedCaseArticles},...b?{journal:b}:{},signal:o.signal})}:{}};if(!this.deps.services)throw new Error("SeedOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let N=this.deps.services.seedOrchestrator($),X=r.template;Le(this.deps,n,0,0,1,"Validating template and building plan");let F;this.runningRuns.add(O);let de=r.mute,J=de?.muted;try{l&&(g=await ii(this.beforeRunCheckpoints,l,O,o.signal,this.checkpointProgress(n)),b?.checkpoint?.(g));let ae=de?.prepared?await de.prepared.acquire(O):void 0;ae&&(J=ae.outcome);let be=ae&&r.emails?r.emails.read.afterLease(ae.outcome,r.emails.accepted):void 0;if(ae&&be)throw J=await ae.release(),new Wt(be.code,be.message);F=await N.execute(X,r.orgId,O).finally(async()=>{ae&&(J=await ae.release())}),J&&(F={...F,mutedAutomation:J});let He=await xn(this.beforeRunCheckpoints,g,h,this.deps.log,`seed:execute ${n}`);g=void 0,He&&(F={...F,checkpoint:He})}catch(ae){throw await b?.end({status:"failure",finishedAt:new Date().toISOString(),objectResults:[]}).catch(D),this.runningRuns.delete(O),ae}await b?.end({finishedAt:new Date().toISOString(),status:F.status,...F.cancelled?{cancelled:!0}:{},objectResults:F.objectResults}).catch(D),c&&(F={...F,scenario:await this.keepScenario(F,c,f)}),this.runningRuns.delete(O),F.cancelled||Le(this.deps,n,100,1,1,"Seed complete");let le=F.totalRecordsCreated;this.deps.infraServices?.performanceTracker?.update(n,le,1),this.deps.infraServices?.performanceTracker?.complete(n),F.cancelled?(this.registry?.abort(n),pe(this.deps,n,{aborted:!0,totalRecords:le}),this.liveTracker?.cancel(n)):(pe(this.deps,n,{status:F.status,totalRecords:le}),F.status==="failure"?this.liveTracker?.fail(n,VC(F)):F.status==="partial"?this.liveTracker?.partial(n):this.liveTracker?.complete(n));let Ee=F.objectResults.some(ae=>ae.recordsCreated+ae.recordsFailed>0),je=F.cancelled===!0?Ee?"cancelled":"stopped":F.status;Z(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:je,...je==="stopped"?{code:rt}:{},guard:a,objects:F.objectResults.map(ae=>({...ft(ae.objectApiName),created:ae.recordsCreated,failed:ae.recordsFailed})),source:y,...F.mutedAutomation?{muted:dt(F.mutedAutomation)}:{},...F.checkpoint?.state==="taken"?{checkpointId:F.checkpoint.checkpointId}:{},...r.fit?{fit:r.fit}:{},...sn(r.emails)});let We=T(this.deps,e,"seed:execute:response",JC(F));if(this.deps.broker.postToWebview(We),this.deps.log(`[TX] ${We.type} id=${We.id}`),d?.ended({result:F}),F.status==="failure"&&!F.cancelled)return{status:"failure"}}catch(R){this.deps.infraServices?.performanceTracker?.complete(n);let k=await xn(this.beforeRunCheckpoints,g,h,this.deps.log,`seed:execute ${n}`),w=k?.state==="deleted"?`${I(R)} ${Kr}`:void 0,O=w!==void 0?new Error(w):R;if(R instanceof Wt){if(R.code===rt)this.registry?.abort(n),pe(this.deps,n,{aborted:!0,totalRecords:0}),this.liveTracker?.cancel(n);else{let C=I(O);this.liveTracker?.fail(n,C),De(this.deps,n,C,!1,{context:i,authored:!0})}let v=R.refusal?.code;return Z(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:"stopped",guard:a,code:R.code,...v!==void 0||r.emails?.read.gate.audit!==void 0?{details:{...sn(r.emails).details,...v!==void 0?{checkpointRefusal:v}:{}}}:{}}),E(this.deps,"seed:execute","seed:error",e,O,{code:R.code,retryable:!1,...v!==void 0?{extraPayload:{checkpointRefusal:v}}:{}}),d?.ended({error:R}),R.code===rt?void 0:{status:"failure"}}this.liveTracker?.fail(n,I(O));let P=$t(R)?R:void 0;Z(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:P?"stopped":"failure",guard:a,source:y,...P?{code:P.code}:{},...k?.state==="taken"?{checkpointId:k.checkpointId}:{},...r.fit?{fit:r.fit}:{},...sn(r.emails)});let b=Hk(R,n,this.deps.log);return E(this.deps,"seed:execute","seed:error",e,R,{...P?{code:P.code}:{},retryable:!0,extraPayload:{...b,...k?{checkpoint:k}:{}}}),De(this.deps,n,I(O),!0,{extraPayload:b,context:i}),d?.ended({error:O}),{status:"failure"}}}};function KC(s){if(s.length>512)throw new Error(`SOQL WHERE clause too long (${s.length} > 512 chars)`);return Qf(s)}var di=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 Os(o,async a=>{let d=[],c=await e.query(a);for(d.push(...c.records);!c.done&&c.nextRecordsUrl;)c=await e.queryMore(c.nextRecordsUrl),d.push(...c.records);return d}));return this.log(`[CloneRecordFetcher] Fetched ${i.length} records from ${t}`),i}async countRecords(e,t,r,n=[]){let o=`SELECT COUNT() FROM ${qe(t)}${this.whereOf(r,n)}`;return(await e.query(o)).totalSize}async fetchSample(e,t,r,n,o=[]){let i=await this.getQueryFields(e,t),a=this.buildSoql(i,t,n,o);return a+=` LIMIT ${r}`,this.cleanRecords(await Os(a,async d=>(await e.query(d)).records))}async getQueryFields(e,t){let r=await this.describe(e,t),n=new Set;n.add("Id");for(let o of r.fields)(o.createable||o.type==="reference")&&n.add(o.name);return Array.from(n)}buildSoql(e,t,r,n=[]){return`SELECT ${e.join(", ")} FROM ${qe(t)}${this.whereOf(r,n)}`}whereOf(e,t){let r=e?KC(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 ci=class{resolveInsertOrder(e,t){if(e.length===0)return[];let r=new Set(e),n=t.filter(u=>u.from!==u.to&&r.has(u.from)&&r.has(u.to)),o=new Map(e.map(u=>[u,new Set])),i=new Map(e.map(u=>[u,new Set])),a=new Map(e.map(u=>[u,new Set]));for(let u of n)o.get(u.to)?.add(u.from),u.required&&(Np(u)?a:i).get(u.to)?.add(u.from);let d=Ji(i).filter(u=>u.length>1);if(d.length>0)throw new Error(QC(d,n.filter(u=>!Np(u))));let c=new Map(e.map(u=>[u,new Set([...i.get(u)??[],...a.get(u)??[]])])),l=Ji(c).some(u=>u.length>1)?i:c;return YC(Ji(o),o,e).flatMap(u=>u.length>1?Yf(u,l):u)}lookupsOf(e,t){return t.filter(r=>r.to===e&&!Np(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===er&&a.name==="ActivityId")&&a.type==="reference"&&a.referenceTo){let d=gs(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 Ql(r))n.push({from:o.sourceObject,to:o.targetObject,fieldApiName:o.relationshipName,relationshipType:"lookup",required:!0});return n}};function YC(s,e,t){let r=new Map;t.forEach((c,l)=>{r.has(c)||r.set(c,l)});let n=new Map;s.forEach((c,l)=>c.forEach(u=>n.set(u,l)));let o=s.map(c=>Math.min(...c.map(l=>r.get(l)??1/0))),i=s.map((c,l)=>{let u=new Set;for(let p of c)for(let g of e.get(p)??[]){let h=n.get(g);h!==void 0&&h!==l&&u.add(h)}return u}),a=new Set,d=[];for(;d.length<s.length;){let c=-1;for(let l=0;l<s.length;l++)a.has(l)||[...i[l]].some(u=>!a.has(u))||(c===-1||o[l]<o[c])&&(c=l);if(c===-1)break;a.add(c),d.push(s[c])}return d}function Np(s){return Ql(new Set([s.from,s.to])).some(e=>e.sourceObject===s.from&&e.targetObject===s.to&&e.relationshipName===s.fieldApiName)}function QC(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(", ")}. ${ZC(t)} must be set when the record is created, so no object of the cycle can be written first.`}function ZC(s){return s.length<=1?s.join(""):`${s.slice(0,-1).join(", ")} and ${s[s.length-1]}`}function jp(s){return s==="insert"||s==="upsert"}function _d(s,e){return{sending:(t,r,n)=>{jp(r)&&s.sending(t,n,r==="upsert"?{upsert:!0}:void 0)},opened:(t,r,n,o)=>{jp(r)&&s.sending(t,n,{job:o,...r==="upsert"?{upsert:!0}:{}})},answered:(t,r,n)=>{if(!jp(r))return;let o=Za(r,n);s.answered(t,o),e?.(o.length)}}}var e$=new Set(["seed:clone:describe-source","seed:clone:preview","seed:clone:execute"]),t$=5,r$=10,n$=-1,qk="Operation blocked by Production Guard: ",an={confirmationDeclined:"PRODUCTION_CONFIRMATION_DECLINED",guardBlocked:"PRODUCTION_GUARD_BLOCKED",failed:"CLONE_FAILED",emailsExceeded:"CLONE_EMAILS_EXCEEDED",apiBudgetExceeded:"API_BUDGET_EXCEEDED",storageExceeded:"CLONE_STORAGE_EXCEEDED"},o$=3;function s$(s,e){let t=s.filter(n=>n.recordCount>0).map(n=>({objectApiName:n.objectApiName,rows:n.recordCount,bytes:Yn(n.objectApiName,{rows:n.recordCount})})).sort((n,o)=>o.bytes-n.bytes),r=Rr({storageBytes:t.reduce((n,o)=>n+o.bytes,0)},e);if(r.verdict==="exceeds")return{estimateMB:r.estimateMB,remainingMB:r.remainingMB,maxMB:r.maxMB,heaviest:t.slice(0,o$).map(({objectApiName:n,rows:o,bytes:i})=>({objectApiName:n,rows:o,mb:i/(1024*1024)}))}}function Wk(s){let e=s<10?100:10;return String(s<=0?0:Math.ceil(s*e-1e-9)/e)}function i$(s,e){let t=s.heaviest.map(r=>`${r.objectApiName} (${r.rows} records, ${Wk(r.mb)} MB)`).join(", ");return`The clone was refused before it wrote anything: its records take about ${Wk(s.estimateMB)} MB of data storage, and ${e} has ${s.remainingMB} MB left of ${s.maxMB} MB. The heaviest: ${t}. Narrow their filter or leave them out, then preview again; or copy a sample of the source that fits with Forge (Depth ALL, Records per object: A sample that fits the target). Nothing was written.`}var a$=6e4,d$={neutralized:!1,fields:[],values:0},c$="PREVIEWED_FOR_OTHER_ORGS",l$="NOT_PREVIEWED",u$="PREVIEW_NOT_HELD",p$=50,Ud=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-DIL62SUN.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 td({org:n,objects:a.map(c=>c.objectApiName),readAutomation:c=>o===void 0?this.readTargetAutomation(e,c):typeof o.unread=="string"?Promise.reject(new Error(o.unread)):Promise.resolve(o),readLimits:()=>Sr(t),...i?{deliverability:i}:{}});return rd(d,a,n)}readTargetAutomation(e,t){let r=this.targetAutomation;return new ge(a$).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),pe(this.deps,i,{aborted:!0,totalInserted:0,totalFailed:0}),this.liveTracker?.cancel(i);let c={status:"partial",objectResults:[],totalSourceRecords:0,totalInserted:0,totalFailed:0,durationMs:o,cancelled:!0};this.deps.broker.postToWebview(T(this.deps,e,"seed:clone:execute:response",c));return}let a=r.refusal?.code,d=a!==void 0?{checkpointRefusal:a}:{};Z(this.deps,{...t,outcome:"stopped",source:void 0,code:r.code,...a!==void 0?{details:d}:{}}),De(this.deps,i,r.message,!1,{context:n,authored:!0,extraPayload:{code:r.code,...d}}),this.liveTracker?.fail(i,r.message)}async handle(e){if(!e$.has(e.type))return!1;switch(e.type){case"seed:clone:describe-source":return await this.handleDescribeSource(e),!0;case"seed:clone:preview":return await this.handlePreview(e),!0;case"seed:clone:execute":return await this.handleExecute(e),!0;default:return!1}}async handleDescribeSource(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ym,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();$e(r.limitInfo,"seed:clone:describe-source");let o=n.sobjects.filter(a=>a.createable&&a.queryable).filter(a=>!ji(a.name)).map(a=>({apiName:a.name,label:a.label,recordCount:n$})),i=T(this.deps,e,"seed:clone:describe-source:response",{objects:o});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} count=${o.length}`)}catch(r){E(this.deps,"seed:clone:describe-source","seed:clone:error",e,r)}}async handlePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ou,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 di({log:this.deps.log}),i=new ci,a=t.objects.map(w=>w.objectApiName),d=new Map(t.objects.map(w=>[w.objectApiName,w.whereClause])),c=new Map,l=new Map,u=[];for(let w of t.objects){let[O,P]=await Promise.all([Hd("target",w.objectApiName,()=>n.describe(w.objectApiName)),Hd("source",w.objectApiName,()=>o.describe(r,w.objectApiName))]);$e(n.limitInfo,`seed:clone:preview describe ${w.objectApiName} in the target`),$e(r.limitInfo,`seed:clone:preview describe ${w.objectApiName}`),c.set(w.objectApiName,O),l.set(w.objectApiName,P);let b=eh(w.objectApiName,Gk(w.objectApiName,c.get(w.objectApiName),l.get(w.objectApiName)),d),[v,C,S]=await Promise.all([o.countRecords(r,w.objectApiName,w.whereClause,b),o.fetchSample(r,w.objectApiName,t$,w.whereClause,b),b.length>0?o.countRecords(r,w.objectApiName,w.whereClause):void 0]),A=S===void 0?0:S-v;u.push({objectApiName:w.objectApiName,recordCount:v,...A>0?{leftToThePlatform:A}:{},sampleRecords:C.map(D=>v$(D,r$))})}let p=i.buildEdgesFromDescribe(a,Jk(c,l)),g=i.resolveInsertOrder(a,p),h=u.map(w=>({...w,relationships:i.lookupsOf(w.objectApiName,p)})),f=m$(i.lookupsFilledAfter(g,p),g),m=y$(g,l,c),y=w$(g,c,l),R={objects:h,insertOrder:g,...f.length>0?{filledAfterInsert:f}:{},...m.length>0?{sourceOnlyLookups:m}:{},...y.length>0?{targetOnlyRequiredLookups:y}:{}},k=T(this.deps,e,"seed:clone:preview:response",R);this.deps.broker.postToWebview(k),this.deps.log(`[TX] ${k.type} id=${k.id}`),this.rememberPreview(e.id,t,new Map(u.map(w=>[w.objectApiName,w.recordCount])),new Set(i.lookupsFilledAfter(g,p).map(w=>w.to)))}catch(r){let n=r instanceof Bd?r:void 0;E(this.deps,"seed:clone:preview","seed:clone:error",e,r,{...n?{code:f$,retryable:!1,extraPayload:{objectApiName:n.objectApiName,org:me(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<=p$)break;this.previewedOrgs.delete(o)}}refusedAgainstItsPreview(e){if(e.previewId===void 0)return{code:l$,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:u$,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:c$,reason:"Clone refused: its preview was made for another source or target org. Preview it again."}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ou,e,"seed:clone:error",this.deps);if(!t)return;let r=this.refusedAgainstItsPreview(t);if(r!==void 0){E(this.deps,e.type,"seed:clone:error",e,new Error(r.reason),{code:r.code});return}let n=e.id,o=Date.now(),i={module:"seed",operation:e.type,...zr(t.objects.map(w=>({objectApiName:w.objectApiName})))},a=new AbortController,d=()=>{},c=new Promise((w,O)=>{d=P=>P===void 0?w():O(P)});c.catch(()=>{}),this.registry?.register(n,"clone",`Clone ${t.objects.length} object(s)`,c,a);let l={action:"seed_clone",module:"seed",operationId:n,orgId:t.targetOrgId,outcome:"failure",source:{origin:"org",orgId:t.sourceOrgId}},u=!1,p,g=0,h,f=!1,m=[],y=!!(t.upsert&&t.externalIdField),R=tS(t.keepContactPoints===!0?{keepContactPoints:!0}:{}),k=()=>R?.report()??d$;try{let w=this.deps.infraServices?.productionGuard;if(!w){Z(this.deps,{...l,outcome:"stopped",source:void 0,code:Se.code}),De(this.deps,n,Se.message,!1,{context:i,extraPayload:{code:Se.code}}),d(new Error(Se.message));return}let O=this.deps.orgManager.getOrg(t.targetOrgId),P={orgId:t.targetOrgId,orgTier:Ce(O),operation:t.upsert?"upsert":"insert",objectName:t.objects.map(_=>_.objectApiName).join(", ")||"CloneData",recordCount:"unknown",module:"clone"},{check:b,decision:v}=await Ze(w,P);if(l.guard=v,(v==="refused"||v==="declined")&&Z(this.deps,{...l,outcome:"stopped",source:void 0}),v==="refused")throw new Error(`${qk}${b.blockedReason??b.impactSummary}`);if(v==="declined"){let _="Operation cancelled by user (confirmation declined).";De(this.deps,n,_,!1,{context:i,extraPayload:{code:an.confirmationDeclined}}),d(new Error(_));return}let C=await q(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),S=await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),A=me(O,t.targetOrgId),D=this.previewedOrgs.get(t.previewId??""),z=D?.recordCounts,U=t.objects.map(_=>({objectApiName:_.objectApiName,recordCount:z?.get(_.objectApiName)??0})),Y=U.filter(_=>_.recordCount>0).map(_=>_.objectApiName),H=(_,K,ce)=>{let Oe=ce!==void 0?{checkpointRefusal:ce}:{};Z(this.deps,{...l,outcome:"stopped",source:void 0,code:_,...ce!==void 0?{details:Oe}:{}}),De(this.deps,n,K,!1,{context:i,authored:!0,extraPayload:{code:_,...Oe}}),d(new Error(K))},M,L=Y.length>0?await this.readTargetAutomation(t.targetOrgId,Y).catch(_=>({unread:I(_)})):{unread:"the clone sends no record"},ee=Y.length>0?await ir({read:L,writes:ai(Y,!0),readDeliverability:()=>Ce(O)==="production"?Promise.resolve(Bt):qt(S),accepted:!1,target:A,run:"clone",keepsAddresses:t.keepContactPoints===!0}):void 0,Q=ee?.gate.verdict==="asks";if(t.checkpointFirst!==void 0){try{M=await si(this.beforeRunCheckpoints,{module:"seed",orgId:t.targetOrgId,operationId:n,written:Y,running:Fd(L,ai(Y,!0)),request:t.checkpointFirst})}catch(K){if(!(K instanceof Wt))throw K;H(K.code,K.message);return}let _=xa(M.planned);if(_){H(_.code,_.message,_.refusal.code);return}}let B=await this.emailGate(t.targetOrgId,S,U,A,L,ee?.gate.deliverability);for(let _ of B?.unknown??[])this.deps.log(`[WARN] seed:clone:execute ${n}: ${_}`);if(B?.refusal&&B.figures){let _=g$(B.figures);Z(this.deps,{...l,outcome:"stopped",source:void 0,code:an.emailsExceeded}),De(this.deps,n,_,!1,{context:i,authored:!0,extraPayload:{code:an.emailsExceeded,...B.figures}}),d(new Error(_));return}let V=await br(S).catch(_=>({unread:I(_)})),we="unread"in V?await ar(S).catch(_=>({unread:I(_)})):V.dailyApiRequests,ie=t.upsert?void 0:s$(U,V);if(ie){let _=i$(ie,A);Z(this.deps,{...l,outcome:"stopped",source:void 0,code:an.storageExceeded}),De(this.deps,n,_,!1,{context:i,authored:!0,extraPayload:{code:an.storageExceeded,org:A,...ie}}),d(new Error(_));return}let re=On({run:mS(U.map(_=>({objectApiName:_.objectApiName,rows:_.recordCount})),{threshold:ct(this.deps).bulk.threshold,perCall:this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200),duplicateRules:No(L),...D?{secondPass:D.secondPass}:{},automationRead:Y.length>0?An(L):0}),...xo(M?.planned),...Tn(ee?.ofRun)},we);re.verdict==="unread"&&this.deps.log(`[WARN] seed:clone:execute ${n}: the daily API requests the target has left could not be read (${re.unread})`);let Ae=$a(re,A);if(Ae){Z(this.deps,{...l,outcome:"stopped",source:void 0,code:an.apiBudgetExceeded}),De(this.deps,n,Ae,!1,{context:i,authored:!0,extraPayload:{code:an.apiBudgetExceeded}}),d(new Error(Ae));return}let he=!1;if(M||Q){let _=U.filter(ce=>ce.recordCount>0).map(ce=>({objectApiName:ce.objectApiName,rows:ce.recordCount})).sort((ce,Oe)=>Oe.rows-ce.rows),K=await w.confirmRun({stage:"write",module:"seed",org:A,orgTier:Ce(O),objects:_,total:_.reduce((ce,Oe)=>ce+Oe.rows,0),storage:En(Rr({storageBytes:_.reduce((ce,Oe)=>ce+Yn(Oe.objectApiName,{rows:Oe.rows}),0)},V)),counted:!0,...$o(re),...M?{checkpoint:M.planned}:{},...ee?.gate.confirmation});if(K!=="confirmed"){let ce=ee?.gate.stop;K!=="declined"&&!M&&ce?H(ce.code,ce.message):H(K==="declined"?Xo:St.unanswered,K==="declined"?"The clone was cancelled before it wrote anything. Nothing was written.":`The clone needed an answer before it wrote \u2014 the checkpoint it takes first reads whole tables of ${A} \u2014 and there was no one to ask. Nothing was written.`);return}he=Q}if(l.details=sn(ee?{read:ee,accepted:he}:void 0).details,ze(this.deps,n,"clone",`Clone ${t.objects.length} object(s)`),this.liveTracker?.register(n,"clone",`Clone ${t.objects.length} object(s)`),M)try{h=await ii(this.beforeRunCheckpoints,M,n,a.signal,(_,K,ce,Oe)=>{Le(this.deps,n,_,K,ce,Oe),this.liveTracker?.updateProgress(n,_,K,ce,Oe)})}catch(_){if(!(_ instanceof Wt))throw _;this.stoppedForCheckpoint(e,l,_,i,Date.now()-o),d(_.code===rt?void 0:_);return}u=!0;let Je=ct(this.deps),Ne=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200;i.batchSize=Ne;let Fe=new Map,W={objects:0,records:0,of:1};p=this.runCreations?.recorder({runId:n,targetOrgId:t.targetOrgId,sourceOrgId:t.sourceOrgId,startedAt:new Date(o).toISOString(),origin:"clone"}),h&&p?.checkpoint?.(h),vr(p,()=>S.identity(),`seed:clone:execute ${n}`),p&&this.runningRuns.add(n);let se=new Pn({...p?{calls:_d(p,_=>{g+=_})}:{},keyPrefixOf:_=>Fe.get(_)?.keyPrefix,connection:S,bulkExecutor:new bn(Je.bulk.threshold),bulkManager:hr(this.deps),retryConfig:Je.retry,signal:a.signal,onProgress:(_,K,ce)=>{Le(this.deps,n,K>0?Math.round(_/K*100):0,_,K,ce),this.liveTracker?.updateProgress(n,Math.round((W.objects+_/Math.max(K,1))/W.of*100),W.records+_,0,ce)},log:_=>this.deps.log(_)}),te=new di({log:this.deps.log}),ue=new ci,$=t.objects.map(_=>_.objectApiName),N=new Set($),X=new Map,F=new Map,de=new Map;for(let _ of $){let[K,ce]=await Promise.all([Hd("target",_,()=>S.describe(_)),Hd("source",_,()=>te.describe(C,_))]);$e(S.limitInfo,`seed:clone:execute describe ${_}`),$e(C.limitInfo,`seed:clone:execute describe ${_} in the source`),X.set(_,K),F.set(_,ce),de.set(_,kr(K).fields??[]),Fe.set(_,{keyPrefix:K.keyPrefix??null,recordTypes:kh(K.recordTypeInfos)})}let J=ue.buildEdgesFromDescribe($,Jk(X,F)),le=ue.resolveInsertOrder($,J),Ee=ue.lookupsFilledAfter(le,J);W.of=Math.max(le.length,1);let je=new Map(t.objects.map(_=>[_.objectApiName,_])),We=new Map,ae=new Map,be=new Map,He=[],Ue=new Zf,ot=0,Ve=!1,Fn=new Map,Ht=[],ds=N.has(Xi),Yt=_=>Nt(S,_),Ii=new Map,lo=new Map,uo=Jn(mr(_=>Nt(C,_)),async _=>F.get(_)??await te.describe(C,_)),Dr=new Map,Ai=async(_,K)=>{if(K.length===0)return;let ce=await uo(_);for(let Oe of ce){let ye=!1;for(let ve of K)Oe in ve&&(ye||=ve[Oe]!==null&&ve[Oe]!==void 0,delete ve[Oe]);ye&&Dr.set(_,(Dr.get(_)??new Set).add(Oe))}},Nr=async(_,K)=>{let ce=(X.get(_)?.fields??[]).filter(ve=>ve.type==="reference"),Oe=await cR({lookups:ce,rows:K,known:Ii,query:Yt});if(Oe.size===0)return;let ye=lo.get(_)??new Map;for(let ve of K)for(let{name:fe}of ce){let Ye=ve[fe];typeof Ye!="string"||!Oe.has(Ye)||(delete ve[fe],ye.set(fe,(ye.get(fe)??0)+1))}ye.size!==0&&(lo.set(_,ye),this.deps.log(`[INFO] seed:clone ${_}: written without a user or a queue the target does not hold, which the platform fills (the owner with the user the clone writes as): `+[...ye].map(([ve,fe])=>`${ve} on ${fe}`).join(", ")))},cs=async(_,K)=>{await Ai(_,K),await Nr(_,K),R&&rS(R,_,de.get(_)??[],K,y?t.externalIdField:void 0),K.length>0&&(f=!0);try{return{outcomes:t.upsert&&t.externalIdField?await se.upsert(_,t.externalIdField,K,Ne):await se.insert(_,K,Ne),stopped:!1}}catch(ce){if(!(ce instanceof Uo))throw ce;return{outcomes:ce.written,stopped:!0}}},pr=(_,K,ce,Oe)=>{_.forEach((ye,ve)=>{let fe=typeof K[ve]?.Id=="string"?K[ve].Id:"";if(ye.success){ce.insertedCount++,fe&&ye.id&&(We.set(fe,ye.id),ce.idMappings.push({sourceId:fe,targetId:ye.id}));let Ye=ye.id;if(Ye)for(let{fieldName:ne,sourceRefId:Pe}of Oe[ve]??[])He.push({objectApiName:ce.objectApiName,newId:Ye,sourceId:fe||void 0,fieldName:ne,sourceRefId:Pe})}else ye.existingId?(ce.linkedCount=(ce.linkedCount??0)+1,fe&&(We.set(fe,ye.existingId),ce.idMappings.push({sourceId:fe,targetId:ye.existingId}))):(ce.failedCount++,ce.errors.push({sourceId:fe,message:ye.errors[0]??"Unknown insert error"}))})},Ti=async _=>{let K=new Map((m.find(fe=>fe.objectApiName===er)?.idMappings??[]).map(fe=>[fe.sourceId,fe.targetId])),ce=new Map;for(let[fe,Ye]of Fn){let ne=K.get(fe);ne&&ce.set(Ye,ne)}let Oe=_.map(fe=>String(fe.Id)).filter(fe=>ce.has(fe));if(Oe.length===0)return new Map;let ye;try{ye=await rh(Yt,[...new Set(Oe.map(fe=>ce.get(fe)??""))])}catch(fe){return this.deps.log(`[seed:clone] tasks written with the clone's emails not looked up, written as read: ${I(fe)}`),new Map}let ve=new Map;for(let fe of Oe){let Ye=ye.get(ce.get(fe)??"");Ye&&ve.set(fe,Ye)}return ve},Dt=async(_,K,ce)=>{if(sh[_]===void 0)return new Map;let Oe;try{Oe=await ih(Yt,_,ce)}catch(ve){return this.deps.log(`[seed:clone] ${_}: the relations the target holds not looked up, written as read: ${I(ve)}`),new Map}let ye=new Map;for(let[ve,fe]of Oe){let Ye=K[ve]?.Id;typeof Ye=="string"&&ye.set(Ye,fe)}return ye},_n=async(_,K)=>{if(ae.size===0)return new Map;let ce=X.get(fr),Oe=[...new Set(K.flatMap(ne=>Object.keys(ne)))].filter(ne=>Xk(ce,ne)),ye;try{ye=await oh(Yt,K.map((ne,Pe)=>({OpportunityId:ne.OpportunityId,[Ss]:ne[Ss],IsPrimary:_[Pe]?.IsPrimary})),ne=>ae.get(ne),Oe)}catch(ne){return this.deps.log(`[seed:clone] ${fr}: 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(ne)}`),new Map}let{found:ve,alike:fe}=ye;if(fe.length>0){this.deps.log(`[seed:clone] ${fr}: ${nh(fe.length)}`);for(let ne of fe)ae.delete(String(K[ne]?.OpportunityId))}let Ye=new Map;for(let[ne,Pe]of ve){let Be=_[ne]?.Id;typeof Be=="string"&&(Ye.set(Be,String(Pe.Id)),be.set(Be,Pe),ae.delete(String(K[ne]?.OpportunityId)))}return Ye},ls=async(_,K)=>{let ce=X.get(fr),Oe=[];if(_.forEach(([fe,Ye],ne)=>{let Pe=be.get(String(fe.Id))??{},Be=Object.entries(K[ne]??{}).filter(([vt,it])=>Xk(ce,vt)&&it!==null&&it!==void 0&&String(Pe[vt]??"")!==String(it));Be.length>0&&Oe.push({Id:Ye,...Object.fromEntries(Be)})}),Oe.length===0||Ve||a.signal.aborted)return;let ye;try{ye=await se.update(fr,Oe,Ne)}catch(fe){if(!(fe instanceof Uo))throw fe;Ve=!0,ye=fe.written}let ve=Oe.flatMap((fe,Ye)=>ye[Ye]?.success?[]:[`${fe.Id}: ${ye[Ye]?.errors[0]??"not updated"}`]);ve.length>0&&this.deps.log(`[seed:clone] ${fr}: linked, and left as the platform wrote them, without the fields of the source's roles: ${ve.slice(0,3).join(" | ")}`)},Hn=async()=>{ds=!1;let _=Ht.splice(0,Ht.length),K=m.find(fe=>fe.objectApiName===er);if(_.length===0||!K||Ve)return;if(a.signal.aborted){Ve=!0;return}let ce=_.map(fe=>Kk(er,fe,X.get(er),N,We)),Oe=Vk(er,_,ce,Ee,We),{outcomes:ye,stopped:ve}=await cs(er,ce);pr(ye,_,K,Oe),W.records+=_.length,ve&&(Ve=!0)};for(let _=0;_<le.length;_++){if(a.signal.aborted){Ve=!0;break}let K=le[_],ce=je.get(K);Le(this.deps,n,Math.round(_/le.length*100),_,le.length,`Cloning ${K}`),W.objects=_,this.liveTracker?.updateProgress(n,Math.round(_/le.length*100),W.records,0,`Cloning ${K}`);let Oe;try{Oe=await te.fetchRecords(C,K,ce.whereClause)}catch(xe){ot++,m.push({objectApiName:K,sourceCount:0,insertedCount:0,failedCount:0,idMappings:[],errors:[{sourceId:"",message:I(xe)}]});continue}let ye=Ue.keep(K,Oe,Gk(K,X.get(K),F.get(K)).map(({name:xe})=>xe)),ve=Oe.length-ye.length;if(K===er)for(let xe of ye){let Qe=xe.ActivityId;typeof xe.Id=="string"&&typeof Qe=="string"&&Qe!==""&&Fn.set(xe.Id,Qe)}let fe=ye.map(xe=>Kk(K,xe,X.get(K),N,We)),Ye=S$(ye,X.get(K));Ye.length>0&&this.deps.log(`[INFO] seed:clone ${K}: ${Ye.length} field(s) the target does not have left out \u2014 ${Ye.join(", ")}`);let ne=Vk(K,ye,fe,Ee,We),Pe=Oh(K,fe,Fe.get(K)?.recordTypes??[]);if(Pe.length>0){ot++,m.push({objectApiName:K,sourceCount:Oe.length,insertedCount:0,failedCount:ye.length,...ve>0?{leftToThePlatform:ve}:{},idMappings:[],errors:Pe.map(xe=>{let Qe=ye.find((tt,Bn)=>Ih(fe[Bn],[xe]));return{sourceId:typeof Qe?.Id=="string"?Qe.Id:xe.recordTypeId,message:Ah(xe)}})});continue}if(K===er&&ds){let xe=ye.map(Qe=>th(Qe));Ht.push(...ye.filter((Qe,tt)=>xe[tt])),ye=ye.filter((Qe,tt)=>!xe[tt]),fe=fe.filter((Qe,tt)=>!xe[tt]),ne=ne.filter((Qe,tt)=>!xe[tt])}let Be=K===Xi?await Ti(ye):K===fr?await _n(ye,fe):await Dt(K,ye,fe),vt=[],it=[];if(Be.size>0){let xe=ye.map(Qe=>!Be.has(String(Qe.Id)));ye.forEach((Qe,tt)=>{xe[tt]||(vt.push([Qe,Be.get(String(Qe.Id))??""]),it.push(fe[tt]))}),ye=ye.filter((Qe,tt)=>xe[tt]),fe=fe.filter((Qe,tt)=>xe[tt]),ne=ne.filter((Qe,tt)=>xe[tt])}if(a.signal.aborted){Ve=!0;break}let{outcomes:ht,stopped:Lr}=await cs(K,fe);if(Lr&&(Ve=!0,ht.length===0))break;if(K===k$&&ht.forEach((xe,Qe)=>{let tt=fe[Qe]?.[Ss];xe.success&&xe.id&&xe.created!==!1&&typeof tt=="string"&&tt!==""&&ae.set(xe.id,tt)}),K===fr&&vt.length>0&&await ls(vt,it),vt.length>0){let xe=X.get(K),Qe=await ah(K,vt,tt=>xe?.fields.find(Bn=>Bn.name===tt)?.updateable!==!1,async tt=>{try{return await se.update(K,tt,Ne)}catch(Bn){if(!(Bn instanceof Uo))throw Bn;return Ve=!0,Bn.written}},()=>Ve||a.signal.aborted);Qe&&this.deps.log(`[seed:clone] ${K}: ${Qe}`)}let go={objectApiName:K,sourceCount:Oe.length,insertedCount:0,failedCount:0,linkedCount:Be.size,...K===fr&&Be.size>0?{writtenByThePlatform:Be.size}:{},...ve>0?{leftToThePlatform:ve}:{},...Ye.length>0?{fieldsNotInTarget:Ye}:{},idMappings:[],errors:[]};for(let[xe,Qe]of Be)We.set(xe,Qe),go.idMappings.push({sourceId:xe,targetId:Qe});if(pr(ht,ye,go,ne),m.push(go),W.records+=ye.length,Ve)break;K===Xi&&await Hn()}await Hn();let jr;if(He.length>0&&(a.signal.aborted&&(Ve=!0),jr=Ve?R$(He):await b$({owed:He,idMap:We,targetConn:S,targetOrgId:t.targetOrgId,stopped:()=>a.signal.aborted,report:_=>{Le(this.deps,n,100,W.records,W.records,_),this.liveTracker?.updateProgress(n,100,W.records,0,_)}}),a.signal.aborted&&(Ve=!0),p&&jr.filled>0)){let _=new Map;for(let{objectApiName:K,newId:ce}of He)_.set(K,[..._.get(K)??[],ce]);for(let[K,ce]of _)p.wroteAgain(K,ce)}for(let _ of m){let K=lo.get(_.objectApiName);K&&(_.lookupsNotCarried=[...K].map(([Oe,ye])=>({field:Oe,records:ye})));let ce=Dr.get(_.objectApiName);ce&&(_.encryptedLeftOut=[...ce].sort())}let Cl=m.reduce((_,K)=>_+K.sourceCount,0),Un=m.reduce((_,K)=>_+K.insertedCount,0),Me=m.reduce((_,K)=>_+(K.linkedCount??0),0),Xe=m.reduce((_,K)=>_+(K.leftToThePlatform??0),0),Ke=m.reduce((_,K)=>_+K.failedCount,0),st=Ke===0&&ot===0?"success":Un+Me>0?"partial":"failure",Tt=jr!==void 0&&jr.filled<jr.owed,et=k(),gt=(Ve||Tt)&&st==="success"?"partial":st,Mr=await this.endKept(p,n,{status:gt,cancelled:Ve});p=void 0;let Qt=await xn(this.beforeRunCheckpoints,h,f,this.deps.log,`seed:clone:execute ${n}`);h=void 0;let mt={status:gt,objectResults:m,totalSourceRecords:Cl,totalInserted:Un,totalLinked:Me,...Xe>0?{totalLeftToThePlatform:Xe}:{},totalFailed:Ke,...jr?{secondPass:jr}:{},durationMs:Date.now()-o,...Ve?{cancelled:!0}:{},contactPoints:et,...Mr&&g>0?{runId:n}:{}};u=!1;let Gt=Ve?Un+Ke>0?"cancelled":"stopped":mt.status;Z(this.deps,{...zk(l,Gt,m,y,et),...Gt==="stopped"?{code:rt}:{},...Qt?.state==="taken"?{checkpointId:Qt.checkpointId}:{}});let Jt=!Ve&&mt.status==="failure"?"No record could be cloned.":void 0;Ve?(this.registry?.abort(n),pe(this.deps,n,{aborted:!0,totalInserted:Un,totalFailed:Ke}),this.liveTracker?.cancel(n)):(pe(this.deps,n,{status:mt.status,totalInserted:Un,totalFailed:Ke}),Jt!==void 0?this.liveTracker?.fail(n,Jt):mt.status==="partial"?this.liveTracker?.partial(n):this.liveTracker?.complete(n));let po={...mt,...Qt?{checkpoint:Qt}:{}},Et=T(this.deps,e,"seed:clone:execute:response",po);this.deps.broker.postToWebview(Et),this.deps.log(`[TX] ${Et.type} id=${Et.id} status=${mt.status}`),d(Jt===void 0?void 0:new Error(Jt))}catch(w){let O=await xn(this.beforeRunCheckpoints,h,f,this.deps.log,`seed:clone:execute ${n}`);u&&Z(this.deps,{...zk(l,"failure",m,y,k()),...O?.state==="taken"?{checkpointId:O.checkpointId}:{}}),await this.endKept(p,n,{status:"failure",cancelled:!1});let P=O?.state==="deleted"?`${I(w)} ${Kr}`:I(w);this.deps.log(`[ERR] seed:clone:execute: ${P}`),De(this.deps,n,I(w),!0,{context:i,extraPayload:{code:P.startsWith(qk)?an.guardBlocked:an.failed,...O?{checkpoint:O}:{}}}),this.liveTracker?.fail(n,P),d(w)}}};function g$(s){let e=[`narrow the filters of ${s.objects.join(", ")} or leave them out`,`turn off ${s.senders.map(t=>`"${t}"`).join(", ")}`,...s.bypasses.map(t=>"give the user the clone writes as "+(t.permissionSet?`the permission set ${t.permissionSet}, whose ${t.permission}`:`a permission set holding ${t.permission}, which`)+" keeps them quiet")];return`The clone was refused before it wrote anything: its records would make ${s.org} send about ${Ub(s.emails,s.limit)}, ${s.remaining} of ${s.max} left today. Past what is left, a flow that sends in the save refuses its record (CANNOT_EXECUTE_FLOW_TRIGGER), and the org's own emails stop for the rest of the day. To clone them, ${e.join("; or ")}. Nothing was written.`}function zk(s,e,t,r,n){return{...s,details:{...s.details,...ks(n).details},outcome:e,objects:t.map(o=>({...ft(o.objectApiName),...r?{upserted:o.insertedCount}:{created:o.insertedCount},failed:o.failedCount})),carried:Object.fromEntries(t.map(o=>[o.objectApiName,o.idMappings.length]))}}function Gk(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)&&gs(s,n.name,n.nillable)).map(n=>({name:n.name,referenceTo:n.referenceTo??[]}))}async function Hd(s,e,t){try{return await t()}catch(r){let n=I(r);throw s==="target"&&h$(r,n)?new Bd(e,n):new Error(`${e} could not be described in the ${s} org: ${n}`)}}var f$="OBJECT_NOT_IN_TARGET",Bd=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 h$(s,e){return s?.errorCode==="NOT_FOUND"||/\bNOT_FOUND\b|requested resource does not exist|INVALID_TYPE/.test(e)}function Jk(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 m$(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 y$(s,e,t){let r=new Set(s);return s.flatMap(n=>{let o=qd(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 w$(s,e,t){return s.flatMap(r=>{let n=qd(t.get(r));return n?(e.get(r)?.fields??[]).filter(o=>o.type==="reference"&&!n.has(o.name)&&o.createable!==!1&&o.defaultedOnCreate!==!0&&gs(r,o.name,o.nillable)).flatMap(o=>(o.referenceTo??[]).map(i=>({objectApiName:r,field:o.name,referenceTo:i}))):[]})}function Vk(s,e,t,r,n){let o=r.filter(c=>c.to===s),i=new Set(o.filter(c=>c.from!==s).map(c=>c.fieldApiName)),a=new Set(o.map(c=>c.fieldApiName)),d=new Set(e.map(c=>c.Id).filter(c=>typeof c=="string"));return t.map((c,l)=>{let u=[];for(let p of a){let g=e[l]?.[p];typeof g!="string"||g===""||n.has(g)||p in c&&(!i.has(p)&&!d.has(g)||(delete c[p],u.push({fieldName:p,sourceRefId:g})))}return u})}async function b$(s){let{owed:e,targetConn:t}=s,{patchCycleFkUpdates:r}=await import("./chunk-P63WJMXQ.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:Ni()});return(Array.isArray(d)?d:[d]).map((c,l)=>{let u=a[l]?.Id;return{id:c.id??(typeof u=="string"?u:""),success:c.success,errors:(c.success?[]:c.errors).map(nw)}})},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 R$(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 qd(s){let e=new Set((s?.fields??[]).map(t=>t.name));return e.size>0?e:null}function S$(s,e){let t=qd(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 v$(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 k$="Opportunity";function Xk(s,e){if(e==="OpportunityId"||e===Ss)return!1;let t=s?.fields.find(r=>r.name===e);return t!==void 0&&t.updateable!==!1}function Kk(s,e,t,r,n){let o=new Set((t?.fields??[]).filter(d=>d.createable===!1).map(d=>d.name)),i=qd(t),a={};for(let[d,c]of Object.entries(e))d==="Id"||o.has(d)||i&&!i.has(d)||(a[d]=c);if(t)for(let d of t.fields){if(d.type!=="reference"||!(d.referenceTo??[]).some(l=>r.has(l)))continue;let c=a[d.name];typeof c=="string"&&n.has(c)&&(a[d.name]=n.get(c))}for(let d of Ki(s,a))delete a[d];return a}var O$=new Set(["double","currency","percent","int","integer"]),Wd=class{validate(e,t,r,n){let o=[],i=new Map(r.map(a=>[a.name,a]));for(let a=0;a<e.length&&o.length<100;a++){let d=e[a];for(let c of t){if(o.length>=100)break;if(!c.sfFieldApiName)continue;let l=i.get(c.sfFieldApiName);if(!l)continue;let u=d[c.csvHeader]??"";if(u===""&&!l.nillable&&l.defaultValue===null){o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"missing_required",message:`Required field "${c.sfFieldApiName}" is empty`,value:u});continue}if(u!==""){if(O$.has(l.type.toLowerCase())){let p=parseFloat(u);isNaN(p)&&o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"type_mismatch",message:`Expected numeric value for field "${c.sfFieldApiName}", got "${u}"`,value:u})}l.length&&l.length>0&&u.length>l.length&&o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"length_exceeded",message:`Value exceeds max length ${l.length} for field "${c.sfFieldApiName}" (got ${u.length})`,value:u}),l.type.toLowerCase()==="picklist"&&l.picklistValues&&l.picklistValues.length>0&&(l.picklistValues.map(g=>g.value).includes(u)||o.push({row:a+1,column:c.csvHeader,field:c.sfFieldApiName,errorType:"invalid_picklist",message:`Invalid picklist value "${u}" for field "${c.sfFieldApiName}"`,value:u}))}}}if(n&&o.length<100){let a=t.find(d=>d.sfFieldApiName===n);if(a){let d=new Map;for(let c=0;c<e.length&&o.length<100;c++){let l=e[c][a.csvHeader]??"";if(l==="")continue;let u=d.get(l);u!==void 0?o.push({row:c+1,column:a.csvHeader,field:n,errorType:"duplicate_external_id",message:`Duplicate external ID "${l}" (also in row ${u})`,value:l}):d.set(l,c+1)}}}return{valid:o.length===0,errors:o,warningCount:0}}};var I$=new Set(["seed:csv:validate","seed:csv:execute"]),A$=100,Yk="IMPORT_CANCELLED",T$=6e4,Mp="CSV_STORAGE_EXCEEDED";function E$(s){let e=s<10?100:10;return String(s<=0?0:Math.ceil(s*e-1e-9)/e)}function P$(s,e,t){let r=e>0?Yn(s,{rows:e})/e:0;return r>0?Math.max(0,Math.floor(t*1024*1024/r)):0}var zd=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-DIL62SUN.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async handle(e){if(!I$.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:Yk}),this.registry?.abort(o),pe(this.deps,o,{aborted:!0,insertedCount:0,failedCount:0}),this.liveTracker?.cancel(o);let d={insertedCount:0,failedCount:0,errors:[],cancelled:!0};this.deps.broker.postToWebview(T(this.deps,e,"seed:csv:execute:response",d));return}let i=r.refusal?.code,a=i!==void 0?{checkpointRefusal:i}:{};Z(this.deps,{...t,outcome:"stopped",source:void 0,code:r.code,...i!==void 0?{details:a}:{}}),E(this.deps,"seed:csv:execute","seed:csv:error",e,r,{code:r.code,retryable:!1,...i!==void 0?{extraPayload:a}:{}}),De(this.deps,o,r.message,!1,{context:n,authored:!0,extraPayload:{code:r.code,...a}}),this.liveTracker?.fail(o,r.message)}async handleValidate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(su,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);$e(r.limitInfo,`seed:csv:validate describe ${t.objectApiName}`);let i=new Wd().validate(t.records,t.columnMappings,n.fields,t.externalIdField),a=T(this.deps,e,"seed:csv:validate:response",i);this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id} valid=${i.valid}`)}catch(r){E(this.deps,"seed:csv:validate","seed:csv:error",e,r)}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(su,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((h,f)=>{i=m=>m===void 0?h():f(m)});a.catch(()=>{}),this.registry?.register(r,"csv","CSV import",a,o);let d={action:"seed_csv_import",module:"seed",operationId:r,orgId:t.orgId,outcome:"failure",source:{origin:"csv"}},c=!1,l,u=0,p,g=!1;try{let h=this.deps.infraServices?.productionGuard;if(!h){Z(this.deps,{...d,outcome:"stopped",source:void 0,code:Se.code}),E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(Se.message),{code:Se.code,retryable:!1}),De(this.deps,r,Se.message,!1,{context:n,extraPayload:{code:Se.code}}),i(new Error(Se.message));return}let f=this.deps.orgManager.getOrg(t.orgId),m={orgId:t.orgId,orgTier:Ce(f),operation:t.externalIdField?"upsert":"insert",objectName:t.objectApiName,recordCount:t.records.length,module:"seed"},{check:y,decision:R}=await Ze(h,m);if(d.guard=R,(R==="refused"||R==="declined")&&Z(this.deps,{...d,outcome:"stopped",source:void 0}),R==="refused")throw hn(y.blockedReason??y.impactSummary);if(R==="declined"){let te="Operation cancelled by user (confirmation declined).";E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(te),{code:Ct.declined}),De(this.deps,r,te,!1,{context:n}),i(new Error(te));return}let k=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),w=me(f,t.orgId),O=(te,ue,$)=>{let N=$!==void 0?{checkpointRefusal:$}:{};Z(this.deps,{...d,outcome:"stopped",source:void 0,code:te,...$!==void 0?{details:N}:{}}),E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(ue),{code:te,retryable:!1,...$!==void 0?{extraPayload:N}:{}}),De(this.deps,r,ue,!1,{context:n,authored:!0,extraPayload:{code:te,...N}}),i(new Error(ue))},P=this.targetAutomation,b=ai([t.objectApiName],!!t.externalIdField),v=await new ge(T$).withTimeout("csv automation",()=>P.read(t.orgId,[t.objectApiName])).catch(te=>({unread:I(te)}));typeof v.unread=="string"&&this.deps.log(`[WARN] seed:csv:execute ${r}: what the org runs on ${t.objectApiName} could not be read (${v.unread}): it is asked about its emails, and a checkpoint holds the object alone`);let C=await ir({read:v,writes:b,readDeliverability:()=>Ce(f)==="production"?Promise.resolve(Bt):qt(k),accepted:!1,target:w,run:"seed",keepsAddresses:!0}),S=C.gate.verdict==="asks",A;if(t.checkpointFirst!==void 0){try{A=await si(this.beforeRunCheckpoints,{module:"seed",orgId:t.orgId,operationId:r,written:[t.objectApiName],running:Fd(v,b),request:t.checkpointFirst})}catch(ue){if(!(ue instanceof Wt))throw ue;O(ue.code,ue.message);return}let te=xa(A.planned);if(te){O(te.code,te.message,te.refusal.code);return}}let D=await br(k).catch(te=>({unread:I(te)})),z="unread"in D?await ar(k).catch(te=>({unread:I(te)})):D.dailyApiRequests,U=Rr({storageBytes:Yn(t.objectApiName,{rows:t.records.length})},D);if(!t.externalIdField&&U.verdict==="exceeds"){let te=t.records.length,ue=P$(t.objectApiName,te,U.remainingMB),$=`The import was refused before it wrote anything: its ${te} rows take about ${E$(U.estimateMB)} MB of data storage, and ${w} has ${U.remainingMB} MB left of ${U.maxMB} MB, room for about ${ue} of them: split the file and import one part at a time, freeing data storage in between as needed. Nothing was written.`;Z(this.deps,{...d,outcome:"stopped",source:void 0,code:Mp});let N={org:w,rows:te,fitting:ue,estimateMB:U.estimateMB,remainingMB:U.remainingMB,maxMB:U.maxMB};E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error($),{code:Mp,retryable:!1,extraPayload:N}),De(this.deps,r,$,!1,{context:n,authored:!0,extraPayload:{code:Mp,...N}}),i(new Error($));return}let Y=On({run:fS([{objectApiName:t.objectApiName,rows:t.records.length}],{threshold:ct(this.deps).bulk.threshold,perCall:this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200),duplicateRules:No(v)})+hS(0,An(v)),...xo(A?.planned),...Tn(C.ofRun)},z);Y.verdict==="unread"&&this.deps.log(`[WARN] seed:csv:execute ${r}: the daily API requests the org has left could not be read (${Y.unread})`);let H=$a(Y,me(f,t.orgId));if(H){Z(this.deps,{...d,outcome:"stopped",source:void 0,code:Co}),E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(H),{code:Co,retryable:!1}),De(this.deps,r,H,!1,{context:n,authored:!0,extraPayload:{code:Co}}),i(new Error(H));return}let M=!1;if(A||S){let te=t.records.length,ue=await h.confirmRun({stage:"write",module:"seed",org:w,orgTier:Ce(f),objects:[{objectApiName:t.objectApiName,rows:te}],total:te,storage:En(Rr({storageBytes:Yn(t.objectApiName,{rows:te})},D)),...$o(Y),...A?{checkpoint:A.planned}:{},...C.gate.confirmation});if(ue!=="confirmed"){let $=C.gate.stop;ue!=="declined"&&!A&&$?O($.code,$.message):O(ue==="declined"?Xo:St.unanswered,ue==="declined"?"The import was cancelled before it wrote anything. Nothing was written.":`The import needed an answer before it wrote \u2014 the checkpoint it takes first reads whole tables of ${w} \u2014 and there was no one to ask. Nothing was written.`);return}M=S}if(d.details=sn({read:C,accepted:M}).details,ze(this.deps,r,"seed",`CSV import ${t.records.length} record(s) into ${t.objectApiName}`),this.liveTracker?.register(r,"csv",`CSV import ${t.records.length} record(s) into ${t.objectApiName}`,t.records.length),A)try{p=await ii(this.beforeRunCheckpoints,A,r,o.signal,(te,ue,$,N)=>{Le(this.deps,r,te,ue,$,N),this.liveTracker?.updateProgress(r,te,ue,$,N)})}catch(te){if(!(te instanceof Wt))throw te;this.stoppedForCheckpoint(e,d,te,n),i(te.code===rt?void 0:te);return}c=!0;let L=ct(this.deps),ee=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200;n.batchSize=ee,l=this.runCreations?.recorder({runId:r,targetOrgId:t.orgId,startedAt:new Date().toISOString(),origin:"csv"}),p&&l?.checkpoint?.(p),vr(l,()=>k.identity(),`seed:csv:execute ${r}`),l&&this.runningRuns.add(r);let Q=new Pn({connection:k,bulkExecutor:new bn(L.bulk.threshold),bulkManager:hr(this.deps),retryConfig:L.retry,signal:o.signal,onProgress:(te,ue,$)=>{let N=ue>0?Math.round(te/ue*100):0;Le(this.deps,r,N,te,ue,$),this.liveTracker?.updateProgress(r,N,te,ue,$)},log:te=>this.deps.log(te),...l?{calls:_d(l,te=>{u+=te})}:{}}),B=t.records.map(te=>C$(te,t.columnMappings)),V=o.signal.aborted,we=[];if(!V){B.length>0&&(g=!0);try{we=t.externalIdField?await Q.upsert(t.objectApiName,t.externalIdField,B,ee):await Q.insert(t.objectApiName,B,ee)}catch(te){if(!(te instanceof Uo))throw te;V=!0,we=te.written}}let ie=[],re=0;for(let te of we)te.success?re++:ie.length<A$&&ie.push(te.errors[0]??"Unknown insert error");let Ae=we.length-re,he=Ae===0?"success":re>0?"partial":"failure",Je=!V&&he==="failure"?ie[0]??"No row could be imported.":void 0;c=!1;let Ne=await xn(this.beforeRunCheckpoints,p,g,this.deps.log,`seed:csv:execute ${r}`);p=void 0,V&&we.length===0?Z(this.deps,{...d,outcome:"stopped",source:void 0,code:Yk}):Z(this.deps,{...d,outcome:V?"cancelled":he,objects:[{...ft(t.objectApiName),...t.externalIdField?{upserted:re}:{created:re},failed:Ae}],...Ne?.state==="taken"?{checkpointId:Ne.checkpointId}:{}});let Fe=await this.endKept(l,r,{status:V&&he==="success"?"partial":he,cancelled:V});l=void 0;let W={insertedCount:re,failedCount:Ae,errors:ie,...V?{cancelled:!0}:{},...Fe&&u>0?{runId:r}:{},...Ne?{checkpoint:Ne}:{}};V?(this.registry?.abort(r),pe(this.deps,r,{aborted:!0,insertedCount:re,failedCount:Ae}),this.liveTracker?.cancel(r)):(pe(this.deps,r,{status:he,insertedCount:re,failedCount:Ae}),Je!==void 0?this.liveTracker?.fail(r,Je):he==="partial"?this.liveTracker?.partial(r):this.liveTracker?.complete(r));let se=T(this.deps,e,"seed:csv:execute:response",W);this.deps.broker.postToWebview(se),this.deps.log(`[TX] ${se.type} id=${se.id} inserted=${re} failed=${Ae}`),i(Je===void 0?void 0:new Error(Je))}catch(h){let f=await xn(this.beforeRunCheckpoints,p,g,this.deps.log,`seed:csv:execute ${r}`);c&&Z(this.deps,{...d,...f?.state==="taken"?{checkpointId:f.checkpointId}:{}}),await this.endKept(l,r,{status:"failure",cancelled:!1});let m=f?.state==="deleted"?`${I(h)} ${Kr}`:I(h);E(this.deps,"seed:csv:execute","seed:csv:error",e,h,{code:vo(h),retryable:!0,...f?{extraPayload:{checkpoint:f}}:{}}),De(this.deps,r,m,!0,{context:n}),this.liveTracker?.fail(r,m),i(h)}}};function C$(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]=$$(n))}return t}function $$(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 x$={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"])},D$=[{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 Lp(s,e){let t=s.toLowerCase(),r=e.toLowerCase();if(t===r)return!0;let n=x$[t];return n?n.has(r):r==="string"}var Gd=class{validateMapping(e,t,r){let n=[],o=[],i=new Map(e.map(d=>[d.apiName,d])),a=new Map(t.map(d=>[d.apiName,d]));for(let[d,c]of Object.entries(r)){let l=i.get(d),u=a.get(c);if(!l||!u)continue;let p=this.checkTypeCompatibility(d,l.type,c,u.type);p.compatible?p.reason&&o.push(p):n.push(p)}return{valid:n.length===0,errors:n,warnings:o}}validateRecords(e,t){let r=[];for(let n=0;n<e.length;n++){let o=e[n];for(let i of t){let a=o[i.apiName];if(i.required&&Qk(a)){r.push({recordIndex:n,field:i.apiName,message:`Required field '${i.apiName}' is missing or empty`});continue}if(Qk(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=Lp(o,i),d=D$.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"||!N$(e))return`Expected valid ${r} string`;break}}};function Qk(s){return s==null||s===""}function N$(s){let e=Date.parse(s);return!isNaN(e)}var Jd=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 Fp=3e4,Zk=6e4,_p="Nothing was read or written.",eO="Nothing was read.",tO="the checkpoints of this window are not open to the Sync page",M$=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"]),rO={insert:0,update:1,upsert:2,delete:3};function Up(s,e){let t=s.objects??[],r="insert";for(let o of t)rO[o.operation]>rO[r]&&(r=o.operation);s.mode==="delta"&&s.propagateDeletes===!0&&(r="delete");let n=t.map(o=>o.objectApiName);return{orgId:s.targetOrgId,orgTier:Ce(e),operation:r,objectName:n.length>0?n.join(", "):"SyncData",recordCount:"unknown",module:"sync"}}function L$(s){return s.map(e=>{let t={...ft(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 F$=new Set(["direct","rename"]),Hp=20,_$=G({fields:Re(G({name:j(),type:j(),createable:Ge(),updateable:Ge()}).loose())});function nO(s,e,t){let r=_$.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 oO(s){if(s==="ask")return{emailsLiftedBy:"Untick Mute automation to be asked about them and sync all the same"};let e=Mw();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 Vd=class{constructor(e){this.deps=e;this.syncConfigStore=new Ot(e.configStore)}deps;activeOperationIds=new Set;dmlTracker=new ea;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-DIL62SUN.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",Yr);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):Yr}readCap(){return Ya(this.deps.services?.getSandforgeSetting?.("sync.maxRecordsPerObject",void 0))}writeGateFor(e,t,r,n,o,i){let a=this.deps.orgManager.getOrg(e.targetOrgId),d=this.targetAutomation,c=this.deps.infraServices?.productionGuard,l=oO(r),u=this.readCap(),p=RS(e,async g=>{let{totalSize:h}=await t.query(g);return Math.min(h,u)});return SS({readStorage:()=>new ge(Fp).withTimeout("sync:limits",()=>br(t)),readApiBudget:()=>new ge(Fp).withTimeout("sync:limits",()=>ar(t)),readAutomation:n??(g=>new ge(Zk).withTimeout("sync:automation",()=>d.read(e.targetOrgId,g))),readLimits:()=>new ge(Fp).withTimeout("sync:limits",()=>Sr(t)),readDeliverability:()=>Ce(a)==="production"?Promise.resolve(Bt):qt(t),emails:{target:me(a,e.targetOrgId),accepted:l.emailsAccepted===!0,keepsAddresses:e.keepContactPoints===!0},confirmAboveRecords:this.confirmAboveRecords(),bulkThreshold:ct(this.deps).bulk.threshold,...o?{checkpointFirst:o}:{},...i?{mutePlan:i}:{},...p?{countTarget:p}:{}},{policy:r,org:me(a,e.targetOrgId),orgTier:Ce(a),...c?{confirm:g=>c.confirmRun(g)}:{},emailsLiftedBy:l.emailsLiftedBy})}setRegistry(e){this.registry=e}setMuteLeases(e){this.muteLeases=e}muteLeases={};setHistoryLogger(e){this.historyLogger=e}setLiveOperationTracker(e){this.liveTracker=e}setRunCreations(e){this.runCreations=e}setBackupRecordStore(e){this.backupRecords=e}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}beforeRunCheckpoints;runCheckpointOf(e,t,r,n){let o=this.beforeRunCheckpoints,i={runId:t},a,d,c,l;return{gate:{scope:async(u,p)=>{if(!o)throw new Error(tO);return a={module:"sync",orgId:e.targetOrgId,operationId:t,written:[...u],running:p,request:r},d=await o.scope(a,i),l=d.refusal,d},take:async u=>{if(!o||!a)throw new Error(tO);let p=await o.take(a,i,{planned:u,...n?{signal:n.signal,onProgress:g=>{let h=Po(g.percentage),f=Math.round(g.percentage),{processedObjects:m,totalObjects:y}=g;Le(this.deps,t,f,m,y,h),this.liveTracker?.updateProgress(t,f,m,y,h)}}:{}});return p.taken?(c=p.checkpoint,n?.recorder?.checkpoint?.(p.checkpoint)):"refusal"in p&&(l=p.refusal),p}},planned:()=>d,taken:()=>c,refusal:()=>l}}async settleRunCheckpoint(e,t,r){let n=e?.taken();if(!(!n||!this.beforeRunCheckpoints))try{return await this.beforeRunCheckpoints.settle(n,t)}catch(o){return this.deps.log(`[WARN] sync ${r}: the checkpoint '${n.name}' taken before the run is kept: ${I(o)}`),n}}isRunning(e){return this.activeOperationIds.has(e)}async handle(e){if(!M$.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=mo(t.objects);return i.length===0?!1:(E(this.deps,r,n,e,new Error(`${yo(i)} ${o}`),{code:Fi,extraPayload:{rules:i}}),!0)}async handleConfigSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(_h,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(Ff(this.syncConfigStore.list(),r.id,r.name)){let o=T(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=T(this.deps,e,"sync:config:save:response",{success:!0,id:r.id});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){E(this.deps,"sync:config:save","sync:error",e,r)}}async handleConfigLoad(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ra,e,"sync:error",this.deps);if(t)try{let r=this.syncConfigStore.load(t.id),n=T(this.deps,e,"sync:config:load:response",{config:r??null});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){E(this.deps,"sync:config:load","sync:error",e,r)}}async handleConfigList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let r=this.syncConfigStore.list().map(o=>{let i=this.syncConfigStore.loadDelta(o.id);return{id:o.id,name:o.name,description:o.description,updatedAt:o.updatedAt,mode:o.mode,propagateDeletes:o.propagateDeletes===!0,watermarks:i.kind==="stored"?i.state.entries.length:0}}),n=T(this.deps,e,"sync:config:list:response",{configs:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(t){E(this.deps,"sync:config:list","sync:error",e,t)}}async handleConfigDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ra,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=T(this.deps,e,"sync:config:delete:response",{success:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){E(this.deps,"sync:config:delete","sync:error",e,r)}}async handleConfigResetDelta(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ra,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=T(this.deps,e,"sync:config:reset-delta:response",{success:!0,id:t.id,cleared:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} cleared=${r}`)}catch(r){E(this.deps,"sync:config:reset-delta","sync:error",e,r)}}deltaStoreFor(){return this.syncConfigStore.deltaStore()}fileStoreFor(){return this.syncConfigStore.fileStore()}idMapFor(){let e=this.runCreations;if(e)return kw(e.idMap(),t=>this.syncConfigStore.isSaved(t))}recordRun(e,t,r,n,o,i){let a=L$(r.objectResults??[]),d=a.some(l=>l.created+l.updated+l.deleted+l.failed+(l.upserted??0)>0),c=r.cancelled===!0?d?"cancelled":"stopped":r.status;Z(this.deps,{action:"sync_execute",module:"sync",operationId:t,orgId:e.targetOrgId,outcome:c,...c==="stopped"?{code:rt}:{},guard:n,objects:a,source:{origin:"org",orgId:e.sourceOrgId},details:{triggeredBy:o,...Vn(i)},...r.mutedAutomation?{muted:dt(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 Up(e,this.deps.orgManager.getOrg(e.targetOrgId))}async assertFieldTypesMatch(e,t,r,n){let o=new Gd,i=[],a=l=>({apiName:l.name,type:l.type});for(let l of e.objects){if(l.operation==="delete")continue;let u=l.objectApiName,p=new ge(n),[g,h]=await Promise.all([p.withTimeout(`describe-source-${u}`,()=>Kt(e.sourceOrgId,u,()=>t.describe(u))),p.withTimeout(`describe-target-${u}`,()=>Kt(e.targetOrgId,u,()=>r.describe(u)))]),f=nO(g,u,"source").map(a),m=nO(h,u,"target").filter(w=>w.createable||w.updateable).map(a),y=eS(l,{creatable:new Set(m.map(w=>w.apiName))}),R=Ch(y.fieldMappings,y.excludedFields),k=[Object.fromEntries(f.filter(w=>!R.has(w.apiName.toLowerCase())).map(w=>[w.apiName,w.apiName])),...l.fieldMappings.filter(w=>F$.has(w.type)).map(w=>({[w.sourceField]:w.targetField}))];for(let w of k)for(let O of o.validateMapping(f,m,w).errors)i.push(`${u}.${O.sourceField} (${O.sourceType}) -> ${u}.${O.targetField} (${O.targetType})`)}if(i.length===0)return;let d=i.slice(0,Hp).join("; "),c=i.length>Hp?` and ${i.length-Hp} more`:"";throw new Error(`Field types do not match between the orgs, so the sync was not started and nothing was written: ${d}${c}. Map each field onto a field of a compatible type, convert the value with a transform, or leave the field out: Exclude as its mapping on the Field Mapping step, or in the object's excludedFields in a saved configuration.`)}async handleDescribeGlobal(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Hh,e,"sync:error",this.deps);if(!t)return;let r=ct(this.deps);try{let n=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),o=new ge(r.timeouts.describeGlobal),i=await o.withTimeout("describe-global",()=>n.describeGlobal());$e(n.limitInfo,"sync:describe-global");let a=i.sobjects.filter(u=>u.queryable&&!ta(u.name)),d,c=[];if(t.targetOrgId===void 0)d=a.filter(u=>u.createable).map(u=>u.name);else{let u=await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),p=await o.withTimeout("describe-global",()=>u.describeGlobal());$e(u.limitInfo,"sync:describe-global target");let g=new Map(p.sobjects.map(h=>[h.name,{createable:h.createable,updateable:h.updateable}]));d=[];for(let h of a){let f=g.get(h.name);if(f&&(f.createable||f.updateable)){d.push(h.name);continue}h.createable&&c.push({objectApiName:h.name,why:f?"notCreateable":"notInTarget"})}}let l=T(this.deps,e,"sync:describe-global:response",{objects:d,...c.length>0?{unwritable:c}:{}});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`)}catch(n){E(this.deps,"sync:describe-global","sync:error",e,n)}}async handleDescribeFields(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Uh,e,"sync:error",this.deps);if(!t)return;let r=t,n=ct(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 ge(n.timeouts.describe),[d,c]=await Promise.all([a.withTimeout("describe-source",()=>o.describe(r.objectApiName)),a.withTimeout("describe-target",()=>i.describe(r.objectApiName))]);$e(o.limitInfo,`sync:describe-fields source ${r.objectApiName}`),$e(i.limitInfo,`sync:describe-fields target ${r.objectApiName}`);let l=p=>p.filter(g=>g.createable).map(g=>({apiName:g.name,label:g.label,type:g.type})),u=T(this.deps,e,"sync:describe-fields:response",{objectApiName:r.objectApiName,sourceFields:l(d.fields),targetFields:l(c.fields)});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`)}catch(o){E(this.deps,"sync:describe-fields","sync:error",e,o)}}async handleWriteOrder(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(tu,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=ct(this.deps).timeouts.describe,i=new Map;for(let l of r.objects){if(l.operation==="delete")continue;let u=l.objectApiName;try{let p=await new ge(o).withTimeout(`describe-target-${u}`,()=>Kt(r.targetOrgId,u,()=>n.describe(u)));i.set(u,iS(l,kr(p)))}catch{}}let{order:a}=aS(r.objects,i),d=await this.encryptedMaskedOf(r,o).catch(()=>[]),c=T(this.deps,e,"sync:write-order:response",{order:a,...d.length>0?{encrypted:d}:{},readCap:this.readCap()});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(n){E(this.deps,"sync:write-order","sync:error",e,n)}}async encryptedMaskedOf(e,t){let r=e.objects.filter(a=>a.operation!=="delete");if(r.length===0)return[];let n=await q(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),o=Jn(mr(async a=>(await n.query(a)).records),a=>new ge(t).withTimeout(`describe-source-${a}`,()=>Kt(e.sourceOrgId,a,()=>n.describe(a)))),i=[];for(let a of r){let d=await o(a.objectApiName);d.length>0&&i.push({objectApiName:a.objectApiName,fields:d})}return i}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(yn,e,"sync:error",this.deps);t&&(this.refusedFieldless(e,t.config,"sync:execute","sync:error",_p)||await this.startExecution(e,t.config,"manual",t.muteAutomation===!0,t.checkpointFirst))}async handleSimulate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(tu,e,"sync:error",this.deps);if(!t||this.refusedFieldless(e,t.config,"sync:simulate","sync:error",eO))return;let r=e.id,n=t.config,o=`Simulation of a sync of ${n.objects.length} object(s), writing nothing`,i=new AbortController;ze(this.deps,r,"sync",o),this.liveTracker?.register(r,"sync",o);let a=this.simulateSync(e,n,r,i,t.checkpointFirst);if(this.registry){let d=a.then(c=>({status:c===null||c.error?"failure":"success"}));this.registry.register(r,"sync",o,d,i)}else await a}async simulateSync(e,t,r,n,o,i){let a=ct(this.deps),d={module:"sync",operation:e.type,...zr(t.objects)};try{let c=await this.readersFor(t,n.signal),{DataSync:l}=await import("./chunk-WT3SCUHS.mjs"),{ConflictResolver:u}=await import("./chunk-CHCHAE4B.mjs"),{FieldMappingService:p}=await import("./chunk-STRMWSIQ.mjs"),{TransformPipeline:g}=await import("./chunk-Q6SXNKV2.mjs"),{toolingQueriesOver:h,toolingValidationRules:f}=await import("./chunk-42BFLWHR.mjs"),{toolingRetrievesOver:m}=await import("./chunk-DIL62SUN.mjs"),y=c.targetConn.tooling,R=async()=>{throw new Error("A simulation writes nothing: the write it reached was refused.")},k=new l({insert:R,update:R,upsert:R,delete:R,describeTargetFields:c.describeTargetFields});if(!this.deps.services)throw new Error("SyncOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let w=o?this.runCheckpointOf(t,r,o):void 0,O=this.deps.services.syncOrchestrator({dataSync:k,conflictResolver:new u,fieldMapping:new p,transformPipeline:new g,querySource:c.querySource,maskedSourceFields:c.maskedSourceFields,queryTarget:c.queryTarget,services:this.deps.services,signal:n.signal,findInTarget:c.findInTarget,bulkThreshold:a.bulk.threshold,describeTargetFields:c.describeTargetFields,readSourceIds:c.readSourceIds,countSource:c.countSource,countPersonAccounts:c.countPersonAccounts,writeGate:this.writeGateFor(t,c.targetConn,"ask",void 0,w?.gate),queryTargetRows:c.queryTargetRows,recordTypes:c.recordTypes,currencies:c.currencies,standardPricebooks:c.standardPricebooks,deltaStore:this.deltaStoreFor(),deltaReads:c.deltaReads,idMap:this.idMapFor(),files:c.files,readValidationRules:f(async A=>(await tr({query:async D=>y.query(D),queryMore:async D=>y.queryMore(D)},A)).records,h(c.targetConn),m(c.targetConn)),onSimulationProgress:(A,D,z)=>{let U=Math.round(A/D*100),Y=`Simulating ${z}`;Le(this.deps,r,U,A,D,Y),this.liveTracker?.updateProgress(r,U,A,D,Y)}});await this.assertFieldTypesMatch(t,c.sourceConn,c.targetConn,a.timeouts.describe);let P=await O.simulate(t),b=w?.planned(),v=[...c.cutAtReadCap],C={...P,...b?{checkpoint:b}:{},readCap:c.readCap,...v.length>0?{cutAtReadCap:v}:{},operationId:r};C.cancelled?this.endCancelled(r):C.error?(this.liveTracker?.fail(r,C.error),De(this.deps,r,C.error,!0,{context:d})):(Le(this.deps,r,100,1,1,"Simulation complete"),pe(this.deps,r,{status:"success",simulated:!0}),this.liveTracker?.complete(r)),this.deps.log(`[sync] simulation ${r} ${C.cancelled?"stopped":"finished"}: `+C.objects.map(A=>`${A.objectApiName} insert=${A.insert} update=${A.update} delete=${A.delete} skipped=${A.skipped} refused=${A.refused} conflicts=${A.conflicts}`).join("; "));let S=T(this.deps,e,"sync:simulate:response",C);return this.deps.broker.postToWebview(S),this.deps.log(`[TX] ${S.type} id=${S.id}`),C}catch(c){return this.liveTracker?.fail(r,I(c)),E(this.deps,"sync:simulate","sync:error",e,c),De(this.deps,r,I(c),!0,{context:d}),i?.(c),null}}async simulateForPipeline(e,t){let r=yn.safeParse({config:e});if(!r.success)throw new Error(`Pipeline sync config failed validation: ${r.error.issues.map(g=>g.message).join("; ")}`);let n=mo(r.data.config.objects);if(n.length>0)throw Object.assign(new Error(`${yo(n)} ${eO}`),{code:Fi});let o=mn("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(g=>({...g,batchSize:g.batchSize??a}))},c=`Pipeline simulation of a sync of ${d.objects.length} object(s), writing nothing`,l=new AbortController,u=()=>l.abort();t?.aborted&&l.abort(),t?.addEventListener("abort",u,{once:!0}),ze(this.deps,i,"sync",c),this.liveTracker?.register(i,"sync",c);let p;try{let g=this.simulateSync(o,d,i,l,void 0,f=>{p=f});this.registry?.register(i,"sync",c,g.then(f=>({status:f===null||f.error?"failure":"success"})),l);let h=await g;if(h===null)throw p instanceof Error?p:new Error(I(p));return h}finally{t?.removeEventListener("abort",u)}}async handleRunControl(e,t){this.deps.log(`[RX] ${e.type} id=${e.id}`);let r=x(Fh,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=T(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=ct(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 Ua({retryConfig:r.retry}),c=(S,A)=>async(D,z,U)=>{let Y=wt(z.objectApiName),H="",M=As(z.where,U?.changedSince);M&&(H+=` WHERE ${M}`),z.orderBy&&(H+=` ORDER BY ${Yl(z.orderBy)}`);let L=!1,ee=await d.execute(async()=>{L=!1;let B=(await S.describe(Y)).fields.map(ie=>ie.name),V=B.length>0?B:["Id"],we={query:async ie=>S.query(ie),queryMore:async ie=>S.queryMore(ie)};return Os(`SELECT ${V.join(", ")} FROM ${Y}${H}`,async ie=>{let re=await tr(we,ie,i);return L||=re.truncated,re.records})});if(!ee.success)throw ee.error??new Error("Query failed after retries");$e(S.limitInfo,`sync:execute query ${Y}`);let Q=ee.result??[];if(L){U?.onBoundReached?.();let B=Q.length>=i?`${i} records (sandforge.sync.maxRecordsPerObject)`:`${Math.max(500,Math.ceil(i/200))} pages`,V=A===e.sourceOrgId?"source":"target";V==="source"&&a.add(z.objectApiName);let we=V==="source"?"this sync copies a subset, not the whole object":"conflict detection ran against a subset of the destination";this.deps.log(`[WARN] sync:execute ${Y} (${V}): read stopped at ${Q.length} record(s) \u2014 bound: ${B}. ${we}.`),Ie(this.deps,"warning","Sync",`${Y}: only ${Q.length} record(s) were read from the ${V} (bound: ${B}) \u2014 ${we}. `+cS(V,i,dS))}return Q},l=async(S,A,D)=>{let U=`SELECT COUNT() FROM ${wt(A.objectApiName)}`,Y=As(A.where,D?.changedSince);Y&&(U+=` WHERE ${Y}`);let{totalSize:H}=await n.query(U);return Math.min(H,i)},u=async(S,A)=>{let D=wt(S.objectApiName),z=As(S.where,A?.changedSince),U=`SELECT COUNT() FROM ${D} WHERE IsPersonAccount = true`+(z?` AND (${z})`:"");try{return(await n.query(U)).totalSize}catch{return 0}},p=new Map,g=async S=>{let A=p.get(S);if(A)return A;let D=await o.describe(S),z=kr(D);return p.set(S,z),z},h=async S=>kr(await o.describe(S)),f=async S=>(await tr({query:async A=>o.query(A),queryMore:async A=>o.queryMore(A)},S)).records,m=Th({query:async S=>o.query(S),queryMore:async S=>o.queryMore(S)},t),y=async(S,A,D,z)=>{let U=await m(S,A,D,z);return $e(o.limitInfo,`sync:simulate lookup ${A.objectApiName}`),U},R=$h({query:async(S,A)=>n.query(S,A),queryMore:async S=>n.queryMore(S)},{query:async S=>o.query(S),queryMore:async S=>o.queryMore(S)},t),k=S=>({pages:{query:async A=>S.query(A),queryMore:async A=>S.queryMore(A)},transport:S,create:async(A,D)=>S.sobject(A).create(D,{headers:Ni()})}),w=async(S,A)=>{let z=`SELECT Id FROM ${wt(S.objectApiName)}`,U=As(S.where,A);U&&(z+=` WHERE ${U}`),S.orderBy&&(z+=` ORDER BY ${Yl(S.orderBy)}`);let{records:Y}=await tr(k(n).pages,z,i);return Y.flatMap(H=>typeof H.Id=="string"?[H.Id]:[])},O={copy:VR({[e.sourceOrgId]:k(n),[e.targetOrgId]:k(o)}),sourceIds:w,store:this.fileStoreFor(),...e.files!==void 0&&JR(this.deps.infraServices?.productionGuard,e.targetOrgId,this.deps.orgManager.getOrg(e.targetOrgId))?{deleteFromTarget:async(S,A)=>ow(await o.sobject(S).destroy(A),S).map(D=>({id:D.id,success:D.success,errors:D.errors}))}:{}},P=async()=>{let{readSyncRecordTypes:S}=await import("./chunk-DJCGURW7.mjs");return S(k(n).pages,k(o).pages)},b=async()=>{let{readRunCurrencies:S}=await import("./chunk-OETEC3P7.mjs");return S(async A=>(await n.query(A)).records,async A=>(await o.query(A)).records,{source:async A=>(await n.tooling.query(A)).records,target:async A=>(await o.tooling.query(A)).records})},v=async()=>{let{readStandardPricebooks:S}=await import("./chunk-EOFO3PHS.mjs");return S(async A=>(await n.query(A)).records,async A=>(await o.query(A)).records)},C=Jn(mr(async S=>(await n.query(S)).records),S=>Kt(e.sourceOrgId,S,()=>n.describe(S)));return{sourceConn:n,targetConn:o,querySource:c(n,e.sourceOrgId),queryTarget:c(o,e.targetOrgId),maskedSourceFields:C,countSource:l,describeTargetFields:g,describeTargetFieldsAgain:h,queryTargetRows:f,recordTypes:P,currencies:b,standardPricebooks:v,findInTarget:y,readSourceIds:S=>w(S),countPersonAccounts:u,deltaReads:R,files:O,readCap:i,cutAtReadCap:a}}async rerunFromSnapshot(e,t){this.deps.log(`[RX] sync:history:rerun id=${e.id}`);let r=x(yn,{...e,payload:{config:t}},"sync:history:error",this.deps);r&&(this.refusedFieldless(e,r.config,"sync:history:rerun","sync:history:error",_p)||await this.startExecution(e,r.config,"rerun"))}async executeScheduled(e,t="schedule"){let r=yn.safeParse({config:e});if(!r.success)throw new Error(`Scheduled sync config failed validation: ${r.error.issues.map(m=>m.message).join("; ")}`);let n=mo(r.data.config.objects);if(n.length>0)throw Object.assign(new Error(`${yo(n)} ${_p}`),{code:Fi});let o=t==="pipeline"?mn("sync:pipeline",crypto.randomUUID(),"sync:execute"):mn("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,Se.code),Qi();let{check:l,decision:u}=await Ze(c,this.buildGuardRequest(d)),p=u;if((u==="refused"||u==="declined")&&this.recordStopped(i,d.targetOrgId,u),u==="refused")throw new Error(`Operation blocked by Production Guard: ${l.blockedReason??l.impactSummary}`);if(u==="declined")throw new Error(`${t==="pipeline"?"Pipeline":"Scheduled"} sync cancelled (confirmation declined).`);this.dmlTracker.register(i,"sync","upsert",d.objects?.length??0),this.activeOperationIds.add(i),this.deps.infraServices?.performanceTracker?.start(i,"sync");let g=`${t==="pipeline"?"Pipeline":"Scheduled"} sync of ${d.objects?.length??0} object(s)`;ze(this.deps,i,"sync",g),this.liveTracker?.register(i,"sync",g,0,{pausable:!0});let h=new AbortController,f=this.executeSync(o,d,i,h,t,p);return this.registry?.register(i,"sync",g,f,h),f}async startExecution(e,t,r,n=!1,o){let i=e.id,a={module:"sync",operation:e.type},d=this.registry?.holdUntilStart(i);try{let c=this.deps.services?.getSandforgeSetting?.("sync.defaultBatchSize",200)??200,l=t,u={...l,objects:l.objects.map(k=>({...k,batchSize:k.batchSize??c}))};Object.assign(a,zr(u.objects));let p=this.deps.infraServices?.productionGuard;if(!p){this.recordRefused(i,u.targetOrgId,Se.code),E(this.deps,"sync:execute","sync:error",e,new Error(Se.message),{code:Se.code}),De(this.deps,i,Se.message,!1,{context:a});return}let{check:g,decision:h}=await Ze(p,this.buildGuardRequest(u)),f=h;if((h==="refused"||h==="declined")&&this.recordStopped(i,u.targetOrgId,h),h==="refused")throw hn(g.blockedReason??g.impactSummary);if(h==="declined"){let k="Operation cancelled by user (confirmation declined).";E(this.deps,"sync:execute","sync:error",e,new Error(k),{code:Ct.declined}),De(this.deps,i,k,!1,{context:a});return}if(d?.signal.aborted){this.answerCancelledBeforeStart(e,u,h);return}if(this.dmlTracker.isDuplicate(i)){this.deps.log(`[WARN] Duplicate sync operation detected: ${i}`),E(this.deps,"sync:execute","sync:error",e,new Error(`Duplicate operation: ${i}`)),De(this.deps,i,`Duplicate operation: ${i}`,!1,{context:a});return}this.dmlTracker.register(i,"sync","upsert",u.objects?.length??0),this.activeOperationIds.add(i),this.deps.infraServices?.performanceTracker?.start(i,"sync");let m=`Sync ${u.objects?.length??0} object(s)`;ze(this.deps,i,"sync",m),this.liveTracker?.register(i,"sync",m,0,{pausable:!0});let y=new AbortController,R=this.executeSync(e,u,i,y,r,f,n,o);this.registry?this.registry.register(i,"sync",m,R,y):await R}catch(c){this.dmlTracker.markFailed(i),E(this.deps,"sync:execute","sync:error",e,c,{code:vo(c)}),De(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=T(this.deps,e,"sync:execute:response",n);this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} (cancelled before it started)`)}endCancelled(e){this.registry?.abort(e),pe(this.deps,e,{aborted:!0}),this.liveTracker?.cancel(e)}async executeSync(e,t,r,n,o,i,a=!1,d){let c=t.id?t:{...t,id:r},l=ct(this.deps),u,p,g=!1,h,f=b=>({measure:v=>b.measure(v),hold:async v=>{let C=await b.hold(v);return h=C.answer.emails,C}}),m=new Jd;this.pauseGates.set(r,m);let y=o==="pipeline"?this.deps.orgManager.getOrg(c.targetOrgId)?.orgId:void 0,R=this.runCreations?.recorder({runId:r,configId:c.id,configName:c.name??"",sourceOrgId:c.sourceOrgId,targetOrgId:c.targetOrgId,...y?{targetOrganizationId:y}:{}}),k=this.backupRecords,w=R&&k?Xa({runId:r,orgId:c.targetOrgId,files:k,meta:this.deps.configStore}):void 0,O=d?this.runCheckpointOf(c,r,d,{signal:n.signal,...R?{recorder:R}:{}}):void 0,P=()=>{try{w?.close()}catch(b){this.deps.log(`[WARN] sync ${r}: the backup of what it wrote over could not be listed whole: `+I(b))}};try{let b=await this.readersFor(c,n.signal),{sourceConn:v,targetConn:C}=b;vr(R,()=>C.identity(),`sync ${r}`);let S=b.queryTargetRows,A=R&&w?Ka({query:S,backup:w,recorder:R,describe:b.describeTargetFields,viewsEncrypted:mr(S)}):void 0,D=new bn(l.bulk.threshold),z=hr(this.deps),U=new Pn({connection:C,bulkExecutor:D,bulkManager:z,retryConfig:l.retry,signal:n.signal,pauseGate:m,onProgress:(W,se,te)=>{let ue=Math.round(W/se*100);Le(this.deps,r,ue,W,se,te),this.liveTracker?.updateProgress(r,ue,W,se,te)},log:W=>this.deps.log(W),...R?{calls:ed(R,A)}:{}}),{DataSync:Y}=await import("./chunk-WT3SCUHS.mjs"),{ConflictResolver:H}=await import("./chunk-CHCHAE4B.mjs"),{FieldMappingService:M}=await import("./chunk-STRMWSIQ.mjs"),{TransformPipeline:L}=await import("./chunk-Q6SXNKV2.mjs"),ee=W=>{W.length>0&&(g=!0)},Q=new Y({upsert:(W,se,te,ue)=>(ee(te),U.upsert(W,se,te,ue)),insert:(W,se,te)=>(ee(se),U.insert(W,se,te)),update:(W,se,te)=>(ee(se),U.update(W,se,te)),delete:(W,se,te)=>(ee(se),U.delete(W,se,te)),describeTargetFields:b.describeTargetFields}),B=new H,V=new M,we=new L,ie={dataSync:Q,conflictResolver:B,fieldMapping:V,transformPipeline:we,querySource:b.querySource,maskedSourceFields:b.maskedSourceFields,queryTarget:b.queryTarget,services:this.deps.services,grappeConfig:vs(this.deps.services),onGrappeEvent:W=>Zi(this.deps,W),countSource:b.countSource,countPersonAccounts:b.countPersonAccounts,describeTargetFields:b.describeTargetFields,describeTargetFieldsAgain:b.describeTargetFieldsAgain,leaseOfTheGate:()=>p?.lease(),queryTargetRows:S,readSourceIds:b.readSourceIds,findInTarget:b.findInTarget,writeGate:(()=>{let W=o==="schedule"||o==="pipeline"?"unattended":"ask";if(!a)return f(this.writeGateFor(c,C,W,void 0,O?.gate));let se=this.targetAutomation;return p=kS((ue,$)=>this.writeGateFor(c,C,W,ue,O?.gate,$),ue=>new ge(Zk).withTimeout("sync:automation",()=>se.read(c.targetOrgId,ue)),ue=>kt(async()=>Mt(C),ue,{...this.muteLeases,writes:vS}),r,{target:me(this.deps.orgManager.getOrg(c.targetOrgId),c.targetOrgId),liftedBy:oO(W).emailsLiftedBy}),f(p.gate)})(),recordTypes:b.recordTypes,currencies:b.currencies,standardPricebooks:b.standardPricebooks,signal:n.signal,pauseGate:m,deltaStore:this.deltaStoreFor(),deltaReads:b.deltaReads,files:{...b.files,onProgress:(W,se)=>{Le(this.deps,r,W,0,0,se),this.liveTracker?.updateProgress(r,W,0,0,se)}},...R?{creations:R}:{},idMap:this.idMapFor()};if(!this.deps.services)throw new Error("SyncOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let re=this.deps.services.syncOrchestrator(ie);await this.assertFieldTypesMatch(c,v,C,l.timeouts.describe),Le(this.deps,r,10,0,1,"Initializing sync");let Ae=await re.execute(c).finally(async()=>{u=await p?.release()}),he=await this.settleRunCheckpoint(O,g,r),Je=[...b.cutAtReadCap],Ne={...Ae,...Je.length>0?{status:Ae.status==="success"?"partial":Ae.status,readCap:b.readCap,cutAtReadCap:Je}:{},...u?{mutedAutomation:u}:{},...he?{checkpoint:he}:{}};if(await R?.end({status:Ne.status,cancelled:Ne.cancelled===!0}),P(),Ne.cancelled?this.endCancelled(r):(Le(this.deps,r,100,1,1,"Sync complete"),pe(this.deps,r,{status:Ne.status??"completed"}),Ne.status==="failure"?this.liveTracker?.fail(r,Ne.error??"No record could be synced."):Ne.status==="partial"?this.liveTracker?.partial(r):this.liveTracker?.complete(r)),this.dmlTracker.markCompleted(r),c.files){let W=Ne.objectResults.flatMap(se=>se.files?[se.files]:[]);this.deps.log(`[sync] ${r} files: ${XR(W)}`)}$e(v.limitInfo,"sync:execute completion (source)"),$e(C.limitInfo,"sync:execute completion (target)");try{this.historyLogger?.logExecution(c,Ne,o)}catch(W){this.deps.log(`[WARN] sync history logging failed: ${I(W)}`)}this.recordRun(c,r,Ne,i,o,h);let Fe=T(this.deps,e,"sync:execute:response",Ne);return this.deps.broker.postToWebview(Fe),this.deps.log(`[TX] ${Fe.type} id=${Fe.id}`),Ne}catch(b){await R?.end({status:"failure"}),P(),this.dmlTracker.markFailed(r);let v=await this.settleRunCheckpoint(O,g,r),C=v?.state==="deleted";if(this.liveTracker?.fail(r,I(b)),b instanceof sS){let z=O?.refusal(),U=C?`${b.message} ${Kr}`:b.message,Y={...z?{checkpointRefusal:z.code}:{},...v?{checkpoint:v}:{}};return Z(this.deps,{action:"sync_execute",module:"sync",operationId:r,orgId:c.targetOrgId,outcome:"stopped",guard:i,code:b.code,details:{triggeredBy:o,...z?{checkpointRefusal:z.code}:{},...Vn(h)}}),E(this.deps,"sync:execute","sync:error",e,b,{code:b.code,extraPayload:Y}),De(this.deps,r,U,!1,{context:{module:"sync",operation:e.type,...zr(c.objects)}}),{...b.result,configId:c.id,operationId:r,status:"failure",timestamp:new Date().toISOString(),error:U,...v?{checkpoint:v}:{}}}bs(b)&&o!=="rerun"&&d===void 0&&this.deps.infraServices?.offlineManager?this.deps.infraServices.offlineManager.enqueue({id:r,type:"sync",orgId:c.targetOrgId,payload:{config:c}})&&this.deps.log(`[OFFLINE] sync queued for replay on reconnect: ${r}`):bs(b)&&o==="rerun"&&this.deps.log(`[OFFLINE] sync replay failed again \u2014 not re-queued (replay outcomes surface via operation:failed): ${r}`);let S=C?new Error(`${I(b)} ${Kr}`):b;E(this.deps,"sync:execute","sync:error",e,b,{...v?{extraPayload:{checkpoint:v}}:{}}),De(this.deps,r,I(S),!0,{context:{module:"sync",operation:e.type,...zr(c.objects)}});let D={...(b instanceof oS?b.result:void 0)??{objectResults:[],totalProcessed:0,totalSuccess:0,totalFailed:0,totalSkipped:0,duration:0},configId:c.id,operationId:r,status:"failure",timestamp:new Date().toISOString(),error:I(S),...v?{checkpoint:v}:{}};try{this.historyLogger?.logExecution(c,D,o)}catch(z){this.deps.log(`[WARN] sync history logging failed: ${I(z)}`)}return this.recordRun(c,r,D,i,o,h),D}finally{this.pauseGates.delete(r),this.activeOperationIds.has(r)&&(this.deps.infraServices?.performanceTracker?.complete(r),this.activeOperationIds.delete(r))}}};var H$=new Set(["sync:history:list","sync:history:detail","sync:history:rerun","sync:history:export"]),Xd=class{constructor(e,t,r){this.deps=e;this.historyStore=t;this.syncOps=r}deps;historyStore;syncOps;async handle(e){if(!H$.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=T(this.deps,e,"sync:history:list:response",{entries:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} count=${t.length}`)}catch(t){E(this.deps,"sync:history:list","sync:history:error",e,t)}}handleDetail(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ru,e,"sync:history:error",this.deps);if(t)try{let r=this.historyStore.load(t.entryId)??null,n=T(this.deps,e,"sync:history:detail:response",{entry:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){E(this.deps,"sync:history:detail","sync:history:error",e,r)}}handleExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(tm,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=T(this.deps,e,"sync:history:export:response",{data:r,format:t.format});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} format=${t.format}`)}catch(r){E(this.deps,"sync:history:export","sync:history:error",e,r)}}async handleRerun(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ru,e,"sync:history:error",this.deps);if(!t)return;let r=this.historyStore.load(t.entryId);if(!r){E(this.deps,"sync:history:rerun","sync:history:error",e,new Error(`History entry not found: ${t.entryId}`),{code:"NOT_FOUND"});return}await this.syncOps.rerunFromSnapshot(e,r.configSnapshot)}};var U$=1e4;async function sO(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=>jt(c).filter(l=>t.has(l.objectApiName)),n=(await e.runs()).find(c=>c.sourceOrgId===s.sourceOrgId&&c.targetOrgId===s.targetOrgId&&r(c).length>0);if(!n)return{leftAsIs:!1,objects:[]};let o=n.created.map(c=>c.objectApiName),i=r(n).sort((c,l)=>o.indexOf(c.objectApiName)-o.indexOf(l.objectApiName)),a,d=[];for(let{objectApiName:c,ids:l}of i){let u=l.slice(0,U$),p;try{p=await e.countInTarget(c,u)+(l.length-u.length)}catch(g){a??=g instanceof Error?g.message:String(g),p=l.length}p>0&&d.push({objectApiName:c,count:p})}return{leftAsIs:!1,run:{runId:n.runId,configName:n.configName,startedAt:n.startedAt,...n.realtime?{realtime:!0}:{}},objects:d,...a!==void 0?{unread:a}:{}}}var B$=new Set(["sync:removal:info","sync:removal:list","sync:remove","sync:remove:sweep","sync:remove:automation","sync:earlier-copies"]),q$=6e4,W$=12e4,iO=6e4,z$=6e4,aO="The run is still writing in another window: remove it once it has ended there.",Kd=class{constructor(e,t,r,n=Ao){this.deps=e;this.history=t;this.isRunning=r;this.self=n;this.configs=new Ot(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)&&Gn(e,this.self)}stillWriting(e){return this.isRunning(e.runId)||Gn(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-DIL62SUN.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async handle(e){if(!B$.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 Ce(t)}infoOf(e,t=[]){let r=jt(e),n=Aw(e,t),o=r.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length})),i=To(e),a=this.keptBack(i),d=gu(e),c=fu(e),l=Ns(e),u={runId:e.runId,configId:e.configId,configName:e.configName,sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,startedAt:e.startedAt,...e.end?{endedAt:e.end.at}:{},...!e.end&&e.inFlight?{inFlight:{objectApiName:e.inFlight.objectApiName,rows:e.inFlight.rows}}:{},...this.elsewhere(e)?{runningElsewhere:!0}:{},...e.realtime?{realtime:!0}:{},created:Ds(e),left:o,...d>0?{overwritten:d}:{},...a.kept.length>0?{putBack:a.kept.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length})),...a.keptUntil!==void 0?{putBackKeptUntil:a.keptUntil}:{}}:{},...a.notKept>0?{putBackNotKept:a.notKept}:{},...c>0?{deleted:c}:{},...e.unkept?{notKeptEncrypted:e.unkept.flatMap(({objectApiName:m,fields:y})=>y.map(R=>`${m}.${R}`))}:{},...l.length>0?{bringBack:l.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length}))}:{},...e.removal?.undo?{removed:e.removal.undo}:{},...n.length>0?{writtenAgain:n}:{}},p=e.removal?.undo?jt(e,!0):[],g=p.length>0?{...u,createdByObject:p.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length}))}:u,h=r.length>0||i.length>0||l.length>0?r:p;if(h.length===0&&i.length===0&&l.length===0)return g;let f=this.refusalOf(e,h,[...i,...l]);return f?{...g,refusal:f}:g}keptBack(e){return qw(e,t=>this.deps.configStore.get(`backup:${t}`),Bw(this.deps.services))}removalStepsOf(e,t=!1){let r=o=>[...new Set(o.map(({objectApiName:i})=>i))],n=r(jt(e,t));return{bringBack:r(Ns(e)),giveBack:r(this.keptBack(To(e)).kept),setToDraft:nr(n),delete:Rn(n)}}guardRequestOf(e,t,r){let n=o=>o.reduce((i,a)=>i+a.ids.length,0);return{orgId:e.targetOrgId,orgTier:this.tierOf(e.targetOrgId),operation:t.length>0?"delete":"update",objectName:[...new Set([...t,...r].map(o=>o.objectApiName))].join(", "),recordCount:n(t)+n(r),module:"sync"}}refusalOf(e,t,r){if(this.isRunning(e.runId))return{code:"RUNNING",message:"The run is still writing: remove it once it has ended."};if(this.elsewhere(e))return{code:"RUNNING",message:aO};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:Se.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 ge(z$).withTimeout(r,async()=>{let o=await q(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=or(o,r);return Ba(t,e,zn(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=x(Gh,e,"sync:remove:error",this.deps);if(t)try{let r=await this.runOf(t.runId),o=r!==void 0&&(jt(r).length>0||To(r).length>0)?await this.creations?.list()??[]:[],i=T(this.deps,e,"sync:removal:info:response",{info:r?this.infoOf(r,o):null});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id}`)}catch(r){E(this.deps,"sync:removal:info","sync:remove:error",e,r)}}async handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Jh,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)&&(Ds(d)>0||gu(d)>0||fu(d)>0||!d.end&&d.inFlight!==void 0)),a=T(this.deps,e,"sync:removal:list:response",{runs:i.map(d=>this.infoOf(d,o))});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id} count=${i.length}`)}catch(n){E(this.deps,"sync:removal:list","sync:remove:error",e,n)}}async handleEarlierCopies(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Vh,e,"sync:remove:error",this.deps);if(t)try{let r=this.creations,n=await sO(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),l=0;for(let u of Ps(a.filter(Jr)))l+=(await d.query(`SELECT COUNT() FROM ${c} WHERE Id IN (${u})`)).totalSize;return l}}),o=T(this.deps,e,"sync:earlier-copies:response",{copies:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(r){E(this.deps,"sync:earlier-copies","sync:remove:error",e,r)}}async sweepInputOf(e,t,r,n){let o=this.targetAutomation,i=[...new Set([...t.created,...t.overwritten??[]].map(l=>l.objectApiName).filter(l=>!Ow.includes(l)))],a;try{a=await new ge(q$).withTimeout(`${r} automation`,()=>o.read(t.targetOrgId,i))}catch(l){a={error:I(l)}}let d=or(e,r),c=await za(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 Fo({...c,ties:{...c.ties,...await Ja(t,c.writtenBetween,await this.creations?.list().catch(()=>[])??[],this.otherModuleRuns)}},d)}async localRunsOn(e){return Ga(await this.creations?.list().catch(()=>[])??[],e)}setOtherModuleRuns(e){this.otherModuleRuns=e}async handleSweepList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Kh,e,"sync:remove:sweep:error",this.deps);if(!t)return;let r=(n,o)=>E(this.deps,"sync:remove:sweep","sync:remove:sweep:error",e,new Error(n),{code:o});try{let n=await this.runOf(t.runId);if(!n){r("Nothing this run created is kept: there is nothing to sweep after.","NOT_KEPT");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){r("The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}let o=await new ge(W$).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 jo(Qr(i,"sync:remove:sweep"),a,n.removal?.removalSpans??[])});this.deps.broker.postToWebview(T(this.deps,e,"sync:remove:sweep:response",{runId:n.runId,listing:o}))}catch(n){E(this.deps,"sync:remove:sweep","sync:remove:sweep:error",e,n,{code:"SWEEP_ERROR",retryable:!0})}}async handleRemovalAutomation(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Yh,e,"sync:remove:automation:error",this.deps);if(!t)return;let r=(n,o)=>E(this.deps,"sync:remove:automation","sync:remove:automation:error",e,new Error(n),{code:o});try{let n=await this.runOf(t.runId);if(!n){r("Nothing this run created is kept: there is nothing to remove.","NOT_KEPT");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){r("The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}let o=hs(this.removalStepsOf(n,t.again===!0),t.sweptObjects??[]),i=[...new Set(Object.values(o).flat())],a=this.targetAutomation,d=await new ge(iO).withTimeout("sync:remove:automation",()=>a.read(n.targetOrgId,i,{undeletes:!0})),c=T(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 yr;E(this.deps,"sync:remove:automation","sync:remove:automation:error",e,n,{code:o?"TIMEOUT":"AUTOMATION_ERROR",retryable:!0})}}sweepOfRemoval(e){let{conn:t,run:r,input:n}=e;return _o({input:async()=>{if(n instanceof Error)throw n;return n},org:Qr(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=Lo(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:Ho(i)}:{},objects:Mo(o),details:{...a,runId:r.runId}})},keepMade:async(o,i,a)=>{await this.creations?.updateRemoval(r.runId,d=>Va(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){E(this.deps,"sync:remove","sync:remove:error",e,new Error(t),{code:r,...n?{retryable:n}:{}})}recordNotRemoved(e,t,r,n={}){Z(this.deps,{action:"cleanup_delete",module:"sync",operationId:e.id,orgId:t.targetOrgId,outcome:r,...n,details:{runId:t.runId}})}setMuteLeases(e){this.muteLeases=e}muteLeases={};async handleRemove(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Xh,e,"sync:remove:error",this.deps);if(!t)return;let r=this.creations;if(!r){this.refuse(e,"What Sync runs created is not kept in this window yet.","NOT_INITIALIZED",!0);return}let n;try{n=await this.runOf(t.runId)}catch(a){E(this.deps,"sync:remove","sync:remove:error",e,a,{code:"REMOVE_ERROR",retryable:!0});return}if(!n){this.refuse(e,"Nothing this run created is kept: it created nothing, or ran before runs kept what they created, or the record of it was dropped to make room.","NOT_KEPT");return}if(this.isRunning(n.runId)){this.refuse(e,"The run is still writing: remove it once it has ended.","RUNNING");return}if(this.elsewhere(n)){this.refuse(e,aO,"RUNNING");return}let o=t.again===!0;if(jt(n,o).length===0&&To(n).length===0&&Ns(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=jt(r,a),c=[...To(r),...Ns(r)],l=d.reduce((b,v)=>b+v.ids.length,0),u=c.reduce((b,v)=>b+v.ids.length,0),p=r.targetOrgId,g=this.deps.infraServices?.productionGuard;if(!g){this.recordNotRemoved(e,r,"stopped",{code:Se.code}),this.refuse(e,Se.message,Se.code);return}let{check:h,decision:f}=await Ze(g,this.guardRequestOf(r,d,c));if(f==="refused"||f==="declined"){this.recordNotRemoved(e,r,"stopped",{guard:f}),f==="refused"?this.refuse(e,`Operation blocked by Production Guard: ${h.blockedReason??h.impactSummary}`,Ct.blocked):this.refuse(e,"Operation cancelled by user (confirmation declined).",Ct.declined,!0);return}if(o?.signal.aborted){this.recordNotRemoved(e,r,"stopped",{guard:f,code:bt});let b={runId:r.runId,status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(T(this.deps,e,"sync:remove:response",{result:b,operationId:e.id}));return}let m=e.id,y=u>0?`Removing ${l} record(s) and file(s) a Sync run created, and giving ${u} record(s) it wrote over or deleted their values back`:`Removing ${l} record(s) and file(s) a Sync run created`,R=new AbortController,k=()=>{},w=new Promise((b,v)=>{k=C=>C===void 0?b():v(C)});w.catch(()=>{}),ze(this.deps,m,"sync",y),this.registry?.register(m,"sync",y,w,R),this.liveTracker?.register(m,"sync",y,l+u);let O,P;try{let b=await q(p,this.deps.orgRegistry,this.deps.orgManager),v=n.sweep?await this.sweepInputOf(b,r,"sync:remove sweep",R.signal).catch(ie=>new Error(I(ie))):void 0;P=v?await this.sweepOfRemoval({conn:b,run:r,input:v,includeChanged:i,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,signal:R.signal,guard:g,operationId:m}):void 0;let C=P;await C?.ask();let S;if(n.muteAutomation===!0){let ie=hs(this.removalStepsOf(r,a),C?.takes??[]),re=[...new Set(Object.values(ie).flat())],Ae=this.targetAutomation,he=await new ge(iO).withTimeout("sync:remove:automation",()=>Ae.read(r.targetOrgId,re,{undeletes:!0})).catch(Je=>({unread:I(Je)}));S=await kt(async()=>Mt(b),he,{...this.muteLeases,writes:Br(ie)})}let A,D=S?.muted,z=async()=>{let ie=S?.prepared;!ie||R.signal.aborted||(A=await ie.acquire(m),D=A.outcome)},U=or(b,"sync:remove"),Y=await Wa(U,r.created),{result:H,notes:M,earlierStamped:L,duplicateSets:ee}=await ma({run:r,org:U,includeChanged:i,...a?{again:a}:{},store:t,configs:this.configs,links:t.idMap(),...this.backups?{backups:this.backups}:{},earlierRuns:Iw(r,await t.list().catch(()=>[])),undelete:ie=>b.soap.undelete(ie),...C?{sweep:ie=>C.first(ie),afterRemoval:ie=>C.afterRemoval(ie),automationMade:C.automationMade}:{},...r.runUserId?{runUserId:r.runUserId}:{},onUndeletable:Wr(this.deps,p,"sync:remove"),beforeFirstWrite:z,signal:R.signal,onProgress:(ie,re,Ae)=>{let he=Math.min(100,Math.round(ie/Math.max(re,1)*100));Le(this.deps,m,he,ie,re,Ae),R.signal.aborted||this.registry?.updateProgress(m,he),this.liveTracker?.updateProgress(m,he,ie,re,Ae)}}).finally(async()=>{A&&(D=await A.release())}),Q=await P?.settle(),B=H.status==="cancelled"?{}:await Y.take(ee);for(let ie of[...M,...B.note?[B.note]:[]])this.deps.log(`[WARN] sync:remove ${m}: ${ie}`);for(let{runId:ie,records:re}of L??[])this.deps.log(`[INFO] sync:remove ${m}: ${re} record(s) given back hold the values of the earlier run ${ie} again, stamped on it`);let V={...H,objects:B.object?[...H.objects,B.object]:H.objects,status:Oo(H.status,Q),...Q?{sweep:Q}:{},...D?{mutedAutomation:D}:{}};Z(this.deps,{action:"cleanup_delete",module:"sync",operationId:m,orgId:p,outcome:Io(H),guard:f,objects:ha(Sn(V.objects),V.restored??[],V.undeleted??[]),...V.leftBy?{leftBy:V.leftBy}:{},...D?{muted:dt(D)}:{},details:{runId:r.runId}});let we=T(this.deps,e,"sync:remove:response",{result:V,operationId:m});this.deps.broker.postToWebview(we),this.deps.log(`[TX] ${we.type} id=${we.id} status=${V.status}`),V.status==="cancelled"||V.sweep?.status==="cancelled"?(pe(this.deps,m,{aborted:!0}),this.liveTracker?.cancel(m)):(pe(this.deps,m,{status:V.status}),V.status==="failure"?(O=new Error("Nothing this run created could be removed."),this.liveTracker?.fail(m,"Nothing this run created could be removed.")):V.status==="partial"?this.liveTracker?.partial(m):this.liveTracker?.complete(m))}catch(b){O=b,await P?.settle().catch(()=>{});let v=$t(b)?b:void 0;this.recordNotRemoved(e,r,v?"stopped":"failure",{guard:f,...v?{code:v.code}:{}}),E(this.deps,"sync:remove","sync:remove:error",e,b,{code:v?.code??"REMOVE_ERROR",retryable:!0}),pe(this.deps,m,{status:"failure"}),this.liveTracker?.fail(m,I(b))}finally{k(O)}}};var G$=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,J$=/^[A-Za-z][A-Za-z0-9_]*$/;function Yd(s,e,t){if(!G$.test(t)||!J$.test(e))return{ok:!1,reason:"not-a-record"};let r=$n(s);return r.ok?{ok:!0,url:new URL(`/lightning/r/${e}/${t}/view`,r.url.origin).toString()}:r}var V$=new Set(["seed:removal:info","seed:removal:list","seed:remove","seed:remove:sweep","seed:open-record"]),dO=6e4,X$=12e4,K$=6e4,cO="The seed is still writing: remove it once it has ended.",lO="The seed is still writing in another window: remove it once it has ended there.",Qd=class{constructor(e,t,r=()=>!1,n=Ao){this.deps=e;this.isRunning=r;this.self=n;this.externalBrowser=t??new Cr}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)&&Gn(e,this.self)}setRunCreations(e){this.creations=e}setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-DIL62SUN.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 V$.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 Ce(t)}infoOf(e){let t=jt(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:Ds(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?jt(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-7CVDVBEE.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:cO};if(this.elsewhere(e))return{code:"RUNNING",message:lO};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:Se.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 ge(K$).withTimeout(r,async()=>{let o=await q(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=or(o,r);return Ba(t,e,zn(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=x(Qh,e,"seed:remove:error",this.deps);if(t)try{let r=await this.runOf(t.runId),n=T(this.deps,e,"seed:removal:info:response",{info:r?await this.withScenario(this.infoOf(r)):null});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){E(this.deps,"seed:removal:info","seed:remove:error",e,r)}}async handleOpenRecord(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(vm,e,"seed:open-record:error",this.deps);if(!t)return;let r=(n,o)=>{E(this.deps,"seed:open-record","seed:open-record:error",e,new Error(n),{code:o})};try{let n=await this.creations?.get(t.runId);if(!n){r("Nothing of this run is kept any more.","NOT_KEPT");return}let o=t.recordId.slice(0,15),i;for(let{objectApiName:u,ids:p}of n.created){let g=p.find(h=>h.slice(0,15)===o);if(g){i={objectApiName:u,id:g};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=Yd(a.instanceUrl,i.objectApiName,i.id);if(!d.ok){let u=d.reason==="not-https"?`its instance URL must use HTTPS, got "${d.protocol}"`:d.reason==="invalid"?"its instance URL is not a valid URL":"the record is not one an address can be built for";r(`Cannot open the record in "${me(a)}": ${u}.`,d.reason==="not-a-record"?"NOT_CREATED":"INVALID_INSTANCE_URL");return}let c=await this.externalBrowser.open(d.url),l=T(this.deps,e,"seed:open-record:response",c);this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id} status=${c.status}`)}catch(n){E(this.deps,"seed:open-record","seed:open-record:error",e,n)}}async handleList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=[];for(let o of await this.creations?.list()??[])t.push(await this.withJobAnswered(o));let r=[];for(let o of t)r.push(await this.withScenario(this.infoOf(o)));let n=T(this.deps,e,"seed:removal:list:response",{runs:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} runs=${t.length}`)}catch(t){E(this.deps,"seed:removal:list","seed:remove:error",e,t)}}async sweepInputOf(e,t,r,n){let o=this.targetAutomation,i;try{i=await new ge(dO).withTimeout(`${r} automation`,()=>o.read(t.targetOrgId,t.created.map(c=>c.objectApiName)))}catch(c){i={error:I(c)}}let a=or(e,r),d=await za(a,t.created,i,n,void 0,[],{...t.runUserId?{runUserId:t.runUserId}:{},ties:{}});return Fo({...d,ties:{...d.ties,...await Ja(t,d.writtenBetween,await this.creations?.list().catch(()=>[])??[],this.otherModuleRuns)}},a)}async localRunsOn(e){return Ga(await this.creations?.list().catch(()=>[])??[],e)}setOtherModuleRuns(e){this.otherModuleRuns=e}async handleSweepList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(em,e,"seed:remove:sweep:error",this.deps);if(!t)return;let r=(n,o)=>E(this.deps,"seed:remove:sweep","seed:remove:sweep:error",e,new Error(n),{code:o});try{let n=await this.runOf(t.runId);if(!n){r("Nothing this run created is kept: there is nothing to sweep after.","NOT_KEPT");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){r("The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}let o=await new ge(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 jo(Qr(i,"seed:remove:sweep"),a,n.removal?.removalSpans??[])});this.deps.broker.postToWebview(T(this.deps,e,"seed:remove:sweep:response",{runId:n.runId,listing:o}))}catch(n){E(this.deps,"seed:remove:sweep","seed:remove:sweep:error",e,n,{code:"SWEEP_ERROR",retryable:!0})}}sweepOfRemoval(e){let{conn:t,run:r}=e;return _o({input:()=>this.sweepInputOf(t,r,"seed:remove sweep",e.signal),org:Qr(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=Lo(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:Ho(o)}:{},objects:Mo(n),details:{...i,runId:r.runId}})},keepMade:async(n,o,i)=>{await this.creations?.updateRemoval(r.runId,a=>Va(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){E(this.deps,"seed:remove","seed:remove:error",e,new Error(t),{code:r,...n?{retryable:n}:{}})}recordNotRemoved(e,t,r,n={}){Z(this.deps,{action:"cleanup_delete",module:"seed",operationId:e.id,orgId:t.targetOrgId,outcome:r,...n,details:{runId:t.runId}})}setMuteLeases(e){this.muteLeases=e}muteLeases={};async handleRemove(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Zh,e,"seed:remove:error",this.deps);if(!t)return;let r=this.creations,n=await this.runOf(t.runId);if(!r||!n){this.refuse(e,"Nothing this run created is kept: it created nothing, or was dropped to make room for newer seeds. To take its records back, rewind the org to a checkpoint taken before it, or empty its objects (DataOps, Cleanup, Empty objects), which deletes all their records.","NOT_KEPT");return}let o=t.again===!0;if(jt(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,cO,"RUNNING");return}if(this.elsewhere(n)){this.refuse(e,lO,"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=jt(r,a),c=d.reduce((O,P)=>O+P.ids.length,0),l=r.targetOrgId,u=this.deps.infraServices?.productionGuard;if(!u){this.recordNotRemoved(e,r,"stopped",{code:Se.code}),this.refuse(e,Se.message,Se.code);return}let{check:p,decision:g}=await Ze(u,{orgId:l,orgTier:this.tierOf(l),operation:"delete",objectName:d.map(O=>O.objectApiName).join(", "),recordCount:c,module:"seed"});if(g==="refused"||g==="declined"){this.recordNotRemoved(e,r,"stopped",{guard:g}),g==="refused"?this.refuse(e,`Operation blocked by Production Guard: ${p.blockedReason??p.impactSummary}`,Ct.blocked):this.refuse(e,"Operation cancelled by user (confirmation declined).",Ct.declined,!0);return}if(o?.signal.aborted){this.recordNotRemoved(e,r,"stopped",{guard:g,code:bt});let O={runId:r.runId,status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(T(this.deps,e,"seed:remove:response",{result:O,operationId:e.id}));return}let h=e.id,f=`Removing ${c} record(s) a Seed run created`,m=new AbortController,y=()=>{},R=new Promise((O,P)=>{y=b=>b===void 0?O():P(b)});R.catch(()=>{}),ze(this.deps,h,"seed",f),this.registry?.register(h,"seed",f,R,m),this.liveTracker?.register(h,"seed",f,c);let k,w;try{let O=await q(l,this.deps.orgRegistry,this.deps.orgManager);w=n.sweep?await this.sweepOfRemoval({conn:O,run:r,includeChanged:i,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,signal:m.signal,guard:u,operationId:h}):void 0;let P=w;await P?.ask();let b;if(n.muteAutomation===!0){let Q=[...new Set(d.map(re=>re.objectApiName))],B=hs({setToDraft:nr(Q),delete:Rn(Q)},P?.takes??[]),V=B.delete??[],we=this.targetAutomation,ie=await new ge(dO).withTimeout("seed:remove automation",()=>we.read(r.targetOrgId,V)).catch(re=>({unread:I(re)}));b=await kt(async()=>Mt(O),ie,{...this.muteLeases,writes:Br(B)})}let v,C=b?.muted,S=async()=>{let Q=b?.prepared;!Q||m.signal.aborted||(v=await Q.acquire(h),C=v.outcome)},A=or(O,"seed:remove"),D=await Wa(A,r.created),{result:z,notes:U,duplicateSets:Y}=await ma({run:r,org:A,includeChanged:i,...a?{again:a}:{},store:t,...P?{sweep:Q=>P.first(Q),afterRemoval:Q=>P.afterRemoval(Q),automationMade:P.automationMade}:{},...r.runUserId?{runUserId:r.runUserId}:{},onUndeletable:Wr(this.deps,l,"seed:remove"),beforeFirstWrite:S,signal:m.signal,onProgress:(Q,B,V)=>{let we=Math.min(100,Math.round(Q/Math.max(B,1)*100));Le(this.deps,h,we,Q,B,V),m.signal.aborted||this.registry?.updateProgress(h,we),this.liveTracker?.updateProgress(h,we,Q,B,V)}}).finally(async()=>{v&&(C=await v.release())}),H=await w?.settle(),M=z.status==="cancelled"?{}:await D.take(Y);for(let Q of[...U,...M.note?[M.note]:[]])this.deps.log(`[WARN] seed:remove ${h}: ${Q}`);let L={runId:z.runId,status:Oo(z.status,H),includeChanged:z.includeChanged,objects:M.object?[...z.objects,M.object]:z.objects,finishedAt:z.finishedAt,...z.leftBy?{leftBy:z.leftBy}:{},...H?{sweep:H}:{},...C?{mutedAutomation:C}:{}};Z(this.deps,{action:"cleanup_delete",module:"seed",operationId:h,orgId:l,outcome:Io(z),guard:g,objects:Sn(L.objects),...L.leftBy?{leftBy:L.leftBy}:{},...C?{muted:dt(C)}:{},details:{runId:r.runId}});let ee=T(this.deps,e,"seed:remove:response",{result:L,operationId:h});this.deps.broker.postToWebview(ee),this.deps.log(`[TX] ${ee.type} id=${ee.id} status=${L.status}`),L.status==="cancelled"||L.sweep?.status==="cancelled"?(pe(this.deps,h,{aborted:!0}),this.liveTracker?.cancel(h)):(pe(this.deps,h,{status:L.status}),L.status==="failure"?(k=new Error("Nothing this run created could be removed."),this.liveTracker?.fail(h,"Nothing this run created could be removed.")):L.status==="partial"?this.liveTracker?.partial(h):this.liveTracker?.complete(h))}catch(O){k=O,await w?.settle().catch(()=>{});let P=$t(O)?O:void 0;this.recordNotRemoved(e,r,P?"stopped":"failure",{guard:g,...P?{code:P.code}:{}}),E(this.deps,"seed:remove","seed:remove:error",e,O,{code:P?.code??"REMOVE_ERROR",retryable:!0}),pe(this.deps,h,{status:"failure"}),this.liveTracker?.fail(h,I(O))}finally{y(k)}}};var Zd="sync:history:all",uO="syncHistory";var ec=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(Zd,n,uO)}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(Zd,r,uO),!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(`
16
+ `)}clear(){this.configStore.delete(Zd)}loadAll(){let e=this.configStore.get(Zd);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 Y$=/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+:/;function Q$(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))Y$.test(r)||e.includes(r)?t++:e.push(r);return t===0?{...s,errors:e}:{...s,errors:e,refusalsDropped:(s.refusalsDropped??0)+t}}var tc=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(Q$)},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 Z$={Report:"ReportFolder",Dashboard:"DashboardFolder",EmailTemplate:"EmailTemplateFolder"},ex=new Set(["compare:execute","compare:permissions","compare:snapshots","compare:drift","compare:validate-deployment","compare:deploy"]),tx=5;function rx(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 rc=class{constructor(e,t={}){this.deps=e;this.options=t}deps;options;validations=new Map;async handle(e){if(!ex.has(e.type))return!1;switch(e.type){case"compare:execute":return await this.handleCompareStart(e),!0;case"compare:permissions":return await this.handlePermissions(e),!0;case"compare:snapshots":return await this.handleSnapshots(e),!0;case"compare:drift":return await this.handleDrift(e),!0;case"compare:validate-deployment":return await this.handleValidateDeployment(e),!0;case"compare:deploy":return await this.handleDeploy(e),!0;default:return!1}}async handleValidateDeployment(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(xm,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-SFGZFB4F.mjs"),a=this.options.waiting??i.DEFAULT_WAITING,d=this.progressTo(e),c=await i.retrieveComponents(i.metadataApiOf(n),n.version,t.components,{waiting:a,onProgress:d});if(c.managed.length>0){E(this.deps,"compare:validate-deployment","compare:error",e,new Error("A managed package installed "+c.managed.map(p=>`${p.componentType} ${p.fullName}`).join(", ")+" in the source, and it owns them: untick them and validate again. Nothing was sent to the target."),{code:"MANAGED",extraPayload:{managed:c.managed.map(p=>({componentType:p.componentType,fullName:p.fullName}))}});return}let l=c.retrieved.length>0?await i.deployPackage(i.metadataApiOf(o),c.zipFile,i.deployOptions(!0,t.testLevel,r),{waiting:a,onProgress:d}):void 0,u=i.deploymentReport(l,c,{sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,checkOnly:!0,testLevel:t.testLevel,runTests:r});u.success&&u.deployId&&this.keepValidation(u.deployId,{sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,zipFile:c.zipFile,components:c.retrieved,testLevel:t.testLevel,runTests:r}),this.post(T(this.deps,e,"compare:validate-deployment:response",{report:u}),u)}catch(n){E(this.deps,"compare:validate-deployment","compare:error",e,n,{code:await this.deployErrorCode(n)})}}async handleDeploy(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Dm,e,"compare:error",this.deps);if(!t)return;let r=this.validations.get(t.validationId);if(!r){E(this.deps,"compare:deploy","compare:error",e,new Error(`No successful validation ${t.validationId} is waiting in this window: validate the deployment, then deploy it. Nothing was deployed.`),{code:"NOT_VALIDATED"});return}if(r.targetOrgId!==t.targetOrgId){E(this.deps,"compare:deploy","compare:error",e,new Error(`Validation ${t.validationId} was run in another org than the one named. Nothing was deployed.`),{code:"TARGET_MISMATCH"});return}let n;try{if(n=await this.passGuard(e,r.targetOrgId,r.components,!1),!n)return;this.validations.delete(t.validationId);let o=await q(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=await import("./chunk-SFGZFB4F.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:rx(d),source:{origin:"org",orgId:r.sourceOrgId}}),this.post(T(this.deps,e,"compare:deploy:response",{report:d}),d)}catch(o){n&&Z(this.deps,{action:"metadata_deploy",module:"compare",operationId:e.id,orgId:r.targetOrgId,outcome:"failure",guard:n}),E(this.deps,"compare:deploy","compare:error",e,o,{code:await this.deployErrorCode(o)})}}async passGuard(e,t,r,n){let o=this.deps.infraServices?.productionGuard??new Lw,i=this.deps.orgManager.getOrg(t),a={orgId:t,orgTier:Ce(i),operation:"deploy",objectName:[...new Set(r.map(l=>l.componentType))].join(", "),recordCount:r.length,module:"compare"};if(n){let l=o.check(a);if(l.allowed)return"allowed";this.refuse(e,l.blockedReason??l.impactSummary);return}let{check:d,decision:c}=await Ze(o,a);if((c==="refused"||c==="declined")&&Z(this.deps,{action:"metadata_deploy",module:"compare",operationId:e.id,orgId:t,outcome:"stopped",guard:c}),c==="refused"){this.refuse(e,d.blockedReason??d.impactSummary);return}if(c==="declined"){E(this.deps,e.type,"compare:error",e,new Error("Operation cancelled by user (deployment confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}return c}refuse(e,t){E(this.deps,e.type,"compare:error",e,new Error(`Operation blocked by Production Guard: ${t}`),{code:"GUARD_BLOCKED"})}keepValidation(e,t){for(this.validations.set(e,t);this.validations.size>tx;){let r=this.validations.keys().next().value;if(r===void 0)break;this.validations.delete(r)}}progressTo(e){return t=>Le(this.deps,e.id,t.total>0?Math.round(t.done/t.total*100):0,t.done,t.total,t.step)}post(e,t){this.deps.broker.postToWebview(e),this.deps.log(`[TX] ${e.type} id=${e.id} deploy=${t.deployId??"-"} status=${t.status}`)}async deployErrorCode(e){let{DeploymentStillRunning:t}=await import("./chunk-SFGZFB4F.mjs");return e instanceof t?"STILL_RUNNING":"DEPLOY_ERROR"}async handleCompareStart(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Es,e,"compare:error",this.deps);if(!t)return;let r=t;try{let n=await this.compareOrgs(r),o=T(this.deps,e,"compare:execute:response",n);this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(n){E(this.deps,"compare:execute","compare:error",e,n)}}async compareOrgs(e,t){t?.throwIfAborted();let r=await 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(h,f)=>{let m=h===e.sourceOrgId?r:n,y=new Map,R=async O=>{t?.throwIfAborted();let P=await m.metadata.list(O);return $e(m.limitInfo,`compare:metadata list ${String(f)}`),Array.isArray(P)?P:[]},k=Z$[f],w=k?(await R([{type:k}])).map(O=>({type:f,folder:O.fullName})):[{type:f}];for(let O=0;O<w.length;O+=3)for(let P of await R(w.slice(O,O+3)))y.set(P.fullName,JSON.stringify(P));return y},l=a(h=>h===e.sourceOrgId?r:n,t),u=new i(c,d,l);if(!this.deps.services)throw new Error("CompareHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let p=this.deps.services.compareOrchestrator({metadataCompare:u,diffEngine:d,services:this.deps.services}),g={id:crypto.randomUUID(),name:"compare-from-ui",sourceOrgId:e.sourceOrgId,targetOrgId:e.targetOrgId,mode:"metadata",componentTypes:e.types,includeManaged:e.includeManaged??!0,createdAt:new Date().toISOString()};return p.execute(g,t)}async handlePermissions(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(na,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(f,m)=>{let y=await Nt(f,"SELECT Id, Name, Label, IsOwnedByProfile FROM PermissionSet WHERE IsOwnedByProfile = false");$e(f.limitInfo,`compare:permissions ${m}`);let R=await Nt(f,"SELECT Id, Name FROM Profile");return $e(f.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(f=>f.Name)),l=new Set(d.permSets.map(f=>f.Name)),u=new Set(a.profiles.map(f=>f.Name)),p=new Set(d.profiles.map(f=>f.Name)),g={permissionSets:{sourceOnly:a.permSets.filter(f=>!l.has(f.Name)).map(f=>({name:f.Name,label:f.Label})),targetOnly:d.permSets.filter(f=>!c.has(f.Name)).map(f=>({name:f.Name,label:f.Label})),shared:a.permSets.filter(f=>l.has(f.Name)).map(f=>({name:f.Name,label:f.Label}))},profiles:{sourceOnly:a.profiles.filter(f=>!p.has(f.Name)).map(f=>({name:f.Name})),targetOnly:d.profiles.filter(f=>!u.has(f.Name)).map(f=>({name:f.Name})),shared:a.profiles.filter(f=>p.has(f.Name)).map(f=>({name:f.Name}))}},h=T(this.deps,e,"compare:permissions:response",{permissions:g});this.deps.broker.postToWebview(h),this.deps.log(`[TX] ${h.type} id=${h.id}`)}catch(n){E(this.deps,"compare:permissions","compare:error",e,n)}}async handleSnapshots(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(na,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(g,h)=>{let f=await g.describeGlobal();$e(g.limitInfo,`compare:snapshots describeGlobal ${h}`);let m=f.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(g=>g.name)),l=new Set(d.objects.map(g=>g.name)),u={source:{orgId:r.sourceOrgId,totalObjects:a.totalObjects,customObjects:a.customObjects,standardObjects:a.standardObjects,queryableObjects:a.queryableObjects},target:{orgId:r.targetOrgId,totalObjects:d.totalObjects,customObjects:d.customObjects,standardObjects:d.standardObjects,queryableObjects:d.queryableObjects},diff:{sourceOnly:a.objects.filter(g=>!l.has(g.name)).map(g=>g.name),targetOnly:d.objects.filter(g=>!c.has(g.name)).map(g=>g.name),sharedCount:a.objects.filter(g=>l.has(g.name)).length},capturedAt:new Date().toISOString()},p=T(this.deps,e,"compare:snapshots:response",{snapshot:u});this.deps.broker.postToWebview(p),this.deps.log(`[TX] ${p.type} id=${p.id}`)}catch(n){E(this.deps,"compare:snapshots","compare:error",e,n)}}async handleDrift(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(na,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(g,h)=>{let f={},m=await Nt(g,"SELECT Name, LanguageLocaleKey, DefaultLocaleSidKey, TimeZoneSidKey, FiscalYearStartMonth FROM Organization LIMIT 1");if($e(g.limitInfo,`compare:drift companyInfo ${h}`),m[0])for(let[y,R]of Object.entries(m[0]))y!=="attributes"&&y!=="Id"&&(f[`Organization.${y}`]=String(R));return f},[a,d]=await Promise.all([i(n,"source"),i(o,"target")]),c=new Set([...Object.keys(a),...Object.keys(d)]),l=[];for(let g of c){let h=a[g],f=d[g];h===void 0?l.push({setting:g,sourceValue:"",targetValue:f??"",status:"missing_source"}):f===void 0?l.push({setting:g,sourceValue:h,targetValue:"",status:"missing_target"}):h!==f?l.push({setting:g,sourceValue:h,targetValue:f,status:"drift"}):l.push({setting:g,sourceValue:h,targetValue:f,status:"match"})}let u={items:l,totalChecked:l.length,driftCount:l.filter(g=>g.status==="drift").length,matchCount:l.filter(g=>g.status==="match").length,missingCount:l.filter(g=>g.status==="missing_source"||g.status==="missing_target").length,detectedAt:new Date().toISOString()},p=T(this.deps,e,"compare:drift:response",{drift:u});this.deps.broker.postToWebview(p),this.deps.log(`[TX] ${p.type} id=${p.id}`)}catch(n){E(this.deps,"compare:drift","compare:error",e,n)}}};import{randomBytes as wx}from"node:crypto";function pO(s,e,t){return s==="delete"?{...ft(e),deleted:t.done,failed:t.failed}:{...ft(e),updated:t.done,failed:t.failed}}async function nc(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:Se.code}),{ran:!1,operationId:r,code:Se.code,message:Se.message};let o=s.orgManager.getOrg(e.orgId),{check:i,decision:a}=await Ze(n,{orgId:e.orgId,orgTier:Ce(o),operation:e.operation,objectName:e.objectNames.join(", "),recordCount:e.recordCount,module:"dataops"}),d=a;if(a==="refused"||a==="declined")return Z(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,outcome:"stopped",guard:a}),{ran:!1,operationId:r,guard:a,message:a==="refused"?`Operation blocked by Production Guard: ${i.blockedReason??i.impactSummary}`:"Operation cancelled by user (confirmation declined)."};ze(s,r,"dataops",e.description);let c=new AbortController,l=()=>{},u=new Promise((f,m)=>{l=y=>y===void 0?f():m(y)});u.catch(()=>{}),s.infraServices?.backgroundRegistry?.register(r,"dataops",e.description,u,c);let p=sr(t,r,"dataops",e.description,e.recordCount),g=[],h=0;try{let f=await e.run((R,k)=>{g.push({objectApiName:R,counts:k}),h+=k.done+k.failed;let w=Math.min(100,Math.round(h/Math.max(e.recordCount,1)*100)),O=`${R}: ${k.done} done, ${k.failed} refused`;Le(s,r,w,h,e.recordCount,O),p.progress(w,h,e.recordCount,O)},c.signal);await e.beforeEnd?.();let m=cu(f),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:f.map(R=>pO(e.operation,R.objectApiName,R.counts))}),y)return s.infraServices?.backgroundRegistry?.abort(r),pe(s,r,{aborted:!0,done:m.done,failed:m.failed}),p.cancel(),l(),{ran:!0,operationId:r,outcome:m,...d?{guard:d}:{},cancelled:!0,error:`Cancelled: ${m.done} record(s) ${e.operation==="delete"?"deleted":"overwritten"} before the cancel; the rest were left as they are.`};if(pe(s,r,{status:m.status,done:m.done,failed:m.failed}),m.status==="failure"){let R=`The org refused the ${m.failed} record(s)`;p.fail(R),l(new Error(R))}else m.status==="partial"?p.partial():p.complete(),l();return{ran:!0,operationId:r,outcome:m,...d?{guard:d}:{}}}catch(f){await e.beforeEnd?.();let m=I(f);return Z(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,outcome:"failure",...d?{guard:d}:{},objects:g.map(y=>pO(e.operation,y.objectApiName,y.counts))}),De(s,r,m,!0,{context:{module:"dataops",operation:e.origin,objectName:e.objectNames.join(", ")}}),p.fail(m),l(f),{ran:!0,operationId:r,outcome:{...cu(g),status:"failure"},...d?{guard:d}:{},error:m}}}var gO=100;async function ox(s,e,t){let r=new Map,n=[],o=t.map(a=>qe(a.name)).filter(a=>a!=="Id"),i=[];for(let a=0;a<o.length;a+=gO)i.push(o.slice(a,a+gO));i.length===0&&i.push([]);for(let a of i){let d=await s.query(`SELECT ${["Id",...a].join(", ")} FROM ${e} ORDER BY Id DESC LIMIT ${200}`);for(let c of d.records){if(typeof c!="object"||c===null)continue;let l={...c};delete l.attributes;let u=typeof l.Id=="string"?l.Id:void 0;if(!u)continue;let p=r.get(u);p?Object.assign(p,l):(r.set(u,l),n.push(u))}}return n.map(a=>r.get(a))}async function sx(s,e,t){let r,n;try{if(r=rr.parse(await s.describe(qe(t))),n=qe(r.name),r.queryable===!1)throw new Error(`${n} cannot be queried.`)}catch(h){return{status:"failed",objectApiName:t,message:I(h)}}let o=js(e,n,r.fields),i=new Set(o.map(h=>h.field.name)),a=r.fields.filter(h=>Pw(h)&&Cw(h)||i.has(h.name)),d=[],c;try{d=await ox(s,n,a)}catch(h){c=I(h)}let l=c?o:js(e,n,r.fields,d),u=e.getPatterns(),p=l.map(h=>{let f=$w(h.field),m=d.map(R=>R[h.field.name]),y=h.detectedBy==="content"?u[h.pattern]:void 0;return{fieldApiName:h.field.name,label:h.field.label,classification:h.classification,detectedBy:h.detectedBy,pattern:h.pattern,filled:m.filter(wa).length,...y?{matched:m.filter(R=>typeof R=="string"&&y.test(R)).length}:{},...f?{searchedFor:f}:{}}}).sort((h,f)=>f.filled-h.filled||h.label.localeCompare(f.label)),g=xw(r);return{status:"scanned",objectApiName:t,label:r.label,sampled:d.length,fields:p,nameField:g?{fieldApiName:g.name,label:g.label}:null,...c!==void 0?{sampleError:c}:{}}}async function fO(s,e,t,r=()=>new Date){let n=r().toISOString(),o=[];for(let i of t.objects)o.push(await sx(s,e,i));return{orgId:t.orgId,scannedAt:n,sampleSize:200,objects:o}}async function ix(s,e,t,r){let n=t.fields.filter(Ew).map(d=>d.name),o=await wn(s,t.name,n,r),i=js(e,t.name,t.fields,o),a=Nw(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=rr.parse(await s.describe(qe(i.objectApiName))),d=l=>({objectApiName:a.name,plan:{objectApiName:a.name,label:a.label,records:0,refused:l}});if(t==="anonymize"){if(a.updateable!==!0){n.push(d(`The connected user may not edit ${a.label} records: erase them with Delete instead, or have an admin grant Edit on ${a.label} in a permission set.`));continue}n.push(await ix(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 aa(s);let c=await da(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 oc(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 ax(s,e){return e.map(t=>({objectApiName:s,fieldApiName:t.field.name,method:t.method,config:{}}))}async function mO(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 ca(s,i.objectApiName,i.ids,n);else{let d=i.erased??[],c=i.records??[];if(d.length===0||c.length===0)continue;let l=e.anonymize(c,ax(i.objectApiName,d)),u=[],p=0;c.forEach((g,h)=>{let f={Id:g.Id};for(let m of d)wa(g[m.field.name])&&(f[m.field.name]=l[h][m.field.name]??null);Object.keys(f).length>1?u.push(f):p++}),a=await rw(s,i.objectApiName,u,n),a.done+=p}o.push({objectApiName:i.objectApiName,counts:a}),r?.(i.objectApiName,a)}return o}var yO="dataops:subject-requests",dx="audit",cx=G({objectApiName:j(),done:Te().int().nonnegative(),failed:Te().int().nonnegative()}),lx=Ei("kind",[G({kind:yt("searched"),at:j(),searchedBy:Re(_e(["email","phone","name"])),objects:Re(G({objectApiName:j(),found:Te().int().nonnegative(),truncated:Ge()}))}),G({kind:yt("exported"),at:j(),records:Te().int().nonnegative()}),G({kind:yt("erased"),at:j(),mode:_e(["anonymize","delete"]),outcome:_e(["success","partial","failure","stopped"]),operationId:j(),objects:Re(cx)})]),ux=G({requestId:j().min(1),orgId:j().min(1),openedAt:j(),events:Re(lx)}),sc=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(yO);return Array.isArray(e)?e.flatMap(t=>{let r=ux.safeParse(t);return r.success?[r.data]:[]}):[]}write(e){this.configStore.set(yO,e.slice(-this.limit),dx)}};function gx(s){return Ll(s).slice(-8)}function fx(s){return`%${s.split("").join("%")}%`}function wO(s,e){return typeof s=="string"&&s.trim().toLowerCase()===e.trim().toLowerCase()}function hx(s,e,t){let r=qe(s.name);if(e==="email"&&t.email){let n=t.email.trim();return{field:s,kind:e,soql:`${r} = '${Zt(n)}'`,matches:o=>wO(o,n)}}if(e==="phone"&&t.phone){let n=gx(t.phone);return{field:s,kind:e,soql:`${r} LIKE '${fx(n)}'`,matches:o=>typeof o=="string"&&Ll(o).includes(n)}}if(e==="name"&&t.name){let n=t.name.trim();return{field:s,kind:e,soql:`${r} = '${Zt(n)}'`,matches:o=>wO(o,n)}}}async function mx(s,e,t){try{let r=rr.parse(await s.describe(qe(e))),n=qe(r.name);if(r.queryable===!1)throw new Error(`${n} cannot be queried.`);let o=Dw(r).flatMap(({field:g,kind:h})=>{let f=hx(g,h,t.identifiers);return f?[f]:[]});if(o.length===0)return{status:"skipped",objectApiName:e,label:r.label};let i=o.map(g=>({fieldApiName:g.field.name,label:g.field.label,kind:g.kind})),a=o.map(g=>g.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(g=>g.nameField===!0),l=[...new Set(["Id",...c?[c.name]:[],...o.map(g=>g.field.name)])].map(qe),u=await s.query(`SELECT ${l.join(", ")} FROM ${n} WHERE ${a} ORDER BY Id LIMIT ${t.limit}`),p=[];for(let g of u.records){if(typeof g!="object"||g===null)continue;let h=g;if(!Jr(h.Id))continue;let f=[...new Set(o.filter(y=>y.matches(h[y.field.name])).map(y=>y.field.name))];if(f.length===0)continue;let m=c?h[c.name]:null;p.push({id:h.Id,name:typeof m=="string"?m:null,matchedBy:f})}return{status:"searched",objectApiName:e,label:r.label,counted:d,records:p,truncated:d>t.limit,searched:i}}catch(r){return{status:"failed",objectApiName:e,message:yx(I(r),t.identifiers)}}}function yx(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 bO(s,e){let t=[];for(let r of e.objects)t.push(await mx(s,r,e));return t}var bx=6e4,Rx=new Set(["dataops:pii-inventory","dataops:dsr:search","dataops:dsr:export","dataops:dsr:erase","dataops:dsr:log"]),Sx=20;function vx(s){let e="payload"in s?s.payload:void 0;return typeof e=="object"&&e!==null&&"dryRun"in e?e.dryRun===!0:!1}function kx(s){return typeof s=="object"&&s!==null&&"success"in s&&s.success===!0}function Ox(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)=>kx(i)?[r[a]?.Id]:[])),n}catch(n){throw _w(n)==="may-have-written"&&e.wrote(t,r.map(o=>o.Id)),n}}}}function Ix(s){return["email","name","phone"].filter(e=>s[e]!==void 0)}var ic=class{constructor(e,t){this.deps=e;this.saveDialog=t??new vn}deps;found=new Map;maskingKey=wx(32).toString("hex");saveDialog;writing=new Hw;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=Ww;setDuplicatesSettle(e){this.duplicatesSettleMs=e}ownReader(){return this.reader??=import("./chunk-DIL62SUN.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 sc(this.deps.configStore)}get detector(){return this.deps.infraServices?.piiDetector??new ba}async session(e,t){let r=await q(e,this.deps.orgRegistry,this.deps.orgManager);return ia(r,t)}async handle(e){if(!Rx.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(vx(e)?void 0:Uw(e,"orgId"),()=>this.handleErase(e)),!0;default:return this.handleLog(e),!0}}async handleInventory(e){let t=x(bm,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:pii-inventory"),n=await fO(r,this.detector,t),o=T(this.deps,e,"dataops:pii-inventory:response",{...n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} objects=${n.objects.length}`)}catch(r){E(this.deps,"dataops:pii-inventory","dataops:error",e,r)}}async handleSearch(e){let t=x(Rm,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 bO(i,{objects:n,identifiers:o,limit:200}),d=this.requestLog,c=t.requestId!==void 0&&d.has(t.requestId,r)?t.requestId:crypto.randomUUID(),l=new Date().toISOString(),u={orgId:r,objects:new Map};for(let f of a)f.status==="searched"&&u.objects.set(f.objectApiName,new Set(f.records.map(m=>m.id)));this.hold(c,u),d.record(c,r,{kind:"searched",at:l,searchedBy:Ix(o),objects:a.flatMap(f=>f.status==="searched"?[{objectApiName:f.objectApiName,found:f.records.length,truncated:f.truncated}]:[])});let p={requestId:c,orgId:r,searchedAt:l,limit:200,objects:a},g=T(this.deps,e,"dataops:dsr:search:response",{...p});this.deps.broker.postToWebview(g);let h=[...u.objects.values()].reduce((f,m)=>f+m.size,0);this.deps.log(`[TX] ${g.type} id=${g.id} records=${h}`)}catch(i){E(this.deps,"dataops:dsr:search","dataops:error",e,i)}}hold(e,t){for(this.found.delete(e),this.found.set(e,t);this.found.size>Sx;){let r=this.found.keys().next().value;if(r===void 0)break;this.found.delete(r)}}heldFor(e,t){let r=this.found.get(e);if(!r||r.orgId!==t)throw new Error("This request has found nothing in this window. Search again: an export or an erasure only acts on the records a search found.");return r}async handleExport(e){let t=x(Sm,e,"dataops:error",this.deps);if(t)try{let r=this.heldFor(t.requestId,t.orgId),n=await this.session(t.orgId,"dataops:dsr:export"),o={},i=0;for(let[u,p]of r.objects){if(p.size===0)continue;let g=rr.parse(await n.describe(u)),h=await wn(n,g.name,g.fields.map(f=>f.name),[...p]);o[u]=h,i+=h.length}let a=new Date().toISOString(),d={sandforgeSubjectRequestVersion:1,requestId:t.requestId,orgId:t.orgId,exportedAt:a,objects:o},c=await this.saveDialog.save(`sandforge-subject-request-${t.requestId.slice(0,8)}.json`,JSON.stringify(d,null,2),["json"]);c.status==="saved"&&this.requestLog.record(t.requestId,t.orgId,{kind:"exported",at:a,records:i});let l=T(this.deps,e,"dataops:dsr:export:response",{requestId:t.requestId,records:i,saved:c});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id} ${c.status} records=${i}`)}catch(r){E(this.deps,"dataops:dsr:export","dataops:error",e,r)}}async handleErase(e){let t=x(km,e,"dataops:error",this.deps);if(!t)return;let{orgId:r,requestId:n,mode:o,dryRun:i}=t;try{let a=this.heldFor(n,r),d=t.records.reduce((L,ee)=>{let Q=a.objects.get(ee.objectApiName);return L+ee.ids.filter(B=>!Q?.has(B)).length},0);if(d>0)throw new Error(`${d} of the records to erase were not found by this request. Search again, and erase from what the search lists.`);let c=await this.session(r,"dataops:dsr:erase"),l=await hO(c,this.detector,o,t.records),u=l.map(L=>L.plan),p=oc(u);if(i){let L=T(this.deps,e,"dataops:dsr:erase:response",{requestId:n,mode:o,dryRun:i,plan:u,written:p});this.deps.broker.postToWebview(L),this.deps.log(`[TX] ${L.type} id=${L.id} plan objects=${u.length}`);return}let g=u.filter(L=>!L.refused&&L.records>0),h=g.reduce((L,ee)=>L+ee.records,0);if(h===0){let L=u.flatMap(ee=>ee.refused?[ee.refused]:[]);throw new Error(L.length>0?`Nothing can be erased. ${L.join(" ")}`:"Nothing is left to erase: the records found are no longer in the org.")}let f=me(this.deps.orgManager.getOrg(r),r),m=await q(r,this.deps.orgRegistry,this.deps.orgManager),y=this.targetAutomation,R=await Xr({act:o==="delete"?"cleanup":"masking",target:f,objects:p,org:Eo(m,L=>new ge(bx).withTimeout("dataops automation",()=>y.read(r,L)),Ce(this.deps.orgManager.getOrg(r))==="production"),accord:t,mayMute:!0,muteLeases:this.muteLeases,voice:"erasure"}),k=kn(R.answer),w=k?{refused:k}:await Xn(R,e.id,t.acceptEmails===!0,"erasure");if("refused"in w){let L=crypto.randomUUID();Z(this.deps,{action:"subject_erase",module:"dataops",operationId:L,orgId:r,outcome:"stopped",code:w.refused.code}),this.requestLog.record(n,r,{kind:"erased",at:new Date().toISOString(),mode:o,outcome:"stopped",operationId:L,objects:[]}),E(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(w.refused.message),{code:w.refused.code,...k?va(k):{}});return}let O=w.held,P={},b=async()=>{if(!(!O||P.back)){P.back=await O.release();for(let L of Vt(P.back,f))this.deps.log(`[INFO] ${L}`)}},v=o==="anonymize"?Gw({query:async L=>m.query(L),serverTime:async()=>(await m.soap.getServerTimestamp()).timestamp},zw(R.answer.automation,p.map(L=>L.objectApiName)),{settleMs:this.duplicatesSettleMs}):void 0,C={},S=async()=>{await b(),!C.read&&(C.read=!0,C.duplicates=await v?.read())},A=()=>Vw(C.duplicates,f,"erasure"),D=()=>O?{mutedAutomation:P.back??O.outcome}:{},z=new hb(void 0,this.maskingKey),U=await nc(this.deps,{orgId:r,operation:o==="delete"?"delete":"update",objectNames:g.map(L=>L.objectApiName),recordCount:h,action:"subject_erase",description:`Erase ${h} record(s) of a subject request`,origin:"dataops:dsr:erase",run:(L,ee)=>mO(v?Ox(c,v):c,z,l,L,ee),beforeEnd:S},this.liveTracker).finally(b),Y=new Date().toISOString();if(!U.ran){this.requestLog.record(n,r,{kind:"erased",at:Y,mode:o,outcome:"stopped",operationId:U.operationId,objects:[]}),E(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(U.message),{...U.code?{code:U.code}:{},extraPayload:D()});return}this.requestLog.record(n,r,{kind:"erased",at:Y,mode:o,outcome:U.outcome.status,operationId:U.operationId,objects:U.outcome.objects});let{duplicates:H}=C;if(U.error!==void 0){let L=A();E(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(L?`${U.error} ${L}`:U.error),{...U.cancelled?{code:rt}:{},extraPayload:{...D(),...H?{duplicates:H}:{}}});return}let M=T(this.deps,e,"dataops:dsr:erase:response",{requestId:n,mode:o,dryRun:i,plan:u,outcome:U.outcome,...D(),...H?{duplicates:H}:{}});this.deps.broker.postToWebview(M),this.deps.log(`[TX] ${M.type} id=${M.id} ${U.outcome.status} done=${U.outcome.done} failed=${U.outcome.failed}`),Jw(H)&&Ie(this.deps,"warning","Erase",A())}catch(a){E(this.deps,"dataops:dsr:erase","dataops:error",e,a)}}handleLog(e){try{let t=this.requestLog.list(),r=T(this.deps,e,"dataops:dsr:log:response",{entries:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} entries=${t.length}`)}catch(t){E(this.deps,"dataops:dsr:log","dataops:error",e,t)}}};var Ax=new Set(["User","Group","RecordType","BusinessHours","Profile","UserRole"]);function OO(s){return s.type==="reference"&&Yy(s)&&s.nillable===!0&&s.filterable===!0&&s.referenceTo?.length===1&&!Ax.has(s.referenceTo[0])}function IO(s,e){return e>0&&s/e>=.9}async function Tx(s,e,t){let r,n,o;try{if(r=rr.parse(await s.describe(qe(e.objectApiName))),n=qe(r.name),r.queryable===!1)throw new Error(`${n} cannot be queried.`);o=(await s.query(`SELECT COUNT() FROM ${n}`)).totalSize}catch(p){return{status:"failed",objectApiName:e.objectApiName,message:I(p)}}let i=r.fields.filter(du).sort((p,g)=>p.label.localeCompare(g.label)),a=r.fields.filter(OO),[d,c,l]=await Promise.all([Qy(s,n,a,o),Zy(s,n,i,e.duplicateKey,o),tw(s,n,r.fields,t,o)]),u=d.fields.filter(p=>IO(p.filled,o)&&p.filled<o).map(p=>{let g=a.find(h=>h.name===p.fieldApiName);return{fieldApiName:p.fieldApiName,label:p.label,referenceTo:g?.referenceTo?.[0]??"",filled:p.filled,empty:o-p.filled}}).sort((p,g)=>g.empty-p.empty||p.label.localeCompare(g.label));return{status:"scanned",objectApiName:e.objectApiName,label:r.label,totalRecords:o,stale:l.stale,orphans:u,duplicates:c.duplicates,keyFields:i.map(p=>({fieldApiName:p.name,label:p.label})),errors:[...d.errors,...c.errors,...l.errors],deletable:r.deletable===!0}}async function AO(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 Tx(s,o,e.staleDays));return{orgId:e.orgId,staleDays:e.staleDays,scannedAt:r,orphanThreshold:.9,bounds:{duplicateGroupLimit:Vy,duplicateSample:Xy,singleFieldQueries:Ky},objects:n}}function Ex(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 Bp(s,e,t,r){let n=(s?.skip??0)+e;return e>0&&n<t?{skip:n,...r}:void 0}function SO(s){return s.flatMap(e=>{let t=typeof e=="object"&&e!==null?e.Id:void 0;return Jr(t)?[t]:[]})}function Px(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"?`'${Zt(e)}'`:void 0}}function Cx(s,e){let t=String(e??"");return typeof e=="string"&&s!=="date"?t.toLowerCase():t}var vO=100,$x=2e3;async function xx(s,e,t,r){let n=qe(e.name),o=qe(t.name),i=await ew(s,n,t.name),a=i.rows.reduce((u,p)=>u+p.count-1,0),d=i.rows.map(u=>Px(t.type,u.value));if(d.some(u=>u===void 0))throw new Error(`Copies of ${e.label} records cannot be picked out by ${t.label}: its values are dates and times, which this cleanup does not compare.`);let c=e.fields.some(u=>u.name==="LastModifiedDate"),l=[];for(let u=0;u<d.length&&l.length<r;u+=vO){let p=d.slice(u,u+vO).join(", "),g=await s.query(`SELECT Id, ${o}${c?", LastModifiedDate":""} FROM ${n} WHERE ${o} IN (${p}) ORDER BY Id LIMIT ${$x}`),h=new Map;for(let f of g.records){if(typeof f!="object"||f===null)continue;let m=f;if(!Jr(m.Id))continue;let y=Cx(t.type,m[t.name]),R=h.get(y)??[];R.push({id:m.Id,modified:typeof m.LastModifiedDate=="string"?m.LastModifiedDate:""}),h.set(y,R)}for(let f of h.values()){f.sort((m,y)=>y.modified.localeCompare(m.modified)||y.id.localeCompare(m.id));for(let m of f.slice(1)){if(l.length>=r)break;l.push(m.id)}}}return{total:a,ids:l}}async function qp(s,e,t,r,n){let o=rr.parse(await s.describe(qe(e))),i=qe(o.name),a=g=>o.fields.find(h=>h.name.toLowerCase()===g.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 g=`LastModifiedDate < LAST_N_DAYS:${t.days}`,h=(await s.query(`SELECT COUNT() FROM ${i} WHERE ${g}`)).totalSize,f=n?.modified!==void 0?Ex(n.modified):void 0,m=f!==void 0&&n?.id!==void 0&&Jr(n.id)?` AND (LastModifiedDate > ${f} OR (LastModifiedDate = ${f} AND Id > '${n.id}'))`:"",y=await s.query(`SELECT Id, LastModifiedDate FROM ${i} WHERE ${g}${m} ORDER BY LastModifiedDate, Id LIMIT ${r}`),R=SO(y.records),k=y.records.at(-1),w=Bp(n,R.length,h,{id:R.at(-1),...typeof k?.LastModifiedDate=="string"?{modified:k.LastModifiedDate}:{}});return{object:o,total:h,ids:R,truncated:(n?.skip??0)+R.length<h,...w?{next:w}:{}}}if(t.kind==="orphans"){let g=a(t.fieldApiName);if(!g||!OO(g))throw new Error(`${t.fieldApiName} is not a lookup of ${o.label} that can leave a record without its parent.`);let h=qe(g.name),f=(await s.query(`SELECT COUNT() FROM ${i}`)).totalSize,m=(await s.query(`SELECT COUNT() FROM ${i} WHERE ${h} = null`)).totalSize;if(!IO(f-m,f))throw new Error(`${g.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&&Jr(n.id)?` AND Id > '${n.id}'`:"",R=await s.query(`SELECT Id FROM ${i} WHERE ${h} = null${y} ORDER BY Id LIMIT ${r}`),k=SO(R.records),w=Bp(n,k.length,m,{id:k.at(-1)});return{object:o,total:m,ids:k,truncated:(n?.skip??0)+k.length<m,...w?{next:w}:{}}}let d=a(t.keyField);if(!d||!du(d))throw new Error(`${t.keyField} is not a field ${o.label} records can be grouped by.`);let c=n?.skip??0,l=await xx(s,o,d,c+r),u=l.ids.slice(c),p=Bp(n,u.length,l.total,{});return{object:o,total:l.total,ids:u,truncated:c+u.length<l.total,...p?{next:p}:{}}}var Dx=6e4,Nx=new Set(["dataops:cleanup:scan","dataops:cleanup:export","dataops:cleanup:delete"]);function EO(s){switch(s.kind){case"stale":return`stale-${s.days}d`;case"orphans":return`orphans-${s.fieldApiName}`;default:return`duplicates-${s.keyField}`}}var ac=class{constructor(e,t){this.deps=e;this.saveDialog=t??new vn}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-DIL62SUN.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 ia(r,t)}async handle(e){if(!Nx.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"dataops:cleanup:scan":return await this.handleScan(e),!0;case"dataops:cleanup:export":return await this.handleExport(e),!0;default:return await this.handleDelete(e),!0}}async handleScan(e){let t=x(wm,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:cleanup:scan"),n=await AO(r,t),o=T(this.deps,e,"dataops:cleanup:scan:response",{...n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} objects=${n.objects.length}`)}catch(r){E(this.deps,"dataops:cleanup:scan","dataops:error",e,r)}}async handleExport(e){let t=x(Om,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:cleanup:export"),n=await qp(r,t.objectApiName,t.recommendation,1e3,t.after),o=await wn(r,n.object.name,n.object.fields.map(l=>l.name),n.ids),i=new Date().toISOString(),a={sandforgeCleanupVersion:1,orgId:t.orgId,objectApiName:n.object.name,recommendation:t.recommendation,exportedAt:i,recommended:n.total,records:o},d=await this.saveDialog.save(`sandforge-cleanup-${n.object.name}-${EO(t.recommendation)}.json`,JSON.stringify(a,null,2),["json"]),c=T(this.deps,e,"dataops:cleanup:export:response",{objectApiName:t.objectApiName,records:o.length,truncated:n.truncated,saved:d,exported:(t.after?.skip??0)+o.length,recommended:n.total,...n.next?{next:n.next}:{}});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id} ${d.status} records=${o.length}`)}catch(r){E(this.deps,"dataops:cleanup:export","dataops:error",e,r)}}async handleDelete(e){let t=x(Im,e,"dataops:error",this.deps);if(!t)return;let{orgId:r,recommendation:n,dryRun:o}=t;try{let i=await this.session(r,"dataops:cleanup:delete"),a=await qp(i,t.objectApiName,n,1e3),{object:d,ids:c}=a;if(d.deletable!==!0)throw new Error(`The connected user may not delete ${d.label} records: Export keeps a copy of them, and an admin grants Delete on ${d.label} in a permission set. Nothing was deleted.`);if(o){let b=await da(i,d,c,await aa(i)),v={objectApiName:d.name,label:d.label,records:c.length,related:b.related,uncounted:b.uncounted},C=T(this.deps,e,"dataops:cleanup:delete:response",{objectApiName:t.objectApiName,dryRun:o,plan:v,truncated:a.truncated,written:oc([v])});this.deps.broker.postToWebview(C),this.deps.log(`[TX] ${C.type} id=${C.id} plan records=${c.length}`);return}if(c.length===0)throw new Error(`No ${d.label} record is left to delete for this recommendation.`);let l=await q(r,this.deps.orgRegistry,this.deps.orgManager),u=me(this.deps.orgManager.getOrg(r),r),p=this.targetAutomation,g=Sa(t),h=await Xr({act:"cleanup",target:u,objects:[{objectApiName:d.name,records:c.length}],org:Eo(l,b=>new ge(Dx).withTimeout("dataops automation",()=>p.read(r,b)),Ce(this.deps.orgManager.getOrg(r))==="production"),accord:t,mayMute:!0,muteLeases:this.muteLeases,...g?{voice:g}:{}}),f=kn(h.answer);if(f){E(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(f.message),{code:f.code,...va(f)});return}let m=await Xn(h,e.id,t.acceptEmails===!0,g);if("refused"in m){E(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(m.refused.message),{code:m.refused.code});return}let y=m.held,R={},k=async()=>{if(!(!y||R.back)){R.back=await y.release();for(let b of Vt(R.back,u))this.deps.log(`[INFO] ${b}`)}},w={objectApiName:d.name,label:d.label,records:c.length},O=await nc(this.deps,{orgId:r,operation:"delete",objectNames:[d.name],recordCount:c.length,action:"cleanup_delete",description:`Delete ${c.length} ${d.name} record(s): ${EO(n)}`,origin:"dataops:cleanup:delete",run:async(b,v)=>{let C=await ca(i,d.name,c,v);return b(d.name,C),[{objectApiName:d.name,counts:C}]},beforeEnd:k},this.liveTracker).finally(k);if(!O.ran){E(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){E(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(O.error),O.cancelled?{code:rt}:void 0);return}let P=T(this.deps,e,"dataops:cleanup:delete:response",{objectApiName:t.objectApiName,dryRun:o,plan:w,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){E(this.deps,"dataops:cleanup:delete","dataops:error",e,i)}}};import{join as LD}from"node:path";async function PO(s){let{permissions:e,objects:t}=s;if(e.viewAllData&&e.modifyAllData)return{kind:"org"};let r={kind:"perObject",viewAllData:e.viewAllData,modifyAllData:e.modifyAllData},n=await s.grants();if("unread"in n)return{...r,unseen:t.map(u=>({objectApiName:u,reason:"permissionsUnread",detail:n.unread}))};let o=await s.describe(t),i={grants:n.grants,describes:o,...s.customSettings?{customSettings:s.customSettings}:{}},a=bb(t,i),d=a.length>0?[...o,...await s.describe(a)]:o,c=Rb(t,{...i,describes:d}),l=[];for(let[u,p]of c)"access"in p||l.push({objectApiName:u,reason:p.reason,...p.detail!==void 0?{detail:p.detail}:{}});return{...r,unseen:l}}function CO(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 jx=1e4,xO={bulkDestroy:()=>Promise.reject(new Error("an estimate sends no job"))};function Wp(s){return xs(xO,s,1,"hard")}var DO=9,Mx=25;function NO(s,e,t){let r=e>0&&xs(xO,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/Ut),jobs:[],toTheBin:!0};let n=Math.ceil(e/$s),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 $r(s,e){return{apiRequests:s,seconds:s*e}}function li(s){return s.reduce((e,t)=>({apiRequests:e.apiRequests+t.apiRequests,seconds:e.seconds+t.seconds}),{apiRequests:0,seconds:0})}function jO(s){return Math.max(1,Math.ceil(s/mu))}function MO(s){return s.notSent?{apiRequests:0,seconds:0}:li([$r(jO(s.records),Kn),$r(1,Fs),$r(s.restCalls,Ea),...s.jobs.map(e=>({apiRequests:iw({stateReads:dw(e)}),seconds:aw(e)}))])}function Lx(s){return s<=0?{apiRequests:0,seconds:0}:li([$r(1,Fs),$r(Math.ceil(s/mu),Kn),$r(Math.ceil(s/Ut),Ea),$r(Math.ceil(s/Ut),Kn)])}function Fx(s){if(s<=0)return{apiRequests:0,seconds:0};let e=Math.ceil(s/Ut);return li([$r(e,Ea),$r(e,Kn)])}var _x=.05,$O={check:2,connect:3};function dc(s,e,t,r=0){let n=t*$O.check+$O.connect,o=t*e+n+s.apiRequests+r,i=Math.ceil(o*_x);return{apiRequests:o+i,seconds:e*Fs+s.seconds,requests:{reads:e,readings:t,passes:s.apiRequests,margin:i,connecting:n,...r>0?{mute:r}:{}}}}function LO(s){let e=s.passes.map(({objectApiName:d,records:c})=>NO(d,Math.max(0,c),s.mode)),t=li([Lx(s.toDraft),$r(s.draftReads??0,Kn),...e.map(MO),...(s.refused??[]).map(Fx)]),r=dc(t,Math.max(0,s.reads),s.readings??2),n=e.reduce((d,c)=>d+c.jobs.reduce((l,u)=>l+Math.ceil(u/jx),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*Mx,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:On(r.apiRequests,s.apiBudget),...a?{batches:s.bulkBatches?On(n,s.bulkBatches):{verdict:"unread",estimate:n,unread:"the limits the org answered list no DailyBulkApiBatches"}}:{}}}function FO(s,e,t,r=0){let n=li(e.map(o=>{let i=NO(o.objectApiName,Math.max(0,o.records),s),a=MO(i);if(!o.idsRead||i.notSent)return a;let d=jO(i.records);return{apiRequests:a.apiRequests-d,seconds:a.seconds-d*Kn}}));return dc(n,Math.max(0,t),1,Math.max(0,r)).apiRequests}var zp=3;function _O(s,e,t=0){return dc({apiRequests:Math.max(0,s),seconds:0},Math.max(0,e),1,Math.max(0,t)).apiRequests}function HO(s,e,t,r=0){let n={apiRequests:s.requests.passes,seconds:s.seconds-s.requests.reads*Fs},o=dc(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:On(o.apiRequests,i)}}var Hx=wb.extend({relationshipName:j().nullish(),polymorphicForeignKey:Ge().optional()}),UO=Ca.extend({deletable:Ge().optional(),fields:Re(Hx)});function Gp(s){return ub.has(s)}var BO={pricebook2:{field:"IsStandard",value:!0}};function qO(s){let e=BO[s.toLowerCase()];return e?`${e.field} = ${String(e.value)}`:void 0}function to(s){let e=BO[s.toLowerCase()];return e?`${e.field} = ${String(!e.value)}`:void 0}var Ux=new Set(["pricebook2","product2"]);function WO(s,e){return e!==void 0&&s.childSObject!==void 0&&s.field!==void 0&&yb(s.childSObject,s.field,e)?"restricted":s.cascadeDelete===!0?"cascade":s.restrictedDelete===!0?"restricted":"lookup"}function Jp(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)?cc(s,i,o.field):void 0;zO(a,r)||t.push({parent:r,child:e(o.childSObject),field:o.field,kind:WO(o,r)})}return t}var ui=5,Bx=8;function zO(s,e){if(s?.polymorphicForeignKey===!0)return!1;let t=s?.referenceTo??[];return t.length>0&&!t.some(r=>r.toLowerCase()===e.toLowerCase())}function qx(s,e,t){let r=cc(s,e,t);return(r?.referenceTo?.length??0)>1||r?.polymorphicForeignKey===!0}function Vp(s,e,t){let r=new Map;for(let h of[...e,...s,...t.keys()])r.set(h.toLowerCase(),h);let n=h=>r.get(h.toLowerCase())??h,o=h=>t.get(h)??t.get(n(h)),i=new Set(s.map(h=>h.toLowerCase())),a=new Set([...e,...s].map(h=>h.toLowerCase())),d=new Map,c=new Map,l=new Set,u=(h,f)=>{let m=c.get(h)??new Set;m.add(f),c.set(h,m)},p=s.map(h=>({top:h,from:h,above:[]}));for(;p.length>0;){let h=[];for(let{top:f,from:m,above:y}of p){let R=o(m);if(!R){l.add(m);continue}for(let k of R.childRelationships??[]){if(WO(k,m)!=="cascade")continue;let w=n(k.childSObject),P=o(w)?.fields.find(S=>S.name.toLowerCase()===k.field.toLowerCase());if(zO(P,m))continue;let b=w.toLowerCase();if(!a.has(b)||b===m.toLowerCase()||y.some(S=>S.object.toLowerCase()===b))continue;let v=[{object:w,field:k.field,parent:m},...y],C=d.get(w)??[];if(v.length>1&&C.length>=Bx){u(w,m);continue}d.set(w,[...C,{object:w,steps:v,emptied:f}]),!(i.has(b)||v.length>=ui)&&h.push({top:f,from:w,above:v})}}p=h}for(let h=!0;h;){h=!1;for(let[f,m]of d)for(let y of m)for(let[R,k]of y.steps.entries())R===0||!c.has(k.object)||y.steps.slice(0,R).some(O=>qx(t,O.object,O.field))||c.get(f)?.has(k.object)||(u(f,k.object),h=!0)}let g=[...d.keys()].filter(h=>!i.has(h.toLowerCase())).sort();return{emptied:new Set(s),routes:d,along:g,routesCut:new Map([...c].map(([h,f])=>[h,[...f].sort()])),undescribed:[...l].filter(h=>!i.has(h.toLowerCase())).sort()}}function Ko(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 Wx(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 cc(s,e,t){let r=t.toLowerCase();return s.get(e)?.fields.find(n=>n.name.toLowerCase()===r)}function lc(s,e,t=to,r=()=>{}){let n=[],o=(i,a,d,c)=>Wx({soql:i,exact:a},d,r(c));for(let[i,a]of s.entries()){if(!e.has(a.object)){let h=[...n,a.field].join(".");return o(`${h} != null`,!1,h,a.parent)}let d=cc(e,a.object,a.field);if(!d){if(i===0)return;let h=s[i-1],f=[...n.slice(0,-1),h.field].join(".");return o(`${f} != null`,!1,f,h.parent)}let c=(d.referenceTo?.length??0)>1||d.polymorphicForeignKey===!0,l=d.relationshipName??void 0,u=i===s.length-1,p=l?[...n,l].join("."):void 0,g=[...n,d.name].join(".");if(c)return p?o(`${p}.Type = '${a.parent}'`,u,g,a.parent):o(`${g} != null`,!1,g,a.parent);if(u){let h=t(a.parent);if(h===void 0&&!Ux.has(a.parent.toLowerCase()))return o(`${g} != null`,!0,g,a.parent);if(!p)return o(`${g} != null`,!1,g,a.parent);let f=h!==void 0?` AND ${p}.${h}`:"";return o(`${p}.Id != null${f}`,!0,g,a.parent)}if(!l||i+1>=ui)return o(`${g} != null`,!1,g,a.parent);n.push(l)}}function GO(s,e,t){let r=[];for(let[n,o]of s.entries()){let i=e.has(o.object)?cc(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>=ui)return;r.push(i.relationshipName)}}function pi(s,e,t=to,r){let n=s.map(a=>lc(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 JO(s,e,t,r,n,o=to,i){let a={object:s,field:e,parent:t};if(r.emptied.has(t))return lc([a],n,o,i);let d=(r.routes.get(t)??[]).map(c=>({object:s,steps:[a,...c.steps],emptied:c.emptied}));return pi(d,n,o,i)}var KO=4,VO=100,zx=/^[A-Za-z0-9]+$/;function XO(s,e){let t=to(s);if(t!==void 0)return t;if(e&&s.toLowerCase()===gr.toLowerCase())return`${_s} = false`}var so="stopped before the org was asked";function YO(s,e,t="COUNT()"){let r=Gp(s),n=[...e,...r?["IsDeleted = false"]:[]],o=n.length===0?"":` WHERE ${n.map(i=>n.length>1?`(${i})`:i).join(" AND ")}`;return{soql:`SELECT ${t} FROM ${qe(s)}${o}`,all:r}}var oo=class{statements=new Map;answers=new Map;ask(e,t){let r=YO(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 Cs([...this.statements].map(([n,{soql:o,all:i,atMost:a}])=>async()=>{if(t()){r=!0,this.answers.set(n,{unread:so});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)})}}),KO),r}answer(e){return this.answers.get(e)??{unread:so}}},gc=class{statements=new Map;answers=new Map;ask(e,t){let r=YO(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 Cs([...this.statements].map(([n,o])=>async()=>{if(t()){r=!0,this.answers.set(n,{counted:{unread:so}});return}try{let i=await e.readIds(n,o),a=i.ids.filter(d=>zx.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)}})}}),KO),r}answer(e){return this.answers.get(e)??{counted:{unread:so}}}};function Yp(s,e){return s.records===void 0?s:e.records===void 0?{unread:e.unread??so}:{records:Math.max(0,s.records-e.records),...e.atMost?{atLeast:!0}:{}}}function Xp(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 Dn(s){return s.records===0&&s.atLeast!==!0}function ro(s){return s===void 0||s.records===void 0||s.records>0}function pc(s){return{unread:`${s}: the lookup its records go by is hidden from the user`}}function Qp(s){return s.records===void 0?s:{...s,atLeast:!0}}function gi(s){return s.records===void 0?s:{...s,atMost:!0}}function Kp(s,e){let t=e.key?s.answer(e.key):pc(e.objectApiName),r=e.going?Yp(t,s.answer(e.going)):t,n=(r.records??0)>0;return e.more&&n&&(r={...r,atLeast:!0}),e.under&&n&&(r=Qp(r)),e.over&&n&&(r=gi(r)),r}function Zp(s,e){return s.every(t=>e.get(t.emptied)!=="unnamed"&&t.steps.every(r=>e.get(r.parent)!=="unnamed"))}function Gx(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 no(s){let e=s.filter(n=>n.records!==void 0);if(e.length===0)return s.length===0?{records:0}:{unread:s[0].unread??so};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 uc="Pricebook2";function Jx(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 QO(s,e,t=()=>!1,r={undo:!0}){let{affected:n,order:o,relations:i,describes:a}=s,d=o.passes.map($=>$.objectApiName),c=a.get(gr)?.fields.some($=>$.name===_s)===!0,l=$=>{let N=XO($,c);if(!($.toLowerCase()===gr.toLowerCase()&&n.emptied.has(Ro)))return N},u=$=>{let N=l($);return N===void 0?[]:[N]},p=new Map,g=$=>p.get($),h=$=>g($),f=$=>lc($,a,l,h),m=$=>pi($,a,l,h),y=($,N,X)=>JO($,N,X,n,a,l,h),R=new oo,k=new Map;for(let $ of d)k.set($,R.ask($,u($)));let w=await R.run(e,t),O=new Map(d.map($=>[$,R.answer(k.get($)??"")])),P=$=>[...Ko($,n)].some(N=>ro(O.get(N))),b=$=>$.filter(N=>ro(O.get(N.emptied))),v=$=>!n.emptied.has($)&&n.routesCut.has($),C=new oo,S=[];for(let{parent:$,child:N,field:X,kind:F}of i){if(F!=="restricted"||N===$||n.emptied.has(N)||!P($))continue;let de=y(N,X,$),J=n.routes.has(N)?m(b(n.routes.get(N)??[])):void 0;S.push({objectApiName:N,field:X,parent:$,...de?{key:C.ask(N,[de])}:{},...de&&J?{going:C.ask(N,[J,de])}:{},...J&&v(N)?{over:!0}:{},...n.emptied.has($)&&!n.routes.has(N)?{naming:""}:{}})}for(let{child:$,field:N,parent:X,rows:F}of wu){if(F===void 0||!P(X)||n.emptied.has($)||!n.routes.has($))continue;let J=a.get($)?.fields.some(Ee=>Ee.name===F.field)===!0?y($,N,X):void 0;if(!J)continue;let le=`${F.field} = ${String(F.value)}`;S.push({objectApiName:$,field:N,parent:X,key:C.ask($,[le,J]),along:!0,...n.emptied.has(X)?{naming:le}:{}})}w=await C.run(e,t)||w;let A=new gc,D=new Map,z=new Map;S.forEach(($,N)=>{if($.naming===void 0||$.key===void 0||(Kp(C,$).records??0)===0)return;let X=`Id IN (SELECT ${qe($.field)} FROM ${qe($.objectApiName)}${$.naming!==""?` WHERE ${$.naming}`:""})`;D.set(N,A.ask($.parent,[...u($.parent),X])),z.set($.parent,[...z.get($.parent)??[],X])}),w=await A.run(e,t)||w;for(let $ of z.keys()){let N=[...D].filter(([F])=>S[F].parent===$).map(([,F])=>A.answer(F));if(N.every(F=>F.counted.records===0))continue;let X=new Set(N.flatMap(F=>F.ids??[]));p.set($,N.every(F=>F.ids!==void 0)&&X.size<=VO?[...X]:"unnamed")}let U=$=>{let N={archived:new Map,kept:new Map,goneBefore:new Map,along:new Map,refusals:[],undoLost:[]};for(let J of o.passes){let le=J.objectApiName;if(!ro(O.get(le)))continue;let Ee=u(le);Gp(le)&&N.archived.set(le,$.ask(le,[...Ee,"IsArchived = true"]));let je=qO(le);je!==void 0&&N.kept.set(le,$.ask(le,[je]));let We=b(J.goneBefore);if(We.length>0){let be=m(We);N.goneBefore.set(le,be?{key:$.ask(le,[...Ee,be]),unreadable:!1}:{unreadable:!0})}let ae=r.undo?b(J.sentBeforeTheirParent):[];for(let be of ae){let He=f(be.steps),Ue=be.steps[0],ot=He?[...Ee,He]:void 0;N.undoLost.push({objectApiName:le,field:Ue.field,parent:Ue.parent,reason:"unordered",...ot?{key:$.ask(le,ot),conditions:ot}:{}})}}for(let J of n.along){let le=b(n.routes.get(J)??[]);if(le.length===0)continue;let Ee=le.map(We=>{let ae=f(We.steps);return{route:We,...ae?{key:$.ask(J,[ae])}:{}}}),je=le.length>1?m(le):void 0;N.along.set(J,{...je?{total:$.ask(J,[je])}:Ee[0].key?{total:Ee[0].key}:{},via:Ee})}let X=J=>o.passes.findIndex(le=>le.objectApiName===J);for(let J of r.undo?o.beforeParent:[]){if(J.reason==="customPrices"){if(!P(uc)||!P(J.parent)||X(uc)>X(J.parent))continue;let We=y(J.objectApiName,"Pricebook2Id",uc),ae=y(J.objectApiName,J.field,J.parent),be=We&&ae?[We,ae]:void 0;N.undoLost.push({objectApiName:J.objectApiName,field:J.field,parent:J.parent,reason:"restricted",...be?{key:$.ask(J.objectApiName,be),conditions:be}:{},...v(uc)||v(J.parent)?{under:!0}:{}});continue}if(!P(J.objectApiName)||!P(J.parent))continue;let le=y(J.objectApiName,J.field,J.parent),Ee=[];if(!n.emptied.has(J.objectApiName)){let We=m(b(n.routes.get(J.objectApiName)??[]));We&&Ee.push(We)}let je=v(J.objectApiName)||v(J.parent);N.undoLost.push({objectApiName:J.objectApiName,field:J.field,parent:J.parent,reason:"restricted",...le?{key:$.ask(J.objectApiName,[...Ee,le]),conditions:[...Ee,le]}:{},...je?{under:!0}:{}})}for(let{child:J,field:le,parent:Ee,rows:je}of wu){if(je===void 0||!P(Ee)||!n.emptied.has(J))continue;let ae=a.get(J)?.fields.some(He=>He.name===je.field)===!0?y(J,le,Ee):void 0;if(!ae||!r.undo||!ro(O.get(J)))continue;let be=`${je.field} = ${String(je.value)}`;N.undoLost.push({objectApiName:J,field:le,parent:Ee,reason:"restricted",key:$.ask(J,[be,ae]),conditions:[be,ae],more:!0})}let F=(J,le,Ee,je=!1)=>{N.refusals.push({code:J,objectApiName:le,key:$.ask(le,Ee),...je?{under:!0}:{}})};for(let J of o.toDraft){if(!P(J))continue;let le="StatusCode != 'Draft'";if(n.emptied.has(J)){F("activatedOrder",J,[le]);continue}let Ee=b(n.routes.get(J)??[]),je=m(Ee);F(Zp(Ee,p)?"activatedOrder":"activatedOrderLeft",J,je?[je,le]:[{soql:le,exact:!1}],je!==void 0&&v(J))}for(let[J,le]of N.kept)N.refusals.push({code:"standardPriceBook",objectApiName:J,key:le});n.emptied.has(Vi)&&ro(O.get(Vi))&&(n.emptied.has(gr)||F("directContactRelation",Vi,[{soql:"IsDirect = true",exact:!n.routes.has(gr)}]));let de=a.get(gr);return n.emptied.has(gr)&&!n.emptied.has(Ro)&&ro(O.get(gr))&&de?.fields.some(J=>J.name===_s)===!0&&F("personAccountContact",gr,[`${_s} = true`]),N},Y=new gc,H=new Map;if(p.size>0){let $=new Set;g=N=>(n.emptied.has(N)||$.add(N),p.get(N)),U(new oo),g=N=>p.get(N);for(let N of[...$].sort()){let X=b(n.routes.get(N)??[]),F=X.filter(le=>p.has(le.emptied));if(F.length===0)continue;let de=p.get(F[0].emptied),J=X.length===1&&Array.isArray(de)?GO(X[0].steps,a,de):void 0;J===void 0?p.set(N,"unnamed"):H.set(N,Y.ask(N,[J]))}w=await Y.run(e,t)||w;for(let[N,X]of H){let F=Y.answer(X);p.set(N,F.ids!==void 0&&F.ids.length<=VO?F.ids:"unnamed")}}let M=new oo,L=U(M);w=await M.run(e,t)||w;let ee=$=>Kp(M,$),Q=new oo,B=new Map;for(let[$,N]of z)N.length===2&&p.get($)==="unnamed"&&B.set($,Q.ask($,[...u($),...N]));let V=new Map,we=new Map;for(let $ of L.undoLost)we.set($.objectApiName,[...we.get($.objectApiName)??[],$]);for(let[$,N]of we){let X=N.filter(de=>!Dn(ee(de)));if(X.length<2)continue;let F=X.map(de=>de.conditions);F.some(de=>de===void 0)||V.set($,Q.ask($,[Gx(F)]))}w=await Q.run(e,t)||w;let ie=S.map(($,N)=>{let X=D.get(N);return{objectApiName:$.objectApiName,field:$.field,parent:$.parent,records:Kp(C,$),...X!==void 0?{keeps:A.answer(X).counted}:{}}}).filter($=>!Dn($.records)),re=$=>{let N=ie.flatMap(J=>J.parent===$&&J.keeps!==void 0?[J.keeps]:[]);if(N.length===0)return;let X=p.get($);if(Array.isArray(X))return{records:X.length};let F=no(N),de=B.get($);return de!==void 0?Xp(F,Q.answer(de)):N.length>1&&(F.records??0)>0?gi(F):F},Ae=ie.filter($=>!Array.isArray(p.get($.parent))&&S.some(N=>N.along===!0&&N.objectApiName===$.objectApiName&&N.field===$.field&&N.parent===$.parent)),he=ie.filter($=>S.some(N=>N.along===!0&&N.objectApiName===$.objectApiName&&N.field===$.field&&N.parent===$.parent)),Je=o.passes.map($=>{let N=$.objectApiName,X=XO(N,c),F=O.get(N)??{unread:so};if(!ro(F))return{objectApiName:N,...X!==void 0?{rows:X}:{},records:F,sent:F};let de=L.goneBefore.get(N),J=de===void 0?F:de.unreadable||de.key===void 0?pc(N):n.routesCut.has(N)?gi(Yp(F,M.answer(de.key))):Yp(F,M.answer(de.key)),le=L.archived.get(N),Ee=L.kept.get(N),je=re(N);return{objectApiName:N,...X!==void 0?{rows:X}:{},records:F,sent:J,...le?{archived:M.answer(le)}:{},...Ee?{kept:M.answer(Ee)}:{},...je&&!Dn(je)?{blocked:je}:{}}}),Ne=r.undo?Je.filter($=>a.get($.objectApiName)?.undeletable===!1&&!Dn($.sent)).map($=>({objectApiName:$.objectApiName,reason:"notRestorable",records:$.sent})):[],Fe=[...L.along].map(([$,{total:N,via:X}])=>{let F=N?M.answer(N):pc($),de=n.routesCut.get($),J=Ae.filter(ae=>ae.objectApiName===$),le=he.filter(ae=>ae.objectApiName===$),Ee=J.length>0?no(J.map(ae=>ae.records)):void 0,je=le.length>0?no(le.map(ae=>ae.records)):void 0,We=Ee?Xp(F,Ee):F;return{objectApiName:$,records:de?Qp(We):We,via:X.map(({route:ae,key:be})=>{let He=be?M.answer(be):pc($),Ue=ae.steps[0],ot=J.filter(Ve=>Ve.field===Ue.field&&Ve.parent===Ue.parent);return{field:Ue.field,parent:Ue.parent,emptied:ae.emptied,records:ot.length>0?Xp(He,no(ot.map(Ve=>Ve.records))):He}}).filter(ae=>!Dn(ae.records)),...je&&!Dn(je)?{blocking:je}:{},...de?{routesNotRead:[...de]}:{}}}).filter($=>!Dn($.records)),W=($,N)=>$.map(X=>({...N(X),records:ee(X)})).filter(X=>!Dn(X.records)),se=Jx([...W(L.undoLost,$=>({objectApiName:$.objectApiName,...$.field!==void 0?{field:$.field}:{},...$.parent!==void 0?{parent:$.parent}:{},reason:$.reason})),...Ne]),te=new Map;for(let $ of se)te.set($.objectApiName,[...te.get($.objectApiName)??[],$]);let ue=no([...te].map(([$,N])=>{let X=V.get($),F=N.filter(J=>J.reason==="notRestorable");if(X===void 0){let J=no(N.map(le=>le.records));return N.length>1&&(J.records??0)>0?gi(J):J}let de=Q.answer(X);return N.some(J=>J.reason!=="notRestorable"&&J.records.atLeast)&&(de.records??0)>0&&(de=Qp(de)),F.length>0?gi(no([de,...F.map(J=>J.records)])):de}));return{objects:Je,along:Fe,refusals:W(L.refusals,$=>({code:$.code,objectApiName:$.objectApiName})),blockers:ie,undoLost:se,undoLostRecords:ue,kept:p,statements:R.size+C.size+A.size+Y.size+M.size+Q.size,...w?{stopped:!0}:{}}}var tI={lookup:0,cascade:1,restricted:2,customPrices:2},ZO="Pricebook2",eg="Product2",eI="PricebookEntry";function Vx(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 Ko(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=Ko(i,s),l=s.emptied.has(i)?[i]:[...c],u=!1;for(let p of Ko(o,s))if(!c.has(p))for(let g of l)g!==p&&(t.push({first:g,then:p,reason:"restricted"}),u=!0);u&&r.push({objectApiName:i,field:a,parent:o,reason:"restricted"})}return s.emptied.has(ZO)&&s.emptied.has(eg)&&(t.push({first:ZO,then:eg,reason:"customPrices"}),n(eI)&&r.push({objectApiName:eI,field:"Product2Id",parent:eg,reason:"customPrices"})),{constraints:t,beforeParent:r}}function Xx(s){return Object.hasOwn(tI,s)}function rI(s,e){let{constraints:t,beforeParent:r}=Vx(s,e),n=[...s.emptied].sort(),o=new Map(n.map(u=>[u,[]]));for(let{first:u,then:p,reason:g}of t)g==="cascade"?o.get(u)?.push({childSObject:p,field:g,cascadeDelete:!0}):o.get(p)?.push({childSObject:u,field:g});let i=new Map(n.map(u=>[u,{name:u,fields:[],childRelationships:o.get(u)??[]}])),a=gh(n,i,({field:u})=>{let p=Xx(u)?u:"lookup";return{first:p==="cascade"?"parent":"child",firmness:tI[p]}}),d=new Map(a.map((u,p)=>[u,p])),c=(u,p)=>(d.get(u)??0)<(d.get(p)??0);return{passes:a.map(u=>{let p=s.routes.get(u)??[];return{objectApiName:u,goneBefore:p.filter(g=>c(g.emptied,u)),sentBeforeTheirParent:p.filter(g=>!c(g.emptied,u))}}),beforeParent:r,unordered:Kx(t.filter(({first:u,then:p})=>!c(u,p))),toDraft:nr([...n,...s.along])}}function Kx(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 Yx(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 Qx=(s,e,t)=>{let r=gb(s,e,"empty",t.customSettings?{customSettings:uh}:{});return{candidates:r.candidates,leftOut:r.leftOut.map(({objectApiName:n,reason:o,detail:i})=>({objectApiName:n,reason:Yx(o),...i===void 0?{}:{detail:i}}))}},Zx=new Set([ch,lh].map(s=>s.toLowerCase()));function nI(s,e){return s.objectApiName<e.objectApiName?-1:s.objectApiName>e.objectApiName?1:0}function eD(s,e){if(s.customSetting===!0&&e.customSettings!==!0)return"customSetting";if(Zx.has(s.name.toLowerCase())&&e.files!==!0)return"files";if(ph(s.name)!==void 0&&e.managedPackages!==!0)return"managedPackage";if(s.undeletable===!1&&e.unrestorable!==!0)return"notRestorable"}function fc(s,e,t,r=Qx){let n=r(s,e,{customSettings:!0}),o=new Map(s.map(u=>[u.name.toLowerCase(),u])),i=new Set(n.candidates.map(u=>u.toLowerCase())),a=new Map(n.leftOut.map(u=>[u.objectApiName.toLowerCase(),u])),d=[],c=[],l=u=>{let p=a.get(u.name.toLowerCase());return p?{...p,objectApiName:u.name}:{objectApiName:u.name,reason:"notDeletable"}};if(t.mode==="objects"){let u=new Set;for(let p of t.objects??[]){let g=p.toLowerCase();if(u.has(g))continue;u.add(g);let h=o.get(g);h?i.has(g)?d.push(h.name):c.push(l(h)):c.push({objectApiName:p,reason:"notFound"})}}else{let u=new Set((t.excluded??[]).map(p=>p.toLowerCase()));for(let p of t.excluded??[])o.has(p.toLowerCase())||c.push({objectApiName:p,reason:"notFound"});for(let p of o.values()){let g=p.name.toLowerCase();if(u.has(g)){c.push({objectApiName:p.name,reason:"excludedByUser"});continue}if(!i.has(g)){c.push(l(p));continue}let h=eD(p,t);h===void 0?d.push(p.name):c.push({objectApiName:p.name,reason:h})}}return d.sort(),c.sort(nI),{mode:t.mode,objects:d,leftOut:c,worked:[...n.candidates].sort()}}function oI(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(nI)}}async function tg(s,e,t,r){await Cs(e.map(n=>async()=>{try{t.set(n,UO.parse(await s.describe(n)))}catch(o){r.set(n,I(o))}}),6)}function rD(s,e){if(e!=="hard")return s;let t=s.objects.filter(r=>!Wp(r));return t.length===0?s:{...s,objects:s.objects.filter(Wp),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 io(s){return s.records}async function sI(s,e){let t=fc(s.global,s.tooling,s.request,s.rule),r=new Map,n=new Map;await tg(e,t.objects,r,n);let o=rD(oI(t,r,n),s.deleteMode),i=new Map([...t.worked,...s.global.map(v=>v.name)].map(v=>[v.toLowerCase(),v])),a=v=>i.get(v.toLowerCase())??v,d=Vp(o.objects,t.worked,r);for(let v=0;v<ui;v++){let C=d.undescribed.filter(S=>!r.has(S)&&!n.has(S));if(C.length===0)break;await tg(e,C,r,n),d=Vp(o.objects,t.worked,r)}let c=v=>d.emptied.has(v)||d.routes.has(v),l=[...new Set(Jp(r,a).filter(({kind:v,parent:C,child:S})=>v==="restricted"&&c(C)&&!c(S)).map(({child:v})=>v))].filter(v=>!r.has(v)&&!n.has(v));await tg(e,l,r,n);let u=Jp(r,a),p=rI(d,u),g=await QO({affected:d,order:p,relations:u,describes:r},e,s.stopped,{undo:s.deleteMode==="recycle"}),h=[...g.objects.filter(v=>io(v.records)===void 0),...g.along.filter(v=>io(v.records)===void 0)].map(v=>v.objectApiName),f=[...g.objects.map(v=>Math.max(0,(io(v.records)??0)-(v.blocked?.records??0))),...g.along.map(v=>io(v.records)??0)].filter(v=>v>0),m=f.reduce((v,C)=>v+C,0),y=g.along.some(v=>v.records.atLeast===!0)||g.objects.some(v=>v.blocked?.atMost===!0),R=g.refusals.filter(v=>v.code==="activatedOrder").reduce((v,C)=>v+(io(C.records)??0),0),k=p.toDraft.filter(v=>!d.emptied.has(v)).map(v=>{let C=d.routes.get(v)??[];if(!Zp(C,g.kept))return{objectApiName:v};let S=pi(C,r,void 0,A=>g.kept.get(A));return{objectApiName:v,...S?{condition:S.soql}:{}}}),w=v=>v.records===void 0||v.records>0,O=g.objects.filter(v=>w(v.records)).length+g.along.filter(v=>w(v.records)).length,P=DO+r.size+n.size+g.statements+2*O,b=LO({mode:s.deleteMode,passes:g.objects.map(v=>({objectApiName:v.objectApiName,records:io(nr([v.objectApiName]).length>0?v.records:v.sent)??0})),toDraft:R,deleted:m,reads:P,draftReads:k.filter(v=>v.condition!==void 0).length,refused:g.blockers.map(v=>io(v.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:g.objects,along:g.along,leftOut:o.leftOut,refusals:g.refusals,blockers:g.blockers,beforeParent:p.beforeParent,unordered:p.unordered,undoLost:g.undoLost,undoLostRecords:g.undoLostRecords,undo:s.deleteMode==="recycle",affected:[...d.emptied,...d.along].sort(),toDraftAlong:k,cost:b,total:{records:m,objects:f.length,uncounted:h,...y?{atLeast:!0}:{}},statements:g.statements,...g.stopped?{stopped:!0}:{}}}var nD=5,oD=$s,hc=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!==pw};this.refused.has(r)||this.refused.size<oD?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=[...gw(this.objectApiName,e),...fw(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,nD)}}};async function iI(s,e,t){let{mode:r}=t,n=()=>t.signal?.aborted===!0,o=t.splitting??la(),i=e.objects.reduce((f,m)=>f+m.count,0),a=[],d=0,c=[],l=f=>{let m=a.find(y=>y.objectApiName===f);if(!m){let y=e.objects.find(R=>R.objectApiName===f);m=new hc(f,y?.count??0),a.push(m)}return m},u=async(f,m)=>{await fa(s,c,{note:(R,k,w,O)=>l(R).note(w?ga(R,k,O,c):k)});let y=a.map(R=>R.result(o,f));if(f)for(let{objectApiName:R,count:k}of e.objects)y.some(w=>w.objectApiName===R)||y.push({...new hc(R,k).result(o,!1),...k>0?{notReached:k}:{}});return{hard:r==="hard",objects:y,cancelled:f,...m!==void 0?{hardRefused:m}:{}}},p=(f,m)=>hw(s,f.objectApiName,m,{mode:r,stopped:n,splitting:o,...t.signal?{signal:t.signal}:{},...t.wait?{wait:t.wait}:{},settle:(y,R)=>{let k=f.deleted+f.gone+f.refused.size+f.refusedUnkept;f.settle(y,R),t.onSettled?.(f.objectApiName,y,R),d+=f.deleted+f.gone+f.refused.size+f.refusedUnkept-k,t.onProgress?.(d,i,f.objectApiName)}});if(r==="hard"&&s.bulkHardDestroy===void 0)return u(!0,uw);if(t.toDraft!==!1){let f=await pa(s,e.objects,e,()=>!0,n,async()=>new Set);if(c=f.drafted,f.cancelled)return u(!0)}for(let{objectApiName:f,count:m}of e.objects){if(n())return u(!0);let y=l(f),R=xs(s,f,m,r),k=[],w=async()=>{let O=k;return k=[],p(y,O)};for await(let O of e.pages(f)){if(n())return u(!0);if(k.push(...O),R&&k.length<$s)continue;let P=await w();if(P.stopped)return u(!0,P.hardRefused)}if(k.length>0){if(n())return u(!0);let O=await w();if(O.stopped)return u(!0,O.hardRefused)}}let g;if(await mw(a,{stopped:n,idsOf:(f,m)=>m===0?f.toSendAgain():f.heldByDependents(),send:async(f,m)=>{let y=await p(f,[...m]);return g=y.hardRefused,y.stopped},deleted:f=>f.deleted}))return u(!0,g);for(let f of a){if(n())return u(!0);let{gone:m,unchecked:y,failure:R}=await yw([...f.refused.keys()],k=>wn(s,f.objectApiName,[],k),()=>!0);for(let k of m)f.refused.delete(k),f.gone++;y.length>0&&f.note(`Not checked: ${y.length} refused record(s) could not be read back once the rest had gone, to tell whether a parent deleted after them took them along`+(R?` \u2014 ${R}`:"."))}return u(!1)}function sD(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 iD(s){return/CreatedDate/.test(I(s))}function rg(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 aD(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 dD(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 aI(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 Aa,d=new Map;if(s.resumed){for await(let M of e.lines())if(M.kind==="settled"){for(let L of[...M.deleted,...M.gone])a.add(L);d.set(M.objectApiName,(d.get(M.objectApiName)??0)+M.deleted.length+M.gone.length)}}let c=new AbortController,l=s.signal?AbortSignal.any([s.signal,c.signal]):c.signal,u=()=>l.aborted,p,g=!1,h=sD(r.readAt),f=new Map(r.passes.map(M=>[M.objectApiName,M])),m=M=>f.get(M)?.rows??to(M),y=new Map,R=new Map,k=()=>r.passes.reduce((M,L)=>M+Math.max(0,(R.get(L.objectApiName)??L.sent??L.records??0)-(d.get(L.objectApiName)??0)),0),w=async(M,L)=>{let ee=async Q=>{let B=await pb(t.ids,M,[{objectApiName:L.objectApiName,...Q!==void 0?{filter:Q}:{}}],{signal:l});return B.stopped?void 0:B.spool};try{let Q=await ee(rg([L.filter,L.own,h]));return Q?{spool:Q,sinceRead:!0}:void 0}catch(Q){if(!iD(Q))throw Q;i.push(`${L.objectApiName} has no CreatedDate: its records were read whole, those made after the preview among them.`);let B=await ee(rg([L.filter,L.own]));return B?{spool:B,sinceRead:!1}:void 0}},O=M=>{let L=y.get(M);if(L)return L;let ee=(async()=>{let Q=r.passes.findIndex(he=>he.objectApiName===M),B=e.idsDirOf(Q,M),V=o.spooled.get(M);if(s.resumed&&V)return R.set(M,V.count),{spool:await Ta.open(B,Pa),count:V.count,sinceRead:V.sinceRead};if(u())return;let we=m(M),ie=await w(B,{objectApiName:M,...we!==void 0?{own:we}:{}});if(!ie)return;let re=ie.spool.count,Ae=f.get(M)?.records;if(Ae!==void 0&&re>Ae){p={code:"ORG_CHANGED",message:`${M} now holds ${re.toLocaleString("en-US")} records to delete, where the preview counted ${Ae.toLocaleString("en-US")}: the org changed beyond what was confirmed, and the emptying stopped before deleting any of them. Preview it again, then resume or undo it.`},c.abort();return}return await e.spooled({objectApiName:M,place:Q,count:re,sinceRead:ie.sinceRead}),R.set(M,re),{spool:ie.spool,count:re,sinceRead:ie.sinceRead}})();return y.set(M,ee),ee},P={objects:r.passes.map(M=>({objectApiName:M.objectApiName,count:M.sent??M.records??0})),pages:M=>({async*[Symbol.asyncIterator](){let L=await O(M);if(L)for await(let ee of L.spool.pages(M)){let Q=a.size>0?ee.filter(B=>!a.has(B)):ee;Q.length>0&&(yield Q)}}})},b=Promise.resolve(),v,C=(M,L,ee)=>{let Q=[],B=[];L.forEach((V,we)=>{let ie=ee[we]?.kind;ie==="deleted"?Q.push(V):ie==="gone"&&B.push(V)}),Q.length>0&&(g=!0),Q.length+B.length!==0&&(b=b.then(async()=>{if(v===void 0)try{await e.settled(M,Q,B)}catch(V){v=I(V),c.abort()}}))},S=[];for(let[M,L]of r.toDraftAlong.entries()){if(L.condition===void 0||u())continue;let ee=e.idsDirOf(r.passes.length+M,L.objectApiName),Q=await w(ee,{objectApiName:L.objectApiName,filter:L.condition});if(!Q)break;let{drafted:B}=await pa(t.deletion,[{objectApiName:L.objectApiName}],Q.spool,()=>!0,u,async()=>new Set);S.push(...B)}let A=await iI(t.deletion,P,{mode:r.deleteMode,signal:l,...s.splitting?{splitting:s.splitting}:{},...s.wait?{wait:s.wait}:{},onSettled:C,onProgress:(M,L,ee)=>{let Q=Math.max(M,k());s.onProgress?.({percentage:Q>0?Math.min(99,Math.round(M/Q*100)):99,step:`${ee}: ${M.toLocaleString("en-US")} of about ${Q.toLocaleString("en-US")} settled`})}}).finally(async()=>{await b,await fa(t.deletion,S,{note:(M,L,ee,Q)=>i.push(ga(M,L,Q,S))})});v!==void 0&&i.push(`The journal of this emptying could not be written (${v}): it stopped there, so that its Undo misses nothing it deleted.`);let D=new Map;for(let[M,L]of y)D.set(M,await L.catch(()=>{}));let z=A.objects.map(M=>aD(M,D.get(M.objectApiName),f.get(M.objectApiName)?.records,A.cancelled));if(!A.cancelled)for(let M of z){if(!D.get(M.objectApiName)?.sinceRead)continue;let ee=m(M.objectApiName),Q=h.replace("CreatedDate <","CreatedDate >=");try{let B=await t.deletion.query(`SELECT COUNT() FROM ${qe(M.objectApiName)} WHERE ${rg([ee,Q])}`);B.totalSize>0&&(M.madeSince=B.totalSize)}catch(B){i.push(`Whether ${M.objectApiName} records were made after the preview could not be read: `+I(B))}}let U=A.cancelled&&p===void 0&&v===void 0,Y=p!==void 0||v!==void 0?g?"partial":"failure":dD(z,U,A.hardRefused,s.resumed&&o.deletedAny),H=z.reduce((M,L)=>M+L.refused,0);return s.resumed&&Y==="partial"&&!g&&H>0&&i.push(`The org refused again the ${H.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:A.hard,passes:z,...A.hardRefused!==void 0?{hardRefused:A.hardRefused}:{},...p!==void 0?{changed:p}:{},deletedAny:g,notes:i}}var cD=/Entity is not in the recycle bin/,lD=/INSUFFICIENT_ACCESS/,uD=5,dI=5e4;function mc(s){return s.slice(0,15)}function ng(s){let e=new Set;for(let t of s){let r=t?.Id;typeof r=="string"&&e.add(mc(r))}return e}function pD(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 gD(s){return{objectApiName:s,planned:0,undeleted:0,alreadyBack:0,notInBin:0,othersDeletion:0,refused:0,reasons:[]}}function fi(s,e){s.reasons.length<uD&&!s.reasons.includes(e)&&s.reasons.push(e)}async function*fD(s,e,t){let r=t?new Aa: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 Ta.open(s.idsDirOf(t.place,e),Pa);for await(let o of n.pages(e)){let i=o.filter(a=>!r.has(a));i.length>0&&(yield i)}}async function cI(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 lI(s,e){let t=s.spooledIn.get(e);return t!==void 0&&s.unendedAttempt!==void 0&&t.attempt===s.unendedAttempt?t:void 0}function hD(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 uI(s){let e=await cI(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/Ut)*zp);let o=lI(e,r);o&&(n+=o.count,t+=Math.ceil(o.count/Ut)*zp);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)/Ut)}return t}async function pI(s){let{journal:e,org:t}=s,r=e.head,n=[],o=()=>s.signal?.aborted===!0,i=await cI(e),a=[],d=new Map,c=!1,l=[...r.passes].reverse();for(let[f,{objectApiName:m}]of l.entries()){let y=gD(m);a.push(y);let R=qe(m),k=lI(i,m);for await(let w of fD(e,m,k)){y.planned+=w.length;for(let O=0;O<w.length;O+=Ut){let P=w.slice(O,O+Ut);if(c||o()){c=!0,y.notReached=(y.notReached??0)+P.length;continue}let[b]=Ps(P,Ut),v,C;try{v=ng((await t.queryDeleted(`SELECT Id FROM ${R} WHERE Id IN (${b}) AND IsDeleted = true`)).records),C=ng((await t.query(`SELECT Id FROM ${R} WHERE Id IN (${b})`)).records)}catch(D){y.refused+=P.length,fi(y,`The recycle bin could not be read: ${I(D)}`);continue}let S=P.filter(D=>v.has(mc(D)));for(let D of P)v.has(mc(D))||(C.has(mc(D))?y.alreadyBack++:(y.notInBin++,fi(y,"No longer in the recycle bin, nor in the org: emptied from the bin, or pushed out of it.")));if(S.length===0)continue;let A;try{let D=await s.undelete(S),z=Array.isArray(D)?D:[D];A=S.map((U,Y)=>z[Y]??{success:!1})}catch(D){let z=I(D);A=S.map(()=>({success:!1,errors:[z]}))}A.forEach((D,z)=>{if(D.success===!0){y.undeleted++;return}let U=pD(D);if(cD.test(U)){y.notInBin++;let Y=d.get(m)??[];Y.length<dI&&Y.push(S[z]),d.set(m,Y),fi(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 lD.test(U)?(y.othersDeletion++,fi(y,`Deleted by another user than the one bringing it back: only Modify All Data brings back another's deletions (${U})`)):(y.refused++,fi(y,U))})}s.onProgress?.({percentage:Math.round((f+1)/Math.max(1,l.length)*100),step:`${m}: ${y.undeleted.toLocaleString("en-US")} brought back`})}}if(!c)for(let f of a){let m=d.get(f.objectApiName)??[];if(m.length===0)continue;f.notInBin>m.length&&n.push(`${f.objectApiName}: past ${dI.toLocaleString("en-US")} records answered not in the recycle bin, whether a parent brought back later took them back was not read: they are counted as not back.`);let y=qe(f.objectApiName);try{let R=0;for(let w of Ps(m,Ut)){let O=await t.query(`SELECT Id FROM ${y} WHERE Id IN (${w})`);R+=ng(O.records).size}let k=Math.min(R,f.notInBin);f.notInBin-=k,f.alreadyBack+=k}catch(R){n.push(`Whether the ${f.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 u=i.wentThrough?hD(e):[],p=a.reduce((f,m)=>f+m.undeleted+m.alreadyBack,0),g=a.reduce((f,m)=>f+m.notInBin+m.othersDeletion+m.refused+(m.notReached??0),0)+u.length;return{status:c?"cancelled":g===0?"success":p>0?"partial":"failure",objects:a.filter(f=>f.planned>0),notes:n,...u.length>0?{previewedLost:u}:{}}}var ur="Nothing was deleted.";function wc(s){return{query:e=>s.query(e),queryMore:e=>s.queryMore(e)}}var og=G({Max:Te(),Remaining:Te()}).loose(),mD=G({DailyApiRequests:og.optional(),DailyBulkApiBatches:og.optional(),DataStorageMB:og.optional()}).loose();async function yD(s){try{let e=mD.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 fI(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 ag(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 wD(s){let e=s.passes.map(n=>({objectApiName:n.objectApiName,records:n.sent.records??0})).filter(n=>n.records>0),t=s.refusals.filter(n=>n.code==="activatedOrder"&&(n.records.records??0)>0).map(n=>({objectApiName:n.objectApiName,records:n.records.records??0})),r=[...e];for(let n of t)r.some(o=>o.objectApiName===n.objectApiName)||r.push(n);return{objects:r,steps:{delete:e.map(n=>n.objectApiName),...t.length>0?{setToDraft:t.map(n=>n.objectApiName)}:{}},written:[...e.map(n=>({...n,write:"delete"})),...t.map(n=>({...n,write:"update"}))]}}async function bD(s,e){let t=[];for(let r of e)try{let n=Ca.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. ${ur}`}}function Yo(s,e={}){let[t,...r]=s;return{ran:!1,refusal:t,...r.length>0?{alsoRefused:r}:{},...e}}async function sg(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 Or)return;throw o}let n=await r.state();return n.open?{runId:t.runId,startedAt:n.head.startedAt,journal:r}:void 0}function mI(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. ${ur}`}}function RD(s){return s.reason==="notRestorable"?`${s.objectApiName}, which Salesforce does not bring back`:`${s.objectApiName} before ${s.parent??"their parent"}`}function yI(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 SD(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=yI(s),r=`${t.atLeast?"at least ":""}${t.records.toLocaleString("en-US")}`,n=[...new Set(e.map(RD))],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. "+ur}}function vD(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. ${ur}`}),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. ${ur}`}),t}function yc(s){return s.records}function kD(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=yc(o.records);if(!i){(a===void 0||a>0)&&t.push(`${o.objectApiName} is now emptied too`);continue}a===void 0&&yc(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=yc(o.records),d=i?yc(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 preview counted ${d.toLocaleString("en-US")}`)}if(e.deleteMode==="recycle"){let o=c=>yI(c).records,i=c=>new Set(c.undoLost.map(l=>`${l.objectApiName}.${l.field??""}.${l.reason}`)),a=i(s);([...i(e)].filter(c=>!a.has(c)).length>0||o(e)>o(s))&&t.push("more records would go beyond what Undo brings back")}return t}function gI(s,e){return{code:"ORG_CHANGED",message:`${s} changed since the preview, beyond what was confirmed: ${e.slice(0,5).join("; ")}${e.length>5?"; \u2026":""}. Preview the emptying again. ${ur}`}}function ig(s,e,t){let r=t.automation?qr(t.automation,t.mutePlan,Br(t.steps)):{firing:[]};return{module:"empty",written:ag(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=wc(t),i=await Qn(o,{orgName:r,registered:s.registered,mode:e.request.mode});if(!i.allowed)return{previewed:!1,refusal:i.refusal};let a=await SI(s,e.request,e.deleteMode),d=await Xr({act:"empty",target:r,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{},...RI(a.preview)}),c=await sg(s.store,i.org.id),l=e.checkpointFirst===!0&&s.checkpoints?await s.checkpoints.scope(ig(s,a.preview,d.answer),{operationId:s.operationId}):void 0,u=s.requestsSent!==void 0?s.requestsSent()-n:void 0,p=bI(a,u,2,Vr(d.mute?.plan)),g={previewId:OD(s.now?.()??new Date),readAt:p.readAt,orgName:r,tier:i.tier,preview:p.preview,request:e.request,organizationId:i.org.id,access:p.access,hardDelete:{permitted:p.permissions.hardDelete,...p.permissions.unread!==void 0?{unread:p.permissions.unread}:{}},peopleActive:ID(p.people),...l?{checkpoint:l}:{},...c?{openRun:{runId:c.runId,startedAt:c.startedAt}}:{}},h=await kI(s,i.org.id,p,{deleteMode:e.deleteMode,acceptNoUndo:e.acceptNoUndo===!0,...e.acceptPeopleActive===!0?{peopleAccepted:!0}:{},automation:d.answer,...l?{checkpoint:l}:{},...c?{open:c.runId}:{}});return{previewed:!0,kept:g,automation:d.answer,refusals:h,...u!==void 0?{requestsSent:u}:{}}}function bI(s,e,t,r){let n=e??s.preview.cost.requests.reads;return{...s,preview:{...s.preview,cost:HO(s.preview.cost,n,t,r)}}}function OD(s){return Vu(s).replace(/^em-/,"ep-")}function RI(s){let e=wD(s);return{objects:e.objects,writes:{steps:e.steps,written:e.written}}}async function SI(s,e,t){let{org:r}=s,n=wc(r),o=await r.serverTime(),i=G({sobjects:Re(Yi)}).loose().parse(await r.describeGlobal()).sobjects,a=await r.toolingObjects(),d=await yD(r),c=await sI({global:i,tooling:a,request:e,deleteMode:t,apiBudget:d.apiBudget,...d.bulkBatches?{bulkBatches:d.bulkBatches}:{},...d.dataStorageMB!==void 0?{dataStorageMB:d.dataStorageMB}:{},stopped:()=>s.signal?.aborted===!0},r),l=await qs(n),u=ag(c),p=new Set(i.filter(R=>R.customSetting===!0).map(R=>R.name)),g=await PO({permissions:l,objects:u,customSettings:u.filter(R=>p.has(R)),grants:async()=>Sb(n,()=>r.userId()),describe:R=>bD(r,R)}),h=await r.userId(),f=new Date(Date.parse(o)-Uu).toISOString(),m=await Bu(r,u,[h,...await fI(r)],f),y=s.voice==="page"?await LS(r,m):m;return{readAt:o,preview:c,permissions:l,access:g,people:y}}function ID(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(mI(s.orgName,r.open)),t.preview.stopped&&n.push({code:"PREVIEW_STOPPED",message:`The preview was stopped before every count was in: preview again. ${MS}`}),r.deleteMode==="hard"&&!t.permissions.hardDelete&&n.push(Hu(t.permissions));let i=qu(s.orgName,t.people,{...r.peopleAccepted!==void 0?{accepted:r.peopleAccepted}:{},voice:vI(s)});i&&n.push(i);let a=r.acceptNoUndo?void 0:SD(t.preview);a&&n.push(a),n.push(...vD(t.preview,s.orgName)),r.checkpoint?.refusal&&n.push({...r.checkpoint.refusal});let d=kn(r.automation);return d&&n.push({code:d.code,message:d.message},...d.alsoRefused),n}function AD(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 preview would delete any more: nothing was sent."],startedAt:e,finishedAt:e}}function TD(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 ED(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 PD(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 CD(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 OI(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 a preview it was confirmed on, or takes up a run.");let o=s.requestsSent?.()??0,i=wc(t),a=await Qn(i,{orgName:r,registered:s.registered,mode:e.confirmed?.request.mode??"objects"});if(!a.allowed)return{ran:!1,refusal:a.refusal};let d=a.org.id,c,l=await sg(s.store,d);if(e.resumeRunId!==void 0){if(!l||l.runId!==e.resumeRunId)return{ran:!1,refusal:{code:"RUN_GONE",message:`${e.resumeRunId} is not the last emptying of ${r} stopped part way: there is nothing of it to take up. ${ur}`}};if(c=l.journal,c.head.mode==="org"&&a.tier==="staging"){let S=await Qn(i,{orgName:r,registered:s.registered,mode:"org"});if(!S.allowed)return{ran:!1,refusal:S.refusal}}}else if(e.confirmed&&e.confirmed.organizationId.slice(0,15)!==d.slice(0,15))return{ran:!1,refusal:gI(r,["it is another org than the one the preview read \u2014 a refreshed sandbox is a new org"])};let u=e.confirmed,p=c?c.head.deleteMode:u?.preview.deleteMode??"recycle",g=[],h,f,m,y;if(u){h=await SI(s,u.request,p);let S=[...kD(u.preview,h.preview),...CO(u.access,h.access).map(A=>`the user is no longer proven to see every record of ${A}`)];if(S.length>0&&g.push(gI(r,S)),h.preview.total.records===0&&h.preview.total.uncounted.length===0&&S.length===0)return{ran:!0,result:AD(n())};f=await Xr({act:"empty",target:r,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{},...RI(h.preview)}),e.checkpointFirst===!0&&(m=s.checkpoints?await s.checkpoints.scope(ig(s,h.preview,f.answer),{operationId:s.operationId}):void 0,m||g.push({code:"CHECKPOINT_REFUSED",message:`Checkpoints cannot be taken from here: run without Checkpoint first. ${ur}`})),h=bI(h,s.requestsSent!==void 0?s.requestsSent()-o:void 0,1,Vr(f.mute?.plan)),g.push(...await kI(s,d,h,{deleteMode:p,acceptNoUndo:e.acceptNoUndo===!0,...e.acceptPeopleActive===!0?{peopleAccepted:(u.peopleActive.who??[]).map(A=>A.userId)}:{},automation:f.answer,...m?{checkpoint:m}:{},...l?{open:l.runId}:{}}))}else{let S=c.head,A=await qs(i);p==="hard"&&!A.hardDelete&&g.push(Hu(A));let D=await s.runWriting?.(d);D!==void 0&&g.push({code:"RUN_WRITING",message:D});let z=S.passes.map(Q=>Q.objectApiName),U=await t.userId(),Y=await t.serverTime(),H=await Bu(t,z,[U,...await fI(t)],new Date(Date.parse(Y)-Uu).toISOString()),M=qu(r,H,{...e.acceptPeopleActive===!0?{accepted:!0}:{},voice:vI(s)});M&&g.push(M);let L=S.passes.map(Q=>({objectApiName:Q.objectApiName,records:Q.sent??Q.records??0})).filter(Q=>Q.records>0);f=await Xr({act:"empty",target:r,objects:L,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{}});let ee=kn(f.answer);ee&&g.push({code:ee.code,message:ee.message},...ee.alsoRefused),y=FO(p,await PD(c),s.requestsSent!==void 0?s.requestsSent()-o:0,Vr(f.mute?.plan))}if(g.length>0)return Yo(g);let R=u&&h?h.preview:void 0,k=R?R.total.records:c.head.passes.reduce((S,A)=>S+(A.records??0),0),w=R?ag(R):c.head.passes.map(S=>S.objectApiName),O=await s.askGuard({operation:p==="hard"?"hardDelete":"delete",objectNames:w,recordCount:k});if(O.decision==="refused"||O.decision==="declined")return Yo([{code:"GUARD",message:O.decision==="refused"?`Production Guard refused the emptying: ${O.reason??"no reason given"}. ${ur}`:`The emptying was declined at Production Guard's confirmation. ${ur}`}],{guard:O.decision});let P=O.decision,b;if(m&&s.checkpoints&&R){let S=await s.checkpoints.take(ig(s,R,f.answer),{operationId:s.operationId},{planned:m,...s.signal?{signal:s.signal}:{},onProgress:({percentage:A})=>s.onProgress?.(Math.round(A/10),`Taking the checkpoint first (${Math.round(A)}%)`)});if(!S.taken)return Yo(["stopped"in S?{code:"CANCELLED",message:`The emptying was stopped while its checkpoint was taken. ${ur}`}:{code:S.refusal.code,message:S.refusal.message}],{guard:P});b=S.checkpoint}let v=async S=>{if(!b||b.state!=="taken"||!s.checkpoints)return b;try{return await s.checkpoints.settle(b,S)}catch{return b}},C=s.lock(d);if("busy"in C)return await v(!1),Yo([hI(r,C.busy)],{guard:P});try{let S=await sg(s.store,d);if(!c&&S)return await v(!1),Yo([mI(r,S.runId)],{guard:P});let A=await Xn(f,s.operationId,e.accord.acceptEmails===!0,s.voice);if("refused"in A)return await v(!1),Yo([{code:A.refused.code,message:A.refused.message}],{guard:P});let D=A.held,z=n(),U=c??await s.store.begin(d,{runId:Vu(z),orgName:r,startedAt:z.toISOString(),readAt:u.readAt,previewId:u.previewId,mode:R.mode,deleteMode:p,request:TD(u.request),passes:R.passes.map(re=>({objectApiName:re.objectApiName,...re.records.records!==void 0?{records:re.records.records}:{},...re.sent.records!==void 0?{sent:re.sent.records}:{},...re.rows!==void 0?{rows:re.rows}:{}})),toDraftAlong:R.toDraftAlong,beforeParent:R.beforeParent,...p==="recycle"?{undoLost:ED(R)}:{}}),Y=R&&R.cost.api.verdict!=="unread"?ua(R.cost.api).splitAllowance:void 0,H,M,L=[];try{H=await aI({org:{deletion:t,ids:t},journal:U,resumed:c!==void 0,...s.signal?{signal:s.signal}:{},splitting:la(Y),now:n,onProgress:({percentage:re,step:Ae})=>s.onProgress?.(re,Ae)})}catch(re){throw await U.ended("failure",[],n()).catch(()=>{}),re}finally{let re=t.lostJobs?.()??[];if(re.length>0&&t.stillRunning){let Ae=await t.stillRunning(re);Ae.length>0&&L.push(`${Ae.length} Bulk API job(s) the org was still running after ten minutes: the mute was given back all the same, and what they delete from now on runs the org's automation.`)}D&&(M=await D.release(),L.push(...Vt(M,r).map(Ae=>Ae.trim())))}let ee=H.passes,Q=n();await U.ended(H.status,ee,Q,H.hardRefused);let B=await v(H.deletedAny),V=[];if(H.status==="success"||H.status==="partial")for(let re of await s.store.runsOf(d))re.runId>=U.head.runId||(await s.store.remove(d,re.runId),V.push(re.runId));let we=await U.state();return{ran:!0,result:{runId:U.head.runId,status:H.status,hard:H.hard,passes:ee,totals:CD(ee),...H.hardRefused!==void 0?{hardRefused:H.hardRefused}:{},undo:H.hard?{offered:!1,why:"hard"}:we.deletedAny?{offered:!0}:{offered:!1,why:"nothingDeleted"},...c?{resumed:!0}:{},notes:[...H.notes,...H.changed?[H.changed.message]:[],...L],...M?{mutedAutomation:M}:{},...B?{checkpoint:B}:{},...V.length>0?{removedRuns:V}:{},...s.requestsSent!==void 0?{requestsSent:s.requestsSent()-o}:{},...y!==void 0?{requestsEstimate:y}:{},startedAt:z.toISOString(),finishedAt:Q.toISOString()},guard:P}}finally{C.lock.release()}}async function II(s,e){let{org:t,orgName:r}=s,n=s.now??(()=>new Date),o=s.requestsSent?.()??0,i=wc(t),a=await Qn(i,{orgName:r,registered:s.registered,mode:"objects"});if(!a.allowed)return{ran:!1,refusal:a.refusal};let d=a.org.id,c=(w,O)=>({ran:!1,refusal:{code:w,message:`${O} Nothing was brought back.`}}),l;try{l=await s.store.open(d,e.runId)}catch(w){if(w instanceof Or)return c("RUN_GONE",w.message);throw w}if((await s.store.lastOf(d))?.runId!==e.runId)return c("NOT_LAST_RUN",`${e.runId} is not the last emptying of ${r}: Undo reaches the last one alone, as what a later emptying deleted may hang from what this one did.`);let p=await l.state();if(l.head.deleteMode==="hard")return c("UNDO_UNAVAILABLE",`${e.runId} deleted for good: Salesforce brings back nothing a hard delete took, what went along included.`);if(p.undone)return c("UNDO_UNAVAILABLE",`${e.runId} was undone already.`);let g=await s.runWriting?.(d),h=[];g!==void 0&&h.push({code:"RUN_WRITING",message:g});let f=l.head.passes.map(w=>({objectApiName:w.objectApiName,records:w.records??0})),m=await Xr({act:"emptyUndo",target:r,objects:f,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{},writes:{steps:{bringBack:f.map(w=>w.objectApiName)},written:[]}}),y=kn(m.answer);if(y&&h.push({code:y.code,message:y.message},...y.alsoRefused),h.length>0){let[w,...O]=h;return{ran:!1,refusal:w,...O.length>0?{alsoRefused:O}:{}}}let R=_O(await uI(l),s.requestsSent!==void 0?s.requestsSent()-o:0,Vr(m.mute?.plan)),k=s.lock(d);if("busy"in k)return{ran:!1,refusal:hI(r,k.busy)};try{let w=await Xn(m,s.operationId,e.accord.acceptEmails===!0,s.voice);if("refused"in w)return{ran:!1,refusal:{code:w.refused.code,message:w.refused.message}};let O,P;try{P=await pI({org:t,undelete:v=>t.undelete(v),journal:l,...s.signal?{signal:s.signal}:{},onProgress:({percentage:v,step:C})=>s.onProgress?.(v,C)})}finally{w.held&&(O=await w.held.release())}let b=n();return P.status!=="cancelled"&&await l.undone(P.status,b),{ran:!0,result:{runId:e.runId,status:P.status,objects:P.objects,notes:[...P.notes,...O?Vt(O,r).map(v=>v.trim()):[]],...O?{mutedAutomation:O}:{},...s.requestsSent!==void 0?{requestsSent:s.requestsSent()-o}:{},requestsEstimate:R,...P.previewedLost?{previewedLost:P.previewedLost}:{},finishedAt:b.toISOString()}}}finally{k.lock.release()}}function $D(s){let e=zn(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=sw(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 AI(s,e,t){let r=Gi(s),n=lw(s,t),o=$D(s),i=[],a=new CR(async(l,u)=>(await zn(s).bulk2.job("ingest",{id:u}).check()).state),d=l=>async(u,p,g)=>{try{return await cw(o.bulk,u,p,g,l)}catch(h){let f=o.last();throw f.closed&&i.push({orgId:e,objectApiName:u,...f.jobId?{jobId:f.jobId}:{}}),h}},c=l=>({totalSize:l.totalSize,done:l.done,records:l.records,...l.nextRecordsUrl?{nextRecordsUrl:l.nextRecordsUrl}:{}});return{describe:l=>s.describe(l),count:async l=>(await s.query(l)).totalSize,countAll:async l=>(await s.query(l,{scanAll:!0})).totalSize,readIds:async(l,u)=>{let p=await s.query(l,{scanAll:u});return{totalSize:p.totalSize,ids:p.records.flatMap(g=>typeof g.Id=="string"?[g.Id]:[])}},query:async(l,u)=>c(await s.query(l,{scanAll:u?.scanAll===!0})),queryMore:async l=>c(await s.queryMore(l)),queryDeleted:l=>n.queryDeleted(l),describeGlobal:()=>s.describeGlobal(),toolingObjects:async()=>{try{return(await s.tooling.describeGlobal()).sobjects.map(l=>l.name)}catch{return[]}},serverTime:async()=>(await s.soap.getServerTimestamp()).timestamp,userId:async()=>(await s.soap.getUserInfo()).userId,limits:()=>s.request({method:"GET",url:"/limits"}),update:(l,u)=>n.update(l,u),destroy:(l,u)=>n.destroy(l,u),bulkDestroy:d("delete"),bulkHardDestroy:d("hardDelete"),undelete:l=>s.soap.undelete(l),lostJobs:()=>[...i],stillRunning:l=>a.stillRunning(l),requestsSent:r}}import{readdir as xD,readFile as DD,rm as TI,stat as EI,writeFile as ND}from"node:fs/promises";import{join as bc}from"node:path";var CI=/^ep-\d{8}-\d{6}-[a-z0-9]{4}$/,jD=50;function Rc(s){return CI.test(s)}var PI=G({records:Te().optional(),unread:j().optional()}).loose(),MD=G({v:yt(1),orgId:j().min(1),kept:G({previewId:j().regex(CI),readAt:j(),orgName:j(),organizationId:j().min(15).max(18),request:G({mode:_e(["objects","org"])}).loose(),preview:G({mode:_e(["objects","org"]),deleteMode:_e(["recycle","hard"]),passes:Re(G({objectApiName:j(),records:PI}).loose()),along:Re(G({objectApiName:j(),records:PI}).loose()),undoLost:Re(G({objectApiName:j()}).loose()),total:G({records:Te()}).loose()}).loose(),access:G({kind:_e(["org","perObject"])}).loose(),peopleActive:G({people:Te(),who:Re(G({userId:j()}).loose()).optional()}).loose()}).loose()}),Sc=class{constructor(e,t=Oa){this.root=e;this.keepMs=t}root;keepMs;async keep(e,t,r=Date.now()){if(!Rc(t.previewId))throw new Error(`Not a preview's id: ${t.previewId}`);await Ia(this.root),await ND(bc(this.root,`${t.previewId}.json`),JSON.stringify({v:1,orgId:e,kept:t}),{mode:ka}),await this.sweep(r)}async read(e,t=Date.now()){if(!Rc(e))return;let r=bc(this.root,`${e}.json`);try{if((await EI(r)).mtimeMs+this.keepMs<=t)return;let n=MD.safeParse(JSON.parse(await DD(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){Rc(e)&&await TI(bc(this.root,`${e}.json`),{force:!0})}async sweep(e){let t;try{t=await xD(this.root)}catch{return}let r=t.filter(o=>o.endsWith(".json")&&Rc(o.slice(0,-5))).sort(),n=Math.max(0,r.length-jD);for(let[o,i]of r.entries()){let a=bc(this.root,i);try{(o<n||(await EI(a)).mtimeMs+this.keepMs<=e)&&await TI(a,{force:!0})}catch{}}}};var FD=6e4,_D=20,Qo="dataops",HD=new Set(["dataops:empty:scope","dataops:empty:preview","dataops:empty:run","dataops:empty:cancel","dataops:empty:undo"]),dn=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 UD(s){return s.passes.filter(e=>e.deleted+e.refused+(e.notReached??0)>0).map(e=>({...ft(e.objectApiName),deleted:e.deleted,failed:e.refused,...(e.notReached??0)>0?{notSent:e.notReached}:{}}))}function BD(s){return s.objects.filter(e=>e.undeleted+e.notInBin+e.othersDeletion+e.refused>0).map(e=>({...ft(e.objectApiName),created:e.undeleted,failed:e.notInBin+e.othersDeletion+e.refused,...(e.notReached??0)>0?{notSent:e.notReached}:{}}))}function qD(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 vc=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)=>AI(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(!HD.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-DIL62SUN.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=nb({root:tb()});if("refusal"in e)throw new dn({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 id(Xu()),previews:new Sc(LD(Xu(),"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=me(i,e),c=this.ownStores(),l=this.orgOf(a,e),u=[],p,g=()=>this.targetAutomation?Promise.resolve(this.targetAutomation):(p??=this.countingReader(m=>u.push(Gi(m))),p),h=Sa(r),f=this.runWriting?.(e,d,t);return{org:l,...l.requestsSent?{requestsSent:()=>(l.requestsSent?.()??0)+u.reduce((m,y)=>m+y(),0)}:{},orgId:e,orgName:d,username:i?.username??d,registered:i,store:c.journals,lock:c.lock,...f?{runWriting:f}:{},automation:Eo(a,async m=>{let y=await g();return new ge(FD).withTimeout("dataops automation",()=>y.read(e,m,{undeletes:!0}))},!1),muteLeases:this.muteLeases,...h?{voice:h}:{},...this.checkpoints?{checkpoints:this.checkpoints}:{},askGuard:async m=>{let y=this.deps.infraServices?.productionGuard;if(!y)return{decision:"refused",reason:Se.message};let{check:R,decision:k}=await Ze(y,{orgId:e,orgTier:Ce(i),operation:m.operation,objectName:m.objectNames.join(", "),recordCount:m.recordCount,module:Qo});return{decision:k,...k==="refused"?{reason:R.blockedReason??R.impactSummary}:{}}},operationId:t,tool:"panel",...n?{signal:n}:{},...o?{onProgress:o}:{}}}fail(e,t,r){if(t instanceof dn){E(this.deps,e.type,"dataops:error",e,t,{code:t.refusal.code,retryable:!1,...t.alsoRefused.length>0||t.mutedAutomation?{extraPayload:{...t.alsoRefused.length>0?{alsoRefused:[...t.alsoRefused]}:{},...t.mutedAutomation?{mutedAutomation:t.mutedAutomation}:{}}}:{}});return}E(this.deps,e.type,"dataops:error",e,t,{code:r})}respond(e,t,r){let n=T(this.deps,e,t,r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}async handleScope(e){let t=x(Am,e,"dataops:error",this.deps);if(t)try{let{orgId:r,...n}=t,o=await this.contextOf(r,e.id,{}),i={query:u=>o.org.query(u)},a=await Qn(i,{orgName:o.orgName,registered:o.registered,mode:n.mode});if(!a.allowed)throw new dn(a.refusal);let d=G({sobjects:Re(Yi)}).loose().parse(await o.org.describeGlobal()).sobjects,c=fc(d,await o.org.toolingObjects(),n),l=await qs(i);this.respond(e,"dataops:empty:scope:response",{mode:c.mode,objects:c.objects,leftOut:c.leftOut,candidates:c.worked,tier:a.tier,hardDelete:{permitted:l.hardDelete,...l.unread!==void 0?{unread:l.unread}:{}}})}catch(r){this.fail(e,r,"EMPTY_SCOPE_ERROR")}}previewStore(){return this.ownStores().previews}async keep(e,t){for(this.previews.set(t.previewId,{orgId:e,kept:t,at:Date.now()});this.previews.size>_D;){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<=Oa?r:await this.previewStore()?.read(t);return n?.orgId===e?n.kept:void 0}async letGo(e){this.previews.delete(e),await this.previewStore()?.remove(e).catch(()=>{})}async handlePreview(e){let t=x(Tm,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 dn(o.refusal);await this.keep(t.orgId,o.kept),this.respond(e,"dataops:empty:preview:response",{...qD(o.kept),automation:o.automation,refusals:o.refusals,...o.requestsSent!==void 0?{requestsSent:o.requestsSent}:{}})}catch(n){this.fail(e,n,"EMPTY_PREVIEW_ERROR")}finally{this.running.delete(e.id)}}handleCancel(e){let t=x(Pm,e,"dataops:error",this.deps);if(!t)return;let r=this.running.get(t.operationId);r&&(this.deps.infraServices?.backgroundRegistry?.abort(t.operationId),r.abort()),this.respond(e,"dataops:empty:cancel:response",{operationId:t.operationId,cancelled:r!==void 0})}async writeAct(e,t,r,n,o,i,a){let d=e.id,c=this.deps.infraServices?.backgroundRegistry,l=new AbortController;this.running.set(d,l),this.writing.set(d,t);let u=()=>{},p=new Promise((f,m)=>{u=y=>y===void 0?f():m(y)});p.catch(()=>{}),ze(this.deps,d,Qo,r),c?.register(d,Qo,r,p,l);let g=sr(this.liveTracker,d,Qo,r),h=(f,m)=>{Le(this.deps,d,f,0,0,m),l.signal.aborted||c?.updateProgress(d,f),g.progress(f,0,0,m)};try{let f=await this.contextOf(t,d,a,l.signal,h),m=await n(f);if(!m.ran)throw o("stopped",{code:m.refusal.code,...m.guard?{guard:m.guard}:{}}),pe(this.deps,d,{status:"refused",code:m.refusal.code}),g.fail(m.refusal.message),u(new Error(m.refusal.message)),new dn(m.refusal,m.alsoRefused??[],m.mutedAutomation);let{result:y}=m;if(o(y.status,{result:y,...m.guard?{guard:m.guard}:{}}),await i(y),y.status==="cancelled")c?.abort(d),pe(this.deps,d,{aborted:!0}),g.cancel(),u();else if(y.status==="failure"){let R="Nothing the emptying set out to do went through: its result says why.";pe(this.deps,d,{status:y.status}),g.fail(R),u(new Error(R))}else pe(this.deps,d,{status:y.status}),y.status==="success"?g.complete():g.partial(),u()}catch(f){throw f instanceof dn||(o("failure",{}),pe(this.deps,d,{status:"failure"}),g.fail(f instanceof Error?f.message:String(f)),u(f)),f}finally{this.running.delete(d),this.writing.delete(d)}}async handleRun(e){let t=x(Em,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 dn({code:"PREVIEW_GONE",message:"The preview this emptying was confirmed on is no longer kept on this machine \u2014 a preview is kept a day: preview it 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=>OI(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:Qo,operationId:e.id,orgId:t.orgId,outcome:o,...i.guard?{guard:i.guard}:{},...i.code!==void 0?{code:i.code}:{},...i.result?{objects:UD(i.result)}:{},...i.result?.mutedAutomation?{muted:dt(i.result.mutedAutomation)}:{},...i.result?.checkpoint?.state==="taken"?{checkpointId:i.result.checkpoint.checkpointId}:{},details:n(i.result)}),async o=>{t.previewId!==void 0&&await this.letGo(t.previewId),this.respond(e,"dataops:empty:run:response",{operationId:e.id,result:o})},t)}catch(r){this.fail(e,r,"EMPTY_RUN_ERROR")}}async handleUndo(e){let t=x(Cm,e,"dataops:error",this.deps);if(t)try{await this.writeAct(e,t.orgId,`Undoing the emptying ${t.runId}`,r=>II(r,{runId:t.runId,accord:t}),(r,n)=>Z(this.deps,{action:"empty_undo",module:Qo,operationId:e.id,orgId:t.orgId,outcome:r,...n.code!==void 0?{code:n.code}:{},...n.result?{objects:BD(n.result)}:{},...n.result?.mutedAutomation?{muted:dt(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 KD}from"node:os";var $I=6e4,WD=2*6e4,zD=50,GD=2880*6e4,JD=60*6e4,VD=250,xI="pipeline-triggers",XD=G({cron:j().optional(),timezone:j().optional(),nextRunAt:Te().optional(),lastFiredAt:Te().optional(),lastOutcome:_e(["started","missed"]).optional()});function hi(s,e){return`pipeline-trigger:${s}:${e}`}var kc=class{constructor(e){this.deps=e;this.now=e.now??(()=>Date.now()),this.newId=e.newId??(()=>globalThis.crypto.randomUUID())}deps;engine=new HS;now;newId;timer;started=!1;firstLook=!0;looking;lookAgain=!1;lastPrune=0;soonest;busyMisses=new Map;refusedMisses=new Map;unscheduled=new Map;start(){this.started||(this.started=!0,this.firstLook=!0,this.deps.log("[pipeline-triggers] started"),this.look())}stop(){this.started&&(this.started=!1,clearTimeout(this.timer),this.timer=void 0,this.deps.log("[pipeline-triggers] stopped"))}reload(){return this.started?this.look():Promise.resolve()}async onSandboxRefresh(e){if(!this.started)return;let t=this.deps.org(e.orgId);for(let r of this.deps.pipelines())for(let n of this.triggersOf(r)){if(!this.engine.firesOnRefreshOf(n,e.orgId)||this.engine.idleReason(n,t)||!this.deps.claims.claim(`refresh:${r.id}:${n.id}:${e.key}`))continue;let o=this.now(),i=await this.problemsOf(r);if(i.length>0){this.refuseStart(r,n,"sandbox_refresh",o,i,{sandboxName:t?.name});continue}this.fire(r,n,"sandbox_refresh",o,t?.name)}}async statuses(){let e=[],t=this.now();for(let r of this.deps.pipelines()){let n=this.triggersOf(r),o;for(let i of n){let a=this.read(r.id,i.id),d=i.type,c={pipelineId:r.id,triggerId:i.id,type:d,armed:!1,...a.lastFiredAt!==void 0?{lastFiredAt:new Date(a.lastFiredAt).toISOString(),...a.lastOutcome?{lastOutcome:a.lastOutcome}:{}}:{},...d==="schedule"?{timezone:this.engine.timezoneOf(i)}:{}},l=this.engine.idleReason(i,this.orgOf(i),t);l||(o??=await this.problemsOf(r),o.length>0&&(l={idle:"cannotRun",detail:o.join(" ")})),!l&&!this.started&&(l={idle:"stopped"});let u;if(!l&&d==="schedule"){let p=this.planOf(i,a)??this.engine.nextRun(i,t);typeof p=="number"?u=p:l=p}e.push(l?{...c,idle:l.idle,...l.detail?{detail:l.detail}:{}}:{...c,armed:!0,...u!==void 0?{nextRunAt:new Date(u).toISOString()}:{}})}}return e}look(){return this.looking?(this.lookAgain=!0,this.looking):(this.looking=this.lookNow().catch(e=>{this.deps.log(`[pipeline-triggers] a look failed: ${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>=JD&&(this.lastPrune=e,this.deps.claims.prune(GD));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(hi(i.id,d.id));let c=this.engine.idleReason(d,this.orgOf(d),e);if(c||(a??=await this.problemsOf(i)),d.type!=="schedule")continue;let l=c?this.unplan(i,d):this.lookAt(i,d,e,t,a??[]);l!==void 0&&(o===void 0||l<o)&&(o=l)}this.sayWhyUnscheduled(i,a)}for(let i of[...this.unscheduled.keys()])n.has(i)||this.unscheduled.delete(i);this.soonest=o,this.forgetAllBut(r)}sayWhyUnscheduled(e,t){if(t===void 0)return;let r=this.unscheduled.get(e.id);if(t.length===0){if(r===void 0)return;this.unscheduled.delete(e.id),this.deps.log(`[pipeline-triggers] "${e.name}" can run again: its triggers start it`);return}let n=t.join(" ");r!==n&&(this.unscheduled.set(e.id,n),this.deps.log(`[pipeline-triggers] "${e.name}" is not scheduled: its triggers start nothing while a step cannot run. ${n}`))}lookAt(e,t,r,n,o){let i=this.read(e.id,t.id),a=this.planOf(t,i);if(a===void 0)return this.plan(e,t,i,r);if(a>r)return a;let d=this.engine.dueBetween(t,a,r,zD),c=[a,...d.times],l=c[c.length-1],u=!n&&r-l<=WD?l:void 0,p=u===void 0?c:c.slice(0,-1),g=this.plan(e,t,i,r),h=p.filter(f=>this.deps.claims.claim(this.dueKey(e,t,f)));if(h.length>0){let f={reason:n?"closed":"asleep",count:h.length,...h.length>1?{lastDueAt:new Date(h[h.length-1]).toISOString()}:{},...d.more?{atLeast:!0}:{}};this.recordMissed(e,"schedule",h[0],f),this.remember(e,t,{lastFiredAt:h[h.length-1],lastOutcome:"missed"}),this.deps.report({kind:"missed",pipelineName:e.name,triggeredBy:"schedule",dueAt:new Date(h[0]).toISOString(),missed:f,...g!==void 0?{nextRunAt:new Date(g).toISOString()}:{}})}return u!==void 0&&this.deps.claims.claim(this.dueKey(e,t,u))&&(o.length>0?this.refuseStart(e,t,"schedule",u,o,{...g!==void 0?{nextRunAt:new Date(g).toISOString()}:{}}):this.fire(e,t,"schedule",u)),g}refuseStart(e,t,r,n,o,i){let a=o.join(" "),d=hi(e.id,t.id),c=r==="schedule"?this.refusedMisses.get(d):void 0,l=c&&c.detail===a?{...c,count:c.count+1}:{runId:`missed-${this.newId()}`,detail:a,firstDueAt:n,count:1};r==="schedule"&&this.refusedMisses.set(d,l);let u={reason:"cannotRun",count:l.count,...l.count>1?{lastDueAt:new Date(n).toISOString()}:{},detail:a};this.recordMissed(e,r,l.firstDueAt,u,l.runId),this.remember(e,t,{lastFiredAt:n,lastOutcome:"missed"}),!(l.count>1)&&this.deps.report({kind:"missed",pipelineName:e.name,triggeredBy:r,dueAt:new Date(n).toISOString(),missed:u,...i})}dueKey(e,t,r){return`due:${e.id}:${t.id}:${r}`}fire(e,t,r,n,o){let i=hi(e.id,t.id);this.refusedMisses.delete(i);let a=this.deps.start(e,r);if(a.started){this.busyMisses.delete(i),this.remember(e,t,{lastFiredAt:n,lastOutcome:"started"}),this.deps.log(`[pipeline-triggers] started "${e.name}" (${r})`),a.run.then(u=>{u?.status==="failed"&&this.deps.report({kind:"failed",pipelineName:e.name,triggeredBy:r,error:u.error??"the run failed",...o?{sandboxName:o}:{}})},u=>{this.deps.report({kind:"failed",pipelineName:e.name,triggeredBy:r,error:I(u),...o?{sandboxName:o}:{}})});return}let d=this.busyMisses.get(i),c=d&&d.busySince===a.busy.startedAt?{...d,count:d.count+1,lastDueAt:n}:{runId:`missed-${this.newId()}`,busySince:a.busy.startedAt,firstDueAt:n,count:1,lastDueAt:n};this.busyMisses.set(i,c);let l={reason:"busy",count:c.count,busySince:c.busySince,...c.count>1?{lastDueAt:new Date(c.lastDueAt).toISOString()}:{}};this.recordMissed(e,r,c.firstDueAt,l,c.runId),this.remember(e,t,{lastFiredAt:n,lastOutcome:"missed"}),this.deps.log(`[pipeline-triggers] "${e.name}" not started (${r}): a run started at ${a.busy.startedAt} is going`),c.count===1&&this.deps.report({kind:"missed",pipelineName:e.name,triggeredBy:r,dueAt:new Date(n).toISOString(),missed:l,...o?{sandboxName:o}:{}})}recordMissed(e,t,r,n,o=`missed-${this.newId()}`){this.deps.record({runId:o,pipelineId:e.id,pipelineName:e.name,status:"missed",triggeredBy:t,startTime:new Date(r).toISOString(),duration:0,stepCount:0,errorCount:0,missed:n})}planOf(e,t){return t.cron===(e.config.cron??"").trim()&&t.timezone===this.engine.timezoneOf(e)?t.nextRunAt:void 0}plan(e,t,r,n){let o=this.engine.nextRun(t,n),i=typeof o=="number"?o:void 0;return this.write(e.id,t.id,{...r,cron:(t.config.cron??"").trim(),timezone:this.engine.timezoneOf(t),nextRunAt:i}),i}unplan(e,t){let r=this.read(e.id,t.id);(r.nextRunAt!==void 0||r.cron!==void 0)&&this.write(e.id,t.id,{...r.lastFiredAt!==void 0?{lastFiredAt:r.lastFiredAt}:{},...r.lastOutcome?{lastOutcome:r.lastOutcome}:{}})}remember(e,t,r){this.write(e.id,t.id,{...this.read(e.id,t.id),...r})}forgetAllBut(e){for(let t of Object.keys(this.deps.store.getByCategory(xI)))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?$I:this.soonest-this.now(),t=Math.min(Math.max(e,VD),$I);this.timer=setTimeout(()=>{this.look()},t),this.timer.unref?.()}triggersOf(e){return(Array.isArray(e.triggers)?e.triggers:[]).flatMap(r=>{let n=_S.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=XD.safeParse(this.deps.store.get(hi(e,t)));return r.success?r.data:{}}write(e,t,r){this.deps.store.set(hi(e,t),r,xI)}};function Zo(){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 JG=65*6e4;var DI=[{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 dg(s,e){return`${s}\0${e}`}var Oc=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=dg(e.operationId,e.stepId),o={...e,expiresAt:new Date(r().getTime()+e.timeoutMs).toISOString()};return new Promise(i=>{let a=l=>{this.waiting.get(n)?.settle===a&&(this.waiting.delete(n),clearTimeout(c),t?.removeEventListener("abort",d),i(l))},d=()=>a({decision:"cancelled",at:r().toISOString()}),c=setTimeout(()=>a({decision:"timedOut",at:r().toISOString()}),e.timeoutMs);if(this.waiting.set(n,{question:o,settle:a}),t?.aborted){d();return}t?.addEventListener("abort",d,{once:!0}),this.deps.announce?.(o),this.deps.ask?.(o).then(l=>{if(l===void 0)return;let u=typeof l=="string"?{decision:l,via:void 0}:l,p=u.decision==="approve"?"approved":"rejected",g=u.via??"notification";this.answer(e.operationId,e.stepId,p,g)||this.deps.tooLate?.(o)},()=>{})})}answer(e,t,r,n){let o=this.waiting.get(dg(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(dg(e,t))}};var NI=50,FI={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 YD(s,e){return`Pipeline "${s}" is already running: the run started ${FI[e.triggeredBy]} at ${e.startedAt} has not ended. A pipeline runs once at a time.`}function QD(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 ZD={approved:"success",rejected:"stopped",timedOut:"stopped",cancelled:"cancelled"};function jI(){try{return mh(KD().username)}catch{return}}function eN(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 MI="A dry run of a pipeline is not available here: nothing ran. Run it, or try the dry run again once SandForge has finished starting.",LI={release:()=>{}};function cg(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 tN=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"]),Ic=class{constructor(e){this.deps=e}deps;pipelineMarketplace;stepRunners;claims=Zo();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??ov()}takeRunLock(e,t,r){if(typeof e.id!="string"||e.id==="")return LI;try{let n=iv(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] ${dv(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.`),LI}}setLiveOperationTracker(e){this.liveTracker=e}approvals(){let e=this.deps.services;return this.approvalGate??=new Oc({...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:jI}),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 Ws(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 So(this.deps.configStore).append({id:crypto.randomUUID(),action:"pipeline_approval",module:"automation",operationId:r,outcome:ZD[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 kc({pipelines:()=>this.savedPipelines(),problems:e=>this.pipelineProblems(e),org:e=>{let t=this.deps.orgManager.getOrg(e);return t?{name:me(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=sa.safeParse(o);return i.success?[i.data]:(t.set(n,au(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] ${Qu(n.busy,e.name)}`),{started:!1,busy:{startedAt:n.busy.acquiredAt,triggeredBy:n.busy.triggeredBy}};let o=`${yf}${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)}`),De(this.deps,o,I(a),!1,{context:{module:"automation",operation:"pipeline:execute"}}),a}).finally(()=>{n.release(),r.release()})}}async handle(e){if(!tN.has(e.type))return!1;switch(e.type){case"pipeline:execute":return await this.handlePipelineRun(e),!0;case"pipeline:templates":return this.handlePipelineTemplates(e),!0;case"pipeline:list":return await this.handlePipelineList(e),!0;case"pipeline:history":return this.handlePipelineHistory(e),!0;case"pipeline:save":return this.handlePipelineSave(e),!0;case"pipeline:delete":return this.handlePipelineDelete(e),!0;case"pipeline:approval":return this.handlePipelineApproval(e),!0;case"pipeline:sync-configs":return this.handleSyncConfigs(e),!0;case"pipeline:seed-templates":return this.handleSeedTemplates(e),!0;case"pipeline:masking-templates":return this.handleMaskingTemplates(e),!0;case"pipeline:rewind-steps":return await this.handleRewindSteps(e),!0;case"pipeline:rewind-grant":return await this.handleRewindGrant(e),!0;case"pipeline:rewind-revoke":return this.handleRewindRevoke(e),!0;case"pipeline:export":return await this.handlePipelineExport(e),!0;case"marketplace:list":return this.handleMarketplaceList(e),!0;case"marketplace:install":return this.handleMarketplaceInstall(e),!0;default:return!1}}async handlePipelineRun(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Ly,e,"pipeline:error",this.deps);if(!t)return;let r=t,n=e.id,o={module:"automation",operation:e.type},i=r.pipeline,a=r.dryRun===!0;if(a&&(!this.dryRunApplier||!this.stepRunners)){E(this.deps,"pipeline:execute","pipeline:error",e,new Error(MI),{code:"DRY_RUN_UNAVAILABLE",retryable:!0});return}let d=typeof i.id=="string"&&i.id!==""?this.claims.hold(i.id,{startedAt:new Date().toISOString(),triggeredBy:"manual"}):{release:()=>{}};if("busy"in d){E(this.deps,"pipeline:execute","pipeline:error",e,new Error(YD(i.name,d.busy)),{code:"PIPELINE_RUNNING",retryable:!0});return}let c=this.takeRunLock(i,"manual",a);if("busy"in c){d.release(),E(this.deps,"pipeline:execute","pipeline:error",e,new Error(Qu(c.busy,i.name)),{code:"PIPELINE_RUNNING",retryable:!0});return}try{let l=await this.runPipeline(i,r.variables??{},"manual",n,{dryRun:a}),u=T(this.deps,e,"pipeline:run:response",{...l,...a?{dryRun:!0}:{}});this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id}`)}catch(l){E(this.deps,"pipeline:execute","pipeline:error",e,l),De(this.deps,n,I(l),!1,{context:o})}finally{c.release(),d.release()}}handlePipelineApproval(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(By,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 cg(e.steps)){let o=Pt.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=sa.safeParse(this.deps.configStore.get(`pipeline:saved:${e}`));return t.success?t.data:void 0}async describeRewindStep(e,t){let r=this.stepRunners,n=Pt.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&&zs(t.config)===i.digest}:void 0;return r?{info:Jv(r,t,o,a),...o?{checkpoint:o}:{}}:{info:{stepId:t.id,valid:!1,why:"missing",...a?{granted:{at:a.grantedAt,digestMatches:a.matches}}:{}}}}async handleRewindSteps(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(qy,e,"pipeline:error",this.deps);if(t)try{let r=this.savedPipeline(t.pipelineId),n=[];for(let i of cg(r?.steps??[]))n.push((await this.describeRewindStep(t.pipelineId,i)).info);let o=T(this.deps,e,"pipeline:rewind-steps:response",{pipelineId:t.pipelineId,steps:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} (${n.length} Rewind steps)`)}catch(r){E(this.deps,"pipeline:rewind-steps","pipeline:error",e,r)}}async handleRewindGrant(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Wy,e,"pipeline:error",this.deps);if(!t)return;let{pipelineId:r,stepId:n,typed:o}=t,i=d=>{let c=T(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=cg(d?.steps??[]).find(f=>f.id===n);if(!c)return a("NOT_SAVED");let l=Pt.safeParse(c.config);if(!l.success)return a("CONFIG_INVALID",{reason:l.error.issues[0]?.message??""});let u=this.deps.orgManager.getOrg(l.data.orgId);if(!u)return a("ORG_UNKNOWN");if(o!==me(u))return a("TYPED_MISMATCH");let{info:p,checkpoint:g}=await this.describeRewindStep(r,c);if(!p.valid)return a("CHECKPOINT_INVALID",{why:p.why??"missing"});if(!g?.kept||g.organizationId===void 0)return a("CHECKPOINT_INVALID",{why:"missing"});let h=jI();this.rewindGrants().write({pipelineId:r,stepId:n,organizationId:g.organizationId,checkpointId:l.data.checkpointId,digest:zs(c.config)??"",grantedAt:new Date().toISOString(),...h!==void 0?{grantedBy:h}:{}}),this.deps.log(`[INFO] pipeline:rewind-grant: Rewind step ${n} of pipeline ${r} confirmed for ${me(u)}, to checkpoint ${l.data.checkpointId}`),i({granted:!0,pipelineId:r,stepId:n,step:(await this.describeRewindStep(r,c)).info})}catch(d){E(this.deps,"pipeline:rewind-grant","pipeline:error",e,d)}}handleRewindRevoke(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(zy,e,"pipeline:error",this.deps);if(t)try{let r=this.rewindGrants().revoke(t.pipelineId,t.stepId),n=T(this.deps,e,"pipeline:rewind-revoke:response",{pipelineId:t.pipelineId,stepId:t.stepId,revoked:r});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} revoked=${r}`)}catch(r){E(this.deps,"pipeline:rewind-revoke","pipeline:error",e,r)}}handleSeedTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.stepRunners?Wv(this.stepRunners):[],r=T(this.deps,e,"pipeline:seed-templates:response",{templates:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} (${t.length} templates)`)}catch(t){E(this.deps,"pipeline:seed-templates","pipeline:error",e,t)}}handleMaskingTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.stepRunners?zv(this.stepRunners):[],r=T(this.deps,e,"pipeline:masking-templates:response",{templates:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} (${t.length} templates)`)}catch(t){E(this.deps,"pipeline:masking-templates","pipeline:error",e,t)}}handleSyncConfigs(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=this.stepRunners?_v(this.stepRunners):[],r=T(this.deps,e,"pipeline:sync-configs:response",{configs:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} (${t.length} configurations)`)}catch(t){E(this.deps,"pipeline:sync-configs","pipeline:error",e,t)}}async buildOrchestrator(e,t){return(await this.buildRunParts(e,t)).orchestrator}async buildRunParts(e,t){let{PipelineBuilder:r}=await import("./chunk-4HW535YJ.mjs"),{TriggerEngine:n}=await import("./chunk-MIDBQ7SD.mjs"),{StepLibrary:o}=await import("./chunk-GGNUACTY.mjs"),{StepExecutor:i}=await import("./chunk-3HROD5RE.mjs"),{ConditionalRouter:a}=await import("./chunk-RTWYLOCA.mjs"),{PipelineHistory:d}=await import("./chunk-ZHJP7L3K.mjs"),c=new i,l=e??{operationId:"",holdBudget:()=>{}};c.wrapHandler("delay",g=>(h,f)=>this.untimed(()=>g(h,f),l));let u;if(this.stepRunners){let{runSync:g,seed:h,anonymize:f,takeCheckpoint:m,rewind:y,backup:R}=this.stepRunners,{simulateSync:k,previewSeed:w,previewMasking:O,estimateTake:P,previewRewind:b}=this.stepRunners,v=await this.checkpointsOf(t),C=this.rewindGrants();u={...this.stepRunners,...t?.id?{pipelineId:t.id}:{},...l.triggeredBy?{trigger:l.triggeredBy}:{},rewindGrant:(S,A)=>C.verify(S,A),checkpointKept:S=>v.get(S),...g?{runSync:(S,A,D)=>this.runSyncUntimed(g,S,A,D,l)}:{},backup:(S,A)=>this.untimed(()=>R(S,A),l),...h?{seed:(S,A)=>this.untimed(()=>h(S,A),l)}:{},...f?{anonymize:(S,A)=>this.untimed(()=>f(S,A),l)}:{},...m?{takeCheckpoint:(S,A)=>this.untimed(()=>m(S,A),l)}:{},...y?{rewind:(S,A)=>this.untimed(()=>y(S,A),l)}:{},...k?{simulateSync:(S,A)=>this.untimed(()=>k(S,A),l)}:{},...w?{previewSeed:(S,A)=>this.untimed(()=>w(S,A),l)}:{},...O?{previewMasking:(S,A)=>this.untimed(()=>O(S,A),l)}:{},...P?{estimateTake:(S,A)=>this.untimed(()=>P(S,A),l)}:{},...b?{previewRewind:(S,A)=>this.untimed(()=>b(S,A),l)}:{},...this.approvals().canAsk?{askApproval:(S,A)=>this.askApproval(S,A,l)}:{}},Vv(c,u)}if(l.dryRun){if(!this.dryRunApplier||!u)throw new Error(MI);await this.dryRunApplier(c,u)}if(!this.deps.services)throw new Error("AutomationHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");return{orchestrator:this.deps.services.automationOrchestrator({builder:new r,triggerEngine:new n,stepLibrary:new o,stepExecutor:c,conditionalRouter:new a,history:new d,services:this.deps.services}),stepExecutor:c}}async runPipeline(e,t,r,n,o={}){let i=o.dryRun===!0,a={module:"automation",operation:"pipeline:execute"},d=this.deps.services?.getSandforgeSetting?.("pipeline.timeout",3e5)??3e5,c=new AbortController,l=!1,u=eN(d,()=>{l=!0,c.abort()}),p=await this.buildOrchestrator({operationId:n,holdBudget:b=>b?u.hold():u.resume(),triggeredBy:r,...i?{dryRun:!0}:{}},e);this.deps.infraServices?.performanceTracker?.start(n,"automation");let g=`${i?"Pipeline dry run":"Pipeline"}: ${e.name}`;ze(this.deps,n,"automation",g);let h=sr(this.liveTracker,n,"automation",g,e.steps.length),f=b=>l&&b.status==="stopped"?{...b,status:"failed"}:b,m=(b,v)=>{let C=v,S=p.getActiveRuns(),A=e.steps.length,D=S[0]?.stepResults.length??0,z=Math.round(D/A*100),U=`Step: ${C.stepResult.stepName} (${C.stepResult.status})`;Le(this.deps,n,z,D,A,U),h.progress(z,D,A,U)},y=(b,v)=>{let{stepId:C}=v;this.postStepUpdate({operationId:n,stepId:C,status:"running"})},R=(b,v)=>{let C=f(v.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}:{}})};p.on("stepCompleted",m),p.on("stepStarted",y),p.on("stepCompleted",R),p.on("stepSkipped",R),u.start();let k=()=>{};this.deps.infraServices?.backgroundRegistry?.register(n,"automation",g,new Promise((b,v)=>{k=C=>C?v(C):b()}),c);let w;try{w=await p.execute(e,t,r,c.signal)}catch(b){throw k(new Error(I(b))),h.fail(I(b)),b}finally{u.end(),p.off?.("stepCompleted",m),p.off?.("stepStarted",y),p.off?.("stepCompleted",R),p.off?.("stepSkipped",R)}let O=l&&w.status==="cancelled",P=O?{...w,status:"failed",error:`Pipeline ran out of time: sandforge.pipeline.timeout stopped it after ${d} ms.`,stepResults:w.stepResults.map(f)}:w;return k(P.status==="failed"?new Error(P.error??"Pipeline failed"):void 0),P.status==="failed"?h.fail(P.error??"Pipeline failed"):P.status==="cancelled"?h.cancel():P.status==="completed_with_warnings"?h.partial():h.complete(),this.deps.infraServices?.performanceTracker?.complete(n),i||this.recordRun(P,e),P.status==="failed"?De(this.deps,n,P.error??"Pipeline failed",O,{context:a}):pe(this.deps,n,{status:P.status,stepResults:P.stepResults.length}),P}postStepUpdate(e){let t={id:this.deps.nextId(),type:"pipeline:step",timestamp:Date.now(),payload:e};this.deps.broker.postToWebview(t)}recordRun(e,t){this.writeHistory({runId:e.id,pipelineId:e.pipelineId,pipelineName:e.pipelineName,status:e.status,triggeredBy:e.triggeredBy,startTime:e.startTime,duration:e.duration??0,stepCount:e.stepResults.filter(r=>r.status!=="skipped").length,errorCount:e.stepResults.filter(r=>r.status==="failed").length,steps:e.stepResults.map(QD)},{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<=NI)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-NI))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 Ot(r).load(o),seedTemplate:o=>new on(r).load(o),maskingTemplate:o=>new ya(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=sa.safeParse(r);if(!n.success||n.data.runsOutside===void 0)continue;let o=n.data;try{let i=vv(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 Sv({...this.exportInput(t,r),stepRefusal:(a,d)=>n.check(a,{steps:t.steps,index:d,declared:i}),problems:o.check(t),checkedWhereItRuns:this.deps.services?.runsFrom==="commandLine"})}async handlePipelineExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(_y,e,"pipeline:error",this.deps);if(t)try{let r=await this.exportPipeline(t.pipelineId),n=T(this.deps,e,"pipeline:export:response",r);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} ${r.exported?`exported ${r.fileName}`:`refused ${r.code}`}`)}catch(r){E(this.deps,"pipeline:export","pipeline:error",e,r)}}handlePipelineTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=T(this.deps,e,"pipeline:templates:response",{templates:DI});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=T(this.deps,e,"pipeline:list:response",{pipelines:r,triggers:n,...o.length>0?{outside:o}:{}});this.deps.broker.postToWebview(i),this.deps.log(`[TX] pipeline:list:response (${r.length} pipelines)`)}catch(t){E(this.deps,"pipeline:list","pipeline:error",e,t)}}commandLineRuns(){try{return this.commandLineHistory??=gv(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=T(this.deps,e,"pipeline:history:response",{history:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] pipeline:history:response (${n.length} entries)`)}catch(t){E(this.deps,"pipeline:history","pipeline:error",e,t)}}handlePipelineSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=x(Hy,e,"pipeline:error",this.deps);if(!t)return;let r=t,n=r.config.runsOutside;if(n!==void 0){let l=Fy.safeParse(n);if(!l.success){E(this.deps,"pipeline:save","pipeline:error",e,new Error(`The pipeline was not saved: runsOutside.${au(l.error)}`),{code:"INVALID_PAYLOAD",retryable:!1});return}}let o=r.id||crypto.randomUUID(),i=`pipeline:saved:${o}`;this.deps.configStore.set(i,{...r.config,id:o,savedAt:new Date().toISOString()},"pipelines");let a=Array.isArray(r.config.steps)?r.config.steps:[],d=this.rewindGrants().revokeChanged(o,a.map(l=>({...typeof l.id=="string"?{id:l.id}:{},...l.type==="rewind"?{type:"rewind"}:{},config:typeof l.config=="object"&&l.config!==null?l.config:{}})));for(let l of d)this.deps.log(`[INFO] pipeline:save ${o}: the confirmation of Rewind step ${l} was taken back, since the save changed what it does`);this.scheduler?.reload();let c=T(this.deps,e,"pipeline:save:response",{success:!0,id:o});this.deps.broker.postToWebview(c),this.deps.log(`[TX] pipeline:save:response id=${o}`)}catch(t){E(this.deps,"pipeline:save","pipeline:error",e,t)}}handlePipelineDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=x(Uy,e,"pipeline:error",this.deps);if(!t)return;let{id:r}=t,n=this.claims.hold(r,{startedAt:new Date().toISOString(),triggeredBy:"manual"});if("busy"in n){let a=this.deps.configStore.get(`pipeline:saved:${r}`),d=typeof a?.name=="string"?a.name:r;E(this.deps,"pipeline:delete","pipeline:error",e,new Error(`Pipeline "${d}" is running: the run started ${FI[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=T(this.deps,e,"pipeline:delete:response",{id:r,deleted:o});this.deps.broker.postToWebview(i),this.deps.log(`[TX] pipeline:delete:response id=${r} deleted=${o}`)}catch(t){E(this.deps,"pipeline:delete","pipeline:error",e,t)}}handleMarketplaceList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{if(!this.pipelineMarketplace)throw new Error("Pipeline Marketplace not available.");let t=x(Gy,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=T(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=T(this.deps,e,"marketplace:list:response",{success:!1,error:I(t)});this.deps.broker.postToWebview(r)}}handleMarketplaceInstall(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Jy,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=T(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=T(this.deps,e,"marketplace:install:response",{success:!1,error:I(n)});this.deps.broker.postToWebview(o)}}};var es=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 ao(s,e){return e.aborted?(s.catch(()=>{}),Promise.reject(_I())):new Promise((t,r)=>{let n=()=>r(_I());e.addEventListener("abort",n,{once:!0}),s.then(o=>{e.removeEventListener("abort",n),t(o)},o=>{e.removeEventListener("abort",n),r(o)})})}function _I(){return Object.assign(new Error("Stopped before its answer came."),{code:"CANCELLED"})}var HI=200,lg=50,ug="ai.enabled",pg="ai.errorResolution",UI="ai:conversations:index",BI="ai",Ac="ai.anthropic.key",rN=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"]),Tc=class{constructor(e){this.deps=e}deps;aiAssistant;asking=new es;setAIAssistant(e){this.aiAssistant=e}async handle(e){if(!rN.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(UI)??[]}saveIndex(e){this.deps.configStore.set(UI,e,BI)}loadConversation(e){return this.deps.configStore.get(this.conversationKey(e))}saveConversation(e){this.deps.configStore.set(this.conversationKey(e.id),e,BI),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<=lg)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-lg).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 (${lg} 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<=HI)return e;let t=e.filter(o=>o.role==="system"),r=e.filter(o=>o.role!=="system"),n=HI-t.length;return[...t,...r.slice(-n)]}isChatRole(e){return e==="user"||e==="assistant"||e==="system"}toConversation(e){let t=e.messages.filter(r=>this.isChatRole(r.role)).map(r=>({id:r.id,role:r.role,content:r.content,timestamp:r.timestamp,tokenCount:r.tokenCount}));return{id:e.id,title:e.title,messages:t,createdAt:e.createdAt,updatedAt:e.updatedAt,totalTokens:t.reduce((r,n)=>r+(n.tokenCount??0),0)}}restoreConversationIfNeeded(e){let t=this.aiAssistant;if(!t||t.getConversation(e))return;let r=this.loadConversation(e);r&&(t.restoreConversation(this.toConversation(r)),this.deps.log(`Restored conversation ${e} from store.`))}async handleChat(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(sy,e,"ai:error",this.deps);if(!t)return;let r=t,n=this.aiAssistant;if(!n){let i=T(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=T(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=T(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=T(this.deps,e,"ai:error",{message:a});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ai:error: ${a}`)}finally{o.end()}}handleChatCancel(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(oa,e,"ai:error",this.deps);t&&this.asking.abort(t.conversationId)}handleConversationCreate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(iy,e,"ai:error",this.deps);if(!t)return;let r=t;if(!this.aiAssistant){let i=T(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=T(this.deps,e,"ai:conversation:created",{conversation:{id:n.id,title:n.title,createdAt:n.createdAt}});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ai:conversation:created id=${n.id}`)}handleConversationLoad(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(oa,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=T(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=T(this.deps,e,"ai:error",{message:`Conversation ${r.conversationId} not found.`});this.deps.broker.postToWebview(i);return}let o=T(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=T(this.deps,e,"ai:conversation:list:response",{conversations:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ai:conversation:list:response count=${t.length}`)}handleConversationDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(oa,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=T(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=T(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(Ac),r=T(this.deps,e,"ai:status:response",{enabled:!!this.aiAssistant&&t,provider:this.aiAssistant?cf:"none",model:this.aiAssistant?uf(this.deps.services?.getSandforgeSetting?.("ai.model",lf.MODEL)):"",budget:this.aiAssistant?this.deps.services?.sessionBudget?.getState():void 0,hasKey:t,errorResolution:this.deps.services?.getSandforgeSetting?.(pg,!0)??!0});this.deps.broker.postToWebview(r),this.deps.log("[TX] ai:status:response")}async enableAIFeature(){await this.writeSetting("ai:save-key",ug,!0)}async writeSetting(e,t,r){if(!this.deps.services?.setSandforgeSetting)return this.deps.log(`[WARN] ${e}: no settings backend \u2014 sandforge.${t} left as-is.`),!1;try{return await this.deps.services.setSandforgeSetting(t,r),!0}catch(n){return this.deps.log(`[ERR] ${e}: writing sandforge.${t} failed: ${I(n)}`),!1}}async rebuildAIStack(e="ai:save-key"){let t=this.deps.services?.reinitAI;if(!t){this.deps.log(`[WARN] ${e}: no AI rebuild wired \u2014 the change applies after a reload.`);return}try{await t()}catch(r){this.deps.log(`[ERR] ${e}: rebuilding the AI stack failed: ${I(r)}`)}}async handleSaveKey(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ay,e,"ai:error",this.deps);if(!t)return;let{apiKey:r,errorResolution:n}=t;try{let o=await this.deps.secretVault.hasSecret(Ac);await this.deps.secretVault.storeSecret(Ac,r),(!o||n!==void 0)&&await this.writeSetting("ai:save-key",pg,n===!0),await this.enableAIFeature(),await this.rebuildAIStack();let i=T(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=T(this.deps,e,"ai:save-key:response",{success:!1,error:i});this.deps.broker.postToWebview(a)}}async handleSettings(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(dy,e,"ai:error",this.deps);if(!t)return;let r=[];t.errorResolution!==void 0&&r.push([pg,t.errorResolution]),t.enabled!==void 0&&r.push([ug,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=T(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(Ac);let t=this.deleteAllConversations();await this.writeSetting("ai:remove-key",ug,!1),await this.rebuildAIStack("ai:remove-key");let r=T(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=T(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 nN=new Set(["ai:anomaly-scan"]),Ec=class{constructor(e){this.deps=e}deps;ruleModules;setRuleModules(e){this.ruleModules=e}async handle(e){return nN.has(e.type)&&e.type==="ai:anomaly-scan"?(await this.handleAnomalyScan(e),!0):!1}async handleAnomalyScan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(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??pn.anomalyScan,c=`SELECT FIELDS(ALL) FROM ${a} LIMIT ${d}`,l=await vh(i,a,c),u=l.records,p={records:u,fields:Object.keys(u[0]??{})},g=this.ruleModules.anomalyDetector.detectAnomalies(p,n),h=T(this.deps,e,"ai:anomaly-scan:response",{success:!0,anomalies:g.anomalies.map(f=>({field:f.field,type:f.type,description:f.description,severity:f.severity})),sample:{read:u.length,limit:l.limit??d}});this.deps.broker.postToWebview(h)}catch(i){this.deps.log(`[ERR] ai:anomaly-scan: ${I(i)}`);let a=T(this.deps,e,"ai:anomaly-scan:response",{success:!1,error:I(i)});this.deps.broker.postToWebview(a)}}};function qI(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"")}function oN(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 sN(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=qI(r);n&&!e.has(n)&&e.set(n,t.name)}return e}function WI(s,e,t=5){if(t<=0)return[];let r=sN(e),n=s.split(/[^A-Za-z0-9_]+/).filter(Boolean),o=[],i=new Set;for(let a=0;a<n.length;a++){let d=Math.min(4,n.length-a);for(let c=d;c>=1;c--){let l=n.slice(a,a+c).join(""),u=oN(qI(l)).map(p=>r.get(p)).find(p=>p!==void 0);if(u){if(!i.has(u)&&(i.add(u),o.push(u),o.length>=t))return o;a+=c-1;break}}}return o}var iN={sync:"Sync",seed:"Seed",dataops:"DataOps"};function zI(s){if(s.code==="STEP_NOT_RUNNABLE")return`A pipeline cannot run a ${s.stepType} step, so the draft leaves it out.`;let e=iN[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 aN=new Set(["WHERE","USING","WITH","GROUP","ORDER","LIMIT","OFFSET","FOR","UPDATE"]),dN=new Set(["WITH","GROUP","ORDER","LIMIT","OFFSET","FOR","UPDATE"]),cN=new Set(["AND","OR","NOT","WHERE"]),lN=/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/,uN=/^([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)(?:\s+[A-Za-z_]\w*)?$/,pN=/^[A-Za-z_]\w*\s*\(([^()]*)\)(?:\s+[A-Za-z_]\w*)?$/,gN=/([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*(?:!=|<>|<=|>=|=|<|>|\bNOT\s+IN\b|\bIN\b|\bLIKE\b|\bINCLUDES\b|\bEXCLUDES\b)/gi;function fN(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 GI=/\(\s*SELECT\b/iy;function hN(s){let e="",t=0;for(;t<s.length;){if(GI.lastIndex=t,s[t]!=="("||!GI.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 mN(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 yN(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 wN(s){let e=uN.exec(s);if(e)return e[1];let t=pN.exec(s);if(t){let r=t[1].trim();return lN.test(r)?r:null}return null}function bN(s){let e=hN(fN(s)).replace(/\bTYPEOF\b[\s\S]*?\bEND\b/gi,"()"),t=mN(e),r=f=>t[f]?.word.toUpperCase();if(r(0)!=="SELECT")return null;let n=t.findIndex(f=>f.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&&!aN.has(d)&&!c.includes(",")&&i.add(d);let l=[],u=e.slice(t[0].end,t[n].start);for(let f of yN(u)){let m=wN(f.trim());m&&l.push(m)}let p=t.findIndex((f,m)=>m>n+1&&f.word.toUpperCase()==="WHERE");if(p>=0){let f=t.findIndex((y,R)=>R>p&&dN.has(r(R)??"")),m=e.slice(t[p].end,f<0?e.length:t[f].start);for(let y of m.matchAll(gN))cN.has(y[1].toUpperCase())||l.push(y[1])}let g=new Set,h=[];for(let f of l){let[m,...y]=f.split("."),R=y.length>0&&i.has(m.toUpperCase())?y.join("."):f,k=R.toUpperCase();g.has(k)||(g.add(k),h.push(R))}return{objectApiName:o,fieldRefs:h}}async function JI(s,e){let t=bN(s);if(!t)return{fieldsChecked:0,problems:[{kind:"no-from"}]};let r=t.objectApiName.toLowerCase(),n=e.catalog.find(l=>l.name.toLowerCase()===r);if(!n)return{rootObject:t.objectApiName,fieldsChecked:0,problems:[{kind:"object-missing",object:t.objectApiName}]};let o;try{o=await e.describe(n.name)}catch(l){return{rootObject:n.name,rootLabel:n.label,fieldsChecked:0,problems:[{kind:"describe-failed",object:n.name,detail:I(l)}]}}let i=new Set(o.fields.map(l=>l.name.toLowerCase())),a=new Set(o.fields.flatMap(l=>l.relationshipName?[l.relationshipName.toLowerCase()]:[])),d=[],c=new Set;for(let l of t.fieldRefs){let[u,...p]=l.split(".");p.length===0?i.has(u.toLowerCase())||d.push({kind:"field-missing",object:n.name,field:u}):!a.has(u.toLowerCase())&&!c.has(u.toLowerCase())&&(c.add(u.toLowerCase()),d.push({kind:"relationship-missing",object:n.name,relationship:u}))}if(d.length===0)try{await e.explain(s)}catch(l){d.push({kind:"org-refused",detail:I(l)})}return{rootObject:n.name,rootLabel:o.label||n.label,fieldsChecked:t.fieldRefs.length,problems:d}}function gg(s){return vN().text(s)}var SN=new Set;function vN(){let s=OS(),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=IS({text:o},SN,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 _t=Ml,zt=Ml.text,VI="{firstName}, {lastName}, {company}, {email} and {caseSubject}";var Y1=[`- "id" and each topic's "key": lower-case letters and digits in words joined by single hyphens, starting with a letter, ${_t.maxKeyLength} characters at most.`,`- "name": at most ${zt.name} characters. "businessContext": what the company does and who its customers are, in two or three sentences, at most ${zt.businessContext} characters.`,`- "customers": "count" is 10 unless the scenario asks for another number, at least the number of topics and at most ${_t.maxCustomers}; "industry" is the customers' industry as an Account Industry value of Salesforce (Retail, Telecommunications, Technology...), at most ${zt.industry} characters.`,`- "topics": ${_t.topics.min} to ${_t.topics.max}, five unless the scenario calls for more or fewer: the subjects customers write to support about. "label": at most ${zt.label} characters.`,`- "utterances": ${_t.utterances.min} to ${_t.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 ${zt.utterance} characters. They may name the customer and the case with ${VI}, 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 ${zt.articleTitle} characters, "summary" at most ${zt.articleSummary}, "body" plain-text paragraphs of 600 to 1,500 characters. No placeholder.`,`- "outOfScope": ${_t.outOfScope.min} to ${_t.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 ${zt.utterance} characters. No placeholder.`,"- No word in braces but the placeholders named here, where they are allowed."];var Q1=[`- "article": what the agent answers the topic from. "title" at most ${zt.articleTitle} characters and none of the titles above; "summary" at most ${zt.articleSummary}; "body" plain-text paragraphs of 1,200 to 3,000 characters, at most ${zt.articleBody}: the policy or the procedure, with the figures, delays and conditions customers ask about. No placeholder in the article.`,`- "facts": ${_t.facts.min} to ${_t.facts.max}, each a sentence of the body copied word for word, at most ${zt.fact} characters: what an answer drawn from the article has to say.`,`- "caseTemplates": ${_t.caseTemplates.min} to ${_t.caseTemplates.max}, two unless the topic needs more: cases customers open on the topic. "subject" at most ${zt.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" ${_t.resolutionSteps.min} to ${_t.resolutionSteps.max} steps, each a comment of the agent who resolved the case, under 400 characters. "description", "followUp" and "resolution" may name ${VI}.`,"- No word in braces but the placeholders named here, where they are allowed."];var kN=new Set(["ai:forge-plan","ai:generate-pipeline","ai:scenario-draft","ai:tool:cancel"]),fg={success:!1,code:"CANCELLED"},XI="AI not configured. Set your API key in Settings > AI.";function ON(s){switch(s){case"Production":return"production";case"Sandbox":return"sandbox";case"Developer":return"developer";case"Scratch":return"scratch";default:return"production"}}var Pc=class{constructor(e){this.deps=e}deps;aiModules;drafting=new es;describeGlobalCache=new Bs({defaultTtl:5*6e4,maxSize:16,maxSizeBytes:50*1024*1024});describeCache=new Bs({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(!kN.has(e.type))return!1;switch(e.type){case"ai:forge-plan":return await this.handleForgePlan(e),!0;case"ai:generate-pipeline":return await this.handleGeneratePipeline(e),!0;case"ai:scenario-draft":return await this.handleScenarioDraft(e),!0;case"ai:tool:cancel":return this.handleCancel(e),!0;default:return!1}}handleCancel(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(py,e,"ai:error",this.deps);t&&this.drafting.abort(t.requestId)}async handleForgePlan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ly,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(T(this.deps,e,"ai:forge-plan:response",{success:!1,code:"AI_NOT_CONFIGURED",error:XI}));return}let a=await ao(this.connect(r),o.signal),d=await ao(this.loadCatalog(r,a),o.signal),c=t.soql??"",l;if(n!==void 0&&i){let{result:p}=await this.draft(i,n,r,a,d,o.signal);c=p.soql,l=p.explanation}let u=await ao(JI(c,{catalog:d,describe:async p=>{let g=await this.describeObject(r,a,p);return{name:g.apiName,label:g.label,fields:g.fields.map(h=>({name:h.apiName,relationshipName:h.relationshipName}))}},explain:p=>a.request(`/query/?explain=${encodeURIComponent(p)}`)}),o.signal);this.deps.broker.postToWebview(T(this.deps,e,"ai:forge-plan:response",{success:u.problems.length===0,soql:c,...l?{explanation:l}:{},...u.rootObject?{rootObject:u.rootObject}:{},...u.rootLabel?{rootLabel:u.rootLabel}:{},fieldsChecked:u.fieldsChecked,problems:u.problems}))}catch(i){if(o.signal.aborted){this.deps.broker.postToWebview(T(this.deps,e,"ai:forge-plan:response",{...fg})),this.deps.log("[TX] ai:forge-plan:response cancelled");return}this.deps.log(`[ERR] ai:forge-plan: ${I(i)}`),this.deps.broker.postToWebview(T(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=WI(t,o),d=await ao(this.describeObjects(r,n,a),i),c={objects:d.length>0?d:o.map(u=>({apiName:u.name,label:u.label,fields:[]}))};return{result:await ao(e.generateSOQL(t,c,{signal:i}),i),described:d}}async loadCatalog(e,t){let r=this.describeGlobalCache.get(e);if(r)return r;let o=(await t.describeGlobal()).sobjects.filter(i=>i.queryable!==!1).map(i=>({name:i.name,label:i.label,labelPlural:i.labelPlural,queryable:i.queryable}));return this.describeGlobalCache.set(e,o),o}async describeObjects(e,t,r){let n=[];for(let o of r)try{n.push(await this.describeObject(e,t,o))}catch(i){this.deps.log(`[WARN] ai:nl2soql describe ${o}: ${I(i)}`)}return n}async describeObject(e,t,r){let n=`${e}::${r}`,o=this.describeCache.get(n);if(o)return o;let i=await t.describe(r),a={apiName:i.name,label:i.label??i.name,fields:i.fields.map(d=>({apiName:d.name,label:d.label??d.name,type:d.type,...d.relationshipName?{relationshipName:d.relationshipName}:{}}))};return this.describeCache.set(n,a),a}async handleGeneratePipeline(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(uy,e,"ai:error",this.deps);if(!t)return;let{description:r,orgIds:n}=t,o=this.drafting.begin(e.id);try{if(!this.aiModules?.pipelineGenerator)throw new Error("AI not configured. Set your API key in Settings > AI to enable this feature.");let i=(n??[]).map(l=>{let u=this.deps.orgManager.getOrg(l);return{orgId:l,alias:u?.alias??l,type:ON(u?.orgType)}}),{suggestions:a=[],...d}=await ao(this.aiModules.pipelineGenerator.generatePipeline(r,i,{signal:o.signal}),o.signal);if(d.steps.length===0&&a.length>0){let l=a.map(zI).join(" ");this.deps.log(`[ERR] ai:generate-pipeline: ${l}`),this.deps.broker.postToWebview(T(this.deps,e,"ai:generate-pipeline:response",{success:!1,error:l,suggestions:a}));return}if(d.steps.length===0)throw new Error("The AI returned a pipeline with no steps, so there is nothing to load. Name the operations it should run, for example: back up Account daily, then compare dev with uat.");let c=T(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(T(this.deps,e,"ai:generate-pipeline:response",{...fg})),this.deps.log("[TX] ai:generate-pipeline:response cancelled");return}this.deps.log(`[ERR] ai:generate-pipeline: ${I(i)}`);let a=T(this.deps,e,"ai:generate-pipeline:response",{success:!1,error:I(i)});this.deps.broker.postToWebview(a)}finally{o.end()}}async handleScenarioDraft(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(gy,e,"ai:error",this.deps);if(!t)return;let r=i=>this.deps.broker.postToWebview(T(this.deps,e,"ai:scenario-draft:response",i));if(t.maskOnly){r({success:!0,sentText:gg(t.text)});return}let n=this.aiModules?.scenarioDrafter;if(!n){r({success:!1,code:"AI_NOT_CONFIGURED",error:XI,sentText:gg(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(IN(i))}catch(i){this.deps.log(`[ERR] ai:scenario-draft: ${I(i)}`),r({success:!1,error:I(i)})}finally{o.end()}}};function IN(s){switch(s.kind){case"complete":return{success:!0,sentText:s.sentText,pack:s.pack};case"stopped":return{...fg,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 AN=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"]),Cc=class{chatHandler;analysisHandler;toolsHandler;subHandlers;constructor(e){this.chatHandler=new Tc(e),this.analysisHandler=new Ec(e),this.toolsHandler=new Pc(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(!AN.has(e.type))return!1;for(let t of this.subHandlers)if(await t.handle(e))return!0;return!1}};function KI(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 YI(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 TN=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"]),EN=10,hg=3e4,ZI=6e4;function eA(s){return`autopilot:${s}`}var mg=(s,e)=>e==="insert"||e==="update",$c={code:"AUTOPILOT_NOT_READY",message:"Autopilot module is not initialized."},ts={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."},PN=new Set(["autopilot:pause","autopilot:resume","autopilot:skip-node"]),xc=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-DIL62SUN.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!==eA(r))}async handle(e){if(!TN.has(e.type))return!1;switch(e.type){case"autopilot:list-objects":return await this.handleListObjects(e),!0;case"autopilot:count-objects":return await this.handleCountObjects(e),!0;case"autopilot:scan-schema":return await this.handleScanSchema(e),!0;case"autopilot:generate-plan":return await this.handleGeneratePlan(e),!0;case"autopilot:fit-plan":return await this.handleFitPlan(e),!0;case"autopilot:fit-undo":return await this.handleFitUndo(e),!0;case"autopilot:execute":return await this.handleExecute(e),!0;case"autopilot:pause":return this.handlePause(e),!0;case"autopilot:resume":return this.handleResume(e),!0;case"autopilot:skip-node":return this.handleSkipNode(e),!0;case"autopilot:compliance-report":return this.handleComplianceReport(e),!0;default:return!1}}refuseNotReady(e){E(this.deps,e.type,"autopilot:error",e,new Error($c.message),{code:$c.code}),PN.has(e.type)&&Ie(this.deps,"error","Autopilot",$c.message,{code:$c.code})}resolveCurrentOperation(){return this.currentOperationId!==void 0?this.operations.get(this.currentOperationId):void 0}evictOldOperations(){for(;this.operations.size>EN;){let e=this.operations.keys().next();if(e.done||this.executingOperations.has(e.value))return;this.operations.delete(e.value),this.currentOperationId===e.value&&(this.currentOperationId=[...this.operations.keys()].pop())}}async handleListObjects(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=x(Vm,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=T(this.deps,e,"autopilot:objects-listed",{objects:o});this.deps.broker.postToWebview(i),this.deps.log(`[TX] ${i.type} id=${i.id} count=${o.length}`)}catch(r){E(this.deps,"autopilot:list-objects","autopilot:error",e,r)}}async handleCountObjects(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=x(Xm,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=T(this.deps,e,"autopilot:objects-counted",{counts:Object.fromEntries(n)});this.deps.broker.postToWebview(o)}catch(r){E(this.deps,"autopilot:count-objects","autopilot:error",e,r)}}async handleScanSchema(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=x(Km,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 l=T(this.deps,e,"autopilot:schema-result",{graph:c});this.deps.broker.postToWebview(l)}catch(i){this.operations.delete(e.id),this.currentOperationId===e.id&&(this.currentOperationId=n),E(this.deps,"autopilot:scan-schema","autopilot:error",e,i),Ie(this.deps,"error","Autopilot",`Schema scan failed: ${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=x(Ym,e,"autopilot:error",this.deps);if(!r)return;let n=r;try{let o=n.complianceFramework!=="none"&&t.scanResult?Xb(this.deps.infraServices?.piiDetector??new ba,t.scanResult.objectDescribes):[],{profile:i,rules:a}=this.orchestrator.buildCompliance(n.complianceFramework,[],o);t.profile=i,t.rules=a;let d=this.orchestrator.generatePlan(t.graph,n.complianceFramework,a,t.scanResult?.scope);t.plan=d,t.fit&&(t.fit={...t.fit,plan:this.orchestrator.generatePlan(t.fit.graph,n.complianceFramework,a,t.fit.scan.scope)}),await this.sendPlanReady(e,t)}catch(o){E(this.deps,"autopilot:generate-plan","autopilot:error",e,o),Ie(this.deps,"error","Autopilot",`Plan generation failed: ${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,Tu(o,a.recordCounts,a.personAccounts),r??await this.readTargetDataStorage(t.targetOrgId)):void 0}catch(l){this.deps.log(`[WARN] ${e.type}: what the plan comes to against the target could not be told (${I(l)})`)}if((t.fit??t).plan!==o)return;let c=T(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 iR(t,r,()=>this.readTargetApiBudget(e),n);return KI(t,Rr(t,r),o)}refuseFit(e,t,r,n){E(this.deps,e.type,"autopilot:error",e,new Error(r),{code:t,...n?{extraPayload:n}:{}})}async handleFitPlan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let{orchestrator:t}=this;if(!t){this.refuseNotReady(e);return}let r=x(Zm,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,Do.NO_PLAN,"No execution plan available. Run generate-plan first.");return}let{targetOrgId:c}=n;if(this.writingTargets.has(c)){this.refuseFit(e,ts.code,ts.message);return}try{let l=await this.readTargetAutomation(c,o),u=r.muteAutomation===!0?await this.planMute(c,l).catch(R=>{if(!$t(R))throw R}):void 0,p=await this.readTargetDataStorage(c),g=r.checkpointFirst!==void 0?await this.checkpointFirstOf(e,c,o,r.checkpointFirst,{read:l,...u?{mute:u}:{}},new AbortController().signal):void 0,h=Vb({storage:p,...r.mode.withinMB!==void 0?{withinMB:r.mode.withinMB}:{},..."unread"in p?{}:{api:p.dailyApiRequests??{unread:"the target's /limits did not list them"}},otherRequests:xo(g&&"estimate"in g?g.estimate:void 0)});if("unread"in h){this.refuseFit(e,Do.STORAGE_UNREAD,`The plan cannot be fitted: the target's data storage left could not be read (${h.unread}). Give the most MB it may use to fit it to that.`,{reason:h.unread});return}let f=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(f,{scan:d,graph:i,plan:o,rules:a,mode:r.mode,budget:h,automation:l,...u?.plan?{mutePlan:u.plan}:{},describeLookups:async R=>nR((await m.describe(R)).fields)})}catch(R){let k=I(R);this.refuseFit(e,Do.READ_REFUSED,`The plan could not be fitted: the source refused a read of it (${k}).`,{reason:k});return}if(n.plan!==o||this.currentOperationId!==n.id||this.writingTargets.has(c)){this.refuseFit(e,Do.STALE,"The plan changed while it was fitted: fit it again.");return}if(y.fitted){n.fit={...y.fitted,report:y.report},await this.sendPlanReady(e,n,p);return}y.report.cannotFit===void 0&&(n.fit=void 0),await this.sendPlanReady(e,n,p,y.report)}catch(l){E(this.deps,"autopilot:fit-plan","autopilot:error",e,l)}}async handleFitUndo(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=this.resolveCurrentOperation();if(!t?.plan){this.refuseFit(e,Do.NO_PLAN,"No execution plan available. Run generate-plan first.");return}if(this.writingTargets.has(t.targetOrgId)){this.refuseFit(e,ts.code,ts.message);return}t.fit=void 0;try{await this.sendPlanReady(e,t)}catch(r){E(this.deps,"autopilot:fit-undo","autopilot:error",e,r)}}async handleExecute(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=this.resolveCurrentOperation();if(!t?.plan||!t.graph||!t.rules||!t.scanResult){Ie(this.deps,"error","Autopilot","No execution plan available. Run generate-plan first.");return}let r=x(Qm,e,"autopilot:error",this.deps);if(!r)return;let n=r,{rules:o,fit:i}=t,a=i?.plan??t.plan,d=i?.graph??t.graph,c=i?.scan??t.scanResult,l=this.deps.infraServices?.productionGuard;if(!l){Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:Se.code}),E(this.deps,"autopilot:execute","autopilot:error",e,new Error(Se.message),{code:Se.code});return}if(this.writingTargets.has(t.targetOrgId)){E(this.deps,"autopilot:execute","autopilot:error",e,new Error(ts.message),{code:ts.code});return}this.writingTargets.set(t.targetOrgId,e.id),this.runningRequests.add(e.id);try{await this.executeRun(e,t,{plan:a,graph:d,rules:o,scanResult:c,...i?{fit:i}:{}},n,l)}finally{this.writingTargets.delete(t.targetOrgId),this.runningRequests.delete(e.id)}}async executeRun(e,t,{plan:r,graph:n,rules:o,scanResult:i,fit:a},d,c){if(!this.orchestrator)return;let l=Array.from(i.recordCounts.values()).reduce((B,V)=>B+V,0),u=a?YI(a.report,l,[...t.scanResult?.recordCounts.values()??[]].reduce((B,V)=>B+V,0)):void 0,p=new AbortController,g=()=>{},h=new Promise((B,V)=>{g=we=>we===void 0?B():V(we)});h.catch(()=>{}),this.registry?.register(e.id,"autopilot","Autopilot run",h,p);let f=this.deps.orgManager.getOrg(t.targetOrgId),m={orgId:t.targetOrgId,orgTier:Ce(f),operation:"insert",objectName:r.waves[0]?.objects[0]??"AutopilotData",recordCount:l,module:"autopilot"},{check:y,decision:R}=await Ze(c,m),k=R;if((R==="refused"||R==="declined")&&Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:R,...u?{fit:u}:{}}),R==="refused"){let B=hn(y.blockedReason??y.impactSummary);E(this.deps,"autopilot:execute","autopilot:error",e,B,{code:Ct.blocked}),g(B);return}if(R==="declined"){let B="Operation cancelled by user (confirmation declined).";E(this.deps,"autopilot:execute","autopilot:error",e,new Error(B),{code:Ct.declined}),g(new Error(B));return}let w=Tu(r,i.recordCounts,i.personAccounts),O,P;if(d.muteAutomation===!0)try{({mute:O,read:P}=await this.runMute(t.targetOrgId,r))}catch(B){if(!$t(B))throw B;Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:k,...u?{fit:u}:{},code:B.code}),E(this.deps,"autopilot:execute","autopilot:error",e,B,{code:B.code}),g(B);return}let b;if(d.checkpointFirst!==void 0&&w.totalRows>0){P??=await this.readTargetAutomation(t.targetOrgId,r);let B=await this.checkpointFirstOf(e,t.targetOrgId,r,d.checkpointFirst,{read:P,mute:O},p.signal);if("refused"in B){Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:k,...u?{fit:u}:{},code:Us.CHECKPOINT_REFUSED});let V=new Error(B.refused);E(this.deps,"autopilot:execute","autopilot:error",e,V,{code:Us.CHECKPOINT_REFUSED}),g(V);return}b=B}w.totalRows>0&&(P??=await this.readTargetAutomation(t.targetOrgId,r));let v=await this.targetEmails(t.targetOrgId,r,w,O?O.automation:P),C=new Set(w.objects.map(({objectApiName:B})=>B)),S=(B,V)=>C.has(B)&&mg(B,V),A=me(f,t.targetOrgId),D=P?await ir({read:P,...O?.plan?{plan:O.plan}:{},writes:S,readDeliverability:async()=>m.orgTier==="production"?Bt:qt(await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager)),accepted:!1,target:A,run:"autopilot",keepsAddresses:d.keepContactPoints===!0}):void 0,z=await aR({plan:w,storage:await this.readTargetDataStorage(t.targetOrgId),readApiBudget:()=>this.readTargetApiBudget(t.targetOrgId),confirmAboveRecords:this.confirmAboveRecords(),emails:v.checks,...v.unread!==void 0?{emailsUncounted:v.unread}:{},org:A,orgTier:m.orgTier,confirm:B=>c.confirmRun(B),...b?{checkpointFirst:b}:{},readBack:sR(w),mute:Vr(O?.plan),...D?{runEmails:D}:{}});if(!z.go){Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:k,...u?{fit:u}:{},code:z.code,details:Vn(z.emails)});let B=new Error(z.message);E(this.deps,"autopilot:execute","autopilot:error",e,B,{code:Us[z.code],...await this.fitOffer(t,z,w,b)}),g(B);return}this.liveTracker?.register(e.id,"autopilot","Autopilot run",l),this.executingOperations.add(t.id);let U=new Map,Y=!1,H=O?.muted,M=z.checkpoint,L,ee=!1,Q=B=>{Y||(Y=!0,Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:B,guard:k,objects:[...U.values()],source:{origin:"org",orgId:t.sourceOrgId},...B==="stopped"?{code:rt}:{},...H?{muted:dt(H)}:{},...L?.state==="taken"?{checkpointId:L.checkpointId}:{},...u?{fit:u}:{},details:Vn(z.emails)}))};try{d.grappeThreshold&&this.deps.log(`[GRAPPE] autopilot threshold set to ${d.grappeThreshold}`);for(let N of r.waves)for(let X of N.objects)this.sendNodeProgress(e,String(X),"processing",N.order);let B=new Map;for(let N of r.waves)for(let X of N.objects)B.set(String(X),N.order);let V=O?.prepared?await O.prepared.acquire(e.id).catch(N=>{if(!$t(N))throw N;return N}):void 0;if($t(V)){M&&(L=await this.settleCheckpoint(M,!1)),Y=!0,Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:k,...u?{fit:u}:{},code:V.code}),this.liveTracker?.fail(e.id,V.message),E(this.deps,"autopilot:execute","autopilot:error",e,V,{code:V.code,...L?{extraPayload:{checkpoint:L}}:{}}),g(V);return}V&&(H=V.outcome);let we=V?D?.afterLease(V.outcome,z.emails?.accepted===!0):void 0;if(V&&we){H=await V.release(),M&&(L=await this.settleCheckpoint(M,!1)),Y=!0,Z(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:k,code:we.code,muted:dt(H),details:Vn(z.emails)});let N=Zw(we.message,"autopilot","Untick Mute automation to be asked about them and run it all the same"),X=new Error(N);this.liveTracker?.fail(e.id,N),E(this.deps,"autopilot:execute","autopilot:error",e,X,{code:Us.EMAILS_NOT_ACCEPTED,...L?{extraPayload:{checkpoint:L}}:{}}),g(X);return}ee=!0;let re=await this.orchestrator.executePlan(r,n,o,i.recordCounts,N=>{let X=String(N.objectApiName);U.set(X,{...ft(X),...N.type==="node-completed"?{created:N.successCount,failed:N.failureCount}:{created:N.partialSuccessCount,failed:N.failureCount??0}});let F=[...U.values()].reduce((de,J)=>de+J.created+J.failed,0);this.liveTracker?.updateProgress(e.id,l>0?Math.round(F/l*100):0,F,l,X),N.type==="node-completed"?this.sendNodeProgress(e,X,"completed",B.get(X)??0,{recordCount:N.successCount,failureCount:N.failureCount,linkedCount:N.linkedCount,refusals:N.refusals,apiCallsUsed:N.apiCallsUsed}):this.sendNodeProgress(e,X,"failed",B.get(X)??0,{recordCount:N.partialSuccessCount,failureCount:N.failureCount,linkedCount:N.linkedCount,refusals:N.refusals,error:N.errors[0]??`Execution failed for ${X}`})},p.signal,i.parentIds,{...d.keepContactPoints===!0?{keepContactPoints:!0}:{},...V?{lease:{assigned:V.outcome.assigned.length,giveBack:()=>V.release()}}:{},...a?{fit:a.run}:{}}).finally(async()=>{V&&(H=await V.release())});M&&(L=await this.settleCheckpoint(M,re.totalSuccess>0));let Ae=new Set(re.completedObjects),he=new Set(re.failedObjects),Je=new Set(re.skippedObjects),Ne=new Set(re.stoppedObjects??[]),Fe=[],W=0,se=[],te=[];for(let N of r.waves)for(let X of N.objects){let F=String(X),de=re.objectOutcomes?.[F],J=re.statuses?.[F],le=re.lookups?.[F],Ee=(de?.leftToThePlatform??[]).reduce((Ue,ot)=>Ue+ot.count,0),je={...de?{recordCount:de.written,failureCount:de.failed,linkedCount:de.linked,refusals:de.refusals,...Ee>0?{leftToThePlatform:Ee}:{},...de.currenciesReplaced?{currenciesReplaced:de.currenciesReplaced}:{},...de.pricesSettled?{pricesSettled:de.pricesSettled}:{},...de.recordTypeGiven?{recordTypeGiven:de.recordTypeGiven}:{},...de.cutSinceFit!==void 0?{cutSinceFit:de.cutSinceFit}:{},...de.sentAgainForALock?{sentAgainForALock:de.sentAgainForALock}:{}}:{},...J?{statusesApplied:J.applied,statusRefusals:J.refusals}:{},...le?{lookupsFilled:le.filled,lookupRefusals:le.refusals}:{}};if(Ae.has(F))this.sendNodeProgress(e,F,"completed",N.order,{recordCount:i.recordCounts.get(F)??0,failureCount:0,...je});else if(he.has(F))this.sendNodeProgress(e,F,"failed",N.order,{...je,error:re.nodeErrors?.[F]??`Execution failed for ${F}`});else if(Je.has(F)){let Ue=i.recordCounts.get(F)??0;U.set(F,{...ft(F),skipped:"counted",...Ue>0?{notSent:Ue}:{}}),this.sendNodeProgress(e,F,"skipped",N.order,{recordCount:0,failureCount:0,...Ue>0?{notSent:Ue}:{}})}else if(Ne.has(F)){let Ue=de?.notSent??0;W+=de?.heldForTheirTask??0,U.set(F,{...ft(F),created:de?.written??0,failed:de?.failed??0,...Ue>0?{notSent:Ue}:{}}),this.sendNodeProgress(e,F,"stopped",N.order,{...je,recordCount:de?.written??0,failureCount:de?.failed??0,...Ue>0?{notSent:Ue}:{}})}let We=()=>U.get(F)??{...ft(F),created:de?.written??0,failed:de?.failed??0},ae=de?.lookupsLeftEmpty??0,be=de?.statusesNotGivenBack??0;if(ae+be>0){let Ue={...ae>0?{lookupsLeftEmpty:ae}:{},...be>0?{statusesNotGivenBack:be}:{}};Fe.push({objectApiName:F,...Ue}),U.set(F,{...We(),...Ue})}le?.leftEmpty!==void 0&&(se.push({objectApiName:F,records:le.leftEmpty,refusals:le.refusals}),U.set(F,{...We(),lookupsNotFilled:le.leftEmpty}));let He=J?.leftDraft??0;J&&He>0&&(te.push({objectApiName:F,records:He,refusals:J.refusals}),U.set(F,{...We(),statusesNotApplied:He}))}let ue=rR(re);Q(re.stopped?re.totalSuccess+re.totalFailure>0?"cancelled":"stopped":ue);let $=T(this.deps,e,"autopilot:completed",{status:ue,totalRecords:re.totalSuccess+re.totalFailure+re.totalSkipped,totalSuccessCount:re.totalSuccess,totalFailureCount:re.totalFailure,totalElapsedMs:re.elapsedMs,totalApiCalls:0,...H?{mutedAutomation:H}:{},...L?{checkpoint:L}:{},...re.cutSinceFit!==void 0?{cutSinceFit:re.cutSinceFit}:{},...se.length>0?{lookupsNotFilled:se}:{},...te.length>0?{statusesNotApplied:te}:{},...re.stopped?{stopped:!0,notWritten:re.stoppedObjects??[],...Fe.length>0?{leftByStop:Fe}:{},...W>0?{emailsHeldForTheirTask:W}:{}}:{}});this.deps.broker.postToWebview($),re.stopped?this.liveTracker?.cancel(e.id):ue==="failure"?this.liveTracker?.fail(e.id,re.fatalError??"No record could be written."):ue==="partial"?this.liveTracker?.partial(e.id):this.liveTracker?.complete(e.id),g()}catch(B){this.liveTracker?.fail(e.id,I(B)),g(B),M&&L===void 0&&(L=await this.settleCheckpoint(M,ee)),Q("failure"),E(this.deps,"autopilot:execute","autopilot:error",e,B,L?{extraPayload:{checkpoint:L}}:void 0),Ie(this.deps,"error","Autopilot",`Execution failed: ${I(B)}`)}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),Ci):5e4}confirmAboveRecords(){let e=this.deps.services?.getSandforgeSetting?.("safety.confirmAboveRecords",Yr);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):Yr}async readTargetDataStorage(e){try{let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return await new ge(hg).withTimeout("autopilot:limits",()=>br(t))}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 kt(async()=>Mt(await q(e,this.deps.orgRegistry,this.deps.orgManager)),t,{...this.muteLeases,writes:mg})}async readTargetAutomation(e,t){let r=this.targetAutomation;return new ge(ZI).withTimeout("autopilot:automation",()=>r.read(e,ja(t))).catch(n=>({unread:I(n)}))}async checkpointFirstOf(e,t,r,n,o,i){let a=this.beforeRunCheckpoints;if(!a)return{refused:wr(new Error("SandForge's checkpoints are not set up in this window"))};let{read:d,mute:c}=o,l="objects"in d?qr(d,c?.plan,mg):{firing:[]},u={module:"autopilot",orgId:t,operationId:e.id,written:ja(r),running:l,request:n},p={operationId:eA(e.id)};try{return{estimate:await a.scope(u,p),take:h=>a.take(u,p,{planned:h,signal:i})}}catch(g){return{refused:wr(g)}}}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:me(a,o),estimateMB:i.estimateMB,...i.verdict==="unread"?{}:{remainingMB:i.remainingMB,maxMB:i.maxMB}};try{let c=await this.planWriteGate(o,r,await this.readTargetDataStorage(o),n?.estimate);return{extraPayload:{...d,writeGate:c}}}catch(c){return this.deps.log(`[WARN] autopilot:execute: what the plan comes to could not be read again (${I(c)})`),{extraPayload:d}}}async readTargetApiBudget(e){let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return new ge(hg).withTimeout("autopilot:limits",()=>ar(t))}async targetEmails(e,t,r,n){let o=this.targetAutomation,i=await oR({plan:r,objects:ja(t),readAutomation:a=>n?"objects"in n?Promise.resolve(n):Promise.reject(new Error(n.unread)):new ge(ZI).withTimeout("autopilot:automation",()=>o.read(e,a)),readLimits:async()=>{let a=await q(e,this.deps.orgRegistry,this.deps.orgManager);return new ge(hg).withTimeout("autopilot:limits",()=>Sr(a))}});i.unread!==void 0&&this.deps.log(`[WARN] autopilot:execute: the emails the target's flows send were not counted: ${i.unread} could not be read`);for(let a of i.checks.filter(d=>d.verdict==="unread"))this.deps.log(`[WARN] autopilot:execute: about ${a.emails} ${a.limit} from the target's flows, against a limit that could not be read: ${a.unread??""}`);return i}sendNodeProgress(e,t,r,n,o){let i=T(this.deps,e,"autopilot:node-progress",{nodeId:t,objectName:t,status:r,wave:n,...o??{}});this.deps.broker.postToWebview(i)}hasExecutingOperation(){return this.executingOperations.size>0}handlePause(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}if(!this.hasExecutingOperation()){Ie(this.deps,"warning","Autopilot","No autopilot execution in progress.");return}try{this.orchestrator.pause();for(let t of this.runningRequests)this.liveTracker?.pause(t);Ie(this.deps,"info","Autopilot","Execution paused.")}catch(t){E(this.deps,"autopilot:pause","autopilot:error",e,t),Ie(this.deps,"error","Autopilot",`Pause failed: ${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){E(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=x(ey,e,"autopilot:error",this.deps);if(!t)return;let r=t;if(!this.hasExecutingOperation()){Ie(this.deps,"warning","Autopilot","No autopilot execution in progress.");return}try{this.orchestrator.skip(r.objectApiName),Ie(this.deps,"info","Autopilot",`Skipped node: ${r.objectApiName}`)}catch(n){E(this.deps,"autopilot:skip-node","autopilot:error",e,n),Ie(this.deps,"error","Autopilot",`Skip failed: ${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=T(this.deps,e,"autopilot:compliance-report",{report:n});this.deps.broker.postToWebview(o)}catch(r){E(this.deps,"autopilot:compliance-report","autopilot:error",e,r),Ie(this.deps,"error","Autopilot",`Report generation failed: ${I(r)}`)}}};import{dirname as Rg}from"node:path";import{AsyncLocalStorage as CN}from"node:async_hooks";var $N=new CN;async function tA(s){let e=new Map;return{result:await $N.run(e,s),sent:e}}function rA(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 yg from"node:path";var Dc="forge:imported-templates",xN=10,nA="forge",DN=G({folder:j().min(1),templates:Re(un()),replacing:Re(j())});function cn(s){if(typeof s!="object"||s===null||Array.isArray(s))return!1;let{id:e}=s;return typeof e=="string"&&e.length>0}function mi(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 wg(s,e){return yg.resolve(s)===yg.resolve(e)}function bg(s){let e=s.get(Dc);if(!Array.isArray(e))return[];let t=[];for(let r of e){let n=DN.safeParse(r);if(!n.success)continue;let{folder:o,templates:i,replacing:a}=n.data;t.push({folder:o,templates:i.filter(cn),replacing:a})}return t}function Nc(s,e){return bg(s).find(t=>wg(t.folder,e))}function oA(s,e,t,r){if(t.length===0)return;let n=bg(s),o=n.findIndex(d=>wg(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(Dc,n.slice(-xN),nA)}function sA(s,e){let t=bg(s).filter(r=>!wg(r.folder,e));t.length>0?s.set(Dc,t,nA):s.delete(Dc)}function NN(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 jN(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:NN(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 iA(s){let{leftOut:e,...t}=s.graph,r=new Map;for(let u of e??[])r.set(u.reason,(r.get(u.reason)??0)+1);let n=[...r].map(([u,p])=>({reason:u,count:p})).sort((u,p)=>p.count-u.count||u.reason.localeCompare(p.reason)),{idRemapWithTheirRecord:o,sample:i,config:a,...d}=s,c=s.remapInJournal?void 0:o,l=a?.sample?{...a.sample}:void 0;return l&&delete l.plan,{...d,graph:{...t,edges:[],withoutEdges:!0},...a?{config:l?{...a,sample:l}:a}:{},...i?{sample:jN(i)}:{},...n.length>0?{leftOutCounts:n}:{},...c?{idRemapWithTheirRecord:c}:{}}}var aA="SELECT Id, Name, Username FROM User WHERE IsActive = true AND UserType = 'Standard' ORDER BY Name LIMIT 2001";function dA(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 Ig=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/,co=j().min(1).max(128),LN=G({recordId:j().regex(Ig,"Invalid Salesforce record ID"),orgId:co}),Mn=tf.superRefine((s,e)=>{if(s.inputMode!=="org"&&s.depth!=="all"&&s.sample===void 0)return;let t=Dl(s);t!==void 0&&e.addIssue({code:"custom",message:t,path:["inputMode"]});let r=FN(s.sample);r!==void 0&&e.addIssue({code:"custom",message:r.message,path:r.path})});function FN(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 _N=G({config:Mn}),HN=G({graph:Fr,config:Mn,anonymizationRules:$i.optional(),files:nf.optional(),retryOf:j().min(1).max(200).optional(),reviewSkipped:Ge().optional(),muteAutomation:Ge().optional(),checkpointFirst:jh.optional()}).superRefine((s,e)=>{let t=rf(s.config,s.files);t!==void 0&&e.addIssue({code:"custom",message:t,path:["files"]})});function UN(s,e){let t=s.check(e);return{check:t,decision:t.allowed?"allowed":"refused"}}var cA="FILES_NOT_ACCEPTED",lA="RETRY_UNAVAILABLE",BN="GRAPH_WITHOUT_EDGES",qN="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.",WN="WHOLE_ORG_DIRECT",zN="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.",GN="WHOLE_ORG_REHEARSAL",JN="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.",VN="A clone of the whole org keeps its journal on disk, which could not be opened. Nothing was written.",Sg="JOURNAL_UNAVAILABLE",XN="RESUME_TARGET_UNREAD",ln=class extends Error{constructor(t,r){super(r);this.code=t;this.name="ForgeRunRefusal"}code};function uA(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 KN(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 Mc="A checkpoint taken before the run takes the org back (Checkpoints \u2192 Rewind\u2026); without one, DataOps \u2192 Cleanup \u2192 Empty objects empties its objects, every record of them.",rs="JOURNAL_GONE",Nn=`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. ${Mc}`,ns="RUN_NOT_IN_HISTORY",vg="REMOVAL_RUNNING",yi="RUN_WRITING",YN="VERIFY_RUNNING",pA="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.",QN="RESUME_UNAVAILABLE",gA="remove the records it created (Forge \u2192 Recent runs), then run the clone again. Nothing was read or written.",fA="RESUME_TARGET_CHANGED",kg="RESUME_CHANGED",ZN=G({forgeId:j().min(1).max(200),graph:Fr.optional(),config:Mn.optional(),muteAutomation:Ge().optional()}).strict(),hA=new Set(["cancelled","failure","interrupted"]),jn="Forge execution was aborted before it started. Nothing was written.",Og="FORGE_RUNNING",ej="FORGE_STOP_AMBIGUOUS",tj={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.`}},rj=G({requestId:j().min(1).max(200).optional()}).optional(),nj=G({template:Nl}),oj=G({forgeId:j().min(1).max(200),includeChanged:Ge().optional(),sweep:Ge().optional(),again:Ge().optional(),muteAutomation:Ge().optional(),sweepLate:Ge().optional(),sweepUntied:Ge().optional()}),sj=G({forgeId:j().min(1).max(200),again:Ge().optional(),sweptObjects:Nh.optional()}),ij=G({forgeId:j().min(1).max(200)}),aj=G({forgeId:j().min(1).max(200),recordId:j().regex(Ig,"Invalid Salesforce record ID")}).strict(),dj=G({forgeId:j().min(1).max(200)}).strict(),cj=G({forgeId:j().min(1).max(200)}).strict(),lj=5e3,uj=G({templateId:j().min(1).max(200)}),pj=G({graph:Fr,config:Mn}),gj=G({framework:j().min(1).max(50),graph:Fr,config:Mn,anonymizationRules:$i.optional()}),fj=G({sourceOrgId:co,targetOrgId:co,objectApiNames:Re(j().regex(/^[A-Za-z][A-Za-z0-9_]*$/).max(80)).max(100)}),hj=G({graph:Fr,config:Mn,anonymizationRules:$i.optional()}),mj=G({targetOrgId:co,graph:Fr}),yj=G({graph:Fr,config:Mn}),wj=G({orgId:co}),bj=G({targetOrgId:co,objectApiNames:Re(j().min(1).max(255)).max(5e3)}),Rj=G({graph:Fr,config:Mn,muteAutomation:Ge().optional()}).refine(s=>s.config.inputMode==="org",{message:"A sample is drawn from a clone of the whole org alone (inputMode org, depth all)",path:["config","inputMode"]}),Sj=G({sourceOrgId:co,soqlQuery:j().min(1).max(2e4),maxRoots:Te().int().min(1).max(Zg).optional()}),vj=[[/ 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."]],kj=[[/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"]],PA=new Set(["SAMPLE_DRAW_INVALID","SAMPLE_DRAW_EMPTY"]);function Oj(s){if(s.code==="ROOTS_EXCEEDED")return new lt(s.code,kj.reduce((t,[r,n])=>t.replace(r,n),s.message));if(!PA.has(s.code))return s;let e=vj.reduce((t,[r,n])=>t.replace(r,n),s.message);return new lt(s.code,e,void 0,void 0,void 0,{...s.sample?{sample:s.sample}:{}})}var Ij="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.",Aj="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.",Tj=16;function mA(s){let e=s.fit();return e?{fit:e}:{}}function jc(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 Ej(){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 nt(s,e,t,r){return x(s,e,t,r)}var Pj={holder:s=>_R(s),take:(s,e)=>{let t=FR(s,{...e,ranFrom:"editor"});return"busy"in t?t:{release:()=>t.lock.release()}}};function wi(s){return s.charAt(0).toUpperCase()+s.slice(1)}function Cj(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 yA(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 $j(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 xj(s,e){let t=s.remap.createdByObject.reduce((d,c)=>d+c.sourceIds.length,0),r=Object.keys(s.remap.table).length,n=$j(s),o=new Set(s.remap.withTheirRecord??[]),i=s.remap.linked.filter(d=>o.has(d)),a=r>La?{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 Dj=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"]),bA=3e4,Nj=6e4,jj=3e4,Mj=6e4,bi=6e4,Lj=12e4;function RA(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 SA="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.",Fj=6e4,_j=10*6e4,Hj=8,Uj=8,os=3e4,Bj=3e4,vA="forge:templates",kA="forge:history";function qj(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 Wj(s,e,t,r){let n=new Map;for(let i of[...e,...t])i.retryOf!==void 0&&!n.has(i.forgeId)&&n.set(i.forgeId,i.retryOf);let o=i=>{let a=new Set;for(let d=n.get(i);d!==void 0;d=n.get(d)){if(d===s)return!0;if(a.has(d))return!1;a.add(d)}return!1};return e.flatMap(i=>{if(!i.resumed||i.remapInJournal||i.targetOrgId!==r)return[];if(!o(i.forgeId))return[];let a=i.idRemapTable??{},d=(i.idRemapExisting??[]).flatMap(l=>{let u=a[l];return u!==void 0?[u]:[]}),c=i.wroteToEarlierParts??[];return c.length===0&&d.length===0?[]:[{span:CA(i.writtenBetween,i),...c.length>0?{wrote:c}:{},...d.length>0?{linked:d}:{}}]})}function CA(s,e){return s?{runStartedAt:new Date(s.first),runEndedAt:new Date(s.last)}:{runDurationMs:e.duration,runRecordedAt:new Date(e.timestamp)}}function zj(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=Rn(r.objects,n),i=t.filter(a=>o.includes(a));return i.length>0?[{forgeId:r.forgeId,objects:i}]:[]})}function Gj(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 Jj(s){return(s.mayHaveBeenWritten??[]).reduce((e,{sourceIds:t})=>e+t.length,0)}function Vj(s,e){if(!e||e.calls===0)return Jj({mayHaveBeenWritten:s});let t=e.lookedFor??new Set,r=(s??[]).reduce((n,{sourceIds:o})=>n+o.filter(i=>!t.has(i)).length,0);return $u(e)+r}function Xj(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 Kj(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 OA="forge";function Yj(s){let e={...s};return delete e.sourceOrgId,delete e.targetOrgId,e}function Qj(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:Zj(e)}:{},...s.failedReads?.length?{failedReads:s.failedReads}:{}}}function Zj(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 e0(s,e){let t=s.nodes.filter(d=>d.included),r=t.map(d=>d.objectApiName).join(", ")||"ForgeData",n=Fw,o=e.inputMode==="org"?void 0:e.maxRecordsPerObject,i=xl(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 t0(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 IA(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 AA(s,e){let t=(e.nodes??[]).map(r=>r.objectApiName).sort();return JSON.stringify([s.sourceOrgId,s.targetOrgId,t])}function r0(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 TA(s,e){return s.apiCalls===void 0?s:{...s,apiCalls:s.apiCalls+e}}function EA(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 n0(s){return s instanceof Error&&s.name==="ForgeAbortedError"}var Lc=class extends Error{constructor(t,r){super(r);this.code=t;this.name="RehearsalStoppedError"}code};function o0(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 Fc=class s{constructor(e,t,r){this.deps=e;this.externalBrowser=t??new Cr,this.saveDialog=r??new vn}deps;abortController=null;stops=new $R;executeOperationId=null;writingTo=null;orchestrator;planGenerator;complianceService;metadataDiff;targetAutomation;targetGaps;requestsSent;muteOrgOf;muteLeases;lostBulkJobs;beforeRunCheckpoints;rehearser;rehearseOperationId=null;templateStore;removalPlans;runJournal;otherModuleRuns=()=>Promise.resolve([]);journalsRunning=new Set;journalLocks=Pj;describeGlobalCache=new Bs({defaultTtl:5*6e4,maxSize:16,maxSizeBytes:50*1024*1024});dmlTracker=new ea;removing=new Set;trials=new MR;simulations=new Ob;sampleSimulations=new Map;verifying=new Set;automationReads=new Map;automationReadAgain=new Set;discoverySent=new Map;liveTracker;lastWriteAt=new Map;static DUPLICATE_COOLDOWN_MS=6e4;static MAX_HISTORY=20;externalBrowser;saveDialog;forgetOrg(e){this.describeGlobalCache.invalidate(e),this.orchestrator?.clearDiscoveryCache([e]);for(let[t,r]of this.automationReads)r.orgId===e&&this.automationReads.delete(t)}setForgeOrchestrator(e,t){this.orchestrator=e,t&&(this.planGenerator=t.planGenerator,this.complianceService=t.complianceService,this.metadataDiff=t.metadataDiff,this.targetAutomation=t.targetAutomation,this.targetGaps=t.targetGaps,this.templateStore=t.templateStore,this.removalPlans=t.removalPlans,this.runJournal=t.runJournal,this.requestsSent=t.requestsSent,this.muteOrgOf=t.muteOrg,this.muteLeases=t.muteLeases,this.lostBulkJobs=t.lostBulkJobs,this.rehearser=t.rehearser,t.journalLocks&&(this.journalLocks=t.journalLocks))}setLiveOperationTracker(e){this.liveTracker=e}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}trackRun(e,t,r,n=!1){let o=this.deps.infraServices?.backgroundRegistry;if(!o)return()=>{};let i=()=>{},a=new Promise((c,l)=>{i=u=>{u===void 0?c():l(u instanceof Error?u:new Error(String(u)))}}),d=new AbortController;return d.signal.addEventListener("abort",()=>{r.abort(),n&&this.orchestrator?.abort()},{once:!0}),o.register(e,"forge",t,a,d),i}isWritingTo(e,t){return this.writingTo===e&&(t===void 0||t!==this.executeOperationId)}async handle(e){if(!Dj.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(cn):[]}}return this.withImportedTemplates(this.templateStore)}async withImportedTemplates(e){let t=Nc(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 sA(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,OA);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,OA)}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=nt(LN,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 w=await o.describeGlobal();$e(o.limitInfo,"forge:preview describeGlobal"),a=w.sobjects.map(O=>({name:O.name,label:O.label,keyPrefix:O.keyPrefix??null})),this.describeGlobalCache.set(n,a)}let d=a.find(w=>w.keyPrefix===i),c=me(this.deps.orgManager.getOrg(n),n),l=(w,O)=>{this.deps.broker.postToWebview(T(this.deps,e,"forge:preview:error",{code:w,orgName:c,message:O}))};if(!d){l("UNKNOWN_KEY_PREFIX",`No object of ${c} has ids starting "${i}": the record is read from the source org picked.`);return}let u=await Sh(o,d.name,`SELECT FIELDS(STANDARD) FROM ${d.name} WHERE Id = '${Zt(r)}' LIMIT 1`);if($e(o.limitInfo,`forge:preview query ${d.name}`),!u||u.length===0){l("RECORD_NOT_FOUND",`Record ${r} is not in ${c}, or the user connected there cannot see it: the record is read from the source org picked.`);return}let p=u[0],g=new Set(["attributes","Id"]),h=Object.entries(p).filter(([w])=>!g.has(w)).filter(([,w])=>w!=null&&String(w)!=="").slice(0,8).map(([w,O])=>({name:w,value:String(O)})),f=await o.describe(d.name);$e(o.limitInfo,`forge:preview describe ${d.name}`);let m=f.fields.length,y=0;try{y=(await o.query(`SELECT COUNT() FROM ${d.name}`)).totalSize}catch{}let R=y*.001,k=T(this.deps,e,"forge:preview:response",{objectApiName:d.name,objectLabel:d.label,recordId:r,fields:h,estimatedRecordCount:y,totalFieldCount:m,estimatedSize:R});this.deps.broker.postToWebview(k)}catch(o){E(this.deps,"forge:preview","forge:preview:error",e,o,{code:"PREVIEW_ERROR"})}}async handleDiscover(e){if(!this.orchestrator){E(this.deps,"forge:discover","forge:discover:error",e,new Error("Forge module is not initialized"),{code:"NOT_INITIALIZED"});return}let t=nt(_N,e,"forge:discover:error",this.deps);if(!t)return;let r=this.withMaxRoots(t.config),n=new AbortController,o=`forge-discover-${this.deps.nextId()}`,{discovery:i,superseded:a}=this.stops.beginDiscovery(e.id,n,o);for(let u of a)this.stopDiscovery(u);ze(this.deps,o,"forge","Discovering object graph");let d=this.trackRun(o,"Discovering object graph",n),c,l=jc(u=>{let p=T(this.deps,e,"forge:discover:progress",u);this.deps.broker.postToWebview(p)},100);try{oe.info("Forge discover started");let u=this.orchestrator,{result:p,sent:g}=await tA(()=>u.discover(r,{...r.inputMode==="org"?{}:{maxNodes:r.maxNodes},signal:n.signal,onProgress:y=>{l(y)}}));if(l.flush(),n.signal.aborted){pe(this.deps,o,{aborted:!0}),this.answerStoppedDiscovery(e,i);return}let h=rA(g,r),f=AA(r,p);this.discoverySent.delete(f),h&&this.discoverySent.set(f,h);for(let y of this.discoverySent.keys()){if(this.discoverySent.size<=Uj)break;this.discoverySent.delete(y)}let m=T(this.deps,e,"forge:discover:response",{graph:h?{...p,discoveryRequests:h}:p});this.deps.broker.replyToRequester(m),pe(this.deps,o,{nodeCount:p.nodes?.length??0}),oe.info("Forge discover finished",{objects:p.nodes?.length??0,records:p.totalRecords})}catch(u){if(l.flush(),n.signal.aborted){pe(this.deps,o,{aborted:!0}),this.answerStoppedDiscovery(e,i);return}c=u,E(this.deps,"forge:discover","forge:discover:error",e,u,{code:"DISCOVER_ERROR",retryable:!0}),De(this.deps,o,I(u),!0)}finally{d(c),this.stops.endDiscovery(i)}}stopDiscovery(e){this.deps.infraServices?.backgroundRegistry?.abort(e.operationId),e.controller.abort()}answerStoppedDiscovery(e,t){let{code:r,message:n}=tj[t.stop??"stopped"];E(this.deps,"forge:discover","forge:discover:error",e,new Error(n),{code:r,retryable:!0})}async handleExecute(e,t){if(!this.orchestrator){E(this.deps,"forge:execute","forge:execute:error",e,new Error("Forge module is not initialized"),{code:"NOT_INITIALIZED"});return}let r=t?t.startedWith:nt(HN,e,"forge:execute:error",this.deps);if(!r)return;let{graph:n,anonymizationRules:o,files:i,reviewSkipped:a,muteAutomation:d}=r,c=this.withMaxRoots(r.config),l=t?t.forgeId:r.retryOf,u=l!==void 0?Cj(l,this.loadHistory()):void 0,p=l===void 0?r.checkpointFirst:void 0;l!==void 0&&r.checkpointFirst!==void 0&&oe.info("Forge run: no checkpoint taken for a retry or a resume, which takes up a run that wrote",{checkpoint:u?.checkpointId??"none"});let g=c.dryRun===!0,h=Nu(n,c),f=kb(c),m=new LR(c,{reviewSkipped:a===!0,...this.trials.before(h)}),y=c.inputMode==="org",R=y&&c.sample!==void 0,k=(Me,Xe)=>{g||Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:Me,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(Xe),{code:Me})};if(n.withoutEdges===!0){k(BN,qN);return}if(y&&a===!0){k(WN,zN);return}let w=y?TR(n):void 0;if(w){k(w.code,w.message);return}let O=i?Qg(c.anonymizePII,i.acceptedAsIs):null;if(O){Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:cA,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(O),{code:cA});return}let P,b,v;if(l!==void 0&&!t){let Me=await this.runToRetry(l,c.targetOrgId);if("refused"in Me){Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:lA,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(Me.refused),{code:lA});return}P=Me.written,b=Me.journalId!==void 0?{journalId:Me.journalId}:{},v=Me.roots}let C=this.deps.infraServices?.productionGuard;if(!C){Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:Se.code,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(Se.message),{code:Se.code});return}let S=this.deps.orgManager.getOrg(c.targetOrgId),A=Ce(S),D=me(S,c.targetOrgId);if(A==="production"){this.refuseAtGate(e,c.targetOrgId,new lt("PRODUCTION_TARGET",`${D} is a production org, or an org SandForge cannot tell is a sandbox, a scratch org or a Developer Edition org: Forge writes to those only. Nothing was read or written.`),void 0,m.context());return}let z=await this.ownerMapRefusal(c);if(z){g||Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",code:z.code,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,z,{code:z.code,retryable:!0});return}let U={orgId:c.targetOrgId,orgTier:A,operation:"insert",...e0(n,c),module:"forge"},Y=new AbortController,H=this.stops.awaitGuard(e.id,Y),{check:M,decision:L}=g?UN(C,U):await Ze(C,U).finally(H);g&&H();let ee=L;if(M.warnings.length>0&&oe.warn("Forge run: Production Guard warnings",{warnings:M.warnings}),(L==="refused"||L==="declined")&&Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",guard:L,context:m.context()}),L==="refused"){E(this.deps,"forge:execute","forge:execute:error",e,new Error(`Operation blocked by Production Guard: ${M.blockedReason??M.impactSummary}`),{code:"GUARD_BLOCKED"});return}if(L==="declined"){E(this.deps,"forge:execute","forge:execute:error",e,new Error("Operation cancelled by user (confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}if(Y.signal.aborted){Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",guard:L,code:bt,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(jn),{code:bt,retryable:!0});return}let Q=`${c.sourceOrgId}:${c.targetOrgId}:${c.recordId??""}`,B=n.nodes?.map(Me=>Me.objectApiName).join(",")??"",V=`forge:${Q}:${B}:${n.totalRecords??0}`+(l!==void 0?`:${t?"resume":"retry"}:${l}`:""),we=this.dmlTracker.isDuplicate(V)?this.dmlTracker.get(V):void 0,ie=this.lastWriteAt.get(V),re=ie!==void 0&&Date.now()-ie<s.DUPLICATE_COOLDOWN_MS;if(we?.status==="pending"||re){oe.warn("Duplicate forge execution detected",{operationId:V}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(`Duplicate forge operation: ${V}`),{code:"DUPLICATE"});return}if(this.executeOperationId!==null){Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:c.targetOrgId,outcome:"stopped",guard:L,code:Og,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error("Another Forge run is still under way in this window: start this one once it has ended. A run asked to stop ends once the step under way is done."),{code:Og,retryable:!0});return}let Ae=n.totalRecords??0;we?(we.status="pending",we.recordCount=Ae,we.registeredAt=new Date().toISOString()):this.dmlTracker.register(V,"forge","upsert",Ae),this.abortController=Y;let he=`forge-execute-${this.deps.nextId()}`,Je=g?"Simulating forge operation":"Executing forge operation";ze(this.deps,he,"forge",Je);let Ne=this.trackRun(he,Je,Y,!0);this.liveTracker?.register(he,"forge",Je),this.executeOperationId=he,this.writingTo=g?null:c.targetOrgId,this.stops.beginRun(e.id,Y);let Fe=Date.now(),W,se,te,ue,$,N=!1,X=()=>{N||!se||(N=!0,se.close())},F={keep:!1},de=!1,J,le=async()=>{if(!W||de)return;de=!0;let Me=W,Xe=F;X(),await(Xe.keep?this.runJournal?.stop(Me,Xe.status,Xe.forgeId):this.runJournal?.end(Me))?.catch(Ke=>{oe.warn(`Forge run journal not ${Xe.keep?"kept":"dropped"}: ${I(Ke)}`)}),this.journalsRunning.delete(Me),J?.release(),J=void 0},Ee={requests:0},je,We=()=>{let Me=this.requestsSent?.();return Me===void 0||je===void 0?void 0:Ee.requests+Me-je},ae,be=!1,He=[],Ue,ot=0,Ve,Fn,Ht,ds,Yt=[],Ii,lo=()=>(Ii??=this.jobsStillRunning(c.targetOrgId,ds,Ee).then(Me=>{Yt=Me}),Ii),uo,Dr={firing:[]},Ai,Nr,cs,pr,Ti=!1,Dt,_n,ls=jc(Me=>{let Xe=T(this.deps,e,"forge:progress",Me);this.deps.broker.postToWebview(Xe)},100),Hn=jc(Me=>{this.deps.broker.postToWebview(T(this.deps,e,"forge:sampling:progress",{...Me}))},100),jr=this.liveProgressOf(he,n),Cl=Ej(),Un=this.orchestrator.on("forge:progress",Me=>{let Xe=Cl(Me),Ke=We(),st=Ke===void 0?Xe:{...Xe,apiCalls:Ke};jr(st);let Tt=st.status;if(Tt==="done"||Tt==="error"||Tt==="skipped"||Tt==="stopped"){ls.flush();let et=T(this.deps,e,"forge:progress",st);this.deps.broker.postToWebview(et);return}ls(st)});try{oe.info("Forge execute started",{source:me(this.deps.orgManager.getOrg(c.sourceOrgId),"unknown org"),target:me(this.deps.orgManager.getOrg(c.targetOrgId),"unknown org")});let Me=this.maxRecordsPerObject(),Xe=Ou(n,{leftOut:new Set(n.nodes.filter(Hi).map(ne=>ne.objectApiName)),retry:l!==void 0}),Ke=new Set(Xe.map(ne=>ne.objectApiName)),st=(ne,Pe)=>Pe==="insert"||Pe==="update"&&Ke.has(ne);if(g){if(p!==void 0||y||R){let ne=await this.automationBeforeTheRun(c.targetOrgId,n);if("automation"in ne){let Pe=d===!0?await kt(()=>this.muteOrg(c.targetOrgId),ne.automation,{...this.muteLeases,writes:st}).then(Be=>Be.plan,Be=>{oe.warn(`Forge simulation: the mute could not be planned (${I(Be)})`)}):void 0;Dr=qr(ne.automation,Pe,st),Ai=Pe}}}else{let ne=await this.automationBeforeTheRun(c.targetOrgId,n);ot=An("automation"in ne?ne.automation:ne);let Pe=ne,Be;if(d===!0){let ht=await kt(()=>this.muteOrg(c.targetOrgId),"automation"in ne?ne.automation:ne,{...this.muteLeases,writes:st});Fn=ht.prepared,Ht=ht.muted,Be=ht.plan,"automation"in ne&&ht.automation&&(Pe={...ne,automation:ht.automation})}if("automation"in ne&&(Dr=qr(ne.automation,Be,st)),Ue=Pe,"automation"in Pe&&(He=If(Pe.automation)),Y.signal.aborted)throw be=!0,new Error(jn);if(m.automationRead(Pe,Xe),pr=await ir({read:"automation"in ne?ne.automation:ne,...Be?{plan:Be}:{},writes:st,applyAssignmentRules:c.applyAssignmentRules===!0,readDeliverability:()=>this.readDeliverability(c.targetOrgId,Y.signal),accepted:!1,target:D,run:"clone",keepsAddresses:c.keepContactPoints===!0}),Ee.requests+=pr.ofRun.read?.requests??0,Y.signal.aborted)throw be=!0,new Error(jn);m.emailsRead(pr.gate.audit);let vt=await this.confirmAutomation(C,{orgId:c.targetOrgId,org:D,orgTier:A,username:S?.username},Pe,Xe,a===!0,pr.gate.confirmation);vt==="confirmed"&&(m.confirm("automation"),pr.gate.verdict==="asks"&&(Ti=!0,m.confirm("emails"))),ee=Ms(ee,vt);let it=y?[]:vb(n,c.maxRecordsPerObject,Me);if(it.length>0){if(Y.signal.aborted)throw be=!0,new Error(jn);let ht=await this.confirmReadCeiling(C,{org:D,orgTier:A,source:me(this.deps.orgManager.getOrg(c.sourceOrgId),c.sourceOrgId)},it,Me);ht==="confirmed"&&m.confirm("volume"),ee=Ms(ee,ht)}}if(Y.signal.aborted)throw be=!0,new Error(jn);let Tt=g?void 0:this.runUserOf(c.targetOrgId),et=await this.loadRecordTypeMappings(c,Y.signal,Ee);if(Y.signal.aborted)throw be=!0,new Error(jn);te=await Tt,Fe=Date.now(),je=this.requestsSent?.(),ds=this.lostBulkJobs?.count;let gt=g?void 0:this.runJournal,Mr;if(gt){let ne=t?.journalId??`forge-run-${Fe}`,Pe;try{Pe=this.journalLocks.take(gt.pathOf(ne),{journalId:ne,target:D,...t?{resumes:!0}:{}})}catch(it){oe.warn(`Forge run journal: its lock not taken (${I(it)})`)}if(Pe&&"busy"in Pe)throw new ln(yi,`${wi(_a(Pe.busy))}: taken up now, two runs would write it; ${Ha(Pe.busy)}, then resume it. Nothing was written.`);J=Pe,W=ne,this.journalsRunning.add(ne);let Be=it=>new ln(XN,`${D} could not be read for the insert calls the run had under way when it stopped (${I(it)}): taken up without them, the run would write their records twice. Reconnect ${D} on Organizations if its session expired, then resume the run again. Nothing was written.`);if(se=await(t?gt.resuming(ne).then(async()=>{let it=await q(c.targetOrgId,this.deps.orgRegistry,this.deps.orgManager).catch(xe=>{throw Be(xe)}),ht={},Lr=await gt.reconcile(ne,KN(Pu(it),ht)).catch(xe=>{throw ht.err!==void 0?Be(ht.err):xe});for(let xe of Cu(Lr,D))oe.info(`Forge resume: ${xe.trim()}`);ue=Lr.uncertain,$=Lr.underway;let go=this.loadHistory().find(xe=>xe.forgeId===t.forgeId);go&&Lr.found.length>0&&await this.withRowsFoundAfterStop(go,Lr.found)}):gt.begin(ne,c.targetOrgId,new Date(Fe),{...this.resumeHeadOf(n,c,o,Me),...d===!0?{muteAutomation:!0}:{},...i?{files:i}:{}},te)).then(()=>gt.open(ne)).catch(it=>{oe.warn(`Forge run journal not started: ${I(it)}`),Mr={err:it}}),t&&!se){let it=Mr?.err;if(it instanceof ln)throw it;let{reason:ht,lift:Lr}=uA(it);throw new ln(Sg,`The journal of the run to resume, in ${Rg(gt.pathOf(ne))}, could not be opened (${ht}). ${Lr}, then resume it again. Nothing was written.`)}}if(y&&!g&&!se){if(!gt||!W||Mr===void 0)throw new ln(Sg,VN);let{reason:ne,lift:Pe}=uA(Mr.err);throw new ln(Sg,`A clone of the whole org keeps its journal on disk, in ${Rg(gt.pathOf(W))}, which could not be opened (${ne}). ${Pe}, then run it again. Nothing was written.`)}R&&(Dt=await this.sampleOf({graph:n,config:c,anonymizationRules:o,readCeiling:Me,dryRun:g,...W!==void 0?{journalId:W}:{},resumes:t!==void 0,...b?{retried:b}:{},volumeCase:f,target:D,lookup:Ee,room:()=>Au(Dr,st).perRecord,onProgress:Hn}));let Qt=await this.rootsOfTheRun({graph:n,config:c,anonymizationRules:o,readCeiling:Me,dryRun:g,resumes:t!==void 0,...v?{retried:v}:{},lookup:Ee});if(Y.signal.aborted)throw be=!0,new Error(jn);let mt,Gt=y?IR(c):void 0,Jt=this.writeGate({guard:C,targetOrgId:c.targetOrgId,org:D,source:me(this.deps.orgManager.getOrg(c.sourceOrgId),c.sourceOrgId),orgTier:A,lookup:Ee,emailsPerInsert:He,...Ue!==void 0?{automation:Ue}:{},...Tn(pr?.ofRun),sentBefore:ot+(this.discoverySent.get(AA(c,n))?.target??0),mute:Vr(Fn?.plan??Ai),mayBeInTarget:ue,...$&&$.length>0?{jobsUnderway:$}:{},...g?{}:{simulated:this.simulations.of(f)},updatedAfterInsert:[...Ke],automationRoom:()=>Au(Dr,st).perRecord,...y?{wholeOrg:{source:me(this.deps.orgManager.getOrg(c.sourceOrgId),c.sourceOrgId),sourceOrgId:c.sourceOrgId,graph:n,anonymizePII:c.anonymizePII,...Gt?{carried:Gt}:{}}}:{},...p!==void 0?{checkpoint:{ask:{module:"forge",orgId:c.targetOrgId,operationId:he,running:Dr,request:p},own:{operationId:he},signal:Y.signal,onEstimate:ne=>{cs=ne},onTaken:ne=>{Nr=ne,gt&&W&&se&&gt.keepCheckpoint(W,ne).catch(Pe=>{oe.warn(`Forge run journal: the checkpoint taken first not named (${I(Pe)})`)})},onProgress:ne=>{let Pe=Po(ne);Le(this.deps,he,ne,0,0,Pe),this.liveTracker?.updateProgress(he,ne,0,0,Pe)}}}:{},onSimulated:ne=>{Ve=ne},...R?{sampled:ne=>{Hn.flush();let Pe=Dt?.drawnAgain,Be=Pe||Dt?.ofTheRunRetried?{...ne,plan:{...ne.plan,...Pe?{drawnAgain:Pe}:{},...Dt?.ofTheRunRetried?{ofTheRunRetried:!0}:{}}}:ne;return m.sampled(Be),Be}}:y?{onSampleOffer:ne=>{_n=ne}}:{},onConfirmed:()=>{ee=Ms(ee,"confirmed"),m.confirm("volume")}}),po=await this.orchestrator.execute(n,c,{recordTypeMappings:et,anonymizationRules:o,files:i,writtenBefore:P,stream:{ceiling:Me,...se?{store:se,summaryBound:La}:{},...Dt?{sample:Dt.stream}:{}},...te?{runUserId:te}:{},...Qt?{roots:Qt}:{},beforeWrite:async ne=>{let Pe=await Jt(ne);if(!Fn||ne.dryRun||mt)return Pe;let Be=await Fn.acquire(he);mt=Be,Ht=Be.outcome;let vt=pr?.afterLease(Be.outcome,Ti);if(vt)throw new lt(vt.code,vt.message);return{...Pe,lease:{assigned:Be.outcome.assigned.length,giveBack:async()=>(await lo(),Be.release())}}}}).catch(ne=>{if(!ER(ne))throw ne;return uo=ne.dryRun,t0(n,Fe,ne.dryRun)}).finally(X).finally(async()=>{mt&&(await lo(),Ht=await mt.release())}),Et=EA(TA(po,Ee.requests),Dt),_=Et.remapInJournal&&se&&W?{journalId:W,journalPart:Math.max(0,se.partCount-1)}:{},K=Ht?{mutedAutomation:Ht,...Yt.length>0?{bulkJobsPastMute:Yt,errors:[...Et.errors??[],...Du(Yt)]}:{}}:{},ce=g?cs:Nr?await this.settleCheckpoint(Nr,(Et.createdCount??Et.idRemapCount-(Et.linkedExistingCount??0))+(Et.updatedCount??0)>0):u,Oe=ce?{checkpoint:ce}:{},ye=t&&!g&&se&&W?await this.wroteToEarlierPartsOf(Et,W,se.partCount-1):{},ve=l!==void 0?{...Et,..._,...K,...Oe,retryOf:l,...t?{resumed:!0}:{},...ye}:{...Et,..._,...K,...Oe};"journalId"in _&&!g&&(F={keep:!0,status:"success",forgeId:ve.forgeId});let fe=ve.createdCount??ve.idRemapCount-(ve.linkedExistingCount??0);ve.status!=="failure"&&fe>0&&this.noteForgeWrite(V),ve.status==="failure"&&(ae=new Error("Forge execution finished with a failure status.")),g?(this.trials.note("simulation",h),Ve&&this.simulations.note(f,Ve),Dt&&uo?.sample&&this.noteSampleSimulation(f,Dt.fingerprint)):(Z(this.deps,{action:"forge_execute",module:"forge",operationId:he,orgId:c.targetOrgId,outcome:ve.status,guard:ee,objects:Zl(ve),source:{origin:"org",orgId:c.sourceOrgId},carried:eu(ve),...ks(ve.contactPoints),...mA(m),context:m.context(ve.decisionsApplied),...Ht?{muted:dt(Ht)}:{},...ce?.state==="taken"?{checkpointId:ce.checkpointId}:{}}),this.addToHistory(ve,c)),oe.info("Forge execute finished",Qj(ve)),await le(),Hn.flush();let Ye=T(this.deps,e,"forge:execute:response",{result:ve,operationId:he,...uo?{wholeOrgDryRun:uo}:{},..._n?{sampleOffer:_n}:{}});this.deps.broker.postToWebview(Ye),this.dmlTracker.markCompleted(V),pe(this.deps,he,{status:ve.status}),ve.status==="failure"?this.liveTracker?.fail(he,"Forge execution finished with a failure status."):ve.status==="partial"?this.liveTracker?.partial(he):this.liveTracker?.complete(he)}catch(Me){Hn.flush();let Xe=jb(Me,t?"resume":"draw")??Me,Ke=Na(Xe)?Xe:Gb(Xe),st=$t(Xe)?Xe:void 0;(Ke?.code==="AUTOMATION_DECLINED"||Ke?.code==="READ_DECLINED"||Ke?.code==="WRITE_DECLINED")&&(ee=Ms(ee,"declined"));let Tt=be||n0(Xe)||Ke!==void 0||st!==void 0;Tt||(ae=Xe);let et=Ke||st?void 0:uR(Xe),gt=et?bh(et):void 0,Mr=gt?Zl(gt):[],Qt=be||Ke||st?"stopped":Tt?Rh(et,Mr):"failure",mt=Ke?Ke.code:st?st.code:be?bt:Qt==="stopped"?rt:Xe instanceof ln?Xe.code:void 0,Gt=Nr?await this.settleCheckpoint(Nr,et?yA(et):!(be||Ke||st)):u;oe.info("Forge execute stopped",{outcome:Qt,...mt?{code:mt}:{},...et?{created:et.successCount,linked:et.linkedCount,failed:et.failedCount}:{}});let Jt=et&&!g?this.keepStoppedRun(EA(et,Dt),n,c,{startedAt:Fe,cancelled:Tt,retryOf:l,resumed:t!==void 0,callsBefore:Ee.requests,...se&&W?{journalId:W,journalPart:Math.max(0,se.partCount-1)}:{},...Gt?{checkpoint:Gt}:{},...te?{runUserId:te}:{},...Yt.length>0?{bulkJobsPastMute:Yt}:{},...t&&se&&W?await this.wroteToEarlierPartsOf({idRemapTable:et.remapTable,idRemapCreated:et.createdByObject,...et.remapInJournal?{remapInJournal:!0}:{}},W,se.partCount-1):{}}):void 0;se&&W&&Jt?F={keep:!0,status:Tt?"cancelled":"failure",forgeId:Jt.forgeId}:t&&(F={keep:!0,...t.end}),g||Z(this.deps,{action:"forge_execute",module:"forge",operationId:he,orgId:c.targetOrgId,outcome:Qt,...mt?{code:mt}:{},guard:ee,...gt?{objects:Mr,source:{origin:"org",orgId:c.sourceOrgId},carried:eu(gt)}:{},...ks(et?.contactPoints),...mA(m),context:m.context(et?.decisionsApplied),...Ht?{muted:dt(Ht)}:{},...Gt?.state==="taken"?{checkpointId:Gt.checkpointId}:{}}),this.dmlTracker.markFailed(V),this.lastWriteAt.delete(V),Dt?.adoptedFrom!==void 0&&W!==void 0&&!F.keep&&!(et&&yA(et))&&await this.giveThePlanBack(W,Dt.adoptedFrom),await le();let po=Nr&&Gt?{checkpoint:Gt}:{},Et=Ke&&Na(Ke)?Oj(Ke):Xe;E(this.deps,"forge:execute","forge:execute:error",e,Et,{code:mt??(Tt?rt:"EXECUTE_ERROR"),retryable:!(Ke&&Na(Ke)&&PA.has(Ke.code)),...Jt?{extraPayload:{result:F.keep?{...Jt,resumable:!0}:Jt}}:Ke?.stop?{extraPayload:{gate:Ke.stop,...po,..._n?{sampleOffer:_n}:{}}}:Nr?{extraPayload:po}:{}}),Tt?(this.deps.infraServices?.backgroundRegistry?.abort(he),pe(this.deps,he,{aborted:!0}),this.liveTracker?.cancel(he)):(De(this.deps,he,I(Xe),!0),this.liveTracker?.fail(he,I(Xe))),F.keep&&this.liveTracker?.offerResume(he,F.forgeId)}finally{await le(),J?.release(),Ne(ae),this.executeOperationId===he&&(this.executeOperationId=null,this.writingTo=null),this.stops.endRun(e.id),Un(),ls.flush(),this.abortController=null}}addToHistory(e,t){let r={...t.inputMode==="org"?iA(e):e,config:Yj(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=TA(wh(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??[],...Du(n.bulkJobsPastMute)]}:{}};return this.addToHistory(a,r),a}async wroteToEarlierPartsOf(e,t,r){let n=this.runJournal;if(!n||e.remapInJournal||r<1)return{};let o=new Set(Hr(e).flatMap(({ids:i})=>i.map(a=>a.slice(0,15))));try{let i=(await n.wroteIn(t,r)).filter(a=>!o.has(a.slice(0,15)));return i.length>0&&i.length<=La?{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 lR(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 jR(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(l=>l.forgeId===c)}let a=await this.withIdsOf(n);if("gone"in a)return{refused:a.gone};let d=n.roots?await this.rootsOfTheRunRetried(n):void 0;return n.roots&&!d?{refused:Ij}:{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()&&yu(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(yu(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=nt(rj,e,"forge:abort:error",this.deps);if(t===null)return;let r=this.stops.stop(t?.requestId,{discovery:n=>this.stopDiscovery(n),run:()=>{this.executeOperationId&&this.deps.infraServices?.backgroundRegistry?.abort(this.executeOperationId),this.abortController?.abort(),this.abortController=null,this.orchestrator?.abort()}});if("refused"in r){if(r.refused==="none"){oe.info("Forge stop: no operation under way answers it");return}E(this.deps,"forge:abort","forge:abort:error",e,new Error(`${r.live} Forge operations are under way in this window, and the stop did not say which one it was for: nothing was stopped. Stop it from its own screen, or from Live Operations.`),{code:ej});return}oe.info("Forge stopped",{what:r.stops.kind})}refuseAtGate(e,t,r,n,o){Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:t,outcome:"stopped",...n?{guard:n}:{},code:r.code,...o?{context:o}:{}}),E(this.deps,"forge:execute","forge:execute:error",e,r,{code:r.code,retryable:!0,...r.stop?{extraPayload:{gate:r.stop}}:{}})}keepAutomationRead(e,t,r){let n=IA(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<=Hj)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([...Rn(t,n,{userKept:o}),...r])],d=i?await new ge(bi).withTimeout("forge:undo-automation",()=>i.read(e,a)).catch(l=>({unread:I(l)})):{unread:"no reader of the target org's automation is set up"},c=new Set(nr(t));return kt(()=>this.muteOrg(e),d,{...this.muteLeases,writes:(l,u)=>u==="delete"||u==="update"&&c.has(l)})}async muteOrg(e){return this.muteOrgOf?this.muteOrgOf(e):Mt(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(IA(e,t));if(o&&Date.now()-o.at<_j)try{return{automation:r0(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(Hi).map(d=>d.objectApiName));try{return{automation:await new ge(bi).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?vu(a):[],l=a?ku(a,d):[],u=a?Iu(a):[{part:"automation",reason:"unread"in r?r.unread:""}];oe.info("Forge target automation before the run",{..."reused"in r?{reused:r.reused}:{},firedOnInsert:c.length,firedOnUpdate:l.length,unread:u.map(y=>y.part)});let p=c.length===0&&l.length===0&&u.length===0,g=a?Af(a):[],h=i.deliverability!==void 0;if(p&&!h&&!(o&&g.length>0))return"allowed";let f=a&&!p?Wb(a,d):[],m=await e.confirmRun({stage:"automation",org:t.org,orgTier:t.orgTier,fired:c,firedOnUpdate:l,updateSteps:qb(n.filter(y=>l.some(R=>R.objectApiName===y.objectApiName))),unread:u,bypass:f,assign:a&&!p?zb(a,f,t.username?{alias:t.org,username:t.username}:void 0):[],...g.length>0?{removal:g}:{},...i});if(m==="confirmed")return"confirmed";throw this.readAutomationAgain(t.orgId),m==="declined"?new lt("AUTOMATION_DECLINED",p&&!h?"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 lt("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 lt("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 lt("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",bu);return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.floor(e),Ci):bu}confirmAboveRecords(){let e=this.deps.services?.getSandforgeSetting?.("safety.confirmAboveRecords",Yr);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):Yr}async readTargetEmailLimits(e){try{let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return await new ge(os).withTimeout("forge:limits",()=>Sr(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 ge(os).withTimeout("forge:limits",()=>br(t))}catch(t){return{unread:I(t)}}}async readTargetApiBudget(e){try{let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return await new ge(os).withTimeout("forge:limits",()=>ar(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 ge(os).withTimeout("forge:limits",()=>ar(r))}catch(r){return{unread:I(r)}}}limitsTransportOf(e,t){return{request:async r=>{t.requests++;let n=await q(e,this.deps.orgRegistry,this.deps.orgManager);return new ge(os).withTimeout("forge:limits",()=>n.request(r))}}}async jobsStillRunning(e,t,r){let n=this.lostBulkJobs;if(!n||t===void 0)return[];let o=n.since(t,e);if(o.length===0)return[];oe.info("Forge execute: waiting for the Bulk API jobs the run lost before the mute is given back",{jobs:o.map(a=>`${a.objectApiName} ${a.jobId??"(no id)"}`)});let i=await n.stillRunning(o,()=>{r.requests++});return i.length>0&&oe.warn("Forge execute: Bulk API jobs still running as the mute is given back; what they write now goes in with the target\u2019s automation",{jobs:i.map(a=>`${a.objectApiName} ${a.jobId??"(no id)"}`)}),i.map(({objectApiName:a,jobId:d})=>({objectApiName:a,...d?{jobId:d}:{}}))}async sampleOf(e){let{config:t}=e,r=this.runJournal?.storagePath;if(r===void 0)throw new Error(Aj);let n=this.setupFingerprintOf(e.graph,t,e.anonymizationRules,e.readCeiling),o=new Date,i,a,d,c=!1,l,u=f=>{if(!(f instanceof pR))throw f};if(e.dryRun||e.journalId===void 0)i=gR(r,n);else if(e.retried&&!e.resumes){i=Ma(r,e.journalId);let f=e.retried.journalId,m=f!==void 0?await Eu.open(Ma(r,f),{fingerprint:n}).catch(u):void 0;m?(a=await yR(m,r,e.journalId),c=!0):d="planGone"}else if(i=Ma(r,e.journalId),!e.resumes){let f=await fR(r,n,o);if(f instanceof Eu)a=await hR(f,r,e.journalId).catch(u),a?l=f.dir:d="planTaken";else if(f==="tooOld")d="tooOld";else{let m=this.sampleSimulations.get(e.volumeCase);m!==void 0&&(d=m===n?"planTaken":"setUpOtherwise")}}await wR(r,o).catch(f=>{oe.warn(`Forge sample: the plans of past simulations were not swept (${I(f)})`)});let p;if(!a&&!e.resumes){let f=await this.readSourceApiBudget(t,e.lookup);"unread"in f||(p=f.remaining)}let g=t.sample?.withinMB;return{stream:{options:t.sample??{},budget:async()=>{e.lookup.requests++;let f=await this.readTargetDataStorage(t.targetOrgId),m=Db({storage:f,bounds:g!==void 0?{withinMB:g}:{},target:e.target});if(m)throw lt.of(m);let y=Fa({storage:f,...g!==void 0?{withinMB:g}:{},automation:e.room()});if(!y)throw new Error("No budget of the sample could be read. Nothing was written.");return y},keepAt:i,fingerprint:n,...a?{plan:a}:{},...p!==void 0?{sourceRequestsLeft:p}:{},onProgress:e.onProgress},fingerprint:n,...d?{drawnAgain:d}:{},...c?{ofTheRunRetried:!0}:{},...l!==void 0?{adoptedFrom:l}:{}}}async giveThePlanBack(e,t){let r=this.runJournal?.storagePath;r!==void 0&&await mR(r,e,t).catch(n=>{oe.warn(`Forge sample: the plan of the simulation was not put back (${I(n)})`)})}noteSampleSimulation(e,t){this.sampleSimulations.delete(e),this.sampleSimulations.set(e,t);for(let r of this.sampleSimulations.keys()){if(this.sampleSimulations.size<=Tj)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 H=Su(n.objects,i);e.onSimulated?.(H);let M=r(H),L;t&&M&&this.beforeRunCheckpoints&&H.totalRows>0&&(L=await this.beforeRunCheckpoints.scope(M,t.own).then(Q=>(t.onEstimate(Q),Q),Q=>{oe.warn(`Forge simulation: ${wr(Q)}`)}));let ee=await xb({objects:n.objects,measures:i,graph:o.graph,anonymizePII:o.anonymizePII,...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{},...L?{checkpoint:L}:{},...n.readBack!==void 0?{readBack:n.readBack}:{},...e.mute!==void 0?{mute:e.mute}:{},...e.deliverability!==void 0?{deliverability:e.deliverability}:{},...e.sentBefore!==void 0?{sentBefore:()=>({target:e.sentBefore??0})}:{},target:{org:e.org,limits:this.limitsTransportOf(e.targetOrgId,e.lookup)},source:{org:o.source,limits:this.limitsTransportOf(o.sourceOrgId,e.lookup)},...a?{sample:a}:{},...e.automationRoom?{automation:e.automationRoom()}:{}});if(!a&&ee.storage.verdict==="exceeds"){let Q=Fa({storage:ee.storage});Q&&e.onSampleOffer?.(Q.budget)}throw oe.info("Forge write gate: the dry run of a clone of the whole org",{records:ee.totalRows,objects:ee.wouldInsert.length,targetRequests:ee.targetRequests.estimate,sourceRequests:ee.sourceRequests.estimate,...ee.bulkBatches?{bulkBatches:ee.bulkBatches.estimate}:{},wouldBeRefused:ee.wouldBeRefused.map(Q=>Q.code)}),new AR(ee)}if(n.dryRun){let H=Ru(n.objects);e.onSimulated?.(H);let M=r(H);return t&&M&&this.beforeRunCheckpoints&&H.totalRows>0&&await this.beforeRunCheckpoints.scope(M,t.own).then(t.onEstimate,L=>{oe.warn(`Forge simulation: ${wr(L)}`)}),{}}let d=i?Eb(i.readWholeOver):void 0;if(d)throw lt.of(d);let c=i?Su(n.objects,i):Ru(n.objects);if(c.totalRows===0)return{};e.lookup.requests++;let l=await this.readTargetDataStorage(e.targetOrgId),u=Rr(c,l,e.automationRoom?$b(c,e.automationRoom()):0);if(a){let H=Nb({sample:a,storage:l,target:e.org});if(H)throw lt.of(H)}let p=this.confirmAboveRecords(),g=p>0&&c.totalRows>p?p:void 0,h=jw(e.orgTier),f=h!==void 0&&c.totalRows>h?h:void 0;oe.info("Forge write gate",{records:c.totalRows,objects:Object.fromEntries(c.objects.slice(0,20).map(H=>[H.objectApiName,H.rows])),storageEstimateMB:Hs(u.estimateMB),...u.verdict==="unread"?{storageUnread:u.unread}:{storageRemainingMB:u.remainingMB,storageMaxMB:u.maxMB},storage:u.verdict});let m=Jb(u,e.org);if(m&&u.verdict==="exceeds"){if(o&&!a&&!("unread"in l)){let M=Fa({storage:l});M&&e.onSampleOffer?.(M.budget)}let H=n.roots&&!o?db(u,e.org,n.roots):void 0;throw H?lt.of(H):new lt("STORAGE_EXCEEDED",`${m} Nothing was written.`,{estimateMB:Number(Hs(u.estimateMB)),remainingMB:u.remainingMB})}u.verdict==="near"?oe.warn("Forge write gate: the records take more than 80 % of the data storage the target has left"):u.verdict==="unread"&&oe.warn("Forge write gate: the data storage the target has left could not be read"),f!==void 0&&oe.warn(`Forge write gate: more than ${f} records, a large volume`);let y=i?Pb(i.files,l,e.org):void 0;if(y?.stop)throw lt.of(y.stop);let R;"unread"in l?(e.lookup.requests++,R=await this.readTargetApiBudget(e.targetOrgId)):R=l.dailyApiRequests;let k=r(c),w;if(t&&k){let H=this.beforeRunCheckpoints;if(!H)throw new lt(In,wr(new Error("SandForge's checkpoints are not set up in this window")));w=await H.scope(k,t.own).catch(M=>{throw new lt(In,wr(M))})}let O=o?await this.readSourceApiBudget(o,e.lookup):void 0,P=Cb({plan:c,...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{},...n.readBack!==void 0?{readBack:n.readBack}:{},...w?{checkpoint:w}:{},...e.mute!==void 0?{mute:e.mute}:{},...e.deliverability!==void 0?{deliverability:e.deliverability}:{},...e.sentBefore!==void 0?{sentBefore:e.sentBefore}:{},budget:R,target:e.org,...o&&i?{wholeOrg:{measures:i,bulkBatches:"unread"in l?l:l.dailyBulkApiBatches,sourceBudget: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 lt.of(P.stop);let b=ua(P.api),v=o&&i&&P.wholeOrg?PR({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;v&&oe.info("Forge write gate: a clone of the whole org",{sourceRequests:P.wholeOrg?.source.estimate,sourceApi:P.wholeOrg?.source.verdict,jobs:v.bulk?.jobs??0,...P.wholeOrg?.bulkBatches?{bulkBatches:P.wholeOrg.bulkBatches.estimate}:{},durationSeconds:Math.round(v.durationSeconds),managedPackages:v.managedPackages?.length??0,personalAsIs:v.personalAsIs?.length??0});let C=async()=>{let H=this.beforeRunCheckpoints;if(!t||!k||!w||!H)return;let M=w,L=await Da(()=>H.take(k,t.own,{planned:M,signal:t.signal,onProgress:({percentage:ee})=>t.onProgress?.(ee)}));if("stop"in L)throw L.stop.code===In?lt.of({...L.stop,code:In}):Object.assign(new Error(L.stop.message),{name:"ForgeAbortedError"});t.onTaken(L.checkpoint)},S=[],A=[];if(e.emailsPerInsert.length>0){e.lookup.requests++;for(let H of Mb(c,e.emailsPerInsert,await this.readTargetEmailLimits(e.targetOrgId)))H.verdict==="exceeds"?S.push(_b(H)):H.verdict==="unread"&&A.push(Hb(H));A.length>0&&oe.warn("Forge write gate: a daily email limit of the target could not be read",{limits:A.map(({limit:H,emails:M})=>({limit:H,emails:M}))}),S.length>0&&oe.warn("Forge write gate: the records take the target past a daily email limit",{limits:S.map(({limit:H,emails:M,remaining:L})=>({limit:H,emails:M,remaining:L}))})}let D=e.automation===void 0?void 0:"automation"in e.automation?Fb(e.automation.automation,Lb(c)):`the target's automation: ${e.automation.unread}`;D!==void 0&&oe.warn("Forge write gate: what of the target sends emails could not all be read, and its emails were not counted");let z=(e.mayBeInTarget??[]).filter(({rows:H})=>H>0),U=e.simulated?Ib(e.simulated,c.totalRows):void 0;if(U?.farAbove&&oe.warn("Forge write gate: far more records than the last simulation of the case",{records:c.totalRows,simulated:U.total}),g===void 0&&u.verdict==="fits"&&S.length===0&&A.length===0&&D===void 0&&z.length===0&&U?.farAbove!==!0&&!P.asks)return await C(),b;let Y=await e.guard.confirmRun({stage:"write",...n.roots?{roots:{...n.roots,source:e.source}}:{},org:e.org,orgTier:e.orgTier,objects:c.objects.map(({objectApiName:H,rows:M})=>({objectApiName:H,rows:M})),total:c.totalRows,...g!==void 0?{aboveRecords:g}:{},...f!==void 0?{largeVolume:f}:{},storage:En(u),...c.leftOut?{leftOut:c.leftOut}:{},...n.objects.some(H=>H.counted)?{counted:!0}:{},...S.length>0?{emails:S}:{},...A.length>0?{emailsUnread:A}:{},...D!==void 0?{emailsUncounted:D}:{},...Ab(c),...Tb(c),...z.length>0?{mayBeInTarget:z.map(({objectApiName:H,rows:M})=>({objectApiName:H,rows:M}))}:{},...z.length>0&&e.jobsUnderway&&e.jobsUnderway.length>0?{jobsUnderway:Gj(e.jobsUnderway)}:{},...n.capped?{capped:n.capped}:{},...U?{simulated:U}:{},...v?{wholeOrg:v,...P.confirmation.checkpoint?{checkpoint:P.confirmation.checkpoint}:{}}:P.confirmation});if(Y==="confirmed")return e.onConfirmed(),await C(),b;throw Y==="declined"?new lt("WRITE_DECLINED","Forge execution was cancelled before it wrote the records it had read. Nothing was written."):new lt("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 ge(Bj).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),{records:a}=await tr({query:async d=>(t.requests++,i.query(d)),queryMore:async d=>(t.requests++,i.queryMore(d))},Yb);return Qb(a)}));for(let o of Zb(r,n))oe.warn(`[forge] ${eR(o)}`);return new tR().buildMapping(r,n)}async handleTemplatesList(e){let{templates:t,importNotMerged:r}=await this.loadTemplates(),n=T(this.deps,e,"forge:templates:list:response",{templates:t.filter(o=>Nl.safeParse(o).success),...r===void 0?{}:{importNotMerged:r}});this.deps.broker.postToWebview(n)}async handleSaveTemplate(e){let t=nt(nj,e,"forge:templates:save:error",this.deps);if(!t)return;let{template:r}=t;try{let o=[r,...(await this.loadTemplates()).templates.filter(i=>i.id!==r.id)];await this.saveTemplates(o)}catch(o){E(this.deps,"forge:templates:save","forge:templates:save:error",e,o);return}let n=T(this.deps,e,"forge:templates:save:response",{success:!0});this.deps.broker.postToWebview(n)}async handleDeleteTemplate(e){let t=nt(uj,e,"forge:templates:delete:error",this.deps);if(!t)return;let{templateId:r}=t;try{let o=(await this.loadTemplates()).templates.filter(i=>i.id!==r);await this.saveTemplates(o)}catch(o){E(this.deps,"forge:templates:delete","forge:templates:delete:error",e,o);return}let n=T(this.deps,e,"forge:templates:delete:response",{success:!0});this.deps.broker.postToWebview(n)}async handleHistoryList(e){await this.keepRunsLeftOver();let t=this.loadHistory(),r=await this.resumableRuns(t),n=[];try{n=await this.removalPlans?.list()??[]}catch(l){oe.warn(`Forge removal plans could not be read: ${I(l)}`)}let o=await this.journalsPresent([...t.flatMap(l=>l.remapInJournal&&l.journalId?[l.journalId]:[]),...n.flatMap(l=>l.inJournal?[l.inJournal.journalId]:[])]),i=t.map(l=>({...l,...r.has(l.forgeId)?{resumable:!0}:{},...l.remapInJournal&&!(l.journalId&&o.has(l.journalId))?{journalGone:!0}:{}})),a=new Set(i.map(l=>l.forgeId)),d=n.filter(l=>!a.has(l.forgeId)&&Ur(l).length>0).map(l=>l.inJournal&&!o.has(l.inJournal.journalId)?{...l,journalGone:!0}:l);await this.dropJournalsNoLongerNamed(t,n);let c=T(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=nt(oj,e,"forge:undo:error",this.deps);if(!r)return;let{forgeId:n}=r,o=r.includeChanged===!0,i=r.sweep===!0,a=r.again===!0,d=r.muteAutomation===!0,c=i&&r.sweepLate===!0,l=i&&r.sweepUntied===!0,u=(O,P)=>this.refuseUndo(e,O,P),p=this.loadHistory().find(O=>O.forgeId===n),g=p?void 0:await this.keptRemovalPlan(n),h,f={},m=p?.targetOrgId??g?.targetOrgId,y=p?p.journalId:g?.inJournal?.journalId;if(y){let O=this.journalBusy(y,"remove");if(O){u(O,yi);return}if(this.removing.has(n)){u("The records of this run are being removed already: its result shows under the run once it ends.",vg);return}let P=this.lockToRemove(y,m);if(P&&"busy"in P){u(P.busy,yi);return}P&&(t.lock=P)}if(m&&y&&(!p||p.idRemapCreated)){if(this.removing.has(n)){u("The records of this run are being removed already: its result shows under the run once it ends.",vg);return}this.removing.add(n);try{let O=await this.callsLookedForBeforeRemoval({forgeId:n,targetOrgId:m,journalId:y,removedBefore:(p??g)?.undo!==void 0});if("unread"in O){u(O.unread,"IN_FLIGHT_UNREAD");return}h=O.reconciled,f=O,h&&h.found.length>0&&(p?p=await this.withRowsFoundAfterStop(p,h.found):g&&(g=await this.planWithRowsFoundAfterStop(g,h.found)))}finally{this.removing.delete(n)}}let R,k,w=()=>{};if(p){let O=Date.parse(p.timestamp);if(!p.idRemapCreated||!p.targetOrgId||Number.isNaN(O)){u(`This run was recorded before Forge kept what a run created: its records cannot be removed from the history. ${Mc}`,"NOT_RECORDED");return}let P=p.remapInJournal&&p.journalId&&p.journalPart!==void 0?{journalId:p.journalId,part:p.journalPart}:void 0,b=Xj(p.mayHaveBeenWritten,{...f,reconciled:h});if(R={...p,targetOrgId:p.targetOrgId,unreachable:Vj(p.mayHaveBeenWritten,h),...b?{notLookedFor:b}:{},...P?{inJournal:P}:{}},p.remapInJournal){if(k=[],a||gn(p).length>0){let v=await this.journalRecordsOf(P,p.undo,a);if("gone"in v){u(v.gone,rs);return}k=v.records,w=v.close}}else k=a?Hr(p):fs(p)}else if(g){if(i){u(SA,"SWEEP_UNAVAILABLE");return}R={...g,unreachable:h&&h.calls>0?$u(h):g.mayHaveBeenWritten??0,...f.callsNotLookedFor?{notLookedFor:{callsAfterRemoval:f.callsNotLookedFor}}:{}};let{inJournal:O}=g;if(O&&(a||Ur(g).length>0)){let P=await this.journalRecordsOf(O,g.undo,a);if("gone"in P){u(P.gone,rs);return}k=P.records,w=P.close}else k=a?g.objects.map(({objectApiName:P,ids:b})=>({objectApiName:P,ids:[...b]})):Ul(g)}else{u("This run is no longer in the Forge history.",ns);return}try{let O=lu(k),P=i&&R.undo!==void 0;if(O===0&&!P){R.undo?u(`The records this run created were already removed, on ${R.undo.removedAt}.`,"ALREADY_REMOVED"):u("This run created no record to remove.","NOTHING_TO_REMOVE");return}if(this.removing.has(n)){u("The records of this run are being removed already: its result shows under the run once it ends.",vg);return}this.removing.add(n);let b=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(e.id);try{await this.removeRun(e,R,k,{includeChanged:o,again:a,muteAutomation:d,sweepLate:c,sweepUntied:l,...!i&&p?.config?.inputMode==="org"?{wholeOrgNotSwept:!0}:{}},i?p:void 0,b)}finally{this.removing.delete(n),b?.release()}}finally{w()}}async journalRecordsOf(e,t,r=!1){let n=this.runJournal;if(!n||!e)return{gone:Nn};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:Nn}}}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:Nn};try{let n=await r.idsOf(e.journalId,e.journalPart);if(!n)return{gone:Nn};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:Nn}}}async planRecordsOf(e,t=!1){let r=this.runJournal;if(!r)return{gone:Nn};try{let{journalId:n,part:o}=e.inJournal,i=await r.idsOf(n,o);if(!i)return{gone:Nn};let a={idRemapTable:i.table,idRemapExisting:i.existing,idRemapCreated:i.createdByObject};if(t)return{records:Hr(a)};let d=await r.leftOf(n,o);return{records:fs({...a,...e.undo?{undo:e.undo}:{},...d?{removalLeft:d}:{}})}}catch(n){return oe.warn(`Forge run journal could not be read: ${I(n)}`),{gone:Nn}}}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=me(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,Pu(i));for(let d of Cu(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((l,{rows:u})=>l+u,0),a=Kj(e.idRemapByObject,t),d;if(e.remapInJournal)d={...e,idRemapCount:e.idRemapCount+i,createdCount:(e.createdCount??0)+i,...a?{idRemapByObject:a}:{}};else{let l=await r.idsOf(n,o).catch(()=>{});if(!l)return e;d={...e,idRemapTable:l.table,idRemapExisting:l.existing,idRemapCreated:l.createdByObject,idRemapCount:Object.keys(l.table).length,createdCount:l.createdByObject.reduce((u,{sourceIds:p})=>u+p.length,0),...a?{idRemapByObject:a}:{}}}this.saveHistory(this.loadHistory().map(l=>l.forgeId===d.forgeId?d:l));let c=_i(d);return c&&await this.removalPlans?.put(c).catch(l=>{oe.warn(`Forge removal plan not kept: ${I(l)}`)}),d}async planWithRowsFoundAfterStop(e,t){let{inJournal:r}=e;if(!r)return e;let n=r.left.map(i=>({...i}));for(let{objectApiName:i,rows:a}of t){let d=n.find(c=>c.objectApiName===i);d?d.count+=a:n.unshift({objectApiName:i,count:a})}let o={...e,inJournal:{...r,left:n}};return await this.removalPlans?.put(o).catch(i=>{oe.warn(`Forge removal plan not kept: ${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=bR.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=xj(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(u=>u.forgeId===e);if(!r)return{refused:"The run to resume is no longer in the history: what it wrote and where it stopped are not known. Run the clone again from Review. Nothing was read or written."};let n=r.targetOrgId,o=this.runJournal;if(!r.journalId||!o)return{refused:`This run kept no journal to take it up from: ${gA}`,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),l=c?.resume?.startedWith;return!c?.resume||!l||c.targetOrgId!==n?{refused:`The journal of this run does not say how it was set up: ${gA}`,targetOrgId:n}:{entry:r,journalId:r.journalId,head:{...c.resume,startedWith:l},targetOrgId:c.targetOrgId,end:a}}async handleResumeRun(e){let t=nt(ZN,e,"forge:execute:error",this.deps);if(!t)return;let r=(y,R,k)=>{k&&Z(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:k,outcome:"stopped",code:y}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(R),{code:y})},n=await this.runToResume(t.forgeId);if("refused"in n){r(QN,n.refused,n.targetOrgId);return}let{entry:o,journalId:i,head:a,targetOrgId:d,end:c}=n,l=this.deps.orgManager.getOrg(d);if(!l){r(fA,"The org this run wrote to is no longer registered in SandForge: add the same org again on Organizations, then resume \u2014 the run checks it is the org it wrote to. Refreshed since, it holds nothing the run wrote: run the clone again. Nothing was read or written.",d);return}if(a.targetSalesforceOrgId!==void 0&&l.orgId&&l.orgId.slice(0,15)!==a.targetSalesforceOrgId.slice(0,15)){r(fA,`${me(l,d)} is no longer the org this run wrote to \u2014 refreshed or replaced since: what the run wrote is not there. Run the clone again from Review into it as it is now. Nothing was read or written.`,d);return}let{graph:u,config:p,anonymizationRules:g}=a.startedWith,h=Dl(p);if(h!==void 0){r(kg,`${h}. Nothing was read or written.`,d);return}let f=this.maxRecordsPerObject(),m=y=>OR(a.fingerprint,y.graph,this.runSetupOf(y.config,g,f,a.targetSalesforceOrgId));if(!m({graph:u,config:p})){r(kg,"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(kg,"The clone on this page is set up otherwise than the run to resume: its objects, filters or decisions changed since.",d);return}await this.handleExecute(e,{forgeId:o.forgeId,journalId:i,head:a,end:c,startedWith:{graph:u,config:p,...g?{anonymizationRules:g}:{},...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&&Ig.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 kR(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=_i(e),o=[...n?[r.put(n)]:[],...t.flatMap(i=>{let a=_i(i);return a&&Ur(a).length>0?[r.putIfAbsent(a)]:[]})];Promise.all(o).catch(i=>{oe.warn(`Forge removal plan not kept: ${I(i)}`)})}refuseUndo(e,t,r){E(this.deps,"forge:undo","forge:undo:error",e,new Error(t),{code:r})}async handleOpenRecord(e){let t=nt(aj,e,"forge:open-record:error",this.deps);if(!t)return;let r=(l,u)=>{E(this.deps,"forge:open-record","forge:open-record:error",e,new Error(l),{code:u})},n=this.loadHistory().find(l=>l.forgeId===t.forgeId);if(!n){r("This run is no longer in the Forge history.",ns);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,rs);return}let i=t.recordId.slice(0,15),a;for(let{objectApiName:l,ids:u}of Hr(o.entry)){let p=u.find(g=>g.slice(0,15)===i);if(p){a={objectApiName:l,id:p};break}}if(!a){r("This record is not one this run created.","NOT_CREATED");return}let d=this.deps.orgManager.getOrg(n.targetOrgId);if(!d){r(pA,"ORG_NOT_FOUND");return}let c=Yd(d.instanceUrl,a.objectApiName,a.id);if(!c.ok){let l=c.reason==="not-https"?`its instance URL must use HTTPS, got "${c.protocol}"`:c.reason==="invalid"?"its instance URL is not a valid URL":"the record is not one an address can be built for";r(`Cannot open the record in "${me(d)}": ${l}.`,c.reason==="not-a-record"?"NOT_CREATED":"INVALID_INSTANCE_URL");return}try{let l=await this.externalBrowser.open(c.url),u=T(this.deps,e,"forge:open-record:response",l);this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id} status=${l.status}`)}catch(l){E(this.deps,"forge:open-record","forge:open-record:error",e,l)}}async handleVerify(e){let t=nt(dj,e,"forge:verify:error",this.deps);if(!t)return;let{forgeId:r}=t,n=(l,u)=>{E(this.deps,"forge:verify:request","forge:verify:error",e,new Error(l),{code:u})},o=this.loadHistory().find(l=>l.forgeId===r);if(!o){n("This run is no longer in the Forge history.",ns);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. ${Mc}`,"NOT_RECORDED");return}let a=o;if(o.remapInJournal&&gn(o).length>0){let l=await this.withIdsOf(o,!0);if("gone"in l){n(l.gone,rs);return}a=l.entry}let d=o.remapInJournal&&a===o?[]:fs(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(pA,"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.",YN);return}this.verifying.add(r);let c=`forge-verify-${this.deps.nextId()}`;try{let l=await q(i,this.deps.orgRegistry,this.deps.orgManager),u=new BR({target:ju(l,"forge:verify"),source:await this.verificationSource(o.sourceOrgId)}),p=o.writtenBetween??await this.datedByItsJournal({journalId:o.journalId,part:o.journalPart,scope:"part"},l),g=await u.verify({records:d,remapTable:a.idRemapTable??{},...p?{runStartedAt:new Date(p.first),runEndedAt:new Date(p.last)}:{runRecordedAt:new Date(o.timestamp)},...a.removalStamps?{removalStamps:a.removalStamps}:{},...o.config?.fieldExclusions?{fieldExclusions:o.config.fieldExclusions}:{},...o.config?.fieldMappings?{fieldMappings:o.config.fieldMappings}:{},writtenWithout:zR(o.writtenWithoutFields??[]),...o.lookupsLeftEmptyByFilter?{leftEmptyByFilter:o.lookupsLeftEmptyByFilter}:{},leftEmptyByTheRun:WR(o.config?.inputMode==="org"),...a.idRemapWithTheirRecord?{withTheirRecord:a.idRemapWithTheirRecord}:{}});this.saveHistory(this.loadHistory().map(f=>f.forgeId===r?{...f,verification:g}:f)),Z(this.deps,{action:"forge_verify",module:"forge",operationId:c,orgId:i,outcome:g.verdict==="verified"?"success":"partial",verdict:g.verdict,details:{forgeId:r,...qR(g)}});let h=T(this.deps,e,"forge:verify:response",{verification:g});this.deps.broker.postToWebview(h),this.deps.log(`[TX] ${h.type} id=${h.id} verdict=${g.verdict}`)}catch(l){Z(this.deps,{action:"forge_verify",module:"forge",operationId:c,orgId:i,outcome:"failure",details:{forgeId:r}}),E(this.deps,"forge:verify:request","forge:verify:error",e,l,{code:"VERIFY_ERROR",retryable:!0})}finally{this.verifying.delete(r)}}async handleExportIds(e){let t=nt(cj,e,"forge:export-ids:error",this.deps);if(!t)return;let r=(c,l)=>{E(this.deps,"forge:export-ids:request","forge:export-ids:error",e,new Error(c),{code:l})},n=this.loadHistory().find(c=>c.forgeId===t.forgeId);if(!n){r("This run is no longer in the Forge history.",ns);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,rs);return}i=Sf(c.entry)}let d=new Date().toISOString().slice(0,10);try{let c=await this.saveDialog.saveStream(`sandforge-forge-id-map-${d}.csv`,async p=>{await p(vf([]));let g=0,h=[];for(let f of i)h.push(f),!(h.length<lj)&&(await p(`
17
+ ${Bl(h)}`),g+=h.length,h=[]);return h.length>0&&await p(`
18
+ ${Bl(h)}`),g+h.length},["csv"]),l=c.status==="saved"?{status:"saved",path:c.path,rows:c.result}:c,u=T(this.deps,e,"forge:export-ids:response",l);this.deps.broker.postToWebview(u),this.deps.log(`[TX] ${u.type} id=${u.id} status=${c.status}`)}finally{a()}}async idMapRowsInJournal(e){let t=this.runJournal;if(!(!t||!e.journalId||e.journalPart===void 0))try{return await t.idMapRowsOf(e.journalId,e.journalPart)}catch(r){oe.warn(`Forge run journal could not be read: ${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 ju(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:l}=t,u=lu(r),p=(S,A)=>this.refuseUndo(e,S,A),g=this.deps.infraServices?.productionGuard;if(!g){Z(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:l,outcome:"stopped",code:Se.code}),p(Se.message,Se.code);return}let h=this.deps.orgManager.getOrg(l),f=Ce(h),{check:m,decision:y}=u>0?await Ze(g,{orgId:l,orgTier:f,operation:"delete",objectName:uu(r).join(", "),recordCount:u,module:"forge"}):{check:void 0,decision:"allowed"};if(m&&(y==="refused"||y==="declined")){Z(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:l,outcome:"stopped",guard:y}),y==="refused"?p(`Operation blocked by Production Guard: ${m.blockedReason??m.impactSummary}`,"GUARD_BLOCKED"):E(this.deps,"forge:undo","forge:undo:error",e,new Error("Operation cancelled by user (confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}if(i?.signal.aborted){Z(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:l,outcome:"stopped",guard:y,code:bt});let S={forgeId:c,status:"cancelled",includeChanged:a,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(T(this.deps,e,"forge:undo:response",{result:S,operationId:e.id}));return}let R=e.id,k=u>0?`Removing ${u} record(s) a Forge run created`:"Sweeping what the target\u2019s automation created during a Forge run",w=new AbortController;ze(this.deps,R,"forge",k);let O=this.trackRun(R,k,w);this.liveTracker?.register(R,"forge",k,u);let P,b,v,C;try{let S=await q(l,this.deps.orgRegistry,this.deps.orgManager),{inJournal:A}=t,D=t.writtenBetween??await this.datedByItsJournal({journalId:t.journalId??A?.journalId,part:t.journalPart??A?.part},S),z={...t.removalStamps,...A?await this.runJournal?.stampsOf(A.journalId,A.part).catch(X=>(oe.warn(`Forge removal stamps not read: ${I(X)}`),{})):{}};u>0&&(b=await this.otherPartsOf(c,l,S));let U=pu(t.removalSpans,b?.spans);o&&(v=await this.sweepOfRemoval({conn:S,entry:o,includeChanged:a,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,removalSpans:U,signal:w.signal,guard:g,orgTier:f,operationId:R,muted:()=>u===0?C:void 0}));let Y=v;await Y?.ask();let H=Y?.takes??[],M=n.muteAutomation===!0&&(u>0||H.length>0)?await this.removalMute(l,uu(r),H,b?.parts.flatMap(X=>X.objects)??[],t.runUserId!==void 0&&u>0):void 0,L;C=M?.muted;let ee=async()=>{let X=M?.prepared;!X||w.signal.aborted||(L=await X.acquire(R),C=L.outcome)},B=await(u===0?(async()=>(await ee(),await Y?.first(),await Y?.afterRemoval(),bw))():Rw(or(S,"forge:undo"),r,{...D?{runStartedAt:new Date(D.first),runEndedAt:new Date(D.last)}:{runDurationMs:t.duration,runRecordedAt:new Date(t.timestamp)},...Object.keys(z).length>0?{removalStamps:z}:{},...U.length>0?{removalSpans:U}:{},...b&&b.laterParts.length>0?{laterParts:b.laterParts}:{},...Y?{sweep:X=>Y.first(X),afterRemoval:X=>Y.afterRemoval(X),automationMade:Y.automationMade}:{},...t.runUserId?{runUserId:t.runUserId}:{},...b&&b.parts.length>0?{otherParts:b.parts.map(X=>X.alongside)}:{},includeChanged:a,onUndeletable:Wr(this.deps,l,"forge:undo"),beforeFirstWrite:ee,signal:w.signal,onProgress:(X,F,de)=>{let J=Math.min(100,Math.round(X/Math.max(F,1)*100));Le(this.deps,R,J,X,F,de),w.signal.aborted||this.deps.infraServices?.backgroundRegistry?.updateProgress(R,J),this.liveTracker?.updateProgress(R,J,X,F,de)}})).finally(async()=>{L&&(C=await L.release())});b&&await this.keepOtherPartStamps(b.parts,B.otherPartStamps??[]);let V=await v?.settle(),we=d?void 0:t.undo?.removedAt,ie=t.unreachable,re=b?zj(B.objects,b.parts):[],Ae=(b?.parts??[]).flatMap(X=>X.undo&&X.records>0?[{forgeId:X.forgeId,records:X.records}]:[]),he={forgeId:c,status:Sw(B.objects,B.cancelled),includeChanged:a,objects:B.objects,finishedAt:new Date().toISOString(),...we?{leftBy:we}:{},...ie>0?{mayHaveBeenWritten:ie}:{},...t.notLookedFor?{notLookedFor:t.notLookedFor}:{},...C?{mutedAutomation:C}:{},...re.length>0?{heldByOtherParts:re}:{},...Ae.length>0?{otherPartsLeft:Ae}:{}};u>0&&Z(this.deps,{action:"cleanup_delete",module:"forge",operationId:R,orgId:l,outcome:Io(he),guard:y,objects:Sn(he.objects),...we?{leftBy:we}:{},...C?{muted:dt(C)}:{}});let Je={...he,status:Oo(he.status,V),...V?{sweep:V}:{},...n.wholeOrgNotSwept?{wholeOrgNotSwept:!0}:{}};n.wholeOrgNotSwept&&oe.info("Forge removal: a clone of the whole org removed without its sweep; what the target\u2019s automation created during the run stays");let Ne=vw(Je,u,t.undo,d),Fe=V&&NR(V,new Date().toISOString(),o?.sweep),W=Object.keys(B.stamps).length>0,se=B.span,te,ue;if(A)(B.objects.some(F=>F.deleted+F.alreadyGone>0)||d&&Ne!==void 0)&&(ue=await this.runJournal?.keepLeftPages(A.journalId,A.part,B.left()).catch(F=>{oe.warn(`Forge removal left not kept: ${I(F)}`)})),W&&await this.runJournal?.keepStamps(A.journalId,A.part,B.stamps).catch(F=>{oe.warn(`Forge removal stamps not kept: ${I(F)}`)});else if((B.gone.length>0||d&&Ne)&&!ww(r)){let X=new Set(B.gone);te=r.flatMap(({ids:F})=>F.filter(de=>!X.has(de)))}if(Ne||W||se||te||ue||Fe){let X=F=>({...F,...Ne?{undo:Ne}:{},...Fe?{sweep:Fe}:{},...W&&!A?{removalStamps:{...F.removalStamps,...B.stamps}}:{},...se?{removalSpans:[...F.removalSpans??[],se]}:{},...te?{removalLeft:te}:{}});this.saveHistory(this.loadHistory().map(F=>F.forgeId===c?{...X(F),...ue?{removalLeftByObject:ue}:{}}:F)),await this.removalPlans?.update(c,F=>{let de={...X(F),...F.inJournal&&ue?{inJournal:{...F.inJournal,left:ue}}:{}};return Ur(de).length>0?de:void 0}).catch(F=>{oe.warn(`Forge removal plan not updated: ${I(F)}`)})}let $=T(this.deps,e,"forge:undo:response",{result:Je,operationId:R});this.deps.broker.postToWebview($);let N=Je.status==="failure"?"No record this run created could be removed.":u===0&&V&&V.status!=="success"?V.refusal??"The sweep left records in the org.":void 0;Je.status==="cancelled"||V?.status==="cancelled"?(pe(this.deps,R,{aborted:!0}),this.liveTracker?.cancel(R)):(pe(this.deps,R,{status:N&&u===0?"failure":Je.status}),N?(P=new Error(N),this.liveTracker?.fail(R,N)):Je.status==="partial"?this.liveTracker?.partial(R):this.liveTracker?.complete(R))}catch(S){P=S,await v?.settle().catch(D=>{oe.warn(`Forge sweep not recorded: ${I(D)}`)});let A=$t(S)?S:void 0;Z(this.deps,{action:"cleanup_delete",module:"forge",operationId:R,orgId:l,outcome:A?"stopped":"failure",guard:y,...A?{code:A.code}:{}}),E(this.deps,"forge:undo","forge:undo:error",e,S,{code:A?.code??"UNDO_ERROR",retryable:!0}),pe(this.deps,R,{status:"failure"}),this.liveTracker?.fail(R,I(S))}finally{b?.close(),O(P)}}async otherPartsOf(e,t,r){let n=[],o=[],i=this.loadHistory(),a=new Set(i.map(u=>u.forgeId)),d=(await this.keptRemovalPlans()).filter(u=>!a.has(u.forgeId)),c=u=>Wj(u,i,d,t),l=[];for(let u of await this.runLineOf(e,i,d)){let p=i.find(f=>f.forgeId===u),g=p?void 0:d.find(f=>f.forgeId===u);(p??g)?.targetOrgId===t&&l.push((p??g)?.removalSpans??[]);let h=p?await this.otherPartFromEntry(p,t,r,c(u)):await this.otherPartFromPlan(g,t,r,c(u));h&&(h.close&&n.push(h.close),o.push(h.part))}return{parts:o,spans:pu(...l),laterParts:c(e),close:()=>n.forEach(u=>u())}}async otherPartObjectsOf(e,t){let r=this.loadHistory(),n=new Set(r.map(a=>a.forgeId)),o=(await this.keptRemovalPlans()).filter(a=>!n.has(a.forgeId)),i=new Set;for(let a of await this.runLineOf(e,r,o)){let d=r.find(u=>u.forgeId===a),c=d?void 0:o.find(u=>u.forgeId===a);if((d??c)?.targetOrgId!==t)continue;let l=d?gn(d):c?Ur(c):[];for(let{objectApiName:u}of l)i.add(u)}return[...i]}async runLineOf(e,t,r){let n=[...t.map(a=>({forgeId:a.forgeId,...a.retryOf!==void 0?{retryOf:a.retryOf}:{},...a.journalId!==void 0?{journalId:a.journalId}:{}})),...r.map(a=>({forgeId:a.forgeId,...a.retryOf!==void 0?{retryOf:a.retryOf}:{},...a.inJournal?{journalId:a.inJournal.journalId}:{}}))],o=this.runJournal,i=new Map;for(;;){let{inLine:a,journals:d}=qj(e,n,i),c=o?[...d].filter(l=>!i.has(l)):[];if(!o||c.length===0)return[...a].filter(l=>l!==e);for(let l of c)i.set(l,await o.partsOf(l).catch(u=>(oe.warn(`Forge run journal parts not read: ${I(u)}`),[])))}}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)||gn(e).length===0)return;let o=e.remapInJournal&&e.journalId&&e.journalPart!==void 0?{journalId:e.journalId,part:e.journalPart}:void 0,i,a;if(o){let c=await this.journalRecordsOf(o,e.undo);if("gone"in c)return;i=c.records,a=c.close}else i=fs(e);let d=e.writtenBetween??await this.datedByItsJournal({journalId:e.journalId,part:e.journalPart},r);return{part:{forgeId:e.forgeId,...o?{inJournal:o}:{},alongside:await this.alongside(i,d,e,e.removalStamps,o,n),...e.undo?{undo:e.undo}:{},objects:gn(e).map(c=>c.objectApiName),records:gn(e).reduce((c,l)=>c+l.count,0)},...a?{close:a}:{}}}async otherPartFromPlan(e,t,r,n){if(!e||e.targetOrgId!==t||this.removing.has(e.forgeId)||Ur(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=Ul(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:Ur(e).map(c=>c.objectApiName),records:Ur(e).reduce((c,l)=>c+l.count,0)},...a?{close:a}:{}}}async alongside(e,t,r,n,o,i){let a={...n,...o?await this.runJournal?.stampsOf(o.journalId,o.part).catch(()=>({})):{}};return{plan:e,span:CA(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 _o({input:async()=>{let o=await this.sweepInputOf(r,t,e.signal);return"gone"in o?{refused:o.gone}:o},org:Qr(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:Ho(i)}:{},objects:Mo(o),details:Lo(o,r.forgeId),...a?{muted:dt(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=Hr(o),a=await this.sweepPartsBeside(e),d=new Set(Object.values(o.idRemapTable??{}).map(p=>p.slice(0,15))),c=this.targetAutomation,l=e.targetOrgId??"",u;if(!c)u={error:"Target automation reader not configured"};else try{u=await new ge(bi).withTimeout("forge:undo-sweep automation",()=>c.read(l,i.map(p=>p.objectApiName)))}catch(p){u={error:I(p)}}return Fo({writtenBetween:e.writtenBetween,created:i,remap:d,automation:DR(u),...e.runUserId?{runUserId:e.runUserId}:{},ties:await this.tiesOf(e),...a.length>0?{otherParts:a}:{},...r?{signal:r}:{}},or(t,"forge:undo-sweep copies"))}async sweepPartsBeside(e){let t=this.loadHistory(),r=new Set(t.map(a=>a.forgeId)),n=(await this.keptRemovalPlans()).filter(a=>!r.has(a.forgeId)),o=[],i=0;for(let a of await this.runLineOf(e.forgeId,t,n)){i++;let d=t.find(u=>u.forgeId===a),c=d?void 0:n.find(u=>u.forgeId===a);if((d??c)?.targetOrgId!==e.targetOrgId)continue;let l;if(d){let u=await this.withIdsOf(d);"gone"in u||(l=Hr(u.entry))}else if(c?.inJournal){let u=await this.planRecordsOf({...c,inJournal:c.inJournal},!0);"gone"in u||(l=u.records)}else c&&(l=c.objects);l&&o.push({part:d?.journalPart??c?.inJournal?.part??i,created:l})}return o}async tiesOf(e){let t=e.writtenBetween,r=await this.localRunsOn(e.targetOrgId,t,e.forgeId);e.targetOrgId!==void 0&&r.push(...await this.otherModuleRuns(e.targetOrgId,t).catch(()=>[]));let n=e.mutedAutomation,o=ZR(e.removalSpans),i=await this.removalPlans?.madeOf(e.forgeId).catch(()=>[]),a=await this.removalPlans?.lateOf(e.forgeId).catch(()=>[]);return{otherRuns:KR(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(!YR(t,d))return{ids:[],...d};let l=await c();return l?{ids:l.flatMap(({ids:u})=>u),...d}:{ids:[],idsUntold:!0,...d}};for(let d of this.loadHistory()){if(o.add(d.forgeId),d.forgeId===r||d.targetOrgId!==e)continue;let c=RA(d);i.push(d.remapInJournal?await a(c,async()=>{let l=await this.withIdsOf(d);return"gone"in l?void 0:Hr(l.entry)}):{ids:Hr(d).flatMap(({ids:l})=>l),...c})}for(let d of n??[]){if(o.has(d.forgeId)||d.forgeId===r||d.targetOrgId!==e)continue;let c=RA(d),l=d.inJournal;i.push(l?await a(c,async()=>{let u=await this.planRecordsOf({...d,inJournal:l},!0);return"gone"in u?void 0:u.records}):{ids:d.objects.flatMap(({ids:u})=>u),...c})}return i}setOtherModuleRuns(e){this.otherModuleRuns=e}setJournalLocks(e){this.journalLocks=e}journalBusy(e,t){let r=t==="remove"?"Removing its records now would delete under it what it goes on writing; remove them once it has ended.":"Taken up now, two runs would write the same journal; resume it once it has ended.";if(this.journalsRunning.has(e))return`A run of this window still writes this run's journal \u2014 a part that resumes it. ${r} Stop it on the Forge page, or let it end. Nothing was read or written.`;let n=this.runJournal;if(!n)return;let o;try{o=this.journalLocks.holder(n.pathOf(e))}catch(i){return`The lock of this run's journal, in ${Rg(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`${wi(_a(o))}. ${r} ${wi(Ha(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:me(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:`${wi(_a(n.busy))}. Removing its records now would delete under it what it goes on writing; remove them once it has ended. ${wi(Ha(n.busy))}. Nothing was read or written.`}:n}async handleUndoSweep(e){let t=nt(ij,e,"forge:undo-sweep:error",this.deps);if(!t)return;let r=(a,d)=>E(this.deps,"forge:undo-sweep","forge:undo-sweep:error",e,new Error(a),{code:d}),n=this.loadHistory().find(a=>a.forgeId===t.forgeId);if(!n){r(SA,ns);return}let o=n.journalId?this.journalBusy(n.journalId,"remove"):void 0;if(o){r(o,yi);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. "+Mc,"NOT_RECORDED");return}try{let a=await new ge(Lj).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:jo(Qr(d,"forge:undo-sweep"),c,n.removalSpans??[])});if("gone"in a){r(a.gone,rs);return}this.deps.broker.postToWebview(T(this.deps,e,"forge:undo-sweep:response",{forgeId:t.forgeId,listing:a}))}catch(a){let d=a instanceof yr;E(this.deps,"forge:undo-sweep","forge:undo-sweep:error",e,a,{code:d?"TIMEOUT":"SWEEP_ERROR",retryable:!0})}}async handlePlanRequest(e){if(!this.planGenerator){E(this.deps,"forge:plan","forge:plan:error",e,new Error("Plan generator not configured"),{code:"NOT_INITIALIZED"});return}let t=nt(pj,e,"forge:plan:error",this.deps);if(!t)return;let{graph:r,config:n}=t,o=`forge-plan-${this.deps.nextId()}`;ze(this.deps,o,"forge","Generating execution plan");try{oe.info("Forge plan generation started");let i=await this.readPersonalFields(r,n),a=await new ge(bA).withTimeout("forge:plan",()=>Promise.resolve(this.planGenerator.generate(i))),d=T(this.deps,e,"forge:plan:response",i===r?{plan:a}:{plan:a,graph:i});this.deps.broker.postToWebview(d),pe(this.deps,o,{waveCount:a.waves?.length??0})}catch(i){let a=i instanceof yr;E(this.deps,"forge:plan","forge:plan:error",e,i,{code:a?"TIMEOUT":"PLAN_ERROR",retryable:a}),pe(this.deps,o,{status:"failure"})}}async readPersonalFields(e,t){let r=this.orchestrator;if(!r)return e;try{return await new ge(bA).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){E(this.deps,"forge:compliance","forge:compliance:error",e,new Error("Compliance service not configured"),{code:"NOT_INITIALIZED"});return}let t=nt(gj,e,"forge:compliance:error",this.deps);if(!t)return;let{framework:r,graph:n,config:o,anonymizationRules:i}=t,a=`forge-compliance-${this.deps.nextId()}`;ze(this.deps,a,"forge","Generating compliance report");try{oe.info("Forge compliance report generation started");let d=await new ge(jj).withTimeout("forge:compliance",()=>Promise.resolve(this.complianceService.generate(r,n,o,i))),c=T(this.deps,e,"forge:compliance:response",{report:d});this.deps.broker.postToWebview(c),pe(this.deps,a,{framework:r})}catch(d){let c=d instanceof yr;E(this.deps,"forge:compliance","forge:compliance:error",e,d,{code:c?"TIMEOUT":"COMPLIANCE_ERROR",retryable:c}),pe(this.deps,a,{status:"failure"})}}async handleMetadataDiffRequest(e){if(!this.metadataDiff){E(this.deps,"forge:metadata-diff","forge:metadata-diff:error",e,new Error("Metadata diff service not configured"),{code:"NOT_INITIALIZED"});return}let t=nt(fj,e,"forge:metadata-diff:error",this.deps);if(!t)return;let{sourceOrgId:r,targetOrgId:n,objectApiNames:o}=t,i=`forge-metadata-diff-${this.deps.nextId()}`;ze(this.deps,i,"forge","Comparing metadata schemas");try{oe.info("Forge metadata diff started");let a=await new ge(Mj).withTimeout("forge:metadata-diff",()=>this.metadataDiff.compare(r,n,o)),d=T(this.deps,e,"forge:metadata-diff:response",{diffs:a});this.deps.broker.postToWebview(d),oe.info("Forge metadata diff finished",{objects:o.length,differences:a.length,objectsMissing:a.filter(c=>c.issue==="object_missing").length}),pe(this.deps,i,{objectCount:o.length})}catch(a){let d=a instanceof yr;E(this.deps,"forge:metadata-diff","forge:metadata-diff:error",e,a,{code:d?"TIMEOUT":"METADATA_DIFF_ERROR",retryable:d}),pe(this.deps,i,{status:"failure"})}}async handleRehearseRequest(e){let t=this.rehearser,r=(b,v,C=!1)=>E(this.deps,"forge:rehearse","forge:rehearse:error",e,b,{code:v,retryable:C});if(!t){r(new Error("Forge rehearsal is not initialized"),"NOT_INITIALIZED");return}let n=nt(hj,e,"forge:rehearse:error",this.deps);if(!n)return;let{graph:o,config:i,anonymizationRules:a}=n;if(i.inputMode==="org"){r(new Error(JN),GN);return}let d=(b,v,C={})=>Z(this.deps,{action:"forge_rehearse",module:"forge",operationId:b,orgId:i.targetOrgId,outcome:v,...C}),c=(b,v,C=!1)=>{d(e.id,"stopped",{code:v}),r(b,v,C)},l=this.deps.infraServices?.productionGuard;if(!l){c(new Error(Se.message),Se.code);return}let u=this.deps.orgManager.getOrg(i.targetOrgId),p=Ce(u),g=me(u,i.targetOrgId);if(p==="production"){c(new Error(`${g} 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."),Og,!0);return}let h=`forge-rehearse-${this.deps.nextId()}`,f="Rehearsing a forge run";this.rehearseOperationId=h,ze(this.deps,h,"forge",f);let m=new AbortController,y=this.trackRun(h,f,m);this.liveTracker?.register(h,"forge",f);let R,k=!1,w=b=>this.deps.broker.postToWebview(T(this.deps,e,"forge:rehearse:progress",{...b})),O=b=>{if(b.phase!=="rehearsing"||!b.call||!b.calls)return;let v=Math.min(100,Math.round((b.call-1)/b.calls*100));m.signal.aborted||this.deps.infraServices?.backgroundRegistry?.updateProgress(h,v),this.liveTracker?.updateProgress(h,v,b.call-1,b.calls,`call ${b.call} of ${b.calls}`)},P=jc(w,100);try{let b=await this.automationBeforeTheRun(i.targetOrgId,o),v="automation"in b?b.automation:void 0,C=await this.loadRecordTypeMappings(i,new AbortController().signal,{requests:0}),S=await t.rehearse(o,i,{recordTypeMappings:C,anonymizationRules:a,signal:m.signal,onProgress:A=>{if(A.phase==="reading"){P(A);return}P.flush(),w(A),O(A)},confirm:async A=>{let D=await l.confirmRun({stage:"rehearsal",org:g,orgTier:p,rows:A.rows,sampled:A.sampled,updates:A.updates.reduce((z,U)=>z+U.updates,0),calls:A.calls,maxCalls:A.maxCalls,fired:v?vu(v):[],firedOnUpdate:v?ku(v,A.updates.map(z=>z.objectApiName)):[],unread:v?Iu(v):[{part:"automation",reason:"unread"in b?b.unread:""}]});if(D==="confirmed"){k=!0;return}throw new Lc(D==="declined"?"REHEARSAL_DECLINED":"CONFIRMATION_UNAVAILABLE",D==="declined"?"The rehearsal was cancelled at its confirmation. Nothing was sent to the target.":"The rehearsal needed a confirmation, and there was no one to ask. Nothing was sent to the target.")}});this.deps.broker.postToWebview(T(this.deps,e,"forge:rehearse:response",{rehearsal:S})),this.trials.note("rehearsal",Nu(o,i)),oe.info("Forge rehearsal",{rows:S.rows,sampled:S.sampled,judged:S.judged,passed:S.passed,notJudged:S.notJudged,calls:S.calls,plannedCalls:S.plannedCalls,codes:[...new Set(S.gaps.flatMap(A=>typeof A.detail?.statusCode=="string"?[A.detail.statusCode]:[]))]}),d(h,"success",{guard:k?"confirmed":"allowed",details:o0(S)}),pe(this.deps,h,{status:"success"}),this.liveTracker?.complete(h)}catch(b){let v=b instanceof Lc?b:void 0,C=b instanceof UR?b:void 0,S=b instanceof HR?b:void 0,A=I(b);if(r(b instanceof Error?b:new Error(A),v?.code??(C?"REHEARSAL_CANCELLED":"REHEARSAL_ERROR"),!0),v||C){let D=v?.code==="REHEARSAL_DECLINED"?"declined":k?"confirmed":void 0;d(h,"stopped",{code:v?.code??"REHEARSAL_CANCELLED",...D?{guard:D}:{},...C?{details:{calls:C.calls}}:{}}),pe(this.deps,h,{aborted:!0}),this.liveTracker?.cancel(h)}else R=b,d(h,"failure",{...k?{guard:"confirmed"}:{},...S?{code:"REHEARSAL_NOT_ROLLED_BACK",details:{recordsLeft:S.ids.length},objects:S.objects.map(({objectApiName:D,created:z})=>({objectApiName:D,created:z,updated:0,deleted:0,failed:0}))}:{}}),De(this.deps,h,A,!0),this.liveTracker?.fail(h,A)}finally{P.flush(),y(R),this.rehearseOperationId===h&&(this.rehearseOperationId=null)}}async handleAutomationRequest(e){if(!this.targetAutomation){E(this.deps,"forge:automation","forge:automation:error",e,new Error("Target automation reader not configured"),{code:"NOT_INITIALIZED"});return}let t=nt(mj,e,"forge:automation:error",this.deps);if(!t)return;let{targetOrgId:r,graph:n}=t,o=`forge-automation-${this.deps.nextId()}`;ze(this.deps,o,"forge","Reading the target org's automation");try{let i=new ge(bi).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(T(this.deps,e,"forge:automation:response",{automation:a})),oe.info("Forge target automation read",{objects:a.objectsRead.length,objectsWithAutomation:a.objects.length,flows:a.objects.reduce((d,c)=>d+c.flows.length,0),triggers:a.objects.reduce((d,c)=>d+c.triggers.length,0),conditionsNotRead:a.conditionsNotRead,unread:a.unread.map(d=>d.part),requests:a.requests}),pe(this.deps,o,{objectCount:a.objectsRead.length})}catch(i){let a=i instanceof yr;E(this.deps,"forge:automation","forge:automation:error",e,i,{code:a?"TIMEOUT":"AUTOMATION_ERROR",retryable:a}),pe(this.deps,o,{status:"failure"})}}async readDeliverability(e,t){let r=()=>{},n=new Promise((o,i)=>{r=()=>i(new Error(jn)),t?.addEventListener("abort",r,{once:!0})});try{return await Promise.race([new ge(Xw).withTimeout("forge:deliverability",async()=>qt(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=Ou(t,{leftOut:new Set(t.nodes.filter(Hi).map(d=>d.objectApiName))}),i=new Set(o.map(d=>d.objectApiName)),{ofRun:a}=await ir({read:r,writes:(d,c)=>c==="insert"||c==="update"&&i.has(d),readDeliverability:()=>Ce(n)==="production"?Promise.resolve(Bt):this.readDeliverability(e),accepted:!1,target:me(n,e),run:"clone"});return a.read?{...r,deliverability:a.read.reading,requests:r.requests+a.read.requests}:r}async handleUndoAutomation(e){let t=nt(sj,e,"forge:undo-automation:error",this.deps);if(!t)return;let r=(c,l)=>E(this.deps,"forge:undo-automation","forge:undo-automation:error",e,c,{code:l}),n=this.targetAutomation;if(!n){r(new Error("Target automation reader not configured"),"NOT_INITIALIZED");return}let o=this.loadHistory().find(c=>c.forgeId===t.forgeId);if(!o?.targetOrgId){r(new Error("This run is no longer in the Forge history."),ns);return}let i=o.journalId?this.journalBusy(o.journalId,"remove"):void 0;if(i){r(new Error(i),yi);return}let a=(t.again===!0?Rf(o):gn(o)).map(c=>c.objectApiName),d=o.targetOrgId;try{let c=await this.otherPartObjectsOf(t.forgeId,d),l=[...new Set([...Rn(a,c,{userKept:o.runUserId!==void 0}),...t.sweptObjects??[]])],u=await new ge(bi).withTimeout("forge:undo-automation",()=>n.read(d,l));this.deps.broker.postToWebview(T(this.deps,e,"forge:undo-automation:response",{forgeId:t.forgeId,automation:u,drafted:nr(a)}))}catch(c){let l=c instanceof yr;E(this.deps,"forge:undo-automation","forge:undo-automation:error",e,c,{code:l?"TIMEOUT":"AUTOMATION_ERROR",retryable:l})}}async handleGapsRequest(e){if(!this.targetGaps){E(this.deps,"forge:gaps","forge:gaps:error",e,new Error("Target gap reader not configured"),{code:"NOT_INITIALIZED"});return}let t=nt(yj,e,"forge:gaps:error",this.deps);if(!t)return;let{graph:r,config:n}=t,o=this.targetGaps,i=`forge-gaps-${this.deps.nextId()}`;ze(this.deps,i,"forge","Reading what the target org holds against the rows");try{let a=await new ge(Fj).withTimeout("forge:gaps",()=>o.read(n.sourceOrgId,n.targetOrgId,r,n));this.deps.broker.postToWebview(T(this.deps,e,"forge:gaps:response",{gaps:a})),oe.info("Forge target gaps read",{gaps:a.gaps.length,blocking:a.gaps.filter(d=>d.severity==="blocking").length,kinds:[...new Set(a.gaps.map(d=>d.kind))],unread:a.unread.map(d=>d.part),requests:a.requests}),pe(this.deps,i,{objectCount:r.nodes.length})}catch(a){let d=a instanceof yr;E(this.deps,"forge:gaps","forge:gaps:error",e,a,{code:d?"TIMEOUT":"GAPS_ERROR",retryable:d}),pe(this.deps,i,{status:"failure"})}}async handleUsersRequest(e){let t=nt(wj,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(aA);$e(r.limitInfo,"forge:users query");let{users:o,truncated:i}=dA(n.records,n.done===!1);this.deps.broker.postToWebview(T(this.deps,e,"forge:users:response",{orgId:t.orgId,users:o,truncated:i}))}catch(r){E(this.deps,"forge:users","forge:users:error",e,r,{code:"USERS_ERROR"})}}async handleTargetRecordsRequest(e){let t=nt(bj,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 ge(os).withTimeout("forge:target-records",()=>r.request(`/services/data/v${r.version}/limits/recordCount`)),o=fb(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(T(this.deps,e,"forge:target-records:response",{targetOrgId:t.targetOrgId,objects:i}))}catch(r){E(this.deps,"forge:target-records","forge:target-records:error",e,r,{code:"TARGET_RECORDS_ERROR"})}}async handleSampleBudgetRequest(e){let t=nt(Rj,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=xR({graph:r,options:n.sample,...n.excludedObjects?{excludedObjects:n.excludedObjects}:{},storage:o,source:i,maxRecordsPerObject:this.maxRecordsPerObject()});this.deps.broker.postToWebview(T(this.deps,e,"forge:sample-budget:response",{targetOrgId:n.targetOrgId,budget:a}))}catch(o){E(this.deps,"forge:sample-budget","forge:sample-budget:error",e,o,{code:"SAMPLE_BUDGET_ERROR"})}}async handlePreviewRoots(e){let t=nt(Sj,e,"forge:previewRoots:error",this.deps);if(!t)return;let{sourceOrgId:r,soqlQuery:n}=t,o=t.maxRoots??this.maxRoots(),i=ib(n);if("issue"in i){let c=lb(i.issue,void 0);this.deps.broker.postToWebview(T(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),l=d.limit!==void 0&&d.limit<=o?d.limit:o+1,{records:u,pages:p}=await new ge(Nj).withTimeout("forge:previewRoots",()=>tr({query:async g=>c.query(g),queryMore:async g=>c.queryMore(g)},ab(a,d,void 0,o),l));$e(c.limitInfo,`forge:previewRoots ${a}`),this.deps.broker.postToWebview(T(this.deps,e,"forge:previewRoots:response",{sourceOrgId:r,soqlQuery:n,objectApiName:a,cap:o,chosen:Math.min(u.length,o),more:u.length>o,...d.limit!==void 0?{limit:d.limit}:{},...d.orderBy!==void 0?{orderBy:d.orderBy}:{},requests:p}))}catch(c){E(this.deps,"forge:previewRoots","forge:previewRoots:error",e,c,{code:"ROOTS_PREVIEW_ERROR",retryable:!0,extraPayload:{soqlQuery:n}})}}maxRoots(){let e=this.deps.services?.getSandforgeSetting?.("forge.maxRoots",$l);return sb(typeof e=="number"?e:void 0,$l)}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(!xl(t)||t.inputMode!=="soql")return;let r=await this.readSourceApiBudget(t,e.lookup),n="unread"in r?void 0:r.remaining,o=n!==void 0?{sourceRequestsLeft:n}:{};if(e.retried&&!e.resumes){let{objectApiName:u,ids:p,sha256:g,readAt:h,query:f}=e.retried;return{...o,plan:{version:1,sourceOrgId:t.sourceOrgId,fingerprint:"",objectApiName:u,...f?{query:f}:{},from:"query",readAt:h,ids:p,sha256:g},planOfTheRunRetried:!0}}let i=this.runJournal?.storagePath;if(i===void 0||e.resumes)return o;await vR(i,new Date).catch(u=>{oe.warn(`Forge roots: the roots of past simulations were not swept (${I(u)})`)});let d=this.setupFingerprintOf(e.graph,t,e.anonymizationRules,e.readCeiling),c;try{c=RR(i,d)}catch(u){if(u instanceof xu)return o;throw u}if(e.dryRun)return{...o,keepAt:c,fingerprint:d};let l;try{l=await SR(c)}catch(u){if(!(u instanceof xu))throw u;u.fault==="changed"&&oe.warn(`Forge roots: the simulation's roots no longer read whole (${u.message})`)}return{...o,fingerprint:d,...l?{plan:l}:{}}}};import{randomUUID as s0}from"node:crypto";import*as DA from"node:os";import*as xr from"node:path";var $A=50*1024*1024,i0=new Set(["migration:pick-file","migration:import-sfdmu","migration:save-sync-config"]),a0="Saved from the SandForge Migration page",d0=new Set([".json"]);function c0(s,e,t){if(typeof s!="string"||s.trim().length===0)throw new Error("Invalid import path: path is empty.");if(!xr.isAbsolute(s))throw new Error(`Invalid import path: "${s}" is not absolute. Pick a file inside the workspace or your home directory.`);let r=xr.resolve(s),n=xr.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=xr.resolve(i);if(process.platform==="win32"){let d=r.toLowerCase(),c=a.toLowerCase();return d===c||d.startsWith(c+xr.sep)}return r===a||r.startsWith(a+xr.sep)}))throw new Error("Invalid import path: the file must be inside an open workspace folder or your home directory.");return r}async function xA(s,e){let t=await s.statSize(e);if(t>$A){let r=(t/1048576).toFixed(1),n=$A/(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 _c=class{constructor(e){this.deps=e}deps;fileReader;setFileReader(e){this.fileReader=e}async handle(e){if(!i0.has(e.type))return!1;switch(e.type){case"migration:pick-file":return await this.handlePickFile(e),!0;case"migration:import-sfdmu":return await this.handleImportSfdmu(e),!0;case"migration:save-sync-config":return this.handleSaveSyncConfig(e),!0;default:return!1}}handleSaveSyncConfig(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(hy,e,"migration:error",this.deps);if(!t)return;let r=n=>{this.deps.broker.postToWebview(T(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 Ot(this.deps.configStore);if(Lf(o.list(),n)){r({success:!1,code:"DUPLICATE_NAME"});return}let a=(Array.isArray(t.config.objects)?t.config.objects:[]).map(u=>typeof u=="object"&&u!==null?u.objectApiName:void 0).filter(u=>typeof u=="string").filter(u=>ta(u));if(a.length>0){r({success:!1,code:"SYNC_CANNOT_COPY",objects:a});return}let d=new Date().toISOString(),c=Mh.safeParse({...t.config,id:s0(),name:n,description:a0,createdAt:d,updatedAt:d});if(!c.success){let[u]=c.error.issues;r({success:!1,code:"INVALID_CONFIG",reason:u?`${u.path.join(".")}: ${u.message}`:c.error.message});return}let l=c.data;o.save(l),this.deps.log(`[TX] migration:save-sync-config:response saved ${l.id}`),r({success:!0,id:l.id,name:l.name})}catch(n){E(this.deps,"migration:save-sync-config","migration:error",e,n)}}getAllowedBaseDirs(){return[...this.deps.services?.getWorkspaceFolders?.()??[],DA.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(T(this.deps,e,"migration:pick-file:response",r===void 0?{}:{filePath:r}))}catch(t){E(this.deps,"migration:pick-file","migration:error",e,t)}}async handleImportSfdmu(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(fy,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=c0(r,d0,this.getAllowedBaseDirs());await xA(n,o);let{SfdmuImporter:i,SfdmuRefusal:a}=await import("./chunk-LNXBCE7E.mjs"),d=new i({readFile:async c=>(c!==o&&await xA(n,c),n.readFile(c))});try{let{config:c,notes:l}=await d.import(o),u=T(this.deps,e,"migration:import-sfdmu:response",{success:!0,config:c,notes:l});this.deps.broker.postToWebview(u)}catch(c){if(!(c instanceof a))throw c;this.deps.log(`[ERR] migration:import-sfdmu: ${c.message}`),this.deps.broker.postToWebview(T(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=T(this.deps,e,"migration:import-sfdmu:response",{success:!1,error:I(n)});this.deps.broker.postToWebview(o)}}};import*as ss from"node:fs/promises";var LA="settings",NA=G({version:j(),exportedAt:j(),exportedBy:j().optional(),categories:Re(_e(["syncMappings","forgePlans","pipelines","anonymizationTemplates",LA])),data:Pi(j(),un())});function jA(s){return s!==LA}var Ag={syncMappings:"sync:config:",forgePlans:"forge:templates",pipelines:"pipeline:saved:",anonymizationTemplates:"anonymization:"},MA={syncMappings:"syncConfigs",forgePlans:"forge",pipelines:"pipelines",anonymizationTemplates:"anonymizationTemplates"},Ri="forge:templates";function l0(s){return typeof s.name=="string"&&s.name.length>0?s.name:s.id}var Hc=class{constructor(e,t){this.configStore=e;this.workspace=t}configStore;workspace;async exportProfile(e,t){try{let r={},n=0;for(let i of e){if(i==="forgePlans"){let l=await this.heldTemplates();r[i]=l.length>0?{[Ri]:l}:{},n+=l.length;continue}let a=Ag[i],d=this.configStore.getKeysByPrefix(a),c={};for(let l of d){let u=this.configStore.get(l);u!==void 0&&(c[l]=u,n++)}r[i]=c}let o={version:"1.0.0",exportedAt:new Date().toISOString(),exportedBy:t,categories:e,data:r};return{success:!0,json:JSON.stringify(o,null,2),categoriesExported:e.length,entriesExported:n}}catch(r){return{success:!1,categoriesExported:0,entriesExported:0,error:r instanceof Error?r.message:String(r)}}}async importProfile(e,t=!0){let r=[];try{let n=JSON.parse(e),o=NA.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(jA),d=0;for(let c of a){let l=i.data[c];if(!l||typeof l!="object"){r.push(`Category "${c}" has no data, skipped.`);continue}if(c==="forgePlans"){d+=await this.importTemplates(l,t,r);continue}let u=Ag[c];for(let[p,g]of Object.entries(l)){if(!p.startsWith(u)){r.push(`Key "${p}" does not match expected prefix "${u}" for category "${c}", skipped.`);continue}if(!t&&this.configStore.has(p)){r.push(`Key "${p}" already exists, skipped.`);continue}if(this.configStore.set(p,g,MA[c]),d++,c==="pipelines"){let h=GS(this.configStore,p.slice(u.length));h.length>0&&r.push(`Pipeline "${p}" was written over: confirm its Rewind ${h.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=NA.safeParse(t);return r.success?{valid:!0,categories:r.data.categories.filter(jA)}:{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(Ag)){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(Ri);return Array.isArray(r)?r.filter(cn):[]}let e=await this.workspace.readTemplates(),t=Nc(this.configStore,this.workspace.folder);return t?mi(e,t.templates,new Set(t.replacing)):[...e]}async importTemplates(e,t,r){let n=await this.heldTemplates(),o=new Set(n.map(c=>c.id)),i=new Set,a=[],d=[];for(let[c,l]of Object.entries(e)){if(c!==Ri){r.push(`Key "${c}" does not match expected prefix "${Ri}" for category "forgePlans", skipped.`);continue}if(!Array.isArray(l)){r.push(`Key "${c}" holds no list of templates, skipped.`);continue}for(let u of l){if(!cn(u)){r.push(`An entry of "${c}" has no id, skipped.`);continue}if(!i.has(u.id)){if(i.add(u.id),o.has(u.id)){if(!t){r.push(`Forge template "${l0(u)}" already exists, skipped.`);continue}d.push(u.id)}a.push(u)}}}return this.workspace?oA(this.configStore,this.workspace.folder,a,d):a.length>0&&this.configStore.set(Ri,mi(n,a,new Set(d)),MA.forgePlans),a.length}};import*as Tg from"node:path";var Uc=class{deps;filePath;constructor(e){this.deps=e,this.filePath=Tg.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(cn):[]}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=mi(r,e.filter(cn),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=Tg.join(this.deps.workspacePath,".sandforge");await this.deps.mkdir(t).catch(()=>{}),await this.deps.writeFile(this.filePath,JSON.stringify(e,null,2))}};var u0=new Set(["config:export","config:import","config:categories","config:validate"]);function p0(s){let e=s.services?.getWorkspaceFolders?.()[0];if(!e)return;let t=new Uc({workspacePath:e,readFile:r=>ss.readFile(r,"utf-8"),writeFile:(r,n)=>ss.writeFile(r,n,"utf-8"),mkdir:r=>ss.mkdir(r,{recursive:!0}).then(()=>{})});return{folder:e,readTemplates:()=>t.list()}}var Bc=class{constructor(e){this.deps=e;this.profileManager=new Hc(e.configStore,p0(e))}deps;profileManager;async handle(e){if(!u0.has(e.type))return!1;switch(e.type){case"config:export":return await this.handleExport(e),!0;case"config:import":return await this.handleImport(e),!0;case"config:categories":return await this.handleCategories(e),!0;case"config:validate":return this.handleValidate(e),!0;default:return!1}}async handleExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(vy,e,"config:error",this.deps);if(!t)return;let r=t;try{let n=await this.profileManager.exportProfile(r.categories),o=T(this.deps,e,"config:export:response",{success:n.success,json:n.json,categoriesExported:n.categoriesExported,entriesExported:n.entriesExported,error:n.error});this.deps.broker.postToWebview(o),this.deps.log(`[TX] config:export:response (${n.entriesExported} entries)`)}catch(n){E(this.deps,"config:export","config:error",e,n)}}async handleImport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ky,e,"config:error",this.deps);if(!t)return;let r=t;try{let n=await this.profileManager.importProfile(r.json,r.overwrite),o=T(this.deps,e,"config:import:response",{success:n.success,categoriesImported:n.categoriesImported,entriesImported:n.entriesImported,warnings:n.warnings,error:n.error});this.deps.broker.postToWebview(o),this.deps.log(`[TX] config:import:response (${n.entriesImported} entries)`)}catch(n){E(this.deps,"config:import","config:error",e,n)}}async handleCategories(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=await this.profileManager.listCategories(),r=T(this.deps,e,"config:categories:response",{categories:t});this.deps.broker.postToWebview(r),this.deps.log("[TX] config:categories:response")}catch(t){E(this.deps,"config:categories","config:error",e,t)}}handleValidate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Oy,e,"config:error",this.deps);if(!t)return;let r=t;try{let n=this.profileManager.validateProfile(r.json),o=T(this.deps,e,"config:validate:response",{valid:n.valid,categories:n.categories,error:n.error});this.deps.broker.postToWebview(o),this.deps.log("[TX] config:validate:response")}catch(n){E(this.deps,"config:validate","config:error",e,n)}}};var g0=G({metric:j(),operator:_e(["gt","gte","lt","lte","eq","neq"]),threshold:Te(),warningThreshold:Te().optional()}),f0=G({id:j(),name:j(),description:j(),category:_e(["security","performance","compliance","custom"]),condition:g0,remediation:j(),enabled:Ge()}),Si=G({id:j(),name:j(),description:j(),rules:Re(f0),createdAt:j(),updatedAt:j()});function FA(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 qc=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";FA(a,n,o)?d="fail":i!==void 0&&FA(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 Wc="governance:policy:",h0="governance",vi=class{constructor(e){this.configStore=e}configStore;getAll(){let e=this.configStore.getKeysByPrefix(Wc),t=[];for(let r of e){let n=this.configStore.get(r);if(n){let o=Si.safeParse(n);o.success&&t.push(o.data)}}return t}getById(e){let t=this.configStore.get(`${Wc}${e}`);if(!t)return;let r=Si.safeParse(t);return r.success?r.data:void 0}save(e){this.configStore.set(`${Wc}${e.id}`,e,h0)}delete(e){return this.configStore.delete(`${Wc}${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 m0={apiUsagePercent:"DailyApiRequests",storageUsagePercent:"DataStorageMB"},y0=new Set(["governance:policies:list","governance:policy:save","governance:policy:delete","governance:evaluate","governance:templates"]),zc=class{constructor(e,t){this.deps=e;this.store=new vi(e.configStore),this.engine=new qc,this.alertEngine=t}deps;store;engine;alertEngine;async handle(e){if(!y0.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=T(this.deps,e,"governance:policies:result",{policies:r});this.deps.broker.postToWebview(n),this.deps.log("[TX] governance:policies:result")}catch(t){E(this.deps,"governance:policies:list","governance:error",e,t)}}handlePolicySave(e){let t=x(wy,e,"governance:error",this.deps);if(t)try{let r=Si.safeParse(t.policy);if(!r.success){E(this.deps,"governance:policy:save","governance:error",e,new Error(`Validation failed: ${r.error.message}`),{code:"VALIDATION_ERROR"});return}this.store.save(r.data);let n=T(this.deps,e,"governance:policy:save:response",{success:!0});this.deps.broker.postToWebview(n),this.deps.log("[TX] governance:policy:save:response")}catch(r){E(this.deps,"governance:policy:save","governance:error",e,r)}}handlePolicyDelete(e){let t=x(yy,e,"governance:error",this.deps);if(t)try{let r=this.store.delete(t.policyId),n=T(this.deps,e,"governance:policy:delete:response",{success:r});this.deps.broker.postToWebview(n),this.deps.log("[TX] governance:policy:delete:response")}catch(r){E(this.deps,"governance:policy:delete","governance:error",e,r)}}async handleEvaluate(e){let t=x(by,e,"governance:error",this.deps);if(!t)return;let r=t;try{let n=this.store.getById(r.policyId);if(!n){E(this.deps,"governance:evaluate","governance:error",e,new Error(`Policy not found: ${r.policyId}`),{code:"NOT_FOUND"});return}let i=await(await q(r.orgId,this.deps.orgRegistry,this.deps.orgManager)).request(`/services/data/${ho}/limits`),a={};for(let[l,{Max:u,Remaining:p}]of Object.entries(i))a[l]=u>0?Math.round((u-p)/u*100):0;for(let[l,u]of Object.entries(m0))u in a&&(a[l]=a[u]);let d=this.engine.evaluatePolicy(n,a);if(this.alertEngine)for(let l of d.ruleResults)l.status==="fail"&&l.actualValue!==null&&this.alertEngine.evaluate(`governance:${l.ruleId}`,l.actualValue,r.orgId);let c=T(this.deps,e,"governance:evaluate:response",{success:!0,result:d});this.deps.broker.postToWebview(c),this.deps.log("[TX] governance:evaluate:response")}catch(n){E(this.deps,"governance:evaluate","governance:error",e,n)}}handleTemplates(e){try{let t=vi.getDefaultTemplates(),r=T(this.deps,e,"governance:templates:response",{templates:t});this.deps.broker.postToWebview(r),this.deps.log("[TX] governance:templates:response")}catch(t){E(this.deps,"governance:templates","governance:error",e,t)}}};var Gc=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 w0=new Set(["OpportunityId","CaseId","ContractId","OrderId"]),Jc=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)||dh(c))continue;let l=this.inferRelationshipType(d.name);a.push({childObject:e,parentObject:c,lookupField:d.name,relationshipType:l,suggestedInsertOrder:0})}return a}inferRelationshipType(e){return w0.has(e)?"masterDetail":"lookup"}};var Vc=class{estimate(e,t=new Set,r=200){let n=r>0?r:200,o=e.map(c=>({objectApiName:c.objectApiName,recordCount:c.count,...c.heldInSource!==void 0?{heldInSource:c.heldInSource}:{},estimatedApiCalls:c.count>0?Math.ceil(c.count/n):0,isParentDependency:t.has(c.objectApiName)})),i=o.reduce((c,l)=>c+l.recordCount,0),a=o.reduce((c,l)=>c+l.estimatedApiCalls,0),d=a*2;return{objects:o,totalRecords:i,totalApiCalls:a,estimatedDurationSec:d}}};var Xc=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 Lp(e,t)}inferType(e,t){return e.apiName===t.apiName&&e.type===t.type?"direct":e.apiName!==t.apiName?"rename":"direct"}};var b0=new Set(["quicksync:suggest-objects","quicksync:detect-relationships","quicksync:preview","quicksync:execute"]),ki={direction:"source_to_target",mode:"full",conflictStrategy:"source_wins",operation:"insert",batchSize:200},Kc=class{constructor(e){this.deps=e}deps;suggester=new Gc;relationshipDetector=new Jc;previewEstimator=new Vc;autoFieldMapper=new Xc;async handle(e){if(!b0.has(e.type))return!1;switch(e.type){case"quicksync:suggest-objects":return await this.handleSuggestObjects(e),!0;case"quicksync:detect-relationships":return await this.handleDetectRelationships(e),!0;case"quicksync:preview":return await this.handlePreview(e),!0;case"quicksync:execute":return await this.handleExecute(e),!0;default:return!1}}async handleSuggestObjects(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ty,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=T(this.deps,e,"quicksync:suggest-objects:response",{suggestions:a,availableObjects:[...i].sort((c,l)=>c.localeCompare(l))});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(n){E(this.deps,"quicksync:suggest-objects","quicksync:error",e,n)}}async handleDetectRelationships(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ry,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(l=>({name:l.name,type:l.type,referenceTo:l.referenceTo??[],relationshipName:l.relationshipName??null})),a=r.availableObjects??(await n.describeGlobal()).sobjects.filter(l=>l.createable&&l.queryable).map(l=>l.name),d=this.relationshipDetector.detect(r.objectApiName??"",i,r.alreadySelected??[],a),c=T(this.deps,e,"quicksync:detect-relationships:response",{suggestions:d});this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(n){E(this.deps,"quicksync:detect-relationships","quicksync:error",e,n)}}async handlePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(ny,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=Ya(this.deps.services?.getSandforgeSetting?.("sync.maxRecordsPerObject",void 0));for(let u of o){let g=(await n.query(`SELECT COUNT() FROM ${u}`)).totalSize??0;i.push({objectApiName:u,count:Math.min(g,a),...g>a?{heldInSource:g}:{}})}let d=new Set(r.parentObjects??[]),c={...this.previewEstimator.estimate(i,d),readCap:a},l=T(this.deps,e,"quicksync:preview:response",{preview:c});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`)}catch(n){E(this.deps,"quicksync:preview","quicksync:error",e,n)}}async handleExecute(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(oy,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let n=of.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 u=0;u<a.length;u++){let p=a[u],g=n.parentObjects.includes(p),[h,f]=await Promise.all([Kt(n.sourceOrgId,p,()=>o.describe(p)),Kt(n.targetOrgId,p,()=>i.describe(p))]),m=h.fields.filter(w=>w.createable).map(w=>({apiName:w.name,label:w.label,type:w.type})),y=f.fields.filter(w=>w.createable).map(w=>({apiName:w.name,label:w.label,type:w.type})),R=this.autoFieldMapper.suggest(m,y),k=this.autoFieldMapper.toMappings(R);d.push({objectApiName:p,operation:ki.operation,fieldMappings:k,transformRules:[],excludedFields:[],batchSize:ki.batchSize,insertOrder:g?0:u+1})}let c={id:e.id,name:`Quick Sync ${new Date().toISOString()}`,description:"Auto-generated by Quick Sync",sourceOrgId:n.sourceOrgId,targetOrgId:n.targetOrgId,direction:ki.direction,mode:ki.mode,objects:d,conflictStrategy:ki.conflictStrategy,enableRollback:!1};Ie(this.deps,"info","Quick Sync",`Starting sync of ${a.length} object(s)`);let l=T(this.deps,e,"quicksync:execute:response",{syncConfig:c,objectCount:a.length});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id}`)}catch(n){E(this.deps,"quicksync:execute","quicksync:error",e,n)}}};var _A=6e4,R0=2880*6e4,S0=60*6e4,Yc=class{deps;schedules=new Map;checkInterval;lastTickTime=0;claims;lastPrune=0;running=new Set;constructor(e){this.deps=e,this.claims=e.claims??Zo()}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()},_A),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+FS)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*_A&&this.deps.log(`[SyncScheduleExecutor] sleep-wake detected (elapsed ${Math.round(t/1e3)}s)`),this.lastTickTime=e,e-this.lastPrune>=S0&&(this.lastPrune=e,this.claims.prune(R0));for(let r of this.schedules.values()){if(!r.enabled||!r.nextRunAt)continue;let n=new Date(r.nextRunAt).getTime();if(Number.isNaN(n)){let i=r.nextRunAt;r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),this.deps.scheduleStore.save(r),this.deps.log(`[SyncScheduleExecutor] ${r.id}: next run "${i}" cannot be read, replaced by ${r.nextRunAt||"none"}`);continue}if(n>e||this.running.has(r.id))continue;if(!this.claims.claim(`sync-schedule:${r.id}:${n}`)){this.deps.log(`[SyncScheduleExecutor] ${r.id} due at ${r.nextRunAt} is run by another window`),r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone);continue}let o=this.deps.configStore.load(r.configId);if(!o){this.deps.log(`[SyncScheduleExecutor] config not found for schedule ${r.id} (configId=${r.configId})`),r.lastRunAt=new Date(e).toISOString(),r.lastResult="failure",r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),r.updatedAt=new Date(e).toISOString(),this.deps.scheduleStore.save(r),r.notifyOnFailure&&this.deps.notificationCenter.notify("error","Sync schedule failed",`${r.name}: sync configuration "${r.configId}" no longer exists. Save the configuration again, or delete the schedule.`);continue}r.notifyOnComplete&&this.deps.notificationCenter.notify("info","Sync schedule started",r.name),this.running.add(r.id);try{let i=await this.deps.onExecute(o);if(r.lastRunAt=new Date(e).toISOString(),r.lastResult=i.cancelled?"cancelled":i.status,r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),r.updatedAt=new Date(e).toISOString(),this.deps.scheduleStore.save(r),i.cancelled)r.notifyOnComplete&&this.deps.notificationCenter.notify("info","Sync schedule cancelled",`${r.name}: ${i.error??"the run was cancelled."} Its entry in the sync history has what it wrote.`);else if(i.status==="failure"){if(r.notifyOnFailure){let a=i.objectResults.flatMap(d=>d.errors)[0];this.deps.notificationCenter.notify("error","Sync schedule failed",`${r.name}: ${a??"the run failed; its entry in the sync history has the details."}`)}}else if(i.status==="partial"&&r.notifyOnComplete){let a=i.objectResults.flatMap(l=>l.errors)[0],d=Qa(i),c=[a,d].filter(l=>l!==void 0);this.deps.notificationCenter.notify("warning",a===void 0&&d!==void 0?"Sync schedule copied part of the source":"Sync schedule completed with errors",`${r.name}: ${c.length>0?c.join("; "):"some records failed; its entry in the sync history has the details."}`)}else r.notifyOnComplete&&this.deps.notificationCenter.notify("success","Sync schedule completed",r.name)}catch(i){if(r.lastRunAt=new Date(e).toISOString(),r.lastResult="failure",r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone),r.updatedAt=new Date(e).toISOString(),this.deps.scheduleStore.save(r),r.notifyOnFailure){let a=i instanceof Error?i.message:String(i);this.deps.notificationCenter.notify("error","Sync schedule failed",`${r.name}: ${a}`)}}finally{this.running.delete(r.id)}}}upsert(e){let t=this.schedules.get(e.id),r={...e,nextRunAt:this.computeNextRunAt(e.cron,e.timezone),lastRunAt:t?.lastRunAt,lastResult:t?.lastResult};return this.schedules.set(r.id,r),this.deps.scheduleStore.save(r),this.deps.log(`[SyncScheduleExecutor] upserted schedule ${r.id}`),r}delete(e){let t=this.schedules.delete(e);return t&&(this.deps.scheduleStore.delete(e),this.deps.log(`[SyncScheduleExecutor] deleted schedule ${e}`)),t}toggle(e,t){let r=this.schedules.get(e);if(r)return r.enabled=t,t&&(r.nextRunAt=this.computeNextRunAt(r.cron,r.timezone)),r.updatedAt=new Date(this.now()).toISOString(),this.deps.scheduleStore.save(r),this.deps.log(`[SyncScheduleExecutor] toggled ${e} -> ${t?"enabled":"disabled"}`),r}getSchedules(){return Array.from(this.schedules.values())}getSchedule(e){return this.schedules.get(e)}computeNextRunAt(e,t){let r=nd(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 Eg="schedule:sync:",HA="syncSchedules",Qc=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${Eg}${e.id}`,e,HA)}load(e){return this.configStore.get(`${Eg}${e}`)}list(){let e=this.configStore.getByCategory(HA);return Object.values(e).sort((r,n)=>n.createdAt.localeCompare(r.createdAt))}delete(e){return this.configStore.delete(`${Eg}${e}`)}loadAll(){return this.list()}};var v0=new Set(["sync:schedule:list","sync:schedule:upsert","sync:schedule:toggle","sync:schedule:delete"]),Zc=class{constructor(e){this.deps=e}deps;executor;executeBridge;inFlight=0;claims=Zo();async handle(e){if(!v0.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 Yc({scheduleStore:new Qc(this.deps.configStore),configStore:new Ot(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=T(this.deps,e,"sync:schedule:list:response",{schedules:t});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id}`)}catch(t){E(this.deps,"sync:schedule:list","sync:schedule:error",e,t)}}handleUpsert(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(rm,e,"sync:schedule:error",this.deps);if(!t)return;let r=t.schedule.configId;if(!new Ot(this.deps.configStore).load(r)){E(this.deps,"sync:schedule:upsert","sync:schedule:error",e,new Error(`Sync configuration not found: ${r}. Save it from the Sync tab first.`),{code:"NOT_FOUND"});return}let{cron:n,timezone:o}=t.schedule,i=nd(n,o,Date.now());if(typeof i!="number"){E(this.deps,"sync:schedule:upsert","sync:schedule:error",e,new Error(i.refused==="unreadable"?`The schedule was not saved: SandForge cannot read the cron expression "${n}" (${i.reason}).`:`The schedule was not saved. ${i.reason}`),{code:"INVALID_SCHEDULE"});return}try{let a=this.getExecutor().upsert(t.schedule),d=T(this.deps,e,"sync:schedule:upsert:response",{success:!0,schedule:a});this.deps.broker.postToWebview(d),this.deps.log(`[TX] ${d.type} id=${d.id}`)}catch(a){E(this.deps,"sync:schedule:upsert","sync:schedule:error",e,a)}}handleToggle(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(nm,e,"sync:schedule:error",this.deps);if(t)try{let r=this.getExecutor().toggle(t.scheduleId,t.enabled);if(!r){E(this.deps,"sync:schedule:toggle","sync:schedule:error",e,new Error(`Schedule not found: ${t.scheduleId}`),{code:"NOT_FOUND"});return}let n=T(this.deps,e,"sync:schedule:toggle:response",{success:!0,schedule:r,scheduleId:t.scheduleId,enabled:t.enabled});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){E(this.deps,"sync:schedule:toggle","sync:schedule:error",e,r)}}handleDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(om,e,"sync:schedule:error",this.deps);if(t)try{let r=this.getExecutor().delete(t.scheduleId),n=T(this.deps,e,"sync:schedule:delete:response",{success:r,scheduleId:t.scheduleId});this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id}`)}catch(r){E(this.deps,"sync:schedule:delete","sync:schedule:error",e,r)}}};var k0=new Set(["direct","rename"]);function UA(s,e,t,r={}){let n={objectApiName:s.objectApiName,fieldMappings:[],addOnFields:[],transformRules:[],applyDeletes:s.applyDeletes},o=r.keepContactPoints===!0?{keepContactPoints:!0}:{};switch(s.match.kind){case"id":return{...n,keyField:"Id",keySource:"Id",...o};case"externalId":return{...n,keyField:s.match.field,keySource:s.match.field,...o};case"syncConfig":{let i=e(s.match.configId);if(!i)throw new Error(`${s.objectApiName}: the saved Sync configuration picked no longer exists.`);if(i.sourceOrgId!==t.sourceOrgId||i.targetOrgId!==t.targetOrgId)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" runs between two other orgs.`);let a=i.objects.find(p=>p.objectApiName===s.objectApiName);if(!a)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" does not carry it.`);let d=mo([a]);if(d.length>0)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" cannot be applied. ${yo(d)}`);let c=wf([a]);if(c.length>0)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" cannot be applied. ${bf(c)}`);let l=a.externalIdField?.trim()||"Id",u=a.fieldMappings.find(p=>p.targetField===l&&k0.has(p.type));return{...n,keyField:l,keySource:l==="Id"?"Id":u?.sourceField??l,fieldMappings:a.fieldMappings,...a.excludedFields?.length?{excludedFields:a.excludedFields}:{},addOnFields:a.addOnFields,transformRules:a.transformRules,...i.keepContactPoints===!0?{keepContactPoints:!0}:{}}}}}var O0=G({entityName:j().min(1),changeType:j().min(1),recordIds:Re(j()),commitTimestamp:Te(),commitUser:j().optional(),transactionKey:j().optional(),changeOrigin:j().optional(),changedFields:Re(j()).optional(),nulledFields:Re(j()).optional()}).loose(),I0=G({event:G({replayId:Te()}).loose(),payload:G({ChangeEventHeader:O0}).loose()}).loose(),el="ChangeEvent";function qA(s){return`/data/${s.endsWith("__c")?s.slice(0,-1):s}${el}`}function WA(s){if(!s.endsWith(el)||s===el)return null;let e=s.slice(0,-el.length);return e.endsWith("__")?`${e}c`:e}function zA(s,e){return s.endsWith("__c")?`${s.slice(0,-3)}__${e}__s`:s.endsWith("Address")?`${s.slice(0,-7)}${e}`:e}function BA(s){let e=s.indexOf(".");return e<0?s:zA(s.slice(0,e),s.slice(e+1))}function A0(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function GA(s,e){let t=I0.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(A0(a))for(let[d,c]of Object.entries(a))o[zA(i,d)]=c;else o[i]=a;for(let i of r.nulledFields??[])o[BA(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(BA),values:o}}var Pg="SandForgeRealtime";function JA(s){return s.changeOrigin.split(";").some(e=>e.trim()===`client=${Pg}`)}var is=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 T0(s){return s instanceof Error?s.message:typeof s=="object"&&s!==null&&"message"in s?String(s.message):String(s)}function VA(s){let e=new Map,t=new Map,r=[],n=!1,o={added(a){a.disable("websocket")},outgoing(a,d){if(a.channel==="/meta/subscribe"&&a.subscription){let c=e.get(a.subscription);c!==void 0&&(a.ext={...a.ext??{},replay:{[a.subscription]:c}})}d(a)},incoming(a,d){if(a.channel==="/meta/subscribe"&&a.successful===!1)t.set(a.subscription??"",a.error??"refused without a reason");else if((a.channel==="/meta/handshake"||a.channel==="/meta/connect")&&a.successful===!1&&a.advice?.reconnect==="none"){if(!n){n=!0;let c=a.error??`${a.channel} refused`;for(let l of r)l(c)}}else if(!a.channel.startsWith("/meta/")){let c=a.data?.event?.replayId;typeof c=="number"&&e.has(a.channel)&&e.set(a.channel,c)}d(a)}},i=s.createClient([o]);return{subscribe(a,d,c){return e.set(a,d),t.delete(a),new Promise((l,u)=>{i.subscribe(a,c).then(()=>l(),p=>{e.delete(a),u(new is(a,t.get(a)??T0(p)))})})},onDown(a){r.push(a)},disconnect(){n=!0,i.disconnect()}}}var XA="SELECT EventChannel, SelectedEntity FROM PlatformEventChannelMember";function KA(s){let e=new Map;for(let t of s){let r=typeof t.SelectedEntity=="string"?t.SelectedEntity:"",n=WA(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 YA(s,e,t,r,n=()=>{}){let o=t.filter(i=>i.sourceOrgId===r.sourceOrgId&&i.targetOrgId===r.targetOrgId);return Promise.all(s.map(async({objectApiName:i,channel:a})=>{let d=!0,c=[];try{c=(await e(i)).fields.filter(u=>u.externalId===!0).map(u=>u.name).sort()}catch(l){d=!1,n(`[realtime] ${i} could not be described in the target: ${I(l)}`)}return{objectApiName:i,channel:a,inTarget:d,externalIdFields:c,syncConfigs:o.filter(l=>l.objects.some(u=>u.objectApiName===i)).map(l=>({id:l.id,name:l.name}))}}))}var rl=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}},Ln=200,QA=new Set(["int","double","currency","percent","long"]),E0="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 P0(s){return s==="DELETE"||s==="GAP_DELETE"}function ZA(s){return s==="CREATE"||s==="UNDELETE"}function tl(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 eT(s){return Object.fromEntries(Object.entries(s).filter(([e])=>e!=="attributes"))}function tT(s){return s==null||s===""}function Cg(s){return String(s).toLowerCase()}var nl=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:Ln,insertOrder:0}}plan;deps;mapping=new Ph;transforms=new Eh;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:E0});return}if(i.recordIds.length===0){t[a].push({outcome:"failed",error:"The change named no record."});return}let d=P0(i.changeType)?"delete":"upsert";if(d==="delete"&&!this.plan.applyDeletes){t[a].push({outcome:"deletes-off"});return}let c=o[o.length-1];(!c||c.kind!==d)&&(c={kind:d,changes:new Map},o.push(c));for(let l of i.recordIds){let u=c.changes.get(l);u?(u.eventIndexes.push(a),u.values={...u.values,...i.values},u.full=u.full||ZA(i.changeType),u.needsRead=u.needsRead||i.changeType.startsWith("GAP_"),u.commitTimestamp=Math.min(u.commitTimestamp,i.commitTimestamp),u.replayId=Math.max(u.replayId,i.replayId)):c.changes.set(l,{recordId:l,eventIndexes:[a],changeType:i.changeType,full:ZA(i.changeType),needsRead:i.changeType.startsWith("GAP_")&&d==="upsert",values:{...i.values},commitTimestamp:i.commitTimestamp,replayId:i.replayId})}});for(let i of o){let a=[...i.changes.values()],d=(c,l)=>{for(let u of c.eventIndexes)t[u].push(l)};try{i.kind==="upsert"?await this.applyUpserts(a,d,r):await this.applyDeletes(a,d,r)}catch(c){let l=I(c);for(let u of a)d(u,{outcome:"failed",error:l})}}return{results:t.map(C0),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"&&QA.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(g=>[g.name,g]));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(g=>g.needsRead),t);let i=e.filter(g=>!g.needsRead||g.full),a=await this.keysOf(i,t,!1);i=i.filter(g=>a.has(g.recordId));let d=await this.readTarget([...new Set([...a.values()])],o,this.writtenFieldsOf(i,a)),c=[],l=[];for(let g of i){let h=a.get(g.recordId),f=d.get(Cg(h))??[];if(f.length>1){t(g,{outcome:"failed",error:`${f.length} records of ${n} in the target have ${this.plan.keyField} = ${String(h)}.`});continue}let m=f[0];if(!m){this.plan.keyField==="Id"?t(g,{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."}):g.full?c.push({change:g,record:this.recordFor(g,h,o,!1)}):l.push(g);continue}let y=String(m.Id),R=this.recordFor(g,h,o,!0),k=tl(m.LastModifiedDate);if(!(k!==null&&k>g.commitTimestamp&&!this.deps.ownWrites.wrote(y,k))){c.push({change:g,record:R,targetId:y});continue}switch(this.deps.conflictStrategy){case"source_wins":c.push({change:g,record:R,targetId:y});break;case"merge":{let O=Object.fromEntries(Object.entries(R).filter(([P,b])=>b!==null||P===this.plan.keyField));Object.keys(O).length>1?c.push({change:g,record:O,targetId:y}):t(g,{outcome:"kept-target"});break}case"manual":r.push(this.held(g,"upsert",R,m)),t(g,{outcome:"held"});break;case"target_wins":case"newest_wins":t(g,{outcome:"kept-target"});break}}if(l.length>0){for(let g of l)g.needsRead=!0;await this.readWhole(l,t);for(let g of l.filter(h=>h.full))c.push({change:g,record:this.recordFor(g,a.get(g.recordId),o,!1)})}if(c.length===0)return;let{outcomes:u}=await this.deps.write(this.objectConfig,c.map(g=>g.record),this.contactPoints),p=[];c.forEach((g,h)=>{let f=u[h];if(f?.success){t(g.change,{outcome:"applied"});let m=f.id??g.targetId;m&&p.push(m)}else t(g.change,{outcome:"failed",error:f?.errors[0]??"The target answered nothing for this record."})}),await this.rememberWrites(p)}async applyDeletes(e,t,r){let n=this.plan.objectApiName,o=new Map((await this.deps.target.describe(n)).fields.map(u=>[u.name,u])),i=await this.keysOf(e,t,!0),a=e.filter(u=>i.has(u.recordId)),d=await this.readTarget([...new Set([...i.values()])],o,[]),c=[];for(let u of a){let p=i.get(u.recordId),g=d.get(Cg(p))??[];if(g.length>1){t(u,{outcome:"failed",error:`${g.length} records of ${n} in the target have ${this.plan.keyField} = ${String(p)}.`});continue}let h=g[0];if(!h){t(u,{outcome:"applied"});continue}let f=String(h.Id),m=tl(h.LastModifiedDate);!(m!==null&&m>u.commitTimestamp&&!this.deps.ownWrites.wrote(f,m))||this.deps.conflictStrategy==="source_wins"?c.push({change:u,targetId:f}):this.deps.conflictStrategy==="manual"?(r.push(this.held(u,"delete",{[this.plan.keyField]:p},h)),t(u,{outcome:"held"})):t(u,{outcome:"kept-target"})}if(c.length===0)return;let{outcomes:l}=await this.deps.write({...this.objectConfig,operation:"delete"},c.map(u=>({Id:u.targetId})));c.forEach((u,p)=>{let g=l[p];t(u.change,g?.success?{outcome:"applied"}:{outcome:"failed",error:g?.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(tl(n.LastModifiedDate)??0).toISOString()}}async keysOf(e,t,r){let{keySource:n}=this.plan,o=e.filter(a=>n!=="Id"&&tT(a.values[n])&&!(n in a.values&&a.full));if(o.length>0){let a=await this.readSource(o.map(d=>d.recordId),`Id, ${qe(n)}`,r);for(let d of o){let c=a.get(d.recordId);c&&(d.values={...d.values,[n]:c[n]??null})}}let i=new Map;for(let a of e){if(n!=="Id"&&!(n in a.values)){t(a,{outcome:"failed",error:r?"The deleted record can no longer be read in the source (it left the recycle bin), so the record to delete in the target cannot be found.":"The source record could not be read back, so its record in the target cannot be found."});continue}let d=this.plan.keyField==="Id"?a.recordId:this.mapped(a)[this.plan.keyField];if(tT(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?[]:Ki(this.plan.objectApiName,o),a={};for(let[d,c]of Object.entries(o)){if(c===void 0||d==="Id"||d===this.plan.keyField||i.includes(d))continue;let l=r.get(d);l&&((n?l.updateable!==!0:l.createable!==!0)||(a[d]=c))}return a[this.plan.keyField]=t,a}writtenFieldsOf(e,t){let r=new Set;for(let n of e)if(t.has(n.recordId))for(let[o,i]of Object.entries(this.mapped(n)))i!==void 0&&r.add(o);return[...r]}async readWhole(e,t){if(e.length===0)return;let r=await this.readSource(e.map(n=>n.recordId),"FIELDS(ALL)",!1);for(let n of e){let o=r.get(n.recordId);if(!o){t(n,{outcome:"failed",error:"The source record could not be read back: it was deleted since."});continue}n.values={...eT(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+=Ln){let d=e.slice(i,i+Ln).map(u=>`'${Zt(u)}'`).join(", "),c=t==="FIELDS(ALL)"?` LIMIT ${Ln}`:"",l=await this.deps.source.query(`SELECT ${t} FROM ${n} WHERE Id IN (${d})${c}`,{includeDeleted:r});for(let u of l)o.set(String(u.Id),u)}return o}async readTarget(e,t,r){let n=wt(this.plan.objectApiName),o=qe(this.plan.keyField),i=QA.has(t.get(this.plan.keyField)?.type??""),a=r.filter(l=>l!=="Id"&&l!==this.plan.keyField&&l!=="LastModifiedDate"&&t.has(l)),d=["Id",...o==="Id"?[]:[o],"LastModifiedDate",...a],c=new Map;for(let l=0;l<e.length;l+=Ln){let p=e.slice(l,l+Ln).map(f=>i?String(Number(f)):`'${Zt(String(f))}'`).join(", "),g=`WHERE ${o} IN (${p})`,h;try{h=await this.deps.target.query(`SELECT ${d.map(qe).join(", ")} FROM ${n} ${g}`)}catch{h=await this.deps.target.query(`SELECT Id${o==="Id"?"":`, ${o}`}, LastModifiedDate FROM ${n} ${g}`)}for(let f of h){let m=Cg(f[this.plan.keyField]);c.set(m,[...c.get(m)??[],eT(f)])}}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+=Ln){let n=e.slice(r,r+Ln).map(i=>`'${Zt(i)}'`).join(", "),o=await this.deps.target.query(`SELECT Id, LastModifiedDate FROM ${t} WHERE Id IN (${n})`);for(let i of o){let a=tl(i.LastModifiedDate);a!==null&&this.deps.ownWrites.record(String(i.Id),a)}}}catch{}}};function C0(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 ol=class{constructor(e){this.deps=e}deps;async open(e){let t={subscribed:[],refused:[],notes:[]};for(let r of e){let n=qA(r),o=a=>{let d;try{d=GA(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 is&&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:rT(d)})}else t.refused.push({objectApiName:r,reason:rT(a)})}}return t}close(){this.deps.transport.disconnect()}};function rT(s){return s instanceof is?s.answer:I(s)}var D0=[2e3,1e4,3e4],N0=6e4,sl=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<N0);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 ol({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 D0){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)=>{JA(i)?t[a]={outcome:"own-write"}:this.config.appliers.has(i.objectApiName)&&r.set(i.objectApiName,[...r.get(i.objectApiName)??[],a])});for(let[i,a]of r){let d=this.config.appliers.get(i);if(d)try{let{results:c,held:l}=await d.apply(a.map(u=>e[u]));c.forEach((u,p)=>{t[a[p]]=u});for(let u of l)this.held.set(u.conflictId,{change:u,applier:d}),this.deps.sink.conflict(u)}catch(c){let l=I(c);for(let u of a)t[u]={outcome:"failed",error:l}}}let n=this.now(),o=new Map;e.forEach((i,a)=>{let d=t[a];d.outcome==="applied"&&this.applied++,d.outcome==="failed"&&this.failed++;let c=Math.max(0,n-i.commitTimestamp);this.lagTotal+=c,this.lagCount++,this.currentLag=c,o.set(i.channel,Math.max(o.get(i.channel)??0,i.replayId))}),this.deps.sink.events(e.map((i,a)=>j0(i,t[a]))),this.deps.replayStore.save(o)}};function j0(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 M0="realtime:replay:",L0="realtime",Oi=class{constructor(e,t){this.configStore=e;this.sourceOrgId=t}configStore;sourceOrgId;get key(){return`${M0}${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)},L0)}forget(){this.configStore.delete(this.key)}};function $g(s){return s.eventsFailed===0?"success":s.eventsApplied>0?"partial":"failure"}function nT(s){return s.slice(0,15)}function oT(s){let e=s.store.recorder({runId:s.sessionId,configId:`realtime:${s.sessionId}`,configName:"",sourceOrgId:s.sourceOrgId,targetOrgId:s.targetOrgId,realtime:!0});s.identity&&vr(e,s.identity,`realtime ${s.sessionId}`);let t=s.backups?Xa({runId:s.sessionId,orgId:s.targetOrgId,files:s.backups,meta:s.meta}):void 0,r=d=>s.target.query(d),n=t?Ka({query:r,backup:t,recorder:e,describe:async d=>kr(await s.target.describe(d)),viewsEncrypted:mr(r)}):void 0,o=new Set,i=(d,c,l,u)=>{if(c==="insert"||c==="upsert"){for(let g of Za(c,u))o.add(nT(g));return}if(c!=="delete")return;let p=l.flatMap((g,h)=>{let f=g.Id;return u[h]?.success===!0&&typeof f=="string"&&!o.has(nT(f))?[f]:[]});p.length>0&&e.deleted?.(d,p)},a;return{runId:s.sessionId,calls:ed(e,n),write:d=>{let c=Promise.resolve();return(l,u,p)=>{let g=c.then(async()=>{let h=await d(l,u,p);return i(l.objectApiName,l.operation,u,h.outcomes),h});return c=g.catch(()=>{}),g}},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 F0=new Set(["realtime:start","realtime:stop","realtime:status","realtime:metrics","realtime:objects","realtime:resolve-conflict"]);function _0(s){let e=r=>q(r,s.orgRegistry,s.orgManager),t=ct(s);return{async openTransport(r){let{streaming:n}=await e(r);return VA({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 tr({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 Kt(r,n,()=>o.describe(n))).fields}}}},writer(r,n){return async(o,i,a)=>{let d=await e(r),c=await Vf(d,Pg),l=new Pn({connection:c,bulkExecutor:new bn(t.bulk.threshold),bulkManager:hr(s),retryConfig:t.retry,onProgress:()=>{},log:p=>s.log(p),...n?{calls:n}:{}});return new nS({upsert:(p,g,h,f)=>l.upsert(p,g,h,f),insert:(p,g,h)=>l.insert(p,g,h),update:(p,g,h)=>l.update(p,g,h),delete:(p,g,h)=>l.delete(p,g,h),describeTargetFields:async p=>kr(await Kt(r,p,()=>d.describe(p))),...a?{contactPoints:a}:{}}).write(o,i)}},async tooling(r,n){let o=await e(r),{records:i}=await tr({query:async a=>o.tooling.query(a),queryMore:async a=>o.tooling.queryMore(a)},n);return i}}}var il=class{constructor(e,t){this.deps=e;this.syncConfigs=new Ot(e.configStore),this.access=t??_0(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(!F0.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(T(this.deps,e,"realtime:status:response",this.statusPayload())),!0;case"realtime:metrics":return this.post(T(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 Oi(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:$g(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=x(Wh,e,"realtime:error",this.deps);if(t)try{let r=await this.access.tooling(t.sourceOrgId,XA),n=this.access.reader(t.targetOrgId),o=await YA(KA(r),i=>n.describe(i),this.syncConfigs.list(),t,i=>this.deps.log(i));this.post(T(this.deps,e,"realtime:objects:response",{objects:o}))}catch(r){let n=Hf(I(r));E(this.deps,"realtime:objects","realtime:error",e,r,n?{code:n}:void 0)}}async handleStart(e){let t=x(Bh,e,"realtime:error",this.deps);if(!t)return;let r=n=>{this.post(T(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(S=>UA(S,A=>this.syncConfigs.load(A),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 rl,d=this.access.reader(t.sourceOrgId),c=this.access.reader(t.targetOrgId),l=crypto.randomUUID(),u=o&&this.runCreations?oT({sessionId:l,sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,store:this.runCreations,...this.backupRecords?{backups:this.backupRecords}:{},meta:this.deps.configStore,target:c,identity:async()=>await this.access.identity?.(t.targetOrgId)??{},log:S=>this.deps.log(S)}):void 0,p=u?u.write(this.access.writer(t.targetOrgId,u.calls)):this.access.writer(t.targetOrgId),g=new Kb,h=Jn(mr(S=>d.query(S)),S=>d.describe(S)),f=new Map(n.map(S=>[S.objectApiName,new nl(S,{source:d,target:c,write:p,conflictStrategy:t.conflictStrategy,ownWrites:a,contactPoints:g,maskedSourceFields:h})])),m,y=()=>{},R=new Promise((S,A)=>{y=D=>{D?m?.fail(D):i.signal.aborted?m?.cancel():m?.complete(),D?A(new Error(D)):S()}});R.catch(()=>{});let k=async()=>{if(!u)return;let S=await u.end({status:$g(w.metrics()),cancelled:i.signal.aborted}).catch(A=>I(A));this.openRuns.delete(u.runId),S!==void 0&&Ie(this.deps,"warning","Real-time sync",`What the session wrote could not all be kept (${S}): removing it may leave some of it in the target.`)},w=new sl({sessionId:l,watchedObjects:t.watchedObjects,appliers:f,flushIntervalMs:t.flushIntervalMs,maxBatchSize:t.maxBatchSize},{openTransport:()=>this.access.openTransport(t.sourceOrgId),replayStore:new Oi(this.deps.configStore,t.sourceOrgId),sink:{events:S=>this.pushEvents(S),conflict:S=>this.pushConflict(S),status:S=>{if(S.status!=="error"){this.pushStatus(S);return}y(S.error),k().then(()=>this.pushStatus(S))}},log:S=>this.deps.log(S)}),O={session:w,abort:i,operationId:e.id,sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,guard:o,finish:S=>y(S),detach:()=>{},endRun:k};this.current=O,this.lastMetrics=null,u&&this.openRuns.add(u.runId);let P;try{P=await w.start()}catch(S){throw await k(),S}let b=w.snapshot();if(P.subscribed.length>0){let S=`Real-time sync of ${P.subscribed.length} object(s)`;this.registry?.register(w.sessionId,"sync",S,R,i),m=sr(this.liveTracker,w.sessionId,"realtime",S);let A=()=>{this.current?.session===w&&this.stopCurrent().then(D=>{D&&this.pushStopped(D,"cancelled")})};i.signal.addEventListener("abort",A,{once:!0}),O.detach=()=>i.signal.removeEventListener("abort",A)}else y(),await k();let v=new Set(P.subscribed),C=(await Promise.all(n.filter(S=>v.has(S.objectApiName)).map(async S=>({objectApiName:S.objectApiName,fields:[...await h(S.objectApiName)].sort()})))).filter(S=>S.fields.length>0);C.length>0&&(O.encryptedLeftOut=C),this.post(T(this.deps,e,"realtime:started",{success:P.subscribed.length>0,sessionId:w.sessionId,watchedObjects:P.subscribed,refused:P.refused,notes:P.notes,...C.length>0?{encryptedLeftOut:C}:{},...b.error?{error:b.error}:{}}))}catch(n){r(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:Se.code}),Qi();let o={orgId:t,orgTier:Ce(this.deps.orgManager.getOrg(t)),operation:r.some(a=>a.applyDeletes)?"delete":"upsert",objectName:r.map(a=>a.objectApiName).join(", "),recordCount:"unknown",module:"sync"},{decision:i}=await Ze(n,o);if(i==="refused"||i==="declined"){Z(this.deps,{action:"realtime_sync",module:"sync",operationId:e.id,orgId:t,outcome:"stopped",guard:i});return}return i}async handleStop(e){let t=x(qh,e,"realtime:error",this.deps);if(!t)return;let r=this.current;if(!r||t.sessionId!==""&&t.sessionId!==r.session.sessionId){this.post(T(this.deps,e,"realtime:status:response",this.statusPayload()));return}let n=await this.stopCurrent();this.post(T(this.deps,e,"realtime:stopped",{sessionId:n??r.session.sessionId,reason:"stopped",success:!0}))}async handleResolve(e){let t=x(zh,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(T(this.deps,e,"realtime:conflict-resolved",{conflictId:t.conflictId,resolution:t.resolution,success:r.success,resolvedValues:r.resolvedValues,...r.error?{error:r.error}:{}}))}};var H0=new Set(["file:save"]),al=class{constructor(e,t){this.deps=e;this.saveDialog=t??new vn}deps;saveDialog;async handle(e){return H0.has(e.type)?(await this.handleSave(e),!0):!1}async handleSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Lh.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(T(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(T(this.deps,e,"file:save:response",n))}};var U0=new Set(["reports:list","reports:audit","reports:lineage"]),B0="forge:history",q0="sync:history:all",sT=50;function W0(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 z0(s){let e=s.graph?.nodes??[];return e.filter(t=>!kf(t)).length+Of(s,e).length}var dl=class{constructor(e){this.deps=e}deps;async handle(e){if(!U0.has(e.type))return!1;switch(e.type){case"reports:list":return this.handleList(e),!0;case"reports:audit":return this.handleAudit(e),!0;case"reports:lineage":return this.handleLineage(e),!0;default:return!1}}handleAudit(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Ry,e,"reports:error",this.deps);if(t===null)return;let r=new So(this.deps.configStore).list(t??{});this.deps.log(`[ReportsHandler] audit trail: ${r.entries.length} of ${r.total} entries`),this.deps.broker.postToWebview(T(this.deps,e,"reports:audit:response",{...r}))}handleLineage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(Sy,e,"reports:error",this.deps);if(t===null)return;let r=new hh(this.deps.configStore);this.deps.broker.postToWebview(T(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(T(this.deps,e,"reports:list:response",{...r}))}readLimit(e){let t=e.payload?.limit;return typeof t!="number"||!Number.isFinite(t)||t<=0?sT:Math.min(Math.floor(t),500)}build(e=sT){let t=this.deps.configStore.get(B0)??[],r=this.deps.configStore.get(q0)??[],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:J0(n)}}forgeReport(e){let t=z0(e),r=W0(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 G0(s){let e=s.sections[0]?.content?.status;return e==="failure"||e==="failed"||e==="partial"}function J0(s){let e=s.length;if(e===0)return{totalOperations:0,successRate:0,avgDuration:0,errorRate:0};let t=s.filter(G0).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 iT(s){return Object.values(s).every(e=>e<50)}var cl=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(Ug.map(async n=>{try{let o=await e.query(`SELECT COUNT() FROM ${n}`);return{objectName:n,count:o.totalSize}}catch{return{objectName:n,count:0}}})),r={};for(let{objectName:n,count:o}of t)r[n]=o;return r}decide(e,t,r,n){let o=Object.values(t).reduce((l,u)=>l+u,0),i=iT(t),a=n!==void 0&&!iT(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 X0(s,e){return`smart-action:${s}:${e??""}`}var K0=300*1e3,Y0=new Set(["smart-action:analyze"]),ll=class{constructor(e){this.deps=e;this.analyzer=new cl({getConnection:t=>q(t,e.orgRegistry,e.orgManager)})}deps;analyzer;cache=new Map;async handle(e){return Y0.has(e.type)&&e.type==="smart-action:analyze"?(await this.handleAnalyze(e),!0):!1}forgetOrg(e){for(let[t,r]of this.cache)r.orgIds.includes(e)&&this.cache.delete(t)}async handleAnalyze(e){let t=x(My,e,"smart-action:error",this.deps);if(t)try{let r=t.targetOrgId,n=t.sourceOrgId,o=X0(r,n),i=this.cache.get(o);if(i&&Date.now()-i.fetchedAt<K0){this.deps.log(`[SmartAction] Cache hit for ${r}`);let c=T(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=T(this.deps,e,"smart-action:analyze:response",{recommendation:a});this.deps.broker.postToWebview(d),this.deps.log("[TX] smart-action:analyze:response")}catch(r){E(this.deps,"smart-action:analyze","smart-action:error",e,r)}}};var Q0=new Set(["execution:abort"]),ul=class{constructor(e,t){this.deps=e;this.registry=t}deps;registry;async handle(e){return Q0.has(e.type)&&e.type==="execution:abort"?(await this.handleAbort(e),!0):!1}async handleAbort(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);try{let t=x(my,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=T(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=T(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=T(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=T(this.deps,e,"execution:abort:response",{success:!0,operationId:r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(t){E(this.deps,"execution:abort","execution:error",e,t)}}};import{readFile as Z0}from"node:fs/promises";import{join as eM}from"node:path";var xg=new Map;function aT(s,e){let t=eM(s,`${e}.json`),r=xg.get(t);if(r)return r;let n=Z0(t,"utf-8").then(o=>JSON.parse(o));return xg.set(t,n),n.catch(()=>xg.delete(t)),n}var tM=new Set(["i18n:locale"]),pl=class{constructor(e,t){this.deps=e;this.localesDir=t}deps;localesDir;async handle(e){return tM.has(e.type)?(await this.handleLocaleRequest(e),!0):!1}async handleLocaleRequest(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=x(jy,e,"i18n:locale:response",this.deps);if(!t)return;let{lng:r}=t;if(!this.localesDir){let n=T(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 aT(this.localesDir,r),o=T(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=T(this.deps,e,"i18n:locale:response",{lng:r,error:I(n)});this.deps.broker.replyToRequester(o)}}};import{AsyncLocalStorage as rM}from"node:async_hooks";function cT(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 dT=new rM;async function lT(s,e,t,r){let n=Symbol("pipeline sync"),o,i=s.registry?.onEvent((d,c,l)=>{c!=="started"||l.module!=="sync"||dT.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 dT.run(n,()=>Ra(t,()=>s.execute(e)));return o!==void 0?{...d,operationId:o}:d}finally{i?.(),r?.removeEventListener("abort",a)}}var nM=G({setting:j().regex(/^sandforge(?:\.[A-Za-z][A-Za-z0-9]*)+$/)}),gl=class{handlerDeps;executeCommand;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;checkpointStore;beforeRunCheckpoints;constructor(e){this.executeCommand=e.executeCommand??(()=>Promise.resolve()),this.refreshDetector=new md({configStore:e.configStore,orgManager:e.orgManager,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:jl,bulkManager:new fh(jl.bulk.maxConcurrentJobs),nextId:()=>this.nextId(),sandboxRefreshes:this.refreshDetector},this.orgHandler=new bd(this.handlerDeps),this.settingsHandler=new Rd(this.handlerDeps),this.monitorHandler=new Dd(this.handlerDeps),this.seedHandler=new Ld(this.handlerDeps),this.seedCloneHandler=new Ud(this.handlerDeps),this.seedCsvHandler=new zd(this.handlerDeps),this.seedRemovalHandler=new Qd(this.handlerDeps,void 0,r=>this.seedHandler.isRunning(r)||this.seedCsvHandler.isRunning(r)||this.seedCloneHandler.isRunning(r)),this.syncHandler=new Vd(this.handlerDeps),this.syncHistoryStore=new ec(e.configStore),this.syncHandler.setHistoryLogger(new tc(this.syncHistoryStore)),this.syncHistoryHandler=new Xd(this.handlerDeps,this.syncHistoryStore,this.syncHandler),this.syncRemovalHandler=new Kd(this.handlerDeps,this.syncHistoryStore,r=>this.syncHandler.isRunning(r)||this.realtimeHandler.isRunning(r)),this.compareHandler=new rc(this.handlerDeps),this.dataOpsHandler=new mb(this.handlerDeps),this.complianceHandler=new ic(this.handlerDeps),this.cleanupHandler=new ac(this.handlerDeps),this.emptyHandler=new vc(this.handlerDeps),this.automationHandler=new Ic(this.handlerDeps),this.aiHandler=new Cc(this.handlerDeps),this.autopilotHandler=new xc(this.handlerDeps),this.forgeHandler=new Fc(this.handlerDeps),this.frozenHandler=new BS(this.handlerDeps),this.frozenHandler.setSaltKeeper(US(e.secretVault));let t=()=>[this.forgeHandler,this.frozenHandler,this.dataOpsHandler,this.complianceHandler,this.emptyHandler,this.autopilotHandler,this.realtimeHandler];this.checkpointHandler=new pd(this.handlerDeps,{isRunning:r=>this.syncHandler.isRunning(r)||this.seedHandler.isRunning(r)||this.seedCsvHandler.isRunning(r)||this.seedCloneHandler.isRunning(r),writingTo:(r,n)=>t().some(o=>o.isWritingTo(r,n))}),this.beforeRunCheckpoints={scope:(r,n)=>this.checkpointHandler.scopeBeforeRun(r,n),take:(r,n,o)=>this.checkpointHandler.takeBeforeRun(r,n,o),settle:(r,n)=>this.checkpointHandler.settleBeforeRun(r,n)},this.forgeHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.autopilotHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.frozenHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.syncHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.seedHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.seedCsvHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.seedCloneHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.emptyHandler.setBeforeRunCheckpoints(this.beforeRunCheckpoints),this.emptyHandler.setRunWriting((r,n,o)=>this.checkpointHandler.writingTo(r,n,"empty it","Nothing was deleted.",{operationId:o})),this.forgeHandler.setOtherModuleRuns(this.otherModuleRuns("forge",t)),this.syncRemovalHandler.setOtherModuleRuns(this.otherModuleRuns("sync",t)),this.seedRemovalHandler.setOtherModuleRuns(this.otherModuleRuns("seed",t)),this.frozenHandler.setOtherModuleRuns(this.otherModuleRuns("frozen",t)),this.migrationHandler=new _c(this.handlerDeps),this.configHandler=new Bc(this.handlerDeps),this.governanceHandler=new zc(this.handlerDeps,this.monitorHandler.getAlertEngine()),this.quickSyncHandler=new Kc(this.handlerDeps),this.syncScheduleHandler=new Zc(this.handlerDeps),this.realtimeHandler=new il(this.handlerDeps),this.fileHandler=new al(this.handlerDeps),this.reportsHandler=new dl(this.handlerDeps),this.smartActionHandler=new ll(this.handlerDeps),this.i18nHandler=new pl(this.handlerDeps,e.localesDir),this.automationHandler.setStepRunners({orgName:r=>{let n=e.orgManager.getOrg(r);return n?me(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 Ot(e.configStore).load(r),listSyncConfigs:()=>new Ot(e.configStore).list(),syncGuard:r=>cT(this.handlerDeps.infraServices?.productionGuard,Up(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?Ce(n):void 0},organizationIdsOf:r=>[e.orgManager.getOrg(r)?.orgId,this.refreshDetector.organizationIdOf(r)].filter(n=>typeof n=="string"&&n!==""),savedSeedTemplate:r=>new on(e.configStore).load(r),listSeedTemplates:()=>new on(e.configStore).list(),seed:(r,n)=>this.seedHandler.seedForPipeline(r,n),maskingTemplates:()=>[...yh.map(r=>({...r,builtIn:!0})),...new ya(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(Qv),this.checkpointHandler.onCheckpointsChanged(()=>{this.automationHandler.revokeVoidGrants()}),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}))})}get sandboxRefreshes(){return this.refreshDetector}postSettings(){this.settingsHandler.postSettings()}forgetOrg(e){bo().remove(e),ek(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(ob(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 So(this.handlerDeps.configStore).list({orgId:r,limit:Kg}).entries,a=[...e==="forge"?[]:await this.forgeHandler.localRunsOn(r,n),...e==="sync"?[]:await this.syncRemovalHandler.localRunsOn(r),...e==="seed"?[]:await this.seedRemovalHandler.localRunsOn(r),...QR(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)}async readCheckpointForRewind(e){let{openCheckpointStore:t,defaultCheckpointStoreRoot:r}=await import("./chunk-XK5W7BVE.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 ul(this.handlerDeps,e)}async replayQueuedOperation(e){let t=mn("offline-replay",e.id,`${e.type}:execute`);switch(e.type){case"sync":await this.syncHandler.rerunFromSnapshot(t,e.payload.config);return;case"seed":{let r={...t,payload:e.payload};await this.seedHandler.handle(r);return}default:throw new Error(`Unsupported queued operation type: ${e.type}`)}}startSyncScheduler(e){this.syncScheduleHandler.startScheduler(t=>this.syncHandler.executeScheduled(t),e)}stopSyncScheduler(){this.syncScheduleHandler.stopScheduler()}stopLiveOperationsPush(){this.monitorHandler.dispose()}async stopRealtime(){await this.realtimeHandler.dispose()}startPipelineTriggers(e){this.automationHandler.startTriggers(e)}stopPipelineTriggers(){this.automationHandler.stopTriggers()}setAIModules(e){this.aiHandler.setAIModules(e),this.handlerDeps.errorResolver=e?.errorResolver}setRuleModules(e){this.aiHandler.setRuleModules(e)}setMigrationServices(e){this.migrationHandler.setFileReader(e)}setPipelineMarketplace(e){this.automationHandler.setPipelineMarketplace(e)}setAutopilotOrchestrator(e){this.autopilotHandler.setOrchestrator(e)}setForgeOrchestrator(e,t){this.forgeHandler.setForgeOrchestrator(e,t)}registerAll(e){let t=(r,n)=>{for(let o of r)e.route(o,async i=>{await n.handle(i)})};t(["org:list","org:connect","org:connect:cancel","org:disconnect","org:select","org:update","org:open-in-browser","org:cli-status"],this.orgHandler),t(["settings:get","settings:update","telemetry:status","telemetry:toggle"],this.settingsHandler),t(["i18n:locale"],this.i18nHandler),t(["seed:execute","seed:automation","seed:describe-global","seed:describe-object","seed:template:save","seed:template:load","seed:template:list","seed:template:delete","seed:list-personas","seed:create-persona","seed:scenario:packs","seed:scenario:prepare","seed:scenario:execute","seed:scenario:agents","seed:scenario:save","seed:scenario:test-file"],this.seedHandler),t(["seed:clone:describe-source","seed:clone:preview","seed:clone:execute"],this.seedCloneHandler),t(["seed:csv:validate","seed:csv:execute"],this.seedCsvHandler),t(["sync:execute","sync:simulate","sync:write-order","sync:pause","sync:resume","sync:describe-global","sync:describe-fields","sync:config:save","sync:config:load","sync:config:list","sync:config:delete","sync:config:reset-delta"],this.syncHandler),t(["sync:history:list","sync:history:detail","sync:history:rerun","sync:history:export"],this.syncHistoryHandler),t(["sync:removal:info","sync:removal:list","sync:remove","sync:remove:sweep","sync:remove:automation","sync:earlier-copies"],this.syncRemovalHandler),t(["seed:removal:info","seed:removal:list","seed:remove","seed:remove:sweep","seed:open-record"],this.seedRemovalHandler),t(["sync:schedule:list","sync:schedule:upsert","sync:schedule:toggle","sync:schedule:delete"],this.syncScheduleHandler),t(["quicksync:suggest-objects","quicksync:detect-relationships","quicksync:preview","quicksync:execute"],this.quickSyncHandler),t(["monitor:refresh","monitor:open-apex-jobs","monitor:live-operations","monitor:storage","monitor:deployments","monitor:api-usage","monitor:error-logs","monitor:sessions","monitor:apex-insights","monitor:sandbox-refresh","monitor:alerts","monitor:alert:acknowledge","monitor:alert:dismiss"],this.monitorHandler),t(["governance:policies:list","governance:policy:save","governance:policy:delete","governance:evaluate","governance:templates"],this.governanceHandler),t(["compare:execute","compare:permissions","compare:snapshots","compare:drift","compare:validate-deployment","compare:deploy"],this.compareHandler),t(["backup:execute","backup:list","backup:objects","backup:export","backup:delete","dataops:rollback","dataops:anonymize","dataops:anonymization-templates","dataops:quality-scan","dataops:anonymization-template:save","dataops:anonymization-template:delete","dataops:anonymize:coverage","dataops:anonymize:preview","dataops:automation","precheck:pii-scan"],this.dataOpsHandler),t(["dataops:pii-inventory","dataops:dsr:search","dataops:dsr:export","dataops:dsr:erase","dataops:dsr:log"],this.complianceHandler),t(["dataops:cleanup:scan","dataops:cleanup:export","dataops:cleanup:delete"],this.cleanupHandler),t(["dataops:empty:scope","dataops:empty:preview","dataops:empty:run","dataops:empty:cancel","dataops:empty:undo"],this.emptyHandler),t(["pipeline:execute","pipeline:templates","pipeline:list","pipeline:history","pipeline:save","pipeline:delete","pipeline:approval","pipeline:sync-configs","pipeline:seed-templates","pipeline:masking-templates","pipeline:rewind-steps","pipeline:rewind-grant","pipeline:rewind-revoke","pipeline:export","marketplace:list","marketplace:install"],this.automationHandler),t(["ai:chat","ai:chat:cancel","ai:conversation:create","ai:conversation:load","ai:conversation:list","ai:conversation:delete","ai:conversation:delete-all","ai:status","ai:save-key","ai:settings","ai:remove-key","ai:tool:cancel","ai:forge-plan","ai:anomaly-scan","ai:generate-pipeline","ai:scenario-draft"],this.aiHandler),t(["autopilot:list-objects","autopilot:count-objects","autopilot:scan-schema","autopilot:generate-plan","autopilot:fit-plan","autopilot:fit-undo","autopilot:execute","autopilot:pause","autopilot:resume","autopilot:skip-node","autopilot:compliance-report"],this.autopilotHandler),t(["forge:preview","forge:discover","forge:execute","forge:pause","forge:resume","forge:abort","forge:templates:list","forge:templates:save","forge:templates:delete","forge:history:list","forge:undo","forge:resume-run","forge:open-record","forge:verify:request","forge:export-ids:request","forge:plan:request","forge:compliance:request","forge:metadata-diff:request","forge:rehearse:request","forge:automation:request","forge:undo-automation:request","forge:undo-sweep:request","forge:gaps:request","forge:users:request","forge:target-records:request","forge:sample-budget:request","forge:previewRoots"],this.forgeHandler),t(["frozen:config:get","frozen:config:save","frozen:select","frozen:extract","frozen:manifest:get","frozen:load","frozen:load:preview","frozen:verify","frozen:remove","frozen:remove:sweep","frozen:remove:automation","frozen:remove:preview","frozen:status","frozen:rules:clear","frozen:rules:create"],this.frozenHandler),t(["checkpoint:list","checkpoint:scope","checkpoint:take","checkpoint:preview","checkpoint:plan-selection","checkpoint:rewind","checkpoint:undo","checkpoint:delete","checkpoint:keep","checkpoint:rename","checkpoint:ignore-fields","checkpoint:rewinds","checkpoint:export","checkpoint:import-read","checkpoint:import"],this.checkpointHandler),t(["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=nM.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("error:boundary",r=>{let{payload:n}=r;this.handlerDeps.log(`[ERR] Webview crash (error:boundary): ${n?.message??"unknown error"}`+(n?.stack?`
19
+ ${n.stack}`:""))})}nextId(){return`ext-${++this.idCounter}`}};var fl=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 oM=100,sM=1e3,iM=3,aM=1e3;function dM(s){return typeof s=="object"&&s!==null&&"protocolVersion"in s&&"payload"in s&&typeof s.payload=="object"}var uT=500;function cM(s){let e=s.map(t=>`${t.path.map(String).join(".")}: ${t.message}`).join("; ");return e.length<=uT?e:`${e.slice(0,uT)}\u2026(+${s.length} issues)`}var ml=class{handlers=new Map;panels=new Set;rateLimiter;telemetry;fixSuggestionNotifier;mismatchCount=0;webviewSeen=!1;firstWebviewCallbacks=[];senders=new Map;constructor(e){this.rateLimiter=new fl(e?.rateLimitMax??oM,e?.rateLimitWindowMs??sM),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(!dM(e)){this.logFn?.("[MessageBroker] Received malformed message: not an envelope");return}let r=Jg.safeParse(e);if(!r.success){let o=cM(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;Bg(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>=iM&&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>aM){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 yl=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 wl=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 bl=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 Rl=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 as="org.",Sl="org-cred.",Dg="orgs",pT=1e4;function lM(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 uM(e)}function uM(s){if(s.orgType===Mi(s.orgType,s.metadata?.edition))return s;let{safetyTier:e,color:t}=_r("Developer");return{...s,orgType:"Developer",safetyTier:e,appearance:{...s.appearance,color:s.appearance.color===Fl?t:s.appearance.color}}}var vl=class{constructor(e,t,r){this.configStore=e;this.secretVault=t;this.orgManager=r}configStore;secretVault;orgManager;loadAll(){let e=this.configStore.getByCategory(Dg),t=new Map,r=[];for(let[n,o]of Object.entries(e)){if(!n.startsWith(as))continue;let i=lM(o),a=i.orgId??i.id,d=n.slice(as.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(as.length);this.secretVault.deleteSecret(`${Sl}${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=`${as}${e.id}`,n=this.configStore.get(r),i=n!==void 0&&Ce(n)==="production"&&Li(e)&&n.appearance?.color===Fl?void 0:n?.appearance?.color,a=n?{...e,alias:n.alias??e.alias,appearance:{...e.appearance,color:i??e.appearance.color,icon:n.appearance?.icon??e.appearance.icon},tags:n.tags??e.tags,...n.staging!==void 0?{staging:n.staging}:{},...e.organizationName===void 0&&n.organizationName!==void 0?{organizationName:n.organizationName}:{}}:e;this.configStore.set(r,a,Dg),this.orgManager.addOrg(a),t&&await this.secretVault.storeObject(`${Sl}${e.id}`,t)}async removeOrg(e){this.configStore.delete(`${as}${e}`),await this.secretVault.deleteSecret(`${Sl}${e}`),this.orgManager.removeOrg(e)}async getCredentials(e){let t=this.secretVault.getObject(`${Sl}${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 ${pT} ms for org "${e}" \u2014 the OS keyring may be locked or unavailable.`))},pT)})])}finally{r!==void 0&&clearTimeout(r)}}updateOrgMetadata(e){this.configStore.set(`${as}${e.id}`,e,Dg),this.orgManager.addOrg(e)}};import{mkdtemp as pM,readFile as gM,rm as fM}from"node:fs/promises";import{tmpdir as hM}from"node:os";import{join as Ng}from"node:path";async function gT(s){let e=await pM(Ng(hM(),"sandforge-sf-"));try{let t={stdout:Ng(e,"stdout.json"),stderr:Ng(e,"stderr.txt")},r;try{await s(t)}catch(o){r=o}let n=o=>gM(o,"utf8").catch(()=>"");return{stdout:await n(t.stdout),stderr:await n(t.stderr),...r!==void 0?{failure:r}:{}}}finally{await fM(e,{recursive:!0,force:!0}).catch(()=>{})}}var yT=10*1024*1024,mM=3e4,kl=3e4,Fg=6e4,fT=12e4,hT=3e4,yM=4,wM=2e3,bM=/["%!\u0000-\u001f\u007f]/,mT=/^[A-Za-z0-9._-]+={0,2}$/;async function _g(s,e){let{exec:t}=await import("child_process"),{promisify:r}=await import("util"),n=await r(t)(s,{maxBuffer:yT,windowsHide:!0,env:Vl(),...e});return{stdout:String(n.stdout),stderr:String(n.stderr)}}function wT(s,e){if(bM.test(s))throw new Error(`The ${e} cannot contain ", %, ! or control characters on Windows: the command prompt that runs sf would act on them.`);return`"${s}"`}async function Ol(s,e){let{exec:t,execFile:r}=await import("child_process");return new Promise(n=>{let o={encoding:"utf8",maxBuffer:yT,windowsHide:!0,timeout:e.timeoutMs,env:Vl()},i={},a=!1,d=u=>{a||(a=!0,clearTimeout(i.timer),n(u))},c=(u,p,g)=>{d({stdout:String(p),stderr:String(g),...u?{failure:{message:u.message,killed:u.killed}}:{}})},l=process.platform==="win32"?t(["sf",...s.map(u=>wT(u.value,u.role))].join(" "),o,c):r("sf",s.map(u=>u.value),o,c);i.timer=setTimeout(()=>{d({stdout:"",stderr:"",failure:{message:`sf did not finish within ${Math.round(e.timeoutMs/1e3)} s`,killed:!0}}),process.platform==="win32"&&l.pid!==void 0&&r("taskkill",["/pid",String(l.pid),"/T","/F"],{windowsHide:!0},()=>{})},e.timeoutMs+wM),l.stdin?.once("error",()=>{}),l.stdin?.end(e.input??"")})}var RM=G({status:Te().optional(),result:un().optional(),message:j().optional(),name:j().optional()}).loose();function bT(s){try{let e=RM.safeParse(JSON.parse(ST(s.stdout)));return e.success?e.data:void 0}catch{return}}function RT(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 SM=G({id:j().min(1),username:j().min(1),instanceUrl:j().min(1),accessToken:j().nullish(),alias:j().nullish(),connectedStatus:j().nullish(),apiVersion:j().nullish(),devHubId:j().nullish(),status:j().nullish(),expirationDate:j().nullish(),edition:j().nullish()}).loose(),vM=G({username:j().min(1),orgId:j().min(1),instanceUrl:j().min(1)}).loose();function jg(s,e,t=Fg){let r=bT(s);if(s.failure||r?.status!==0)throw RT(s,r,e,t);let n=vM.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 Mg(s){let e=Wi(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 ST(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 kM(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 OM(s,e){let t=s;return t.killed===!0?`its ${e/1e3} s limit`:typeof t.code=="number"?`exit code ${t.code}`:Xl(I(s))??"an error that says nothing"}async function IM(s,e){let t=Date.now(),r=o=>process.platform==="win32"?wT(o,"temporary folder path"):kM(o),n=!1;try{let o=await gT(async a=>{let d=`${s} > ${r(a.stdout)} 2> ${r(a.stderr)}`;n=!0,await _g(d,{timeout:e})}),i=o.failure===void 0?void 0:n?OM(o.failure,e):I(o.failure);return{ran:n,stdout:o.stdout,stderr:o.stderr,ms:Date.now()-t,...i?{failure:Rs(i)}:{}}}catch(o){return{ran:n,stdout:"",stderr:"",ms:Date.now()-t,failure:Rs(I(o))}}}function vT(s){if(!s.ran)return`could not be made (${(s.failure??"").slice(0,200)})`;let e=Al(s.stderr);return`ended with ${s.failure??"exit code 0"} after ${Hg(s.ms)} s, with ${s.stdout.length} chars in its stdout file and ${s.stderr.length} in its stderr file${e?` ("${e}")`:""}`}function Al(s){let e=Xl(s);return e===void 0?void 0:Rs(e).slice(0,200)}function Hg(s){return(s/1e3).toFixed(1)}function kT(s,e){return s.ms>=e-500}function AM(s,e,t,r,n){let o=Al(s.stderr),i=a=>a.length>0?a.join(" | "):"none";return[`first run: ${Hg(s.ms)} s of the ${n/1e3} s allowed`+(kT(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: ${vT(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: ${Rs(process.cwd())}`,`variables ${Bf()}`].join("; ")}function TM(s,e,t,r,n){let o=Al(s.stderr),i=process.platform==="win32"?"where.exe sf":"which -a sf",a=new Set(t.sf.map(l=>l.replace(/[\\/][^\\/]*$/,""))).size,d=t.runs?`This window runs ${t.runs}${a>1?` (sf is found in ${a} folders of its PATH)`:""}`:t.failure?`${i} could not run in this window (${t.failure.slice(0,200)})`:`${i} finds no sf this window can run`,c=r===void 0?"":r===""?", and its sf --version printed nothing either":`, and its sf --version says ${r}`;return`sf org list --json ended without an error and printed nothing${o?` (it said: ${o})`:""}, so there are no orgs to read. It ran ${Hg(s.ms)} s${kT(s,n)?`, its ${n/1e3} s limit,`:""} and exited with code 0. Run again with its output sent to a file, it ${vT(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 Lg(s){return s.connectedStatus!==void 0?s.connectedStatus==="Connected":s.isScratch===!0&&s.status==="Active"&&s.isExpired!==!0}function EM(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 PM(s){let e=await Wf({instanceUrl:s.instanceUrl,accessToken:s.accessToken,...s.apiVersion?{version:s.apiVersion}:{}});return zi(e)}async function CM(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 Il=class{constructor(e=Jf,t=PM){this.readToken=e;this.readKind=t}readToken;readKind;versionAnswer;async isCliAvailable(){try{let{stdout:e}=await _g("sf --version",{timeout:mM});return this.versionAnswer=Al(e)??"",!0}catch{return!1}}async listOrgs(e){let t=await this.readOrgEntries(),r=this.dedupeByOrgId(t.filter(a=>Lg(a))),n=new Set(r.map(a=>a.orgId));for(let a of this.dedupeByOrgId(t.filter(d=>!Lg(d))))n.has(a.orgId)||e?.({username:a.username,...a.alias?{alias:a.alias}:{},orgId:a.orgId,reason:EM(a),why:"notConnected"});let o=await CM(r.map(a=>async()=>{try{return{entry:await this.withUsableToken(a)}}catch(d){return{entry:a,reason:I(d)}}}),yM),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||!Lg(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 Ol([{value:"org",role:"command"},{value:"display",role:"command"},{value:"--target-org",role:"flag"},{value:e,role:"username"},{value:"--json",role:"flag"}],{timeoutMs:hT}),r=bT(t);if(r?.name==="NamedOrgNotFoundError")return;if(t.failure||r?.status!==0)throw RT(t,r,"sf org display",hT);let n=SM.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:Mg(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"}),jg(await Ol(t,{timeoutMs:Fg}),"sf org login jwt")}async loginWithRefreshToken(e){if(!mT.test(e.clientId))throw new Error("The consumer key holds characters the Salesforce CLI does not accept.");if(!mT.test(e.refreshToken))throw new Error("Salesforce issued a refresh token the Salesforce CLI cannot store (unexpected characters).");let t=new URL(Mg(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}
20
+ `;return jg(await Ol(r,{timeoutMs:Fg,input:n}),"sf org login sfdx-url")}async readOrgEntries(){let e="sf org list --json",t=Date.now(),r,n="";try{let a=await _g(e,{timeout:kl});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=ST(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 IM(e,kl),n=await qf(),o=AM(t,r,n,this.versionAnswer,kl);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(TM(t,r,n,this.versionAnswer,kl))}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:Mg(t),role:"login URL"}];return e&&r.push({value:"--alias",role:"flag"},{value:e,role:"alias"}),r.push({value:"--json",role:"flag"}),jg(await Ol(r,{timeoutMs:fT}),"sf org login web",fT)}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(Kl(e.accessToken))return e;let t=await this.readToken(e.username);if(!Kl(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=Wn({isScratch:e.isScratch,isSandbox:e.isSandbox,edition:e.orgEdition}),{safetyTier:r,color:n}=_r(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??fo.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 $M(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 Tl=class{deps;results=new Map;constructor(e){this.deps=e}async execute(e,t){let r=Date.now(),{items:n,managedLeftOut:o}=await $M(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 xM(){return globalThis.crypto.randomUUID()}function OT(s){return{stepId:s.id,stepName:s.name,stepType:s.type,status:"skipped"}}function DM(s,e){let t={};for(let r of s.variables)r.defaultValue!==void 0&&(t[r.name]=r.defaultValue);return{...t,...e}}function NM(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 IT(s){return`Validation failed: ${s.join(", ")}`}function jM(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 El=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 f=this.createRun(e,t,r);return f.status="failed",f.error=IT(o),f.endTime=new Date().toISOString(),this.emit("failed",{runId:f.id,error:f.error}),f}let i=this.refuseUnrunnable(e,t,r);if(i)return i;let a=this.createRun(e,t,r);a.status="running",this.activeRuns.set(a.id,a);let d=new AbortController,c=()=>d.abort();n?.aborted&&d.abort(),n?.addEventListener("abort",c,{once:!0}),this.aborters.set(a.id,d),this.emit("started",{runId:a.id,pipelineId:e.id});let l=DM(e,t),{steps:u}=e,p=this.deps.conditionalRouter,g=!1,h=0;for(;h<u.length;){if(this.cancelledRuns.has(a.id)||d.signal.aborted){a.status="cancelled";break}let f=u[h],m=await this.runStep(f,a,l,d.signal);if(a.stepResults.push(m),m.status==="skipped"){this.emit("stepSkipped",{runId:a.id,stepResult:m}),h+=1;continue}if(this.emit("stepCompleted",{runId:a.id,stepResult:m}),Object.assign(l,NM(m)),l[Tf]=m.status==="completed"?"succeeded":"failed",d.signal.aborted||m.status==="stopped"){a.status="cancelled";break}if(m.status==="failed"&&(g=!0,!f.continueOnError)){a.status="failed",a.error=m.error;break}let y=h+1;if(p.endsRun(f,m))y=u.length;else{let R=p.getNextStep(f,m),k=R?u.findIndex((w,O)=>O>h&&w.id===R):-1;k!==-1&&(y=k)}for(let R of u.slice(h+1,y)){let k=OT(R);a.stepResults.push(k),this.emit("stepSkipped",{runId:a.id,stepResult:k})}h=y}return a.status==="running"&&(a.status=g?"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 OT(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?[IT(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)??jM(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:xM(),pipelineId:e.id,pipelineName:e.name,status:"queued",triggeredBy:r,stepResults:[],variables:t,startTime:new Date().toISOString()}}};var Pl=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 FM=3e4;function _M(s,e,t={}){let r=Wn({isSandbox:e.isSandbox,edition:e.orgType,...t.typeScratch===!0&&s.scratch===!0?{isScratch:!0}:{}}),{safetyTier:n,color:o}=_r(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:fo.DEFAULT_API_VERSION,edition:e.orgType,features:[]},status:"connected",lastConnected:new Date().toISOString(),tags:[]}}function HM(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 UM(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 BM(s,e,t={}){return{compareOrchestrator:n=>new Tl(n),automationOrchestrator:n=>new El(n),seedOrchestrator:n=>new uS(n),syncOrchestrator:n=>new lS(n),getSandforgeSetting:(n,o)=>o,isAIEnabled:()=>!1,configStore:s,showNotification:n=>e(` notification: ${n}`),runsFrom:"commandLine",...t}}function I5(s){let{log:e}=s,t=s.waitMs??5*6e4,r=Jl();Gf("command line");let n=dR(LM(s.storeDir,"configStore.json")),o=new Map,i=new bl({get:k=>Promise.resolve(o.get(k)),store:(k,w)=>(o.set(k,w),Promise.resolve()),delete:k=>(o.delete(k),Promise.resolve())}),a=new Rl,d=new vl(n,i,a),c=new Il,l=new jS;l.setSfdxBridge(c);let u=new ml;u.setLogFunction(e);let p=new yl(u),g=BM(n,e,s.services),h=new gl({log:e,broker:u,stateSync:new wl(u),orgManager:a,orgRegistry:d,configStore:n,secretVault:i,authProvider:l,sfdxBridge:c,services:g});h.setLiveOperationTracker(new Pl),s.compose?.({handlers:h,configStore:n,orgRegistry:d,orgManager:a,services:g,log:e}),h.registerAll(p);let f=[],m=new Set,y,R={webview:{postMessage:k=>{f.push(k);let w=UM(k);w&&e(` ${w}`),s.onPost?.(k);for(let O of[...m])O(k);return Promise.resolve(!0)},onDidReceiveMessage:k=>(y=k,{dispose:()=>{y=void 0}})}};return u.registerPanel(R),{posted:f,async connect(k){let w=await Kf(k),O=await l.validateConnection(w.accessToken,w.instanceUrl),P=_M(w,O,{typeScratch:s.typeScratchOrgs===!0});return await d.saveOrg(P,{loginUrl:w.instanceUrl,instanceUrl:w.instanceUrl,accessToken:w.accessToken,username:w.username}),P},connectingRequests:()=>Jl()-r,request(k){let w=y;if(!w)return Promise.reject(new Error("No panel is registered with the broker."));let O=k.responseType??`${k.type}:response`,P=k.timeoutMs??FM,b={id:k.id??`wv-${MM()}`,type:k.type,timestamp:Date.now(),...k.payload!==void 0?{payload:k.payload}:{}},v=Date.now();return new Promise(C=>{let S=z=>{m.delete(A),clearTimeout(D),C(z)},A=z=>{let U=HM(z,b.id,O);if(!U)return;let Y=Date.now()-v;S({outcome:U,message:z,elapsedMs:Y,late:Y>P})},D=setTimeout(()=>S({outcome:"unanswered",elapsedMs:Date.now()-v,late:!0}),Math.max(t,P));m.add(A),w({protocolVersion:1,payload:b})})}}}export{Cn as a,AT as b,on as c,Ju as d,Xu as e,id as f,ov as g,dd as h,iv as i,dL as j,Qu as k,dv as l,fL as m,gv as n,hL as o,yE as p,I5 as q};