sandforge 1.80.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.
- package/README.md +48 -0
- package/bin/sandforge-pipeline.mjs +12 -0
- package/bin/sandforge-users.mjs +12 -0
- package/lib/{chunk-J525F5KI.mjs → chunk-27Z76O2O.mjs} +1 -1
- package/lib/chunk-2JZGCCPG.mjs +9 -0
- package/lib/{chunk-ELFXJHU7.mjs → chunk-2UU42PTD.mjs} +1 -1
- package/lib/{chunk-N652NMZ4.mjs → chunk-32EUNQT6.mjs} +52 -52
- package/lib/chunk-3C2ZZIFN.mjs +7 -0
- package/lib/chunk-3CX7GPCR.mjs +7 -0
- package/lib/chunk-3HEMJTAP.mjs +925 -0
- package/lib/{chunk-BY2HJFFG.mjs → chunk-3HROD5RE.mjs} +1 -1
- package/lib/{chunk-OHWNPXWW.mjs → chunk-3MGMNK3Q.mjs} +1 -1
- package/lib/{chunk-PZPJKATS.mjs → chunk-3SKLBRPL.mjs} +8 -8
- package/lib/chunk-3XG25GTF.mjs +7 -0
- package/lib/chunk-42BFLWHR.mjs +7 -0
- package/lib/chunk-466F37VD.mjs +7 -0
- package/lib/chunk-47UHTN3Q.mjs +7 -0
- package/lib/chunk-4JKR4PTZ.mjs +8 -0
- package/lib/{chunk-COFG7Q6R.mjs → chunk-52EXDVPN.mjs} +1 -1
- package/lib/{chunk-SAR5622P.mjs → chunk-54HYHHVL.mjs} +1 -1
- package/lib/{chunk-RSWDYIHY.mjs → chunk-5GBO4KD5.mjs} +1 -1
- package/lib/chunk-5K2I2DMP.mjs +11 -0
- package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
- package/lib/{chunk-BV6VTP3J.mjs → chunk-6GQUZ4IP.mjs} +1 -1
- package/lib/chunk-6KP6WETK.mjs +9 -0
- package/lib/{chunk-MJVTDA5Q.mjs → chunk-6VSZNZHH.mjs} +1 -1
- package/lib/{chunk-XUWL6ZPC.mjs → chunk-7CVDVBEE.mjs} +1 -1
- package/lib/{chunk-UCD54V2M.mjs → chunk-7EYQYZJP.mjs} +1 -1
- package/lib/{chunk-5K5VLULK.mjs → chunk-7LKI7OAS.mjs} +1 -1
- package/lib/chunk-7PY3VQP3.mjs +7 -0
- package/lib/chunk-7SDZR6SR.mjs +7 -0
- package/lib/chunk-7WSLT5VX.mjs +8 -0
- package/lib/chunk-A32ISQ6M.mjs +28 -0
- package/lib/{chunk-M3ROUWDX.mjs → chunk-A65ADTCR.mjs} +1 -1
- package/lib/chunk-A7JJWOLT.mjs +7 -0
- package/lib/chunk-AUS6NFLZ.mjs +8 -0
- package/lib/chunk-BMTNTBBM.mjs +7 -0
- package/lib/{chunk-SOU4FRYN.mjs → chunk-BN33LVPQ.mjs} +1 -1
- package/lib/chunk-BNKT3R3F.mjs +7 -0
- package/lib/{chunk-K2FBZIXY.mjs → chunk-BWWQXU2B.mjs} +1 -1
- package/lib/{chunk-IC2C2GOF.mjs → chunk-BXZ73A5M.mjs} +1 -1
- package/lib/{chunk-WA7EYLAQ.mjs → chunk-C2N2TNEU.mjs} +1 -1
- package/lib/{chunk-BKDV4ENO.mjs → chunk-C3LNYAVJ.mjs} +1 -1
- package/lib/{chunk-XLXIPIEW.mjs → chunk-CBL42DUU.mjs} +1 -1
- package/lib/chunk-CCEH7L53.mjs +7 -0
- package/lib/chunk-CELEBWEZ.mjs +7 -0
- package/lib/chunk-CV47FDQW.mjs +7 -0
- package/lib/{chunk-2UZPIMUC.mjs → chunk-CZLJZQCS.mjs} +1 -1
- package/lib/chunk-DBBPDSFN.mjs +7 -0
- package/lib/chunk-DIL62SUN.mjs +7 -0
- package/lib/chunk-DIS254AN.mjs +7 -0
- package/lib/{chunk-BTWDMNN3.mjs → chunk-DJCGURW7.mjs} +1 -1
- package/lib/{chunk-F6GUDTOB.mjs → chunk-DT3T7FRD.mjs} +1 -1
- package/lib/{chunk-IGYH7GMA.mjs → chunk-DWMRIWV5.mjs} +1 -1
- package/lib/{chunk-YRQGKDHM.mjs → chunk-EEFUE2ES.mjs} +1 -1
- package/lib/{chunk-FGRG7ANU.mjs → chunk-EOFO3PHS.mjs} +1 -1
- package/lib/{chunk-KBJ5VERV.mjs → chunk-FA4ZKDCU.mjs} +1 -1
- package/lib/{chunk-WU3GLFZO.mjs → chunk-FKK5YBGZ.mjs} +1 -1
- package/lib/chunk-FOIWWK7G.mjs +156 -0
- package/lib/chunk-FZF23M6R.mjs +7 -0
- package/lib/chunk-G2JR3F63.mjs +7 -0
- package/lib/{chunk-JEERQRLW.mjs → chunk-GBGHJTPC.mjs} +1 -1
- package/lib/{chunk-3RZQZHEB.mjs → chunk-GCGHHN4K.mjs} +1 -1
- package/lib/{chunk-RPI7LRTW.mjs → chunk-GGNUACTY.mjs} +1 -1
- package/lib/{chunk-EMNC6YI4.mjs → chunk-GGUOIDWP.mjs} +1 -1
- package/lib/chunk-GHPR5UVV.mjs +7 -0
- package/lib/{chunk-X5JYBPXP.mjs → chunk-GJ6SZVHT.mjs} +1 -1
- package/lib/{chunk-W622GUAW.mjs → chunk-H4JUYUSL.mjs} +1 -1
- package/lib/{chunk-XAMBCQPU.mjs → chunk-H4OBZIX3.mjs} +1 -1
- package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
- package/lib/{chunk-L77FJZEP.mjs → chunk-HFUDCNU5.mjs} +1 -1
- package/lib/chunk-HIHCYMSL.mjs +7 -0
- package/lib/chunk-HKUWHVI7.mjs +9 -0
- package/lib/chunk-HQQVANWQ.mjs +20 -0
- package/lib/chunk-ICIYL45C.mjs +7 -0
- package/lib/chunk-IRZJU2PG.mjs +22 -0
- package/lib/chunk-ISSP2FZ5.mjs +7 -0
- package/lib/chunk-IVZJSDJD.mjs +7 -0
- package/lib/chunk-J24TIGSI.mjs +10 -0
- package/lib/{chunk-UNJA4J37.mjs → chunk-JESRFE2Z.mjs} +4 -4
- package/lib/chunk-JFNLKHY6.mjs +8 -0
- package/lib/chunk-JH27IKCO.mjs +9 -0
- package/lib/chunk-JJITOWZK.mjs +7 -0
- package/lib/{chunk-E5AHXLS6.mjs → chunk-JKT5YAQ2.mjs} +1 -1
- package/lib/{chunk-IWDREM66.mjs → chunk-JLZRZL5E.mjs} +1 -1
- package/lib/{chunk-FPKYYFM7.mjs → chunk-JPEVIXNH.mjs} +1 -1
- package/lib/chunk-JQZTMFO7.mjs +7 -0
- package/lib/chunk-KIMQQ6JQ.mjs +7 -0
- package/lib/{chunk-MILU7WFN.mjs → chunk-KJYEQHYP.mjs} +1 -1
- package/lib/chunk-KKOA62S4.mjs +474 -0
- package/lib/chunk-KP5G6FUC.mjs +7 -0
- package/lib/{chunk-JWTSEDIQ.mjs → chunk-L4INJ5TZ.mjs} +1 -1
- package/lib/{chunk-OLSGVAIL.mjs → chunk-LAUOSXMN.mjs} +53 -53
- package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
- package/lib/{chunk-KDGMAGQR.mjs → chunk-LHU6CPGE.mjs} +1 -1
- package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
- package/lib/chunk-LXDSRP2W.mjs +7 -0
- package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
- package/lib/{chunk-TTKXMDBN.mjs → chunk-MKTXJCXN.mjs} +4 -4
- package/lib/chunk-MUEQRIK7.mjs +9 -0
- package/lib/{chunk-IOIWJ3DJ.mjs → chunk-NLB3RGIY.mjs} +1 -1
- package/lib/{chunk-O2HDYYUV.mjs → chunk-NWOI25WY.mjs} +1 -1
- package/lib/chunk-O2PUGRNW.mjs +10 -0
- package/lib/chunk-O4BROUGM.mjs +7 -0
- package/lib/chunk-OETEC3P7.mjs +7 -0
- package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
- package/lib/chunk-P55MKIZX.mjs +37 -0
- package/lib/chunk-P63WJMXQ.mjs +7 -0
- package/lib/chunk-PBE44M2Y.mjs +7 -0
- package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
- package/lib/chunk-PE435FVH.mjs +15 -0
- package/lib/chunk-PPGDAUEQ.mjs +7 -0
- package/lib/{chunk-SE4QEZUG.mjs → chunk-PPHVWUFY.mjs} +1 -1
- package/lib/{chunk-CU2INBND.mjs → chunk-PR74GYVI.mjs} +1 -1
- package/lib/chunk-PWVDNN2C.mjs +7 -0
- package/lib/{chunk-6XYKJSGX.mjs → chunk-PYRZFUVU.mjs} +1 -1
- package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
- package/lib/{chunk-DYFALGRT.mjs → chunk-Q3DY7TO2.mjs} +1 -1
- package/lib/{chunk-BGUEWRK2.mjs → chunk-Q6SXNKV2.mjs} +1 -1
- package/lib/chunk-QAPVKPEC.mjs +7 -0
- package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
- package/lib/{chunk-TSLJUSLW.mjs → chunk-RCYEBY42.mjs} +1 -1
- package/lib/chunk-RLWB7F26.mjs +7 -0
- package/lib/{chunk-FXXLX4O6.mjs → chunk-RTWYLOCA.mjs} +1 -1
- package/lib/chunk-RYRMUPMY.mjs +7 -0
- package/lib/chunk-SAMWHL22.mjs +13 -0
- package/lib/{chunk-IZQZ6ZUF.mjs → chunk-SFGZFB4F.mjs} +1 -1
- package/lib/{chunk-FKG7Q3WH.mjs → chunk-SNEOKYV7.mjs} +1 -1
- package/lib/{chunk-3TJON4F3.mjs → chunk-STRMWSIQ.mjs} +1 -1
- package/lib/chunk-SZGGFST2.mjs +272 -0
- package/lib/{chunk-SOGQW4IG.mjs → chunk-T7WREYA5.mjs} +1 -1
- package/lib/{chunk-NTFIRZP6.mjs → chunk-TCBAE65A.mjs} +1 -1
- package/lib/{chunk-KYEDBS54.mjs → chunk-TEIBWMJM.mjs} +1 -1
- package/lib/{chunk-YKKRIEH4.mjs → chunk-TMA34QMA.mjs} +1 -1
- package/lib/chunk-TQ2TQHTT.mjs +9 -0
- package/lib/{chunk-HEKAZJRH.mjs → chunk-TWV4A5RK.mjs} +1 -1
- package/lib/{chunk-CEX3NEZL.mjs → chunk-UHFLKP26.mjs} +1 -1
- package/lib/chunk-UV74P4H2.mjs +7 -0
- package/lib/{chunk-WR4Q363I.mjs → chunk-V3R45ZWT.mjs} +1 -1
- package/lib/{chunk-GSKCGQIP.mjs → chunk-VPDEJGPS.mjs} +1 -1
- package/lib/{chunk-HLWMJF6Y.mjs → chunk-VQJMP3DC.mjs} +1 -1
- package/lib/chunk-VV3B6IC3.mjs +7 -0
- package/lib/{chunk-PJ5I73CK.mjs → chunk-VYOYXTCU.mjs} +1 -1
- package/lib/{chunk-NZC67CGR.mjs → chunk-VZT4E2OJ.mjs} +1 -1
- package/lib/{chunk-AEKONPF4.mjs → chunk-VZVICK7Q.mjs} +1 -1
- package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
- package/lib/chunk-WEMLDUQA.mjs +7 -0
- package/lib/{chunk-MYW5QNGI.mjs → chunk-WOOUISSO.mjs} +1 -1
- package/lib/{chunk-G35N4P7D.mjs → chunk-WSUKC2U3.mjs} +1 -1
- package/lib/{chunk-ZVAED4QV.mjs → chunk-WT3SCUHS.mjs} +1 -1
- package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
- package/lib/{chunk-DBB3EMIN.mjs → chunk-XFU3HRUV.mjs} +1 -1
- package/lib/chunk-XK5W7BVE.mjs +7 -0
- package/lib/{chunk-2GTBABKU.mjs → chunk-XO5FBOQF.mjs} +1 -1
- package/lib/{chunk-CHYDMRSV.mjs → chunk-XSKPYGMT.mjs} +1 -1
- package/lib/chunk-XU25YA46.mjs +9 -0
- package/lib/chunk-XZISAZA6.mjs +7 -0
- package/lib/chunk-Y4TDVDP2.mjs +13 -0
- package/lib/chunk-YAIIRFKJ.mjs +8 -0
- package/lib/{chunk-LKQ5RKIV.mjs → chunk-YAJQS3OL.mjs} +1 -1
- package/lib/{chunk-74Q6DORA.mjs → chunk-YGJF55VJ.mjs} +1 -1
- package/lib/chunk-YH4DYI6D.mjs +7 -0
- package/lib/chunk-YMDFF657.mjs +10 -0
- package/lib/{chunk-2BA2XKAY.mjs → chunk-YT22LMF7.mjs} +1 -1
- package/lib/{chunk-IG2MTQRP.mjs → chunk-Z42PHCVZ.mjs} +1 -1
- package/lib/{chunk-2NBYT7GR.mjs → chunk-ZHIZY3ZC.mjs} +1 -1
- package/lib/chunk-ZQO5PDX5.mjs +48 -0
- package/lib/chunk-ZRUDYB7O.mjs +7 -0
- package/lib/{chunk-BXU6WFMH.mjs → chunk-ZUBBEP75.mjs} +1 -1
- package/lib/chunk-ZUOPC4W2.mjs +7 -0
- package/lib/{chunk-GGD7ON3M.mjs → chunk-ZUTUYBNW.mjs} +1 -1
- package/lib/{chunk-MHMH6MTP.mjs → chunk-ZXFL2MSN.mjs} +1 -1
- package/lib/sandforge-autopilot.mjs +11 -11
- package/lib/sandforge-backup.mjs +63 -32
- package/lib/sandforge-checkpoint.mjs +1 -348
- package/lib/sandforge-cleanup.mjs +1 -1
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +1 -1
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +11 -11
- package/lib/sandforge-env.mjs +186 -140
- package/lib/sandforge-frozen.mjs +1 -266
- package/lib/sandforge-mcp.mjs +33 -14
- package/lib/sandforge-monitor.mjs +1 -1
- package/lib/sandforge-pipeline.mjs +88 -0
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge-users.mjs +157 -0
- package/lib/sandforge.mjs +1 -22
- package/lib/sf/sandforge/autopilot.mjs +20 -0
- package/lib/sf/sandforge/backup.mjs +20 -0
- package/lib/sf/sandforge/checkpoint.mjs +20 -0
- package/lib/sf/sandforge/cleanup.mjs +20 -0
- package/lib/sf/sandforge/clone.mjs +20 -0
- package/lib/sf/sandforge/compare.mjs +20 -0
- package/lib/sf/sandforge/dataops.mjs +20 -0
- package/lib/sf/sandforge/empty.mjs +20 -0
- package/lib/sf/sandforge/env.mjs +20 -0
- package/lib/sf/sandforge/frozen.mjs +20 -0
- package/lib/sf/sandforge/hardis-commands.mjs +20 -0
- package/lib/sf/sandforge/index.mjs +20 -0
- package/lib/sf/sandforge/mcp.mjs +20 -0
- package/lib/sf/sandforge/monitor.mjs +20 -0
- package/lib/sf/sandforge/pipeline.mjs +20 -0
- package/lib/sf/sandforge/seed.mjs +20 -0
- package/lib/sf/sandforge/sync.mjs +20 -0
- package/lib/sf/sandforge/users.mjs +20 -0
- package/lib/sfHelpHook.mjs +7 -0
- package/lib/sfPlugin.mjs +11 -0
- package/oclif.manifest.json +1 -0
- package/package.json +18 -3
- package/lib/chunk-2CNCDM56.mjs +0 -7
- package/lib/chunk-3F6Q5E7I.mjs +0 -14
- package/lib/chunk-4VS2V6WU.mjs +0 -25
- package/lib/chunk-5P4PHJRL.mjs +0 -9
- package/lib/chunk-5TC3QB4U.mjs +0 -10
- package/lib/chunk-7ABODJ4G.mjs +0 -7
- package/lib/chunk-7EGQP6S4.mjs +0 -7
- package/lib/chunk-7FFGJWHN.mjs +0 -7
- package/lib/chunk-7YDNUBO5.mjs +0 -7
- package/lib/chunk-A527W53V.mjs +0 -7
- package/lib/chunk-ADOAS63R.mjs +0 -7
- package/lib/chunk-B5QQJ4SI.mjs +0 -7
- package/lib/chunk-CION3VMZ.mjs +0 -7
- package/lib/chunk-CSBS5U5I.mjs +0 -7
- package/lib/chunk-DB7RBE5D.mjs +0 -7
- package/lib/chunk-E5ZB3LU5.mjs +0 -7
- package/lib/chunk-EFR2Y7E4.mjs +0 -7
- package/lib/chunk-EHQ3FX6X.mjs +0 -7
- package/lib/chunk-EQNW3UC2.mjs +0 -7
- package/lib/chunk-F43REJDZ.mjs +0 -10
- package/lib/chunk-GSG7WZHM.mjs +0 -7
- package/lib/chunk-HOJYWTP7.mjs +0 -20
- package/lib/chunk-HS4YRX4J.mjs +0 -7
- package/lib/chunk-I7O6C2B5.mjs +0 -8
- package/lib/chunk-IFETCRWE.mjs +0 -10
- package/lib/chunk-IQXHJEYB.mjs +0 -7
- package/lib/chunk-JPUR2CFX.mjs +0 -10
- package/lib/chunk-K327QKMD.mjs +0 -7
- package/lib/chunk-KRCA6IPH.mjs +0 -8
- package/lib/chunk-LPBMBW3O.mjs +0 -13
- package/lib/chunk-LWW4U276.mjs +0 -7
- package/lib/chunk-MFG4MUIO.mjs +0 -9
- package/lib/chunk-MJU2PGZQ.mjs +0 -15
- package/lib/chunk-OAZRPP4I.mjs +0 -7
- package/lib/chunk-OO6CLPEH.mjs +0 -7
- package/lib/chunk-OPXCV2KL.mjs +0 -7
- package/lib/chunk-P33PSCXK.mjs +0 -7
- package/lib/chunk-Q3DM32KF.mjs +0 -11
- package/lib/chunk-QR3WELJQ.mjs +0 -7
- package/lib/chunk-QWT2C74M.mjs +0 -7
- package/lib/chunk-R3X3LV64.mjs +0 -14
- package/lib/chunk-RMBPOTD7.mjs +0 -7
- package/lib/chunk-SIHORWVK.mjs +0 -7
- package/lib/chunk-T62WNR54.mjs +0 -7
- package/lib/chunk-TTFDUKUS.mjs +0 -47
- package/lib/chunk-VE6XKGGD.mjs +0 -7
- package/lib/chunk-VGW4MXXZ.mjs +0 -7
- package/lib/chunk-VS7ZXUII.mjs +0 -824
- package/lib/chunk-VXQLDM4R.mjs +0 -7
- package/lib/chunk-VYXMVJL5.mjs +0 -7
- package/lib/chunk-W7U5E5ZL.mjs +0 -9
- package/lib/chunk-WXAQ7FK3.mjs +0 -115
- package/lib/chunk-YS4G22C2.mjs +0 -7
- package/lib/chunk-ZM6OJGIG.mjs +0 -7
- package/lib/chunk-ZUTYVST5.mjs +0 -7
package/lib/chunk-3F6Q5E7I.mjs
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
-
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
-
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
-
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
-
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a as uR,b as ba,c as pR,d as gR}from"./chunk-IC2C2GOF.mjs";import{b as Hy}from"./chunk-VGW4MXXZ.mjs";import{a as Ol,b as Jy,c as Vy,d as zi,e as ys}from"./chunk-2BA2XKAY.mjs";import{a as Yy}from"./chunk-OAZRPP4I.mjs";import{c as Xy,d as Ky}from"./chunk-JEERQRLW.mjs";import{c as fR,l as hR}from"./chunk-HOJYWTP7.mjs";import{a as Cw,d as Lw,e as Fw,f as Rs,g as fo,h as jl,i as Zi,j as _w,k as Uw,l as Bw,m as Hw}from"./chunk-E5ZB3LU5.mjs";import{a as Sb,b as ql,c as tR,d as rR,e as nR,h as oR,i as sR,j as iR,m as aR,n as dR,o as ya,p as Wl,q as wa,r as cR}from"./chunk-EFR2Y7E4.mjs";import{b as Zb,e as eR}from"./chunk-O2HDYYUV.mjs";import{$ as Yb,A as ga,B as Fb,C as _b,D as fa,E as ha,F as ma,G as un,H as Ub,I as Bb,L as Hb,M as qb,N as Wb,O as zb,P as Gb,R as Hl,S as Jb,T as Vb,U as Xb,Z as Kb,a as na,aa as Qb,c as oa,d as sa,e as kb,f as Ob,g as Ib,h as Ct,j as ia,k as aa,l as Ur,m as bo,n as Ro,o as vo,p as Ab,q as Tb,r as Eb,s as da,t as ca,u as la,v as Pb,w as jb,x as Nb,y as $b,z as Lb}from"./chunk-ZM6OJGIG.mjs";import{b as ua,g as pa}from"./chunk-MHMH6MTP.mjs";import{e as mr,g as Cb,i as Db,k as xb,l as So,m as Mb}from"./chunk-COFG7Q6R.mjs";import{a as lR}from"./chunk-YRQGKDHM.mjs";import{a as sf,b as vi,e as hy,g as nn,h as Kt,i as By,m as qy}from"./chunk-MJU2PGZQ.mjs";import{a as jt}from"./chunk-LWW4U276.mjs";import{a as Ey,b as Py}from"./chunk-XCA5AONB.mjs";import{a as Li,b as my,c as yy,d as wy,e as fs,f as by,g as Ry,h as vy,j as Sy}from"./chunk-WR2GIKWE.mjs";import{$ as Vf,$b as mm,A as Af,Ab as Wh,B as Tn,Bb as zh,Bc as Ye,C as cl,Ca as ah,Cb as Gh,Cc as hs,D as Tf,Da as dh,Db as Jh,Dc as Cy,E as Ef,Ea as ch,Eb as Vh,Ec as Dy,F as ki,Fa as lh,Fb as Xh,G as Pf,Ga as uh,Gb as Ii,H as Cf,Ha as ph,Hb as Kh,I as Df,Ia as gh,Ib as Yh,J as xf,Ja as fh,Jb as Qh,K as Mf,Ka as hh,Kb as Zh,L as jf,La as mh,Lb as em,M as ll,Ma as yh,Mb as tm,N as Nf,Na as wh,Nb as rm,O as $f,Oa as bh,Ob as nm,P as Lf,Pa as jr,Pb as om,Q as Ff,Qa as Rh,Qb as sm,R as _f,Ra as hl,Rb as im,S as Uf,Sa as Oi,Sb as am,T as Bf,Ta as as,Tb as dm,U as Hf,Ua as vh,Ub as cm,V as qf,Va as Sh,Vb as lm,W as Wf,Wb as um,X as zf,Xb as pm,Y as Gf,Yb as gm,Z as Jf,Zb as fm,_ as no,_b as hm,a as xr,aa as Xf,ac as ym,b as Re,ba as Kf,bc as wm,c as bi,ca as Yf,cc as bm,d as St,da as ul,dc as Rm,e as Qr,ea as Qf,ec as vm,f as ro,fa as Zf,fb as kh,fc as Sm,g as st,ga as eh,gb as Oh,gc as km,h as ar,ha as th,hb as Ih,hc as Om,i as An,ia as rh,ib as Ah,ic as Im,j as T,ja as nh,jb as Th,jc as Am,k as ke,ka as oh,kb as Eh,kc as ml,l as ze,la as sh,lb as Ph,lc as Tm,m as Le,ma as ih,mb as Ch,mc as Em,n as ge,na as pl,nb as Dh,nc as Pm,o as E,oa as gl,ob as xh,oc as Cm,p as Ri,pa as fl,pb as Mh,pc as Dm,q as rs,qb as jh,qc as xm,r as Mr,rb as Nh,rc as Mm,s as je,sb as $h,sc as jm,t as vf,tb as Lh,tc as Nm,u as Sf,ub as Fh,uc as D,v as kf,vb as _h,w as Of,wb as Uh,wc as $i,x as Si,xb as Bh,yb as Hh,z as If,zb as qh}from"./chunk-2CNCDM56.mjs";import{g as Ni}from"./chunk-SIHORWVK.mjs";import{a as Tt,b as ss,c as lf,d as uf}from"./chunk-CE6ZDGBB.mjs";import{a as xy,b as My,c as jy,d as Ny,e as $y,f as Ui,g as co,h as xn,i as Lr,j as on,k as Bi}from"./chunk-B5QQJ4SI.mjs";import{b as Dn,c as Uy}from"./chunk-BOGNK4LV.mjs";import{$a as _l,Ab as Ul,Bb as fb,Cb as hb,Fb as mb,Ga as $l,Gb as yb,Ha as Ll,Ib as Bl,Ja as Fl,Jb as wb,Kb as bb,L as Ww,Lb as Rb,Mb as vb,Na as ta,P as zw,Pa as eb,Qa as vs,Ra as tb,Ta as rb,Ua as nb,Va as ob,Wa as sb,Xa as ib,Za as ab,_a as db,a as fi,aa as Gw,b as _g,bb as ho,db as cb,eb as ra,fb as lb,g as Iw,i as Ml,ja as Jw,ka as Vw,la as ea,ma as Nl,n as Aw,o as Qi,oa as Xw,ob as ub,p as Tw,pa as Kw,q as Ew,qa as Yw,qb as mo,r as Pw,ra as Qw,sb as pb,ta as Zw,tb as yo,ub as wo,y as qw,yb as gb,zb as hr}from"./chunk-4VS2V6WU.mjs";import{h as Dw}from"./chunk-KYEDBS54.mjs";import{a as xw,b as Mw,f as jw,g as Nw,h as $w}from"./chunk-K2FBZIXY.mjs";import{a as cy,b as oo,c as so,d as rn,e as ly,f as vl,i as ky,j as Oy,k as _i,l as Iy,m as Ay,q as Il,r as ws,s as Mn,t as Vi}from"./chunk-F43REJDZ.mjs";import{B as sy,C as Vt,D as xi,E as Mi,F as ji,K as iy,L as bl,M as Rl,N as Xt,O as ay,P as dy,Q as tn,U as cr,V as Cn,a as rf,b as $m,c as Lm,d as Fm,e as Jt,f as _m,g as yl,h as Um,i as Bm,j as Hm,k as qm,m as En,o as ls,p as Ym,pa as Gi,q as Qm,s as Zm,t as ey,ta as Ji,u as us,w as ty,x as ry,y as ny,z as oy}from"./chunk-JPUR2CFX.mjs";import{d as Fi}from"./chunk-T63U4OZJ.mjs";import{J as Gy,d as Hi,h as qi,i as Wy,k as zy,x as Wi}from"./chunk-IFETCRWE.mjs";import{b as uy,f as py,o as Et,p as ps,q as Sl,r as ao,s as kl,t as gs,w as gy,x as fy}from"./chunk-PZPJKATS.mjs";import{a as Ty}from"./chunk-YYZL7UGV.mjs";import{a as Ci,c as Di}from"./chunk-SAR5622P.mjs";import{b as Fg}from"./chunk-KDGMAGQR.mjs";import{A as ms,B as Ut,a as tl,c as Pg,d as rl,e as Cg,f as es,g as nl,h as Dg,j as xg,k as Mg,l as gi,m as jg,n as ol,o as Ng,p as $g,q as Lg,r as q,s as Pt,t as kt,v as Fy,w as $r,x as _y,z as mt}from"./chunk-MFG4MUIO.mjs";import{B as is,D as Rf,p as mf}from"./chunk-EQNW3UC2.mjs";import{a as Ai,b as Mt,c as Nr,d as ds,e as Ti,f as cs,g as Ei,h as Zr,i as Wm,j as Pi,k as wl}from"./chunk-GSKCGQIP.mjs";import{a as De}from"./chunk-5LFSFYFJ.mjs";import{b as Zn,c as Ag,e as Tg,f as Eg,g as pi}from"./chunk-HS4YRX4J.mjs";import{a as wf,d as bf}from"./chunk-CU2INBND.mjs";import{a as yf}from"./chunk-YKKRIEH4.mjs";import{a as io,d as Pn}from"./chunk-TUACWKIH.mjs";import{$ as aw,A as Qy,Aa as dn,Ba as cn,D as jn,E as Tl,F as Zy,G as ew,H as tw,Ha as ln,I as rw,Ia as bs,J as nw,K as pr,Ka as Pl,L as Qt,La as Cl,Ma as Dl,Na as bw,O as sn,Oa as Rw,P as uo,Pa as vw,Q as Xi,Qa as xl,R as po,S as an,T as go,Ta as ut,U as Ki,Ua as Sw,Va as kw,W as Yi,Wa as Ow,X as ow,Y as sw,Z as iw,_ as gr,a as nf,b as to,ba as El,c as ft,d as of,e as K,ea as dw,f as lt,h as af,ha as cw,i as et,ia as lw,j as df,ja as uw,k as al,ka as fr,l as cf,m as ns,n as dl,o as lr,p as fe,pa as pw,q as Ly,r as Nt,ra as gw,s as $t,sa as fw,ta as hw,ua as mw,va as yw,w as Yt,x as _r,ya as ww,z as Al}from"./chunk-VYXMVJL5.mjs";import{q as ur,r as Fr,s as lo}from"./chunk-AEKONPF4.mjs";import{c as Kg,f as wi,g as Yg,j as Qg,l as Zg,r as ef,s as tf}from"./chunk-JWTSEDIQ.mjs";import{a as de}from"./chunk-4TLYUZD5.mjs";import{b as pf,e as gf,k as ff,m as hf}from"./chunk-WIO4XO4F.mjs";import{a as dr}from"./chunk-EADHKH3A.mjs";import{i as os}from"./chunk-INIT2UKJ.mjs";import{a as Zo}from"./chunk-SU65Z2BA.mjs";import{e as Jm,h as en,k as Vm,l as Xm,m as Km}from"./chunk-L77FJZEP.mjs";import{E as ir,F as ts,M as zg,O as Gg,X as Jg,Y as Vg,_ as Xg,a as hi,b as Gt,c as mi,e as Bg,i as Hg,l as yi,m as il,n as qg,o as Wg,p as eo,q as sr}from"./chunk-A527W53V.mjs";import{a as zt,d as sl,f as Ug,h as Fe}from"./chunk-TZE3Y7IQ.mjs";import{f as zm,j as Gm}from"./chunk-GGD7ON3M.mjs";import{a as Ig,b as A}from"./chunk-CA5NAXSU.mjs";import{$ as qp,$a as Kp,$b as Te,Ab as si,Ac as Kr,Ad as Rg,Bc as ag,Cb as Go,Cc as Cr,Dc as dg,Dd as Qo,Ec as Zc,Ed as _t,F as Up,Fc as cg,Fd as vg,Gc as lg,Gd as el,Hc as ai,Hd as ci,Ic as ug,Id as li,Jd as Sg,Kd as kg,Ld as Og,Md as ui,Pc as pg,V as Bp,Wb as gt,Wc as Ko,Xa as Vp,Yb as In,Yc as Yr,Z as Hp,Zb as og,_ as zc,_a as Xp,a as Pp,ab as Yp,ac as Qn,ad as gg,b as Cp,bb as ri,bc as Kc,c as Np,ca as Tr,cb as Qp,cc as Er,da as ti,db as Zp,ea as Wp,eb as ni,ec as be,ed as Dr,fa as Gc,fd as ot,ga as Jc,gb as eg,ha as zp,hb as tg,ia as Vc,ib as rg,j as Kn,k as Yn,kc as Yc,lc as Jo,ld as di,mc as Vo,n as Xr,o as zo,oa as Gp,ob as ng,oc as sg,p as $p,pa as Jp,pb as Xc,pc as ig,q as Lp,qd as fg,r as Fp,rd as hg,sd as Yo,uc as Pr,wd as mg,x as _p,xc as Xo,xd as yg,y as Wc,yb as oi,yc as ii,yd as wg,zc as Qc,zd as bg}from"./chunk-TTFDUKUS.mjs";import{a as Dp,b as L,e as Me,f as Je,i as Xn,k as Se,l as V,o as xp,p as Zs,s as ei,u as Ke,v as vt,x as Mp,y as jp,z as Wo}from"./chunk-7EANH5PY.mjs";function pn(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 DI="/lightning/setup/AsyncApexJobs/home";function mR(s){let e=pn(s);return e.ok?{ok:!0,url:new URL(DI,e.url.origin).toString()}:e}import{randomBytes as xI}from"node:crypto";import{createReadStream as MI}from"node:fs";import{open as jI,readdir as NI,rm as $I,stat as LI}from"node:fs/promises";import{homedir as FI}from"node:os";import{join as Zt,resolve as _I}from"node:path";import{createInterface as UI}from"node:readline";var zl="journal.ndjson",Ra=2e3,vR=/^em-\d{8}-\d{6}-[a-z0-9]{4}$/,yR="abcdefghijklmnopqrstuvwxyz0123456789";function Jl(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(xI(4),o=>yR[o%yR.length]).join("");return`em-${t}-${r}-${n}`}function Gl(s){return vR.test(s)}function Vl(s=process.env){let e=s.SANDFORGE_JOURNAL_DIR,t=e!==void 0&&e.trim()!==""?_I(e):Zt(FI(),".sandforge");return Zt(t,"empty")}var BI=L().regex(/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,"Not a record id"),Br=L().regex(/^[A-Za-z][A-Za-z0-9_]*$/,"Not an API name").max(80),Ss=Wo.datetime({offset:!0}),wR=Se(BI).max(Ra),SR=Ke(["success","partial","failure","cancelled"]),kR=V({v:vt(1),kind:vt("head"),runId:L().regex(vR),organizationId:L().min(15).max(18),orgName:L(),startedAt:Ss,readAt:Ss,previewId:L(),mode:Ke(["objects","org"]),deleteMode:Ke(["recycle","hard"]),request:V({mode:Ke(["objects","org"]),objects:Se(L()).optional(),excluded:Se(L()).optional(),customSettings:Je().optional(),files:Je().optional(),managedPackages:Je().optional(),unrestorable:Je().optional()}).strict(),passes:Se(V({objectApiName:Br,records:Me().int().nonnegative().optional(),sent:Me().int().nonnegative().optional(),rows:L().max(200).optional()})),toDraftAlong:Se(V({objectApiName:Br,condition:L().optional()})),beforeParent:Se(V({objectApiName:Br,field:L(),parent:Br,reason:Ke(["restricted","customPrices"])})),undoLost:Se(V({objectApiName:Br,field:L().optional(),parent:Br.optional(),reason:Ke(["restricted","unordered","notRestorable"]),records:Me().int().nonnegative().optional(),atLeast:vt(!0).optional()})).optional()}),HI=V({kind:vt("attempt"),at:Ss,resumed:Je()}),OR=V({kind:vt("spooled"),objectApiName:Br,place:Me().int().nonnegative(),count:Me().int().nonnegative(),sinceRead:Je()}),qI=V({kind:vt("settled"),objectApiName:Br,deleted:wR,gone:wR}),WI=V({objectApiName:Br,planned:Me().int().nonnegative(),deleted:Me().int().nonnegative(),gone:Me().int().nonnegative(),refused:Me().int().nonnegative(),notReached:Me().int().nonnegative().optional(),madeSince:Me().int().nonnegative().optional(),reasons:Se(L())}),IR=V({kind:vt("end"),at:Ss,status:SR,hardRefused:L().optional(),passes:Se(WI)}),zI=V({kind:vt("undo"),at:Ss,status:SR}),bR=Zs("kind",[kR,HI,OR,qI,IR,zI]),yr=class extends Error{constructor(e){super(e),this.name="EmptyJournalDamaged"}};function GI(s){return s==="success"||s==="partial"}var va=class s{constructor(e,t){this.dir=e;this.head=t}dir;head;static async begin(e,t){let r=kR.parse({v:1,kind:"head",...t});await Wi(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 RR(Zt(e,zl))){r.kind==="head"&&(t=r);break}if(t===void 0)throw new yr("The journal of this emptying names nothing it was to do.");return new s(e,t)}idsDirOf(e,t){return Zt(this.dir,"ids",`${e}-${gt(t)}`)}async write(e,t="a"){let r=Zt(this.dir,zl),n=await jI(r,t,Hi);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(OR.parse({kind:"spooled",...e}))}async settled(e,t,r){for(let n=0;n<Math.max(t.length,r.length);n+=Ra)await this.write({kind:"settled",objectApiName:e,deleted:t.slice(n,n+Ra),gone:r.slice(n,n+Ra)})}ended(e,t,r,n){return this.write(IR.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 RR(Zt(this.dir,zl))}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":GI(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*RR(s){let e=MI(s,{encoding:"utf8"}),t=UI({input:e,crlfDelay:1/0}),r,n=0,o=(i,a)=>{try{return bR.parse(JSON.parse(i))}catch{throw new yr(`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 yr("The journal of this emptying is not on this machine."):i}finally{t.close(),e.destroy()}if(r)try{yield bR.parse(JSON.parse(r.raw))}catch{return}}var Sa=class{constructor(e){this.root=e}root;orgDir(e){return Zt(this.root,zy(e))}begin(e,t){return va.begin(Zt(this.orgDir(e),t.runId),{...t,organizationId:e})}async runsOf(e){let t=this.orgDir(e),r;try{r=await NI(t)}catch(n){if(n.code==="ENOENT")return[];throw n}return r.filter(Gl).sort().map(n=>({runId:n,dir:Zt(t,n)}))}async lastOf(e){return(await this.runsOf(e)).at(-1)}async open(e,t){if(!Gl(t))throw new yr(`Not an emptying's id: ${t}`);let r=Zt(this.orgDir(e),t);try{await LI(r)}catch{throw new yr(`No journal of the emptying ${t} is on this machine.`)}return va.open(r)}async remove(e,t){Gl(t)&&await $I(Zt(this.orgDir(e),t),{recursive:!0,force:!0})}};import{randomUUID as Pj}from"node:crypto";import{join as Cj}from"node:path";var ko=new Map,AR=(s,e)=>`${s}::${e}`;async function Bt(s,e,t,r=Date.now){let n=AR(s,e),o=ko.get(n);if(o&&r()-o.at<3e5)return o.value;let i=t();ko.set(n,{at:r(),value:i});try{return await i}catch(a){throw ko.get(n)?.value===i&&ko.delete(n),a}}function TR(s){let e=AR(s,"");for(let t of ko.keys())t.startsWith(e)&&ko.delete(t)}var JI=V({orgId:L(),detectedAt:L(),evidence:Ke(["connection","monitor","production"]),previousOrganizationId:L().optional(),organizationId:L().optional(),previousInstanceName:L().optional(),instanceName:L().optional(),sandboxName:L().optional(),reportedBy:L().optional()}),VI=V({organizationId:L(),instanceName:L().optional(),formerOrganizationIds:Se(L()),refreshes:Se(JI)}),ER="sandbox-refresh:",XI="sandbox-refresh",PR=10,KI=20,YI=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function Xl(s){return s!==void 0&&YI.test(s)?s.slice(0,15):void 0}function CR(s){try{return new URL(s).hostname.toLowerCase()}catch{return}}function QI(s){let e=CR(s.instanceUrl),t=".my.salesforce.com";return e?.endsWith(t)?e.slice(0,-t.length):void 0}function ZI(s,e,t){let r=t.toLowerCase(),n=QI(s);return n&&CR(e.instanceUrl)?.startsWith(`${n}--${r}.`)?!0:e.username.toLowerCase()===`${s.username.toLowerCase()}.${r}`}var ka=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=Xl(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,KI),refreshes:(l?[u,...c]:[u,...a.refreshes]).slice(0,PR)}),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||!ZI(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,PR)}),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=Xl(t);return r!==void 0&&this.refreshesOf(e).some(n=>n.organizationId===r)}baselineOf(e){let t=Xl(e.orgId);return t===void 0?void 0:{organizationId:t,formerOrganizationIds:[],refreshes:[]}}read(e){let t=this.deps.configStore.get(`${ER}${e}`);if(t===void 0)return;let r=VI.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(`${ER}${e}`,t,XI)}emit(e){for(let t of this.listeners)try{t(e)}catch(r){this.deps.log?.(`[sandbox-refresh] a listener failed: ${String(r)}`)}}};var eA=5,tA=5e3,rA=3e4,nA=V({device_code:L().min(1).max(4096),user_code:L().regex(/^[A-Za-z0-9-]{4,32}$/),verification_uri:L().min(1).max(2048),interval:Me().int().positive().max(300).optional(),expires_in:Me().int().positive().optional()}),oA=V({access_token:L().min(1),refresh_token:L().min(1).optional(),instance_url:L().min(1).max(2048)}),DR=V({error:L().min(1),error_description:L().optional()}),Nn=class extends Error{constructor(){super("Sign-in cancelled."),this.name="DeviceLoginCancelledError"}},Oa=class extends Error{constructor(e){super(e),this.name="RefusedByHostError"}};function sA(s,e){return new Promise((t,r)=>{if(e?.aborted){r(new Nn);return}let n=()=>{clearTimeout(o),r(new Nn)},o=setTimeout(()=>{e?.removeEventListener("abort",n),t()},s);e?.addEventListener("abort",n,{once:!0})})}function MR(s){let e=pn(s);if(!(!e.ok||e.url.username!==""||e.url.password!=="")&&!(e.url.port!==""||!Og(e.url.hostname)))return e.url}function xR(s){return`Salesforce refused the device sign-in: ${s.error_description?`${s.error_description} (${s.error})`:s.error}`}var Ia=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??sA}async authorize(e,t,r){let n=await this.post(e,{response_type:"device_code",client_id:t},r),o=DR.safeParse(n);if(o.success)throw new Error(xR(o.data));let i=nA.safeParse(n);if(!i.success)throw new Error("Salesforce answered the device sign-in without a usable code.");let a=MR(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,Lp);return{deviceCode:i.data.device_code,userCode:i.data.user_code,verificationUri:a.href,intervalMs:(i.data.interval??eA)*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 Nn;if(c instanceof Oa)throw c;continue}let d=DR.safeParse(a);if(d.success){if(d.data.error==="authorization_pending")continue;if(d.data.error==="slow_down"){o+=tA;continue}throw new Error(xR(d.data))}return iA(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 Nn;let n=AbortSignal.timeout(rA),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 Nn:a}let i=await o.text();try{return JSON.parse(i)}catch{throw new Oa(`Salesforce answered HTTP ${o.status} with a page instead of JSON. Check the login URL.`)}}};function iA(s){let e=oA.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=MR(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 wr=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 aA,readdir as dA}from"node:fs/promises";import{join as jR}from"node:path";var cA=/^[^.][^@/\\]*@[^/\\]+\.json$/;async function NR(s,e=Date.now()){let t=jR(s,".sfdx"),r;try{r=await dA(t)}catch{return 0}let n=new Set;return await Promise.all(r.filter(o=>cA.test(o)&&!o.endsWith(".partial.json")).map(async o=>{let i=await lA(jR(t,o),e);i&&n.add(i)})),n.size}async function lA(s,e){try{let t=JSON.parse(await aA(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 uA}from"node:os";var pA=new Set(["org:list","org:connect","org:connect:cancel","org:disconnect","org:select","org:update","org:open-in-browser","org:cli-status"]),$R=15e3,LR="The Salesforce CLI holds no connected org yet. Use Log in with your browser on the Organizations page: it opens the Salesforce login page.",Aa=class{constructor(e,t={}){this.deps=e;this.browser=t.browser??new wr,this.deviceLogin=t.deviceLogin??new Ia,this.countCliOrgs=t.countCliOrgs??(()=>NR(uA())),this.connectTo=t.connectTo??(r=>Lg(r))}deps;browser;deviceLogin;countCliOrgs;connectTo;pendingSignIns=new Map;async handle(e){if(!pA.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=D(fm,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:ke(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){ke(this.deps,"error","Salesforce CLI",`${zo} ${e}`,{actions:[{label:"Install the CLI",command:"sf-cli-install",url:$p}]})}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,zo,"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);ke(this.deps,"error","Import Failed",d),this.failConnect(e,d,"SFDX_IMPORT_FAILED");return}if(n.length===0){ke(this.deps,"info","Import",LR,{autoDismissMs:null,code:"NO_CLI_ORGS"}),this.failConnect(e,LR,"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}`),ke(this.deps,"success","Import",`Imported ${n.length} org(s) from SF CLI.`),r.length>0&&ke(this.deps,"warning","Import",this.reportUnreadable(r),{autoDismissMs:null}),this.ackConnect(e,o[0])}catch(t){let r=A(t);this.deps.log(`[ERR] org:sfdx-import: ${r}`),ke(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=>`${be(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 Mg(this.connectTo({instanceUrl:o,accessToken:n,version:t.metadata.apiVersion}).then(l=>Zn(l)),$R,`the org did not answer within ${$R/1e3} s`),a=In({isSandbox:i.sandbox,edition:i.edition}),{safetyTier:d,color:c}=Er(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 (${A(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){ke(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){ke(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=In({isSandbox:o.isSandbox,edition:o.orgType}),{safetyTier:a,color:d}=Er(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:Kn.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}`),ke(this.deps,"success","Connected",`${be(c)} connected.`)}catch(o){let i=A(o);this.deps.log(`[ERR] org:username-password: ${i}`),ke(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=ui(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}".`;ke(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,zo,"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=A(n);this.deps.log(`[ERR] org:oauth-web: ${o}`),ke(this.deps,"error","OAuth Failed",o),this.failConnect(e,o,"OAUTH_WEB_FAILED")}}async handleJwt(e){let t=D(hm,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=A(n);this.deps.log(`[ERR] org:jwt: ${o}`),ke(this.deps,"error","JWT Sign-in Failed",o),this.failConnect(e,o,"JWT_LOGIN_FAILED")}}async handleOAuthDevice(e){let t=D(mm,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=A(o);this.deps.log(`[ERR] org:oauth-device: ${i}`),ke(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=D(ym,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,zo,"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]);ke(this.deps,"success",r,`${be(n.org)} connected.`),this.ackConnect(e,o??n.org.id)}async handleOrgDisconnect(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(wm,e,"org:error",this.deps);if(!t)return;let r=t;gi().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=D(bm,e,"org:error",this.deps);if(!t)return;let{orgId:r}=t;if(!this.deps.orgManager.getOrg(r)){ke(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=D(vm,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=D(Rm,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=pn(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 "${be(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 gA(s){let e=Bp.safeParse(s.services?.getSandforgeSetting?.("forge.graphView","auto"));return e.success?e.data:"auto"}function fA(s){return s.services?.getSandforgeSetting?.("grappe.enabled",!1)===!0}var hA=new Set(["settings:get","settings:update","telemetry:status","telemetry:toggle"]),Ta=class{constructor(e){this.deps=e}deps;async handle(e){if(!hA.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:gA(this.deps),grappeEnabled:fA(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=D(Sm,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=D(km,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: ${A(n)}`);let o=T(this.deps,e,"telemetry:toggle:response",{success:!1,enabled:this.deps.services.getSandforgeSetting?.("telemetry",!1)??!1,error:A(n)});this.deps.broker.postToWebview(o)}}};var Kl={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"}},Yl=1,FR=.15,mA=.55;function _R(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 yA(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 Ql(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 UR(s){switch(s){case"up":return"degrading";case"down":return"improving";case"stable":return"stable"}}function BR(s){return s.direction!=="up"?0:Math.min(15,Math.max(0,Math.abs(s.changePercent)*.5))}function ks(s){return s>=70?"healthy":s>=40?"warning":"critical"}function HR(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 qR(s){let e=s.max-s.remaining;return`${s.usedPercent}% used (${e.toLocaleString()} / ${s.max.toLocaleString()})`}var Ea=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 Yl;let t=e*FR;return Math.max(mA,Yl-t)}computeOptionalDimensionWeight(e){return e===0?0:FR}addCoreLimitFactors(e,t,r){for(let[n,o]of Object.entries(Kl)){let i=e.limits.find(p=>p.name===n);if(!i)continue;let a=_R(i.usedPercent),d=this.fetchTrendData(e,n),c=d?UR(d.direction):"stable",l=d?BR(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:ks(u),detail:qR(i),recommendation:HR(i.name,i.usedPercent),trend:c})}}addRemainingLimitFactors(e,t,r){let n=new Set(Object.keys(Kl)),o=e.limits.filter(c=>!n.has(c.name)&&c.usedPercent>0);if(o.length===0)return;let i=Object.values(Kl).reduce((c,l)=>c+l.weight,0),d=Math.max(0,(Yl-i)*r)/o.length;for(let c of o){let l=_R(c.usedPercent),u=this.fetchTrendData(e,c.name),p=u?UR(u.direction):"stable",g=u?BR(u):0,h=Math.max(0,Math.round(l-g));t.push({name:c.name,category:"limits",score:h,weight:d,status:ks(h),detail:qR(c),recommendation:HR(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(Ql(n,50,500)*.4+Ql(o,200,2e3)*.3+Ql(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:ks(a),detail:d,recommendation:c,trend:"stable"})}addCoverageDimension(e,t,r){if(e.codeCoverage===void 0)return;let n=yA(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:ks(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:ks(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 wA=Se(V({version:L()}));function WR(s){let e=wA.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 bA(s){if(!s)return;let e=new Date(s);return Number.isNaN(e.getTime())?void 0:e.toISOString()}var Pa=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=bA(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 zR(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 Zl=1440*60*1e3,GR=7*Zl,RA=500*1024,vA=900*1e3,SA=2,kA="trends",OA=new Set(ri),IA=Zl,Da=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>=Ca(n-GR)),d=a.filter(l=>l.timestamp>=Ca(n-IA)),c={};for(let l of r)c[l]=this.computeTrend(l,a,d);return c}getHistory(e,t=Zl){let r=Ca(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)<vA}append(e,t,r,n){let o=Ca(n-GR),i=[...t,r].filter(d=>d.timestamp>=o).map(d=>({...d,limits:d.limits.filter(c=>OA.has(c.name))})),a=this.trimToSizeLimit(i);return this.configStore.set(this.trendKey(e),a,kA),this.lastSaveTimestamps.set(e,n),a}computeTrend(e,t,r){let{values:n,timestamps:o}=JR(e,t),{values:i}=JR(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)<=SA?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<=RA);)t.shift();return t}};function Ca(s){return new Date(s).toISOString()}function JR(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 xa=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||!AA(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 AA(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 Oo="alert:state:",eu="alerts";var Ma=class{constructor(e){this.configStore=e}configStore;saveAlerts(e){this.configStore.set(`${Oo}active`,e,eu)}loadAlerts(){let e=this.configStore.get(`${Oo}active`);return Array.isArray(e)?e:[]}saveDefinitions(e){this.configStore.set(`${Oo}definitions`,e,eu)}loadDefinitions(){let e=this.configStore.get(`${Oo}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(`${Oo}history`,i,eu)}loadHistory(){let e=this.configStore.get(`${Oo}history`);return Array.isArray(e)?e:[]}};var tu=[{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 ja=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 Na=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 $a=class{fetchLogs;analyses=new Map;truncatedCache=new Map;constructor(e){this.fetchLogs=e}analyze(e){let t=TA(e),r=EA(e),n=PA(e),o=e.durationMs,i=CA(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 TA(s){return Math.min(Math.floor(s.logSize/500),100)}function EA(s){return Math.min(Math.floor(s.logSize/1e3),150)}function PA(s){return Math.min(s.logSize*10,6e6)}function CA(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 DA=new Set(Qp);function XR(s){return typeof s=="string"&&DA.has(s)?s:"Unknown"}function xA(){let s=new Map;return{load:e=>s.get(e),save:(e,t)=>{s.set(e,t)}}}function VR(s){return`${s.sandboxName}:${s.refreshDate}`}var La=class{querySandboxes;onRefreshDetected;seen;refreshCache=new Map;supportedCache=new Map;truncatedCache=new Map;constructor(e,t,r=xA()){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(VR(c))||this.onRefreshDetected?.(c)}let a=o.map(VR);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=>Zp(r.status))}};var Fa=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 KR=new Set(["Queued","Processing"]),_a=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=>KR.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=>KR.has(r.status)).length,completed:t.filter(r=>r.status==="Completed").length,failed:t.filter(r=>r.status==="Failed").length}}};var MA=3e4,jA=1440*60*1e3,YR=100,QR=50,ZR=20,ev="sandbox-process-seen:";function NA(s){return{load:e=>{let t=s.get(`${ev}${e}`);return Array.isArray(t)?t.filter(r=>typeof r=="string"):void 0},save:(e,t)=>{s.set(`${ev}${e}`,t,"sandbox-refresh")}}}function tv(s){let e=new Da(s.configStore),t=new Ma(s.configStore),r=new xa(R=>{s.log(`[ALERT] ${R.severity}: ${R.message}`);let k=R.severity==="critical"?"error":"warning";s.notify(k,R.message),t.saveAlerts(r.getActiveAlerts())}),n=t.loadDefinitions(),o=n.length>0?n:tu;for(let R of o)r.addDefinition(R);n.length===0&&t.saveDefinitions(tu);let i=t.loadAlerts();r.restoreAlerts(i);let a=new ja(async(R,k)=>{let I=await s.getConnection(R),{records:S,truncated:C}=await ss(I,`SELECT Id, Operation, Status, DurationMilliseconds, LogLength, StartTime, LogUser.Username FROM ApexLog WHERE Status != 'Success' AND StartTime > ${k} ORDER BY StartTime DESC LIMIT ${QR}`,QR);return De(I.limitInfo,"monitor:error-logs apexLog"),{records:S.map(O=>({id:O.Id,errorType:O.Status,message:`${O.Operation} - ${O.Status}`,timestamp:O.StartTime,user:O.LogUser?.Username??void 0,context:O.Operation})),truncated:C}}),d=async(R,k)=>{let I=await s.getConnection(R),S=await I.query(`SELECT COUNT() FROM ApexLog WHERE Status != 'Success' AND StartTime > ${k}`);return De(I.limitInfo,"monitor:refresh apexLogCount"),S.totalSize},c=new Na(async R=>{let k=await s.getConnection(R),{records:I,truncated:S}=await ss(k,`SELECT Id, UsersId, Users.Username, LoginType, SessionType, CreatedDate, SourceIp FROM AuthSession ORDER BY CreatedDate DESC LIMIT ${YR}`,YR);return De(k.limitInfo,"monitor:sessions authSession"),{records:I.map(C=>({sessionId:C.Id,userId:C.UsersId,username:C.Users?.Username??C.UsersId,sessionType:C.SessionType??C.LoginType??"Unknown",loginTime:C.CreatedDate,sourceIp:C.SourceIp??""})),truncated:S}}),l=new $a(async(R,k)=>{let I=await s.getConnection(R),{records:S,truncated:C}=await ss(I,`SELECT Id, Operation, Status, DurationMilliseconds, LogLength, StartTime, LogUser.Username FROM ApexLog ORDER BY StartTime DESC LIMIT ${k}`,k);return De(I.limitInfo,"monitor:apex-insights apexLog"),{records:S.map(O=>({id:O.Id,operation:O.Operation??"Unknown",status:O.Status,durationMs:O.DurationMilliseconds??0,logSize:O.LogLength??0,startTime:O.StartTime,user:O.LogUser?.Username??"Unknown"})),truncated:C}}),u=new Set,p=new La(async R=>{if(u.has(R))return{supported:!1,events:[],truncated:!1};let k=await s.getConnection(R),I;try{I=await ss(k,`SELECT Id, SandboxName, Status, CreatedDate, Description FROM SandboxProcess ORDER BY CreatedDate DESC LIMIT ${ZR}`,ZR)}catch(S){let C=S instanceof Error?S.message:String(S);if(C.includes("SandboxProcess")&&C.includes("not supported"))return u.add(R),{supported:!1,events:[],truncated:!1};throw S}return De(k.limitInfo,"monitor:sandbox-refresh sandboxProcess"),{supported:!0,events:I.records.map(S=>({orgId:R,sandboxName:S.SandboxName??"Unknown",refreshDate:S.CreatedDate,status:XR(S.Status),sourceOrg:S.Description??void 0})),truncated:I.truncated}},R=>s.onSandboxRefreshCompleted?.(R),NA(s.configStore)),g=new Map,h=async(R,k)=>{let I=g.get(R);if(I&&Date.now()-I.fetchedAt<MA)return I.data;let S=await k.request(`/services/data/${Yn}/limits`);return g.set(R,{data:S,fetchedAt:Date.now()}),S},f=async R=>{try{let k=await s.getConnection(R),S=(await h(R,k)).DailyApiRequests;if(!S||!S.Max)return{name:"apiLimits",status:"unknown",score:0,message:"No API limit reported"};let C=Math.round((S.Max-S.Remaining)/S.Max*100);return{name:"apiLimits",status:C>80?"critical":C>60?"warning":"ok",score:100-C,message:`API usage at ${C}%`,percent:C}}catch{return{name:"apiLimits",status:"unknown",score:0,message:"Unable to fetch limits"}}},m=async R=>{try{let k=await s.getConnection(R),S=(await h(R,k)).DataStorageMB;if(!S||!S.Max)return{name:"storage",status:"unknown",score:0,message:"No storage limit reported"};let C=Math.round((S.Max-S.Remaining)/S.Max*100);return{name:"storage",status:C>85?"critical":C>70?"warning":"ok",score:100-C,message:`Storage usage at ${C}%`,percent:C}}catch{return{name:"storage",status:"unknown",score:0,message:"Unable to fetch storage"}}},y=async R=>{let k;try{let C=new Date(Date.now()-jA).toISOString();k=await d(R,C)}catch{return{name:"recentErrors",status:"unknown",score:0,message:"Unable to fetch error logs"}}let I=Math.max(0,100-k*5);return{name:"recentErrors",status:k>10?"critical":k>3?"warning":"ok",score:I,count:k,message:`${k} recent errors`}},b=new _a(async R=>{let k=await s.getConnection(R),I=await Tt(k,`SELECT Id, JobType, Status, NumberOfErrors, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${Xr.monitorJobs}`);return De(k.limitInfo,"monitor:refresh asyncJobs"),I.map(S=>({id:S.Id,jobType:S.JobType??"Batch",status:S.Status,createdBy:S.CreatedById,createdDate:S.CreatedDate,failedRecords:S.NumberOfErrors}))}),v=async R=>{try{await b.fetch(R);let k=b.getJobStats(R),I=Math.max(0,100-k.failed*10);return{name:"activeJobs",status:k.failed>5?"critical":k.failed>0?"warning":"ok",score:I,count:k.failed,outOf:k.total,message:`${k.active} active, ${k.failed} failed of ${k.total} recent jobs`}}catch{return{name:"activeJobs",status:"unknown",score:0,message:"Unable to fetch jobs"}}},w=new Fa([f,m,y,v]);return{trendStorage:e,alertStateStore:t,alertEngine:r,errorLogMonitor:a,userSessionMonitor:c,apexLogAnalyzer:l,sandboxRefreshTracker:p,healthCheck:w,healthSignals:{apiLimits:f,storage:m,recentErrors:y,activeJobs:v},getOrFetchLimits:h,forgetOrg:R=>{g.delete(R)}}}var rv=25e3,nv=20,$A=20,LA=20,FA=500,iv=`SELECT Id, JobType, Status, NumberOfErrors, JobItemsProcessed, TotalJobItems, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${Xr.monitorJobs}`,_A=`SELECT Id, JobType, Status, NumberOfErrors, CreatedDate, CreatedById FROM AsyncApexJob ORDER BY CreatedDate DESC LIMIT ${Xr.monitorJobs}`,UA=new Set([iv,_A]),BA=new Set(["Queued","Preparing","Processing"]),HA=new Set(["BatchApex","Queueable","Future"]),Os=3600*1e3,ov=Os,sv=3;function ru(s){let e=Math.floor(s/60),t=s%60;return e>0?`${e}h${String(t).padStart(2,"0")}m`:`${t}m`}function qA(s,e){return s.status===e.status&&s.batchesProcessed===e.batchesProcessed&&s.totalBatches===e.totalBatches}function WA(s,e,t){let r=new Map;for(let n of e){let o=s?.get(n.id);if(o!==void 0&&qA(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 zA(s,e,t){let r=[],n=[],o=[];for(let a of s){if(!BA.has(a.status)||!HA.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>=Os){n.push({job:a,stillMs:c,done:l,total:u});continue}if(d?.movedWhileWatched===!0&&c!==null&&c<Os)continue;let p=t-Date.parse(a.createdDate);p>=ov&&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=ru(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 ${Os/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<sv)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 ${sv}-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=ru(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 ${ru(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 ${ov/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 ${Os/6e4}m of watching; a job without batch counters never is.`})}return r}var GA=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"]),Ua=class{constructor(e,t){this.deps=e;this.externalBrowser=t??new wr;let r=tv({configStore:e.configStore,log:n=>e.log(n),notify:(n,o)=>ke(e,n,"Alert",o),getConnection:async 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 Pa;healthCalculator=new Ea;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)},FA),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(!GA.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&&UA.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 ${rv}ms bound; skipping ${t}`),!0):!1}async handleRefresh(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(jr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{await new fe(rv).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),Tt(n,iv)]);if(o.status==="rejected")throw o.reason;let a=zR(o.value);De(n.limitInfo,"monitor:refresh limits");let d=[];for(let I of a){let S=this.alertEngine.evaluate(I.name,I.usedPercent,t.orgId);S&&d.push(S)}if(this.alertStateStore.saveAlerts(this.alertEngine.getActiveAlerts()),d.length>0&&this.alertStateStore.saveHistory(d),i.status==="rejected")throw i.reason;let c=i.value;if(De(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(I=>({id:I.Id,jobType:I.JobType??"Unknown",status:I.Status,createdBy:I.CreatedById,createdDate:I.CreatedDate,failedRecords:I.NumberOfErrors,batchesProcessed:I.JobItemsProcessed??null,totalBatches:I.TotalJobItems??null})),p=c.length>=Xr.monitorJobs,g=u.map(({id:I,jobType:S,status:C,createdBy:O,createdDate:P,failedRecords:_})=>({id:I,jobType:S,status:C,createdBy:O,createdDate:P,failedRecords:_})),h=WA(this.jobProgress.get(t.orgId),u,l);this.jobProgress.set(t.orgId,h);let f=zA(u,h,l),m={orgId:t.orgId,limits:a,timestamp:new Date().toISOString()},y=this.trendStorage.recordAndGetTrends(t.orgId,m,ri),[b,v]=await Promise.all([this.fetchOrgInfo(t.orgId,n),this.computeOrgHealth(t.orgId)]);b&&this.deps.sandboxRefreshes?.observe(t.orgId,{organizationId:b.orgId,instanceName:b.instanceName||void 0},"monitor");let w=this.healthCalculator.calculate({limits:a,orgId:t.orgId,trends:y,orgInfo:b}),R=w.overallScore;if(this.pastDeadline(r,"the monitor:data reply"))return;let k=T(this.deps,e,"monitor:data",{limits:a,jobs:g,jobsTruncated:p,healthScore:R,healthReport:w,trends:y,jobInsights:f,orgInfo:b,orgHealthStatus:v,lastUpdated:new Date().toISOString()});this.deps.broker.postToWebview(k),this.deps.log(`[TX] ${k.type} id=${k.id}`)}catch(n){if(this.pastDeadline(r,`the failure "${A(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()=>WR(await t.request("/services/data")),queryOrg:async()=>{let n=this.deps.orgManager.getOrg(e),o=await Tt(t,"SELECT Name, Id, OrganizationType, InstanceName, NamespacePrefix, CreatedDate FROM Organization LIMIT 1");De(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=D(jr,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/${Yn}/limits/recordCount`);De(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,LA),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 Tt(n,`SELECT QualifiedApiName, Label FROM EntityDefinition WHERE QualifiedApiName IN (${d.map(h=>`'${h}'`).join(", ")})`);De(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=D(jr,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 ${nv}`)).records;De(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>=nv});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=D(jr,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);De(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=D(Rh,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=mR(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 "${be(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=D(jr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await this.errorLogMonitor.fetch(r.orgId),i=[...this.errorLogMonitor.getErrorsByType(r.orgId).entries()].map(([d,c])=>({type:d,count:c})),a=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=D(jr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await this.userSessionMonitor.fetch(r.orgId),o=this.userSessionMonitor.getActiveUserCount(r.orgId),i=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=D(jr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{let n=await this.apexLogAnalyzer.fetchAndAnalyze(r.orgId,$A),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 Tt(r,"SELECT Id, InstanceName FROM Organization");De(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: ${A(r)}`)}}async handleSandboxRefresh(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(jr,e,"monitor:error",this.deps);if(!t)return;let r=t;try{await this.checkSandboxIdentity(r.orgId);let n=await this.sandboxRefreshTracker.fetch(r.orgId),o=this.sandboxRefreshTracker.isRefreshInProgress(r.orgId),i=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=D(hl,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=D(hl,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 yt={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 gn(s,e){return Object.assign(new Error(e),{code:s})}function av(s,e,t){let r=li(s);if(r==="refused")return gn(yt.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 gn(yt.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 nu(s){return s.objects.flatMap(e=>e.fieldRules.filter(t=>t.ruleType==="ai_generate").map(t=>`${e.objectApiName}.${t.fieldApiName}`))}function Ba(s,e,t){let r=t(e)??ni.find(d=>d.id===e);if(r==null)return{refusal:gn(yt.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=no.safeParse(r);if(!i.success){let d=i.error.issues[0];return{refusal:gn(yt.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=nu(i.data);return a.length>0?{refusal:gn(yt.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 ou="seed:template:",dv="seedTemplates",$n=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${ou}${e.id}`,e,dv)}load(e){return this.configStore.get(`${ou}${e}`)}list(){let e=this.configStore.getByCategory(dv);return Object.values(e).sort((r,n)=>n.updatedAt.localeCompare(r.updatedAt))}delete(e){return this.configStore.delete(`${ou}${e}`)}};var Ha=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 cv=[{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"]}}}],qa=class{customPersonas=new Map;customCounter=0;getBuiltInPersonas(){return[...cv]}getPersona(e){let t=cv.find(r=>r.id===e);return t||this.customPersonas.get(e)}async createCustomPersona(e,t){let r=VA(e),n=await t(r),o=KA(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())}},lv=Mp(s=>typeof s=="string"&&s.trim().length>0?Number(s):s,Me().finite()),Ln=lv.optional().catch(void 0),su=L().min(1).optional().catch(void 0),iu={faker:V({method:L().transform((s,e)=>{let t=tg(s);return t||(e.addIssue({code:jp.custom,message:`unknown faker method ${s}`}),Dp)}),locale:su}),random_pick:V({values:Se(xp([L(),Me(),Je()]).transform(String)).min(1)}),weighted_pick:V({values:ei(L(),lv).refine(s=>Object.keys(s).length>0)}),range:V({min:Ln,max:Ln,currency:su}),sequence:V({prefix:su,start:Ln,step:Ln,padLength:Ln}),pattern:V({pattern:L().min(1)}),ai_generate:V({prompt:L().min(1)}),relative_date:V({minDaysFromNow:Ln,maxDaysFromNow:Ln})},JA={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 VA(s){let e=Object.keys(iu);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}: ${JA[r]}`),"",`Faker methods: ${eg.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(`
|
|
9
|
-
`)}function XA(s){let e=s.generator;if(typeof e!="string"||!Object.hasOwn(iu,e))return null;let r=iu[e].safeParse(s.params??{});if(!r.success)return null;let n=typeof s.fieldType=="string"?s.fieldType:"string";return e==="ai_generate"&&!Vp(n)?null:{fieldType:n,generator:e,params:r.data,examples:Array.isArray(s.examples)?s.examples.filter(o=>typeof o=="string"):[]}}function KA(s){let e;try{e=Gp(Jp,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=XA(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 Io="SEED_WRITE_DECLINED",uv=6e4;function Hr(s){let e=s?.read.gate.audit;return e===void 0?{}:{details:{deliverability:e,...s?.accepted===!0?{confirmed:"emails"}:{}}}}var fv="the checkpoints of this window are not open to the Seed page",Lt=class extends Error{constructor(t,r,n){super(r);this.code=t;this.refusal=n;this.name="SeedCheckpointStopped"}code;refusal};async function Is(s,e){try{if(!s)throw new Error(fv);return{ask:e,planned:await s.scope(e,{})}}catch(t){throw new Lt(an,ur(t))}}async function As(s,e,t,r,n){let o=await Yi(async()=>{if(!s)throw new Error(fv);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,lo(i))})});if("stop"in o)throw new Lt(o.stop.code,o.stop.message,o.stop.refusal);return o.checkpoint}async function fn(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: `+A(o)),e}}function Ts(s,e){let t=new Set(s);return(r,n)=>t.has(r)&&(n==="insert"||e&&n==="update")}function Ga(s,e){return typeof s.unread=="string"?{firing:[]}:Dr(s,void 0,e)}function YA(s,e,t){return t==="refuse"?{code:yt.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:ww,message:s.gate.stop?.message??"The seed was refused for its emails. Nothing was written."}}var QA={ask:(s,e)=>s.confirmRun(e),unanswered:"goOn"};function ZA(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 pv(s,e,t){if(Zo(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 Wa=1e3;function eT(s){return Array.isArray(s.objectResults)?{...s,objectResults:s.objectResults.map(e=>{let t=e.createdIds.length>Wa||e.errors.length>Wa;return t?{...e,createdIds:e.createdIds.slice(0,Wa),errors:e.errors.slice(0,Wa),truncated:t}:e})}:s}function gv(s){return{query:async e=>s.tooling.query(e),queryMore:async e=>s.tooling.queryMore(e)}}function tT(s){return s.objectResults.flatMap(t=>t.errors)[0]??"The seed wrote no records."}var rT=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"]),za=class{constructor(e){this.deps=e;this.seedTemplateStore=new $n(e.configStore),this.templateManager=new Ha(()=>crypto.randomUUID(),()=>new Date().toISOString(),this.seedTemplateStore),this.personaManager=new qa}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-7YDNUBO5.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 ya({org:n,objects:r,writes:o,readAutomation:c=>i===void 0?new fe(uv).withTimeout("seed automation",()=>d.read(e,c)):typeof i.unread=="string"?Promise.reject(new Error(i.unread)):Promise.resolve(i),readLimits:()=>fr(t),...a?{deliverability:a}:{},...i===void 0?{readDeliverability:()=>Te(this.deps.orgManager.getOrg(e))==="production"?Promise.resolve(Nt):$t(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=D(Kf,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,be(n,t.orgId),sR(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(!rT.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}`),!!D(eh,e,"seed:error",this.deps))try{let{listScenarioPacks:t,nodeScenarioPackFiles:r}=await import("./chunk-5K5VLULK.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=D(th,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-SE4QEZUG.mjs"),{seedObjectAccess:a}=await import("./chunk-FKG7Q3WH.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=D(rh,e,"seed:error",this.deps);if(!t)return;let{compileScenario:r,ScenarioCompileError:n}=await import("./chunk-HEKAZJRH.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=no.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-XUWL6ZPC.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=A(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=D(nh,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-FPKYYFM7.mjs"),{scenarioCasePicklists:o,toolingQueryAll:i}=await import("./chunk-SE4QEZUG.mjs"),{scenarioProjectOf:a}=await import("./chunk-QR3WELJQ.mjs"),d=await n(i(gv(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=D(oh,e,"seed:error",this.deps);if(t)try{let{nodeScenarioPackFiles:r,saveScenarioPack:n}=await import("./chunk-5K5VLULK.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=D(sh,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-FPKYYFM7.mjs"),{nodeAgentTestSpecFiles:c}=await import("./chunk-NTFIRZP6.mjs"),{toolingQueryAll:l}=await import("./chunk-SE4QEZUG.mjs"),{findScenarioPack:u,nodeScenarioPackFiles:p}=await import("./chunk-5K5VLULK.mjs"),{nodeScenarioSidecarFiles:g}=await import("./chunk-XUWL6ZPC.mjs"),{scenarioProjectOf:h,writeRunTestFile:f}=await import("./chunk-QR3WELJQ.mjs"),m=this.workspaceFolders(),y=await f({sidecar:g(),spec:c()},{runId:t.runId,storagePath:n.storagePath,project:await h(m),alias:be(i,o.targetOrgId),choice:t.choice,...t.overwrite!==void 0?{overwrite:t.overwrite}:{},readCatalog:()=>d(l(gv(a))),findPack:(b,v)=>u(p(),m,b,v)});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=D(Qf,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=D(ul,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=D(ul,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=D(Zf,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: ${A(r)}`),"[]"}}:async()=>"[]"}async handleDescribeGlobal(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Xf,e,"seed:error",this.deps);if(!t)return;let r=t,n=st(this.deps);try{let o=await q(r.orgId,this.deps.orgRegistry,this.deps.orgManager),d=(await new fe(n.timeouts.describeGlobal).withTimeout("describe-global",()=>o.describeGlobal())).sobjects.filter(l=>l.createable).filter(l=>!si(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=D(Yf,e,"seed:error",this.deps);if(!t)return;let r=t,n=st(this.deps);try{let o=await q(r.orgId,this.deps.orgRegistry,this.deps.orgManager),i=gt(r.objectApiName),d=await new fe(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:rg(p),objectApiName:r.objectApiName})),l=tR(i,d.recordTypeInfos,i===eo?await ql(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=D(Vf,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,QA,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&&je(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,A(i));let a=pv(i,n,this.deps.log);E(this.deps,"seed:execute","seed:error",e,i,{code:ro(i),retryable:!0,extraPayload:a}),je(this.deps,n,A(i),!0,{extraPayload:a,context:o})}}async clearSeed(e,t,r,n,o=!1){let i=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200,a=e.template.objects.map(ce=>({...ce,batchSize:ce.batchSize??i}));Object.assign(r,Mr(a));let d=await q(e.orgId,this.deps.orgRegistry,this.deps.orgManager),c={...e.template,objects:a},l=c.objects.some(ce=>ce.objectApiName===eo)?rR(c,await ql(d)):{template:c,personObjects:[]};if("refusal"in l)return{refusal:{code:"RECORD_TYPES_MIXED",message:l.refusal}};let u={orgId:e.orgId,template:l.template,personObjects:l.personObjects,locale:await nR(e.locale,d)},p=e.template.objects.reduce((ce,oe)=>ce+oe.recordCount,0),g=[],h=ce=>{g.push(ce),this.deps.log(`[WARN] seed:execute ${t}: ${ce}`)},f=this.deps.orgManager.getOrg(u.orgId),m=be(f,u.orgId),y=l.template.objects.map(ce=>({objectApiName:ce.objectApiName,recordCount:ce.recordCount})),b=this.targetAutomation,v=await new fe(uv).withTimeout("seed automation",()=>b.read(u.orgId,y.map(ce=>ce.objectApiName))).catch(ce=>({unread:A(ce)})),w=oR(l.template,o),R;if("muteAutomation"in e&&e.muteAutomation===!0)try{R=await mt(async()=>Pt(d),v,{...this.muteLeases,writes:w})}catch(ce){if(!kt(ce))throw ce;return K(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",code:ce.code}),{refusal:{code:ce.code,message:ce.message,extraPayload:{},failed:{authored:!0}}}}R&&(u.mute=R);let k=dR(e.fit,p);k&&(u.fit=k);let I=iR(v,R?.plan,w),S=await Yt({read:v,...R?.plan?{plan:R.plan}:{},writes:w,readDeliverability:()=>Te(f)==="production"?Promise.resolve(Nt):$t(d),accepted:!1,target:m,run:"seed",keepsAddresses:!0}),C={read:S,accepted:!1};u.emails=C;let O=S.gate.verdict==="asks",P;if(e.checkpointFirst!==void 0){let ce={module:"seed",orgId:u.orgId,operationId:t,written:y.filter(oe=>oe.recordCount>0).map(oe=>oe.objectApiName),running:I.running??{firing:[]},request:e.checkpointFirst};try{P=await Is(this.beforeRunCheckpoints,ce)}catch(oe){if(!(oe instanceof Lt))throw oe;return K(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",code:oe.code}),{refusal:{code:oe.code,message:oe.message,extraPayload:{},failed:{authored:!0}}}}}let{seedObjectAccess:_,templateTheOrgTakes:J}=await import("./chunk-FKG7Q3WH.mjs"),B=await J(l.template,_(d)),re=qb(rs(this.deps.services),l.template),{describedFieldsOf:H,requiredForAccountKinds:j}=await import("./chunk-J525F5KI.mjs"),N=0,Y=H(async ce=>(N++,d.describe(ce))),Q=await Hb(B,{describeCreateableFields:Y.createable,describeRequiredFields:j(Y,l.personObjects)},re),U={duplicateRules:ho(v),partition:re,slices:Q,slicesRead:N,bulkThreshold:st(this.deps).bulk.threshold,automationRead:dn(v)},G=await Jb(d,B,l.personObjects,be(f,u.orgId),P?.planned,{...cn(S.ofRun),..._y(R?.plan)},U);if(G.check.verdict==="unread"&&h(`the data storage the org has left could not be read (${G.check.unread}): whether the records fit is not known`),G.refusal){let ce=G.refusedFor==="checkpoint",oe=ce?an:G.refusedFor==="apiRequests"?uo:Hl,le=ce?G.checkpointRefusal?.code:void 0;K(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",code:oe,...le!==void 0?{details:{checkpointRefusal:le}}:{}});let Ae=G.check,Z=ce?void 0:aR(Vb(G),B,l.personObjects,I.room,U);return{refusal:{code:oe,message:G.refusal,extraPayload:{...Ae.verdict==="unread"||oe!==Hl?{}:{estimateMB:Number(bs(Ae.estimateMB)),remainingMB:Ae.remainingMB,maxMB:Ae.maxMB,org:be(f,u.orgId)},...le!==void 0?{checkpointRefusal:le}:{},...Z?{fit:Z}:{}},failed:{authored:!0}}}}let pe=await this.readAutomation(u.orgId,d,y.map(ce=>ce.objectApiName),m,w,R?.automation??v,S.gate.deliverability),me=wa(pe,y,m);for(let ce of me.unknown??[])h(ce);if(me.refusal)return K(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",code:Wl}),{refusal:{code:Wl,message:me.refusal,extraPayload:{...me.figures?{...me.figures}:{},...o?{scenario:!0}:{}},failed:{authored:!0}}};let ne=this.deps.infraServices?.productionGuard;if(!ne)return K(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",code:Re.code}),{refusal:{code:Re.code,message:Re.message,failed:{authored:!1}}};let he={orgId:u.orgId,orgTier:Te(f),operation:"insert",objectName:"SeedData",recordCount:p,module:"seed"},{check:qe,decision:Ie}=await Ye(ne,he);if((Ie==="refused"||Ie==="declined")&&K(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",guard:Ie}),Ie==="refused")throw Qr(qe.blockedReason??qe.impactSummary);if(Ie==="declined")return{refusal:{code:St.declined,message:"Operation cancelled by user (confirmation declined).",failed:{authored:!1}}};if(G.check.verdict==="unread"||G.api.verdict==="near"||P!==void 0||O){let ce=await n.ask(ne,{stage:"write",module:"seed",org:m,orgTier:Te(f),objects:l.template.objects.map(oe=>({objectApiName:oe.objectApiName,rows:oe.recordCount})).sort((oe,le)=>le.rows-oe.rows),total:p,storage:ln(G.check),counted:!0,...po(G.api),...P?{checkpoint:P.planned}:{},...S.gate.confirmation});if(ce==="confirmed"&&O&&(C.accepted=!0),ce==="declined")return K(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",guard:Ie,code:Io,...Hr(C)}),{refusal:{code:Io,message:"The seed was cancelled before it wrote anything. Nothing was written.",failed:{authored:!0}}};if(ce==="unavailable"&&O){let oe=YA(S,m,n.unanswered);return K(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",guard:Ie,code:oe.code,...Hr(C)}),{refusal:{...oe,failed:{authored:!0}}}}if(ce==="unavailable"&&P!==void 0)return K(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",guard:Ie,code:yt.unanswered}),{refusal:{code:yt.unanswered,message:`The seed needed an answer before it wrote \u2014 the checkpoint it takes first reads whole tables of ${m} \u2014 and there was no one to ask. Nothing was written.`,failed:{authored:!0}}};if(ce==="unavailable"&&n.unanswered==="refuse")return K(this.deps,{action:"seed_execute",module:"seed",operationId:t,orgId:u.orgId,outcome:"stopped",guard:Ie,code:yt.unanswered}),{refusal:{code:yt.unanswered,message:`The seed needed an answer before it wrote \u2014 ${ZA(G,m)} \u2014 and no Approval step before it approved the run: put one before it. Nothing was written.`,failed:{authored:!0}}};ce==="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:d,run:u,plannedRecords:p,guardDecision:Ie,automation:pe,orgName:m,warnings:g,...P?{checkpoint:P}:{}}}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}}async seedForPipeline(e,t){let r=this.deps.orgManager.getOrg(e.orgId);if(!r)throw gn(yt.orgUnknown,`The org the seed writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was written.`);let n=av(Te(r),e.answer,be(r,e.orgId));if(n)throw n;let o=Ba(e.orgId,e.templateId,l=>this.seedTemplateStore.load(l));if("refusal"in o)throw o.refusal;let i=An("seed:pipeline",crypto.randomUUID(),"seed:execute"),a=i.id,d={module:"seed",operation:i.type},c={ask:()=>Promise.resolve(e.answer.approved?"confirmed":"unavailable"),unanswered:"refuse"};return _i(e.answer,async()=>{let l=await this.clearSeed(o.asked,a,d,c);if("refusal"in l)throw gn(l.refusal.code,l.refusal.message);if(t?.aborted)throw K(this.deps,{action:"seed_execute",module:"seed",operationId:a,orgId:e.orgId,outcome:"stopped",guard:l.guardDecision,code:ft}),new jt("The seed was cancelled before it wrote anything. Nothing was written.");let u=cR(l.automation,l.orgName);for(let b of u)this.deps.log(`[INFO] seed:execute ${a}: ${b}`);let p,g=`Pipeline seed of ${o.asked.template.name}`,{abortController:h,execution:f}=this.beginSeed(i,l,a,d,g,{pipeline:e.pipeline,ended:b=>{p=b}});this.registry?.register(a,"seed",g,f,h);let m=()=>{this.registry?this.registry.abort(a):h.abort()};t?.addEventListener("abort",m,{once:!0});try{await f}finally{t?.removeEventListener("abort",m)}let y=p;if(y===void 0)throw new Error("The seed ended without a result.");if("error"in y)throw y.error instanceof Error?y.error:new Error(A(y.error));return{operationId:a,runId:y.result.operationId,result:y.result,automation:u,warnings:l.warnings}})}async executeSeed(e,t,r,n,o,i,a,d,c,l){let u=st(this.deps),p=new Date().toISOString(),g,h=!1,f={},m=r.template.name,y={origin:"generator",...typeof m=="string"?{label:m}:{}};try{let b=ar(this.deps),v=new na({retryConfig:u.retry,signal:o.signal,onRetry:(se,we,xe)=>{this.deps.log(`[RETRY] seed insert attempt=${se} code=${we.originalError.statusCode} delay=${xe}ms`)}}),w=this.deps,R=crypto.randomUUID(),k=this.runCreations?.recorder({runId:R,targetOrgId:r.orgId,startedAt:p,...d?{pipeline:d.pipeline}:{}});hr(k,()=>t.identity(),`seed:execute ${n}`);let I={base:0,total:0},S=(se,we,xe)=>{let Xe=I.base+se,Ue=Math.max(I.total,Xe,we,1),it=Math.round(Xe/Ue*100);Le(w,n,it,Xe,Ue,xe),this.liveTracker?.updateProgress(n,it,Xe,Ue,xe)},C=Sb({conn:t,bulkThreshold:u.bulk.threshold,bulkManager:b,retry:v,signal:o.signal,label:`seed:execute ${n}`,log:se=>this.deps.log(se),onProgress:S,...k?{calls:{sending:(se,we,xe)=>k.sending(se,we,xe),answered:(se,we)=>k.answered(se,we)}}:{}}),O=async(se,we,xe,Xe)=>{xe.length>0&&(h=!0);let Ue=await C(se,we,xe,Xe);return k?.note(we,Ue.successIds),Ue},P=se=>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: ${A(se)}`),{SeedValidator:_}=await import("./chunk-EMNC6YI4.mjs"),{DataPlanBuilder:J}=await import("./chunk-KBJ5VERV.mjs"),{FieldMapper:B}=await import("./chunk-2NBYT7GR.mjs"),{ReferenceLinker:re}=await import("./chunk-CEX3NEZL.mjs"),{AIDataGenerator:H}=await import("./chunk-MILU7WFN.mjs"),{FakerFallback:j}=await import("./chunk-MYW5QNGI.mjs"),{readExistingParentIds:N,readPresentParentIds:Y}=await import("./chunk-IWDREM66.mjs"),{seedObjectAccess:Q}=await import("./chunk-FKG7Q3WH.mjs"),{describedFieldsOf:U,requiredForAccountKinds:G}=await import("./chunk-J525F5KI.mjs"),{seedTargetOf:pe}=await import("./chunk-DBB3EMIN.mjs"),me=c?(await import("./chunk-OHWNPXWW.mjs")).seedKnowledge:void 0,ne=new H(this.buildSeedCallAI()),he=new j(r.locale),qe=new B({aiGenerator:ne,fakerFallback:he}),Ie=new re,ce=new _,oe=new J,{SeedGrappeAdapter:le}=await import("./chunk-PTTHSSQO.mjs"),Ae=rs(this.deps.services),Z=U(se=>t.describe(se)),ve={validator:ce,describeCreateableFields:Z.createable,describeVisibleFields:Z.visible,describeComputedFields:Z.computed,describePicklistValues:Z.picklistValues,describeFieldLengths:Z.lengths,describeRequiredFields:G(Z,r.personObjects),objectAccess:Q(t),readExistingParentIds:(se,we,xe)=>N(t,se,we,xe),readPresentParentIds:(se,we)=>Y(t,se,we),describeKeyPrefix:Z.keyPrefix,...pe(t),planBuilder:oe,fieldMapper:qe,referenceLinker:Ie,insert:O,generateId:()=>crypto.randomUUID(),now:()=>new Date().toISOString(),services:this.deps.services,grappeAdapter:new le(()=>crypto.randomUUID(),Ae?.grappeSize),grappeConfig:Ae,onGrappeEvent:se=>Ri(this.deps,se),onProgress:se=>{I.base=se.processedRecords,I.total=se.totalRecords,S(0,se.totalRecords,`Insert ${se.objectApiName}`)},signal:o.signal,...c&&me?{onRowIds:(se,we)=>{se==="Case"&&Object.assign(f,we)},knowledge:me({org:t,plan:{publish:!0,links:c.compiled.closedCaseArticles},...k?{journal:k}:{},signal:o.signal})}:{}};if(!this.deps.services)throw new Error("SeedOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let x=this.deps.services.seedOrchestrator(ve),M=r.template;Le(this.deps,n,0,0,1,"Validating template and building plan");let F;this.runningRuns.add(R);let W=r.mute,ae=W?.muted;try{l&&(g=await As(this.beforeRunCheckpoints,l,R,o.signal,this.checkpointProgress(n)),k?.checkpoint?.(g));let se=W?.prepared?await W.prepared.acquire(R):void 0;se&&(ae=se.outcome);let we=se&&r.emails?r.emails.read.afterLease(se.outcome,r.emails.accepted):void 0;if(se&&we)throw ae=await se.release(),new Lt(we.code,we.message);F=await x.execute(M,r.orgId,R).finally(async()=>{se&&(ae=await se.release())}),ae&&(F={...F,mutedAutomation:ae});let xe=await fn(this.beforeRunCheckpoints,g,h,this.deps.log,`seed:execute ${n}`);g=void 0,xe&&(F={...F,checkpoint:xe})}catch(se){throw await k?.end({status:"failure",finishedAt:new Date().toISOString(),objectResults:[]}).catch(P),this.runningRuns.delete(R),se}await k?.end({finishedAt:new Date().toISOString(),status:F.status,...F.cancelled?{cancelled:!0}:{},objectResults:F.objectResults}).catch(P),c&&(F={...F,scenario:await this.keepScenario(F,c,f)}),this.runningRuns.delete(R),F.cancelled||Le(this.deps,n,100,1,1,"Seed complete");let z=F.totalRecordsCreated;this.deps.infraServices?.performanceTracker?.update(n,z,1),this.deps.infraServices?.performanceTracker?.complete(n),F.cancelled?(this.registry?.abort(n),ge(this.deps,n,{aborted:!0,totalRecords:z}),this.liveTracker?.cancel(n)):(ge(this.deps,n,{status:F.status,totalRecords:z}),F.status==="failure"?this.liveTracker?.fail(n,tT(F)):F.status==="partial"?this.liveTracker?.partial(n):this.liveTracker?.complete(n));let ue=F.objectResults.some(se=>se.recordsCreated+se.recordsFailed>0),$e=F.cancelled===!0?ue?"cancelled":"stopped":F.status;K(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:$e,...$e==="stopped"?{code:et}:{},guard:a,objects:F.objectResults.map(se=>({...lt(se.objectApiName),created:se.recordsCreated,failed:se.recordsFailed})),source:y,...F.mutedAutomation?{muted:ot(F.mutedAutomation)}:{},...F.checkpoint?.state==="taken"?{checkpointId:F.checkpoint.checkpointId}:{},...r.fit?{fit:r.fit}:{},...Hr(r.emails)});let Ne=T(this.deps,e,"seed:execute:response",eT(F));if(this.deps.broker.postToWebview(Ne),this.deps.log(`[TX] ${Ne.type} id=${Ne.id}`),d?.ended({result:F}),F.status==="failure"&&!F.cancelled)return{status:"failure"}}catch(b){this.deps.infraServices?.performanceTracker?.complete(n);let v=await fn(this.beforeRunCheckpoints,g,h,this.deps.log,`seed:execute ${n}`),w=v?.state==="deleted"?`${A(b)} ${Fr}`:void 0,R=w!==void 0?new Error(w):b;if(b instanceof Lt){if(b.code===et)this.registry?.abort(n),ge(this.deps,n,{aborted:!0,totalRecords:0}),this.liveTracker?.cancel(n);else{let C=A(R);this.liveTracker?.fail(n,C),je(this.deps,n,C,!1,{context:i,authored:!0})}let S=b.refusal?.code;return K(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:"stopped",guard:a,code:b.code,...S!==void 0||r.emails?.read.gate.audit!==void 0?{details:{...Hr(r.emails).details,...S!==void 0?{checkpointRefusal:S}:{}}}:{}}),E(this.deps,"seed:execute","seed:error",e,R,{code:b.code,retryable:!1,...S!==void 0?{extraPayload:{checkpointRefusal:S}}:{}}),d?.ended({error:b}),b.code===et?void 0:{status:"failure"}}this.liveTracker?.fail(n,A(R));let k=kt(b)?b:void 0;K(this.deps,{action:"seed_execute",module:"seed",operationId:n,orgId:r.orgId,outcome:k?"stopped":"failure",guard:a,source:y,...k?{code:k.code}:{},...v?.state==="taken"?{checkpointId:v.checkpointId}:{},...r.fit?{fit:r.fit}:{},...Hr(r.emails)});let I=pv(b,n,this.deps.log);return E(this.deps,"seed:execute","seed:error",e,b,{...k?{code:k.code}:{},retryable:!0,extraPayload:{...I,...v?{checkpoint:v}:{}}}),je(this.deps,n,A(R),!0,{extraPayload:I,context:i}),d?.ended({error:R}),{status:"failure"}}}};function nT(s){if(s.length>512)throw new Error(`SOQL WHERE clause too long (${s.length} > 512 chars)`);return Ug(s)}var Es=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 ${Fe(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 ${Fe(t)}${this.whereOf(r,n)}`}whereOf(e,t){let r=e?nT(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 Ps=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&&(au(u)?a:i).get(u.to)?.add(u.from);let d=fi(i).filter(u=>u.length>1);if(d.length>0)throw new Error(sT(d,n.filter(u=>!au(u))));let c=new Map(e.map(u=>[u,new Set([...i.get(u)??[],...a.get(u)??[]])])),l=fi(c).some(u=>u.length>1)?i:c;return oT(fi(o),o,e).flatMap(u=>u.length>1?_g(u,l):u)}lookupsOf(e,t){return t.filter(r=>r.to===e&&!au(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===Gt&&a.name==="ActivityId")&&a.type==="reference"&&a.referenceTo){let d=Go(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 il(r))n.push({from:o.sourceObject,to:o.targetObject,fieldApiName:o.relationshipName,relationshipType:"lookup",required:!0});return n}};function oT(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 au(s){return il(new Set([s.from,s.to])).some(e=>e.sourceObject===s.from&&e.targetObject===s.to&&e.relationshipName===s.fieldApiName)}function sT(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(", ")}. ${iT(t)} must be set when the record is created, so no object of the cycle can be written first.`}function iT(s){return s.length<=1?s.join(""):`${s.slice(0,-1).join(", ")} and ${s[s.length-1]}`}function du(s){return s==="insert"||s==="upsert"}function Ja(s,e){return{sending:(t,r,n)=>{du(r)&&s.sending(t,n,r==="upsert"?{upsert:!0}:void 0)},opened:(t,r,n,o)=>{du(r)&&s.sending(t,n,{job:o,...r==="upsert"?{upsert:!0}:{}})},answered:(t,r,n)=>{if(!du(r))return;let o=ha(r,n);s.answered(t,o),e?.(o.length)}}}var aT=new Set(["seed:clone:describe-source","seed:clone:preview","seed:clone:execute"]),dT=5,cT=10,lT=-1,hv="Operation blocked by Production Guard: ",qr={confirmationDeclined:"PRODUCTION_CONFIRMATION_DECLINED",guardBlocked:"PRODUCTION_GUARD_BLOCKED",failed:"CLONE_FAILED",emailsExceeded:"CLONE_EMAILS_EXCEEDED",apiBudgetExceeded:"API_BUDGET_EXCEEDED",storageExceeded:"CLONE_STORAGE_EXCEEDED"},uT=3;function pT(s,e){let t=s.filter(n=>n.recordCount>0).map(n=>({objectApiName:n.objectApiName,rows:n.recordCount,bytes:jn(n.objectApiName,{rows:n.recordCount})})).sort((n,o)=>o.bytes-n.bytes),r=gr({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,uT).map(({objectApiName:n,rows:o,bytes:i})=>({objectApiName:n,rows:o,mb:i/(1024*1024)}))}}function mv(s){let e=s<10?100:10;return String(s<=0?0:Math.ceil(s*e-1e-9)/e)}function gT(s,e){let t=s.heaviest.map(r=>`${r.objectApiName} (${r.rows} records, ${mv(r.mb)} MB)`).join(", ");return`The clone was refused before it wrote anything: its records take about ${mv(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 fT=6e4,hT={neutralized:!1,fields:[],values:0},mT="PREVIEWED_FOR_OTHER_ORGS",yT="NOT_PREVIEWED",wT="PREVIEW_NOT_HELD",bT=50,Xa=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-7YDNUBO5.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 ya({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:()=>fr(t),...i?{deliverability:i}:{}});return wa(d,a,n)}readTargetAutomation(e,t){let r=this.targetAutomation;return new fe(fT).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: ${A(n)}`),!1}finally{this.runningRuns.delete(t)}}stoppedForCheckpoint(e,t,r,n,o){let{operationId:i}=t;if(r.code===et){K(this.deps,{...t,outcome:"stopped",source:void 0,code:et}),this.registry?.abort(i),ge(this.deps,i,{aborted:!0,totalInserted:0,totalFailed:0}),this.liveTracker?.cancel(i);let c={status:"partial",objectResults:[],totalSourceRecords:0,totalInserted:0,totalFailed:0,durationMs:o,cancelled:!0};this.deps.broker.postToWebview(T(this.deps,e,"seed:clone:execute:response",c));return}let a=r.refusal?.code,d=a!==void 0?{checkpointRefusal:a}:{};K(this.deps,{...t,outcome:"stopped",source:void 0,code:r.code,...a!==void 0?{details:d}:{}}),je(this.deps,i,r.message,!1,{context:n,authored:!0,extraPayload:{code:r.code,...d}}),this.liveTracker?.fail(i,r.message)}async handle(e){if(!aT.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=D(ih,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();De(r.limitInfo,"seed:clone:describe-source");let o=n.sobjects.filter(a=>a.createable&&a.queryable).filter(a=>!si(a.name)).map(a=>({apiName:a.name,label:a.label,recordCount:lT})),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=D(pl,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 Es({log:this.deps.log}),i=new Ps,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[R,k]=await Promise.all([Va("target",w.objectApiName,()=>n.describe(w.objectApiName)),Va("source",w.objectApiName,()=>o.describe(r,w.objectApiName))]);De(n.limitInfo,`seed:clone:preview describe ${w.objectApiName} in the target`),De(r.limitInfo,`seed:clone:preview describe ${w.objectApiName}`),c.set(w.objectApiName,R),l.set(w.objectApiName,k);let I=Hg(w.objectApiName,wv(w.objectApiName,c.get(w.objectApiName),l.get(w.objectApiName)),d),[S,C,O]=await Promise.all([o.countRecords(r,w.objectApiName,w.whereClause,I),o.fetchSample(r,w.objectApiName,dT,w.whereClause,I),I.length>0?o.countRecords(r,w.objectApiName,w.whereClause):void 0]),P=O===void 0?0:O-S;u.push({objectApiName:w.objectApiName,recordCount:S,...P>0?{leftToThePlatform:P}:{},sampleRecords:C.map(_=>PT(_,cT))})}let p=i.buildEdgesFromDescribe(a,bv(c,l)),g=i.resolveInsertOrder(a,p),h=u.map(w=>({...w,relationships:i.lookupsOf(w.objectApiName,p)})),f=kT(i.lookupsFilledAfter(g,p),g),m=OT(g,l,c),y=IT(g,c,l),b={objects:h,insertOrder:g,...f.length>0?{filledAfterInsert:f}:{},...m.length>0?{sourceOnlyLookups:m}:{},...y.length>0?{targetOnlyRequiredLookups:y}:{}},v=T(this.deps,e,"seed:clone:preview:response",b);this.deps.broker.postToWebview(v),this.deps.log(`[TX] ${v.type} id=${v.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 Ka?r:void 0;E(this.deps,"seed:clone:preview","seed:clone:error",e,r,{...n?{code:vT,retryable:!1,extraPayload:{objectApiName:n.objectApiName,org:be(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<=bT)break;this.previewedOrgs.delete(o)}}refusedAgainstItsPreview(e){if(e.previewId===void 0)return{code:yT,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:wT,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:mT,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=D(pl,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,...Mr(t.objects.map(w=>({objectApiName:w.objectApiName})))},a=new AbortController,d=()=>{},c=new Promise((w,R)=>{d=k=>k===void 0?w():R(k)});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),b=Db(t.keepContactPoints===!0?{keepContactPoints:!0}:{}),v=()=>b?.report()??hT;try{let w=this.deps.infraServices?.productionGuard;if(!w){K(this.deps,{...l,outcome:"stopped",source:void 0,code:Re.code}),je(this.deps,n,Re.message,!1,{context:i,extraPayload:{code:Re.code}}),d(new Error(Re.message));return}let R=this.deps.orgManager.getOrg(t.targetOrgId),k={orgId:t.targetOrgId,orgTier:Te(R),operation:t.upsert?"upsert":"insert",objectName:t.objects.map($=>$.objectApiName).join(", ")||"CloneData",recordCount:"unknown",module:"clone"},{check:I,decision:S}=await Ye(w,k);if(l.guard=S,(S==="refused"||S==="declined")&&K(this.deps,{...l,outcome:"stopped",source:void 0}),S==="refused")throw new Error(`${hv}${I.blockedReason??I.impactSummary}`);if(S==="declined"){let $="Operation cancelled by user (confirmation declined).";je(this.deps,n,$,!1,{context:i,extraPayload:{code:qr.confirmationDeclined}}),d(new Error($));return}let C=await q(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),O=await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),P=be(R,t.targetOrgId),_=this.previewedOrgs.get(t.previewId??""),J=_?.recordCounts,B=t.objects.map($=>({objectApiName:$.objectApiName,recordCount:J?.get($.objectApiName)??0})),re=B.filter($=>$.recordCount>0).map($=>$.objectApiName),H=($,X,ie)=>{let Oe=ie!==void 0?{checkpointRefusal:ie}:{};K(this.deps,{...l,outcome:"stopped",source:void 0,code:$,...ie!==void 0?{details:Oe}:{}}),je(this.deps,n,X,!1,{context:i,authored:!0,extraPayload:{code:$,...Oe}}),d(new Error(X))},j,N=re.length>0?await this.readTargetAutomation(t.targetOrgId,re).catch($=>({unread:A($)})):{unread:"the clone sends no record"},Y=re.length>0?await Yt({read:N,writes:Ts(re,!0),readDeliverability:()=>Te(R)==="production"?Promise.resolve(Nt):$t(O),accepted:!1,target:P,run:"clone",keepsAddresses:t.keepContactPoints===!0}):void 0,Q=Y?.gate.verdict==="asks";if(t.checkpointFirst!==void 0){try{j=await Is(this.beforeRunCheckpoints,{module:"seed",orgId:t.targetOrgId,operationId:n,written:re,running:Ga(N,Ts(re,!0)),request:t.checkpointFirst})}catch(X){if(!(X instanceof Lt))throw X;H(X.code,X.message);return}let $=Ki(j.planned);if($){H($.code,$.message,$.refusal.code);return}}let U=await this.emailGate(t.targetOrgId,O,B,P,N,Y?.gate.deliverability);for(let $ of U?.unknown??[])this.deps.log(`[WARN] seed:clone:execute ${n}: ${$}`);if(U?.refusal&&U.figures){let $=RT(U.figures);K(this.deps,{...l,outcome:"stopped",source:void 0,code:qr.emailsExceeded}),je(this.deps,n,$,!1,{context:i,authored:!0,extraPayload:{code:qr.emailsExceeded,...U.figures}}),d(new Error($));return}let G=await pr(O).catch($=>({unread:A($)})),pe="unread"in G?await Qt(O).catch($=>({unread:A($)})):G.dailyApiRequests,me=t.upsert?void 0:pT(B,G);if(me){let $=gT(me,P);K(this.deps,{...l,outcome:"stopped",source:void 0,code:qr.storageExceeded}),je(this.deps,n,$,!1,{context:i,authored:!0,extraPayload:{code:qr.storageExceeded,org:P,...me}}),d(new Error($));return}let ne=sn({run:Gb(B.map($=>({objectApiName:$.objectApiName,rows:$.recordCount})),{threshold:st(this.deps).bulk.threshold,perCall:this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200),duplicateRules:ho(N),..._?{secondPass:_.secondPass}:{},automationRead:re.length>0?dn(N):0}),...go(j?.planned),...cn(Y?.ofRun)},pe);ne.verdict==="unread"&&this.deps.log(`[WARN] seed:clone:execute ${n}: the daily API requests the target has left could not be read (${ne.unread})`);let he=Xi(ne,P);if(he){K(this.deps,{...l,outcome:"stopped",source:void 0,code:qr.apiBudgetExceeded}),je(this.deps,n,he,!1,{context:i,authored:!0,extraPayload:{code:qr.apiBudgetExceeded}}),d(new Error(he));return}let qe=!1;if(j||Q){let $=B.filter(ie=>ie.recordCount>0).map(ie=>({objectApiName:ie.objectApiName,rows:ie.recordCount})).sort((ie,Oe)=>Oe.rows-ie.rows),X=await w.confirmRun({stage:"write",module:"seed",org:P,orgTier:Te(R),objects:$,total:$.reduce((ie,Oe)=>ie+Oe.rows,0),storage:ln(gr({storageBytes:$.reduce((ie,Oe)=>ie+jn(Oe.objectApiName,{rows:Oe.rows}),0)},G)),counted:!0,...po(ne),...j?{checkpoint:j.planned}:{},...Y?.gate.confirmation});if(X!=="confirmed"){let ie=Y?.gate.stop;X!=="declined"&&!j&&ie?H(ie.code,ie.message):H(X==="declined"?Io:yt.unanswered,X==="declined"?"The clone was cancelled before it wrote anything. Nothing was written.":`The clone needed an answer before it wrote \u2014 the checkpoint it takes first reads whole tables of ${P} \u2014 and there was no one to ask. Nothing was written.`);return}qe=Q}if(l.details=Hr(Y?{read:Y,accepted:qe}: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)`),j)try{h=await As(this.beforeRunCheckpoints,j,n,a.signal,($,X,ie,Oe)=>{Le(this.deps,n,$,X,ie,Oe),this.liveTracker?.updateProgress(n,$,X,ie,Oe)})}catch($){if(!($ instanceof Lt))throw $;this.stoppedForCheckpoint(e,l,$,i,Date.now()-o),d($.code===et?void 0:$);return}u=!0;let Ie=st(this.deps),ce=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200;i.batchSize=ce;let oe=new Map,le={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),hr(p,()=>O.identity(),`seed:clone:execute ${n}`),p&&this.runningRuns.add(n);let Ae=new un({...p?{calls:Ja(p,$=>{g+=$})}:{},keyPrefixOf:$=>oe.get($)?.keyPrefix,connection:O,bulkExecutor:new en(Ie.bulk.threshold),bulkManager:ar(this.deps),retryConfig:Ie.retry,signal:a.signal,onProgress:($,X,ie)=>{Le(this.deps,n,X>0?Math.round($/X*100):0,$,X,ie),this.liveTracker?.updateProgress(n,Math.round((le.objects+$/Math.max(X,1))/le.of*100),le.records+$,0,ie)},log:$=>this.deps.log($)}),Z=new Es({log:this.deps.log}),ve=new Ps,x=t.objects.map($=>$.objectApiName),M=new Set(x),F=new Map,W=new Map,ae=new Map;for(let $ of x){let[X,ie]=await Promise.all([Va("target",$,()=>O.describe($)),Va("source",$,()=>Z.describe(C,$))]);De(O.limitInfo,`seed:clone:execute describe ${$}`),De(C.limitInfo,`seed:clone:execute describe ${$} in the source`),F.set($,X),W.set($,ie),ae.set($,mr(X).fields??[]),oe.set($,{keyPrefix:X.keyPrefix??null,recordTypes:pf(X.recordTypeInfos)})}let z=ve.buildEdgesFromDescribe(x,bv(F,W)),ue=ve.resolveInsertOrder(x,z),$e=ve.lookupsFilledAfter(ue,z);le.of=Math.max(ue.length,1);let Ne=new Map(t.objects.map($=>[$.objectApiName,$])),se=new Map,we=new Map,xe=new Map,Xe=[],Ue=new Bg,it=0,Be=!1,Uo=new Map,rr=[],Bo=M.has(mi),Sn=$=>Tt(O,$),Jn=new Map,Or=new Map,Xs=Cn(cr($=>Tt(C,$)),async $=>W.get($)??await Z.describe(C,$)),Ht=new Map,Ks=async($,X)=>{if(X.length===0)return;let ie=await Xs($);for(let Oe of ie){let ye=!1;for(let ee of X)Oe in ee&&(ye||=ee[Oe]!==null&&ee[Oe]!==void 0,delete ee[Oe]);ye&&Ht.set($,(Ht.get($)??new Set).add(Oe))}},Ir=async($,X)=>{let ie=(F.get($)?.fields??[]).filter(ee=>ee.type==="reference"),Oe=await Ww({lookups:ie,rows:X,known:Jn,query:Sn});if(Oe.size===0)return;let ye=Or.get($)??new Map;for(let ee of X)for(let{name:te}of ie){let Ee=ee[te];typeof Ee!="string"||!Oe.has(Ee)||(delete ee[te],ye.set(te,(ye.get(te)??0)+1))}ye.size!==0&&(Or.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(([ee,te])=>`${ee} on ${te}`).join(", ")))},Ho=async($,X)=>{await Ks($,X),await Ir($,X),b&&xb(b,$,ae.get($)??[],X,y?t.externalIdField:void 0),X.length>0&&(f=!0);try{return{outcomes:t.upsert&&t.externalIdField?await Ae.upsert($,t.externalIdField,X,ce):await Ae.insert($,X,ce),stopped:!1}}catch(ie){if(!(ie instanceof So))throw ie;return{outcomes:ie.written,stopped:!0}}},bt=($,X,ie,Oe)=>{$.forEach((ye,ee)=>{let te=typeof X[ee]?.Id=="string"?X[ee].Id:"";if(ye.success){ie.insertedCount++,te&&ye.id&&(se.set(te,ye.id),ie.idMappings.push({sourceId:te,targetId:ye.id}));let Ee=ye.id;if(Ee)for(let{fieldName:Pe,sourceRefId:at}of Oe[ee]??[])Xe.push({objectApiName:ie.objectApiName,newId:Ee,sourceId:te||void 0,fieldName:Pe,sourceRefId:at})}else ye.existingId?(ie.linkedCount=(ie.linkedCount??0)+1,te&&(se.set(te,ye.existingId),ie.idMappings.push({sourceId:te,targetId:ye.existingId}))):(ie.failedCount++,ie.errors.push({sourceId:te,message:ye.errors[0]??"Unknown insert error"}))})},kn=async $=>{let X=new Map((m.find(te=>te.objectApiName===Gt)?.idMappings??[]).map(te=>[te.sourceId,te.targetId])),ie=new Map;for(let[te,Ee]of Uo){let Pe=X.get(te);Pe&&ie.set(Ee,Pe)}let Oe=$.map(te=>String(te.Id)).filter(te=>ie.has(te));if(Oe.length===0)return new Map;let ye;try{ye=await Wg(Sn,[...new Set(Oe.map(te=>ie.get(te)??""))])}catch(te){return this.deps.log(`[seed:clone] tasks written with the clone's emails not looked up, written as read: ${A(te)}`),new Map}let ee=new Map;for(let te of Oe){let Ee=ye.get(ie.get(te)??"");Ee&&ee.set(te,Ee)}return ee},qo=async($,X,ie)=>{if(Jg[$]===void 0)return new Map;let Oe;try{Oe=await Vg(Sn,$,ie)}catch(ee){return this.deps.log(`[seed:clone] ${$}: the relations the target holds not looked up, written as read: ${A(ee)}`),new Map}let ye=new Map;for(let[ee,te]of Oe){let Ee=X[ee]?.Id;typeof Ee=="string"&&ye.set(Ee,te)}return ye},Vn=async($,X)=>{if(we.size===0)return new Map;let ie=F.get(ir),Oe=[...new Set(X.flatMap(Pe=>Object.keys(Pe)))].filter(Pe=>vv(ie,Pe)),ye;try{ye=await Gg(Sn,X.map((Pe,at)=>({OpportunityId:Pe.OpportunityId,[ts]:Pe[ts],IsPrimary:$[at]?.IsPrimary})),Pe=>we.get(Pe),Oe)}catch(Pe){return this.deps.log(`[seed:clone] ${ir}: 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: ${A(Pe)}`),new Map}let{found:ee,alike:te}=ye;if(te.length>0){this.deps.log(`[seed:clone] ${ir}: ${zg(te.length)}`);for(let Pe of te)we.delete(String(X[Pe]?.OpportunityId))}let Ee=new Map;for(let[Pe,at]of ee){let Ge=$[Pe]?.Id;typeof Ge=="string"&&(Ee.set(Ge,String(at.Id)),xe.set(Ge,at),we.delete(String(X[Pe]?.OpportunityId)))}return Ee},Bc=async($,X)=>{let ie=F.get(ir),Oe=[];if($.forEach(([te,Ee],Pe)=>{let at=xe.get(String(te.Id))??{},Ge=Object.entries(X[Pe]??{}).filter(([Wt,At])=>vv(ie,Wt)&&At!==null&&At!==void 0&&String(at[Wt]??"")!==String(At));Ge.length>0&&Oe.push({Id:Ee,...Object.fromEntries(Ge)})}),Oe.length===0||Be||a.signal.aborted)return;let ye;try{ye=await Ae.update(ir,Oe,ce)}catch(te){if(!(te instanceof So))throw te;Be=!0,ye=te.written}let ee=Oe.flatMap((te,Ee)=>ye[Ee]?.success?[]:[`${te.Id}: ${ye[Ee]?.errors[0]??"not updated"}`]);ee.length>0&&this.deps.log(`[seed:clone] ${ir}: linked, and left as the platform wrote them, without the fields of the source's roles: ${ee.slice(0,3).join(" | ")}`)},Ys=async()=>{Bo=!1;let $=rr.splice(0,rr.length),X=m.find(te=>te.objectApiName===Gt);if($.length===0||!X||Be)return;if(a.signal.aborted){Be=!0;return}let ie=$.map(te=>Sv(Gt,te,F.get(Gt),M,se)),Oe=Rv(Gt,$,ie,$e,se),{outcomes:ye,stopped:ee}=await Ho(Gt,ie);bt(ye,$,X,Oe),le.records+=$.length,ee&&(Be=!0)};for(let $=0;$<ue.length;$++){if(a.signal.aborted){Be=!0;break}let X=ue[$],ie=Ne.get(X);Le(this.deps,n,Math.round($/ue.length*100),$,ue.length,`Cloning ${X}`),le.objects=$,this.liveTracker?.updateProgress(n,Math.round($/ue.length*100),le.records,0,`Cloning ${X}`);let Oe;try{Oe=await Z.fetchRecords(C,X,ie.whereClause)}catch(We){it++,m.push({objectApiName:X,sourceCount:0,insertedCount:0,failedCount:0,idMappings:[],errors:[{sourceId:"",message:A(We)}]});continue}let ye=Ue.keep(X,Oe,wv(X,F.get(X),W.get(X)).map(({name:We})=>We)),ee=Oe.length-ye.length;if(X===Gt)for(let We of ye){let Ve=We.ActivityId;typeof We.Id=="string"&&typeof Ve=="string"&&Ve!==""&&Uo.set(We.Id,Ve)}let te=ye.map(We=>Sv(X,We,F.get(X),M,se)),Ee=ET(ye,F.get(X));Ee.length>0&&this.deps.log(`[INFO] seed:clone ${X}: ${Ee.length} field(s) the target does not have left out \u2014 ${Ee.join(", ")}`);let Pe=Rv(X,ye,te,$e,se),at=gf(X,te,oe.get(X)?.recordTypes??[]);if(at.length>0){it++,m.push({objectApiName:X,sourceCount:Oe.length,insertedCount:0,failedCount:ye.length,...ee>0?{leftToThePlatform:ee}:{},idMappings:[],errors:at.map(We=>{let Ve=ye.find((Ze,On)=>ff(te[On],[We]));return{sourceId:typeof Ve?.Id=="string"?Ve.Id:We.recordTypeId,message:hf(We)}})});continue}if(X===Gt&&Bo){let We=ye.map(Ve=>qg(Ve));rr.push(...ye.filter((Ve,Ze)=>We[Ze])),ye=ye.filter((Ve,Ze)=>!We[Ze]),te=te.filter((Ve,Ze)=>!We[Ze]),Pe=Pe.filter((Ve,Ze)=>!We[Ze])}let Ge=X===mi?await kn(ye):X===ir?await Vn(ye,te):await qo(X,ye,te),Wt=[],At=[];if(Ge.size>0){let We=ye.map(Ve=>!Ge.has(String(Ve.Id)));ye.forEach((Ve,Ze)=>{We[Ze]||(Wt.push([Ve,Ge.get(String(Ve.Id))??""]),At.push(te[Ze]))}),ye=ye.filter((Ve,Ze)=>We[Ze]),te=te.filter((Ve,Ze)=>We[Ze]),Pe=Pe.filter((Ve,Ze)=>We[Ze])}if(a.signal.aborted){Be=!0;break}let{outcomes:Hc,stopped:CI}=await Ho(X,te);if(CI&&(Be=!0,Hc.length===0))break;if(X===CT&&Hc.forEach((We,Ve)=>{let Ze=te[Ve]?.[ts];We.success&&We.id&&We.created!==!1&&typeof Ze=="string"&&Ze!==""&&we.set(We.id,Ze)}),X===ir&&Wt.length>0&&await Bc(Wt,At),Wt.length>0){let We=F.get(X),Ve=await Xg(X,Wt,Ze=>We?.fields.find(On=>On.name===Ze)?.updateable!==!1,async Ze=>{try{return await Ae.update(X,Ze,ce)}catch(On){if(!(On instanceof So))throw On;return Be=!0,On.written}},()=>Be||a.signal.aborted);Ve&&this.deps.log(`[seed:clone] ${X}: ${Ve}`)}let qc={objectApiName:X,sourceCount:Oe.length,insertedCount:0,failedCount:0,linkedCount:Ge.size,...X===ir&&Ge.size>0?{writtenByThePlatform:Ge.size}:{},...ee>0?{leftToThePlatform:ee}:{},...Ee.length>0?{fieldsNotInTarget:Ee}:{},idMappings:[],errors:[]};for(let[We,Ve]of Ge)se.set(We,Ve),qc.idMappings.push({sourceId:We,targetId:Ve});if(bt(Hc,ye,qc,Pe),m.push(qc),le.records+=ye.length,Be)break;X===mi&&await Ys()}await Ys();let Ar;if(Xe.length>0&&(a.signal.aborted&&(Be=!0),Ar=Be?TT(Xe):await AT({owed:Xe,idMap:se,targetConn:O,targetOrgId:t.targetOrgId,stopped:()=>a.signal.aborted,report:$=>{Le(this.deps,n,100,le.records,le.records,$),this.liveTracker?.updateProgress(n,100,le.records,0,$)}}),a.signal.aborted&&(Be=!0),p&&Ar.filled>0)){let $=new Map;for(let{objectApiName:X,newId:ie}of Xe)$.set(X,[...$.get(X)??[],ie]);for(let[X,ie]of $)p.wroteAgain(X,ie)}for(let $ of m){let X=Or.get($.objectApiName);X&&($.lookupsNotCarried=[...X].map(([Oe,ye])=>({field:Oe,records:ye})));let ie=Ht.get($.objectApiName);ie&&($.encryptedLeftOut=[...ie].sort())}let _e=m.reduce(($,X)=>$+X.sourceCount,0),He=m.reduce(($,X)=>$+X.insertedCount,0),tt=m.reduce(($,X)=>$+(X.linkedCount??0),0),rt=m.reduce(($,X)=>$+(X.leftToThePlatform??0),0),ct=m.reduce(($,X)=>$+X.failedCount,0),Qe=ct===0&&it===0?"success":He+tt>0?"partial":"failure",pt=Ar!==void 0&&Ar.filled<Ar.owed,nr=v(),qt=(Be||pt)&&Qe==="success"?"partial":Qe,or=await this.endKept(p,n,{status:qt,cancelled:Be});p=void 0;let xt=await fn(this.beforeRunCheckpoints,h,f,this.deps.log,`seed:clone:execute ${n}`);h=void 0;let It={status:qt,objectResults:m,totalSourceRecords:_e,totalInserted:He,totalLinked:tt,...rt>0?{totalLeftToThePlatform:rt}:{},totalFailed:ct,...Ar?{secondPass:Ar}:{},durationMs:Date.now()-o,...Be?{cancelled:!0}:{},contactPoints:nr,...or&&g>0?{runId:n}:{}};u=!1;let Rt=Be?He+ct>0?"cancelled":"stopped":It.status;K(this.deps,{...yv(l,Rt,m,y,nr),...Rt==="stopped"?{code:et}:{},...xt?.state==="taken"?{checkpointId:xt.checkpointId}:{}});let Jr=!Be&&It.status==="failure"?"No record could be cloned.":void 0;Be?(this.registry?.abort(n),ge(this.deps,n,{aborted:!0,totalInserted:He,totalFailed:ct}),this.liveTracker?.cancel(n)):(ge(this.deps,n,{status:It.status,totalInserted:He,totalFailed:ct}),Jr!==void 0?this.liveTracker?.fail(n,Jr):It.status==="partial"?this.liveTracker?.partial(n):this.liveTracker?.complete(n));let Qs={...It,...xt?{checkpoint:xt}:{}},Vr=T(this.deps,e,"seed:clone:execute:response",Qs);this.deps.broker.postToWebview(Vr),this.deps.log(`[TX] ${Vr.type} id=${Vr.id} status=${It.status}`),d(Jr===void 0?void 0:new Error(Jr))}catch(w){let R=await fn(this.beforeRunCheckpoints,h,f,this.deps.log,`seed:clone:execute ${n}`);u&&K(this.deps,{...yv(l,"failure",m,y,v()),...R?.state==="taken"?{checkpointId:R.checkpointId}:{}}),await this.endKept(p,n,{status:"failure",cancelled:!1});let k=R?.state==="deleted"?`${A(w)} ${Fr}`:A(w);this.deps.log(`[ERR] seed:clone:execute: ${k}`),je(this.deps,n,A(w),!0,{context:i,extraPayload:{code:k.startsWith(hv)?qr.guardBlocked:qr.failed,...R?{checkpoint:R}:{}}}),this.liveTracker?.fail(n,k),d(w)}}};function RT(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 ${yw(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 yv(s,e,t,r,n){return{...s,details:{...s.details,...ns(n).details},outcome:e,objects:t.map(o=>({...lt(o.objectApiName),...r?{upserted:o.insertedCount}:{created:o.insertedCount},failed:o.failedCount})),carried:Object.fromEntries(t.map(o=>[o.objectApiName,o.idMappings.length]))}}function wv(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)&&Go(s,n.name,n.nillable)).map(n=>({name:n.name,referenceTo:n.referenceTo??[]}))}async function Va(s,e,t){try{return await t()}catch(r){let n=A(r);throw s==="target"&&ST(r,n)?new Ka(e,n):new Error(`${e} could not be described in the ${s} org: ${n}`)}}var vT="OBJECT_NOT_IN_TARGET",Ka=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 ST(s,e){return s?.errorCode==="NOT_FOUND"||/\bNOT_FOUND\b|requested resource does not exist|INVALID_TYPE/.test(e)}function bv(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 kT(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 OT(s,e,t){let r=new Set(s);return s.flatMap(n=>{let o=Ya(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 IT(s,e,t){return s.flatMap(r=>{let n=Ya(t.get(r));return n?(e.get(r)?.fields??[]).filter(o=>o.type==="reference"&&!n.has(o.name)&&o.createable!==!1&&o.defaultedOnCreate!==!0&&Go(r,o.name,o.nillable)).flatMap(o=>(o.referenceTo??[]).map(i=>({objectApiName:r,field:o.name,referenceTo:i}))):[]})}function Rv(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 AT(s){let{owed:e,targetConn:t}=s,{patchCycleFkUpdates:r}=await import("./chunk-7EGQP6S4.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:oi()});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(zm)}})},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 TT(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 Ya(s){let e=new Set((s?.fields??[]).map(t=>t.name));return e.size>0?e:null}function ET(s,e){let t=Ya(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 PT(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 CT="Opportunity";function vv(s,e){if(e==="OpportunityId"||e===ts)return!1;let t=s?.fields.find(r=>r.name===e);return t!==void 0&&t.updateable!==!1}function Sv(s,e,t,r,n){let o=new Set((t?.fields??[]).filter(d=>d.createable===!1).map(d=>d.name)),i=Ya(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 yi(s,a))delete a[d];return a}var DT=new Set(["double","currency","percent","int","integer"]),Qa=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(DT.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 xT=new Set(["seed:csv:validate","seed:csv:execute"]),MT=100,kv="IMPORT_CANCELLED",jT=6e4,cu="CSV_STORAGE_EXCEEDED";function NT(s){let e=s<10?100:10;return String(s<=0?0:Math.ceil(s*e-1e-9)/e)}function $T(s,e,t){let r=e>0?jn(s,{rows:e})/e:0;return r>0?Math.max(0,Math.floor(t*1024*1024/r)):0}var Za=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-7YDNUBO5.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async handle(e){if(!xT.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: ${A(n)}`),!1}finally{this.runningRuns.delete(t)}}stoppedForCheckpoint(e,t,r,n){let{operationId:o}=t;if(r.code===et){K(this.deps,{...t,outcome:"stopped",source:void 0,code:kv}),this.registry?.abort(o),ge(this.deps,o,{aborted:!0,insertedCount:0,failedCount:0}),this.liveTracker?.cancel(o);let d={insertedCount:0,failedCount:0,errors:[],cancelled:!0};this.deps.broker.postToWebview(T(this.deps,e,"seed:csv:execute:response",d));return}let i=r.refusal?.code,a=i!==void 0?{checkpointRefusal:i}:{};K(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}:{}}),je(this.deps,o,r.message,!1,{context:n,authored:!0,extraPayload:{code:r.code,...a}}),this.liveTracker?.fail(o,r.message)}async handleValidate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(gl,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);De(r.limitInfo,`seed:csv:validate describe ${t.objectApiName}`);let i=new Qa().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=D(gl,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){K(this.deps,{...d,outcome:"stopped",source:void 0,code:Re.code}),E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(Re.message),{code:Re.code,retryable:!1}),je(this.deps,r,Re.message,!1,{context:n,extraPayload:{code:Re.code}}),i(new Error(Re.message));return}let f=this.deps.orgManager.getOrg(t.orgId),m={orgId:t.orgId,orgTier:Te(f),operation:t.externalIdField?"upsert":"insert",objectName:t.objectApiName,recordCount:t.records.length,module:"seed"},{check:y,decision:b}=await Ye(h,m);if(d.guard=b,(b==="refused"||b==="declined")&&K(this.deps,{...d,outcome:"stopped",source:void 0}),b==="refused")throw Qr(y.blockedReason??y.impactSummary);if(b==="declined"){let Z="Operation cancelled by user (confirmation declined).";E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(Z),{code:St.declined}),je(this.deps,r,Z,!1,{context:n}),i(new Error(Z));return}let v=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),w=be(f,t.orgId),R=(Z,ve,x)=>{let M=x!==void 0?{checkpointRefusal:x}:{};K(this.deps,{...d,outcome:"stopped",source:void 0,code:Z,...x!==void 0?{details:M}:{}}),E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(ve),{code:Z,retryable:!1,...x!==void 0?{extraPayload:M}:{}}),je(this.deps,r,ve,!1,{context:n,authored:!0,extraPayload:{code:Z,...M}}),i(new Error(ve))},k=this.targetAutomation,I=Ts([t.objectApiName],!!t.externalIdField),S=await new fe(jT).withTimeout("csv automation",()=>k.read(t.orgId,[t.objectApiName])).catch(Z=>({unread:A(Z)}));typeof S.unread=="string"&&this.deps.log(`[WARN] seed:csv:execute ${r}: what the org runs on ${t.objectApiName} could not be read (${S.unread}): it is asked about its emails, and a checkpoint holds the object alone`);let C=await Yt({read:S,writes:I,readDeliverability:()=>Te(f)==="production"?Promise.resolve(Nt):$t(v),accepted:!1,target:w,run:"seed",keepsAddresses:!0}),O=C.gate.verdict==="asks",P;if(t.checkpointFirst!==void 0){try{P=await Is(this.beforeRunCheckpoints,{module:"seed",orgId:t.orgId,operationId:r,written:[t.objectApiName],running:Ga(S,I),request:t.checkpointFirst})}catch(ve){if(!(ve instanceof Lt))throw ve;R(ve.code,ve.message);return}let Z=Ki(P.planned);if(Z){R(Z.code,Z.message,Z.refusal.code);return}}let _=await pr(v).catch(Z=>({unread:A(Z)})),J="unread"in _?await Qt(v).catch(Z=>({unread:A(Z)})):_.dailyApiRequests,B=gr({storageBytes:jn(t.objectApiName,{rows:t.records.length})},_);if(!t.externalIdField&&B.verdict==="exceeds"){let Z=t.records.length,ve=$T(t.objectApiName,Z,B.remainingMB),x=`The import was refused before it wrote anything: its ${Z} rows take about ${NT(B.estimateMB)} MB of data storage, and ${w} has ${B.remainingMB} MB left of ${B.maxMB} MB, room for about ${ve} of them: split the file and import one part at a time, freeing data storage in between as needed. Nothing was written.`;K(this.deps,{...d,outcome:"stopped",source:void 0,code:cu});let M={org:w,rows:Z,fitting:ve,estimateMB:B.estimateMB,remainingMB:B.remainingMB,maxMB:B.maxMB};E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(x),{code:cu,retryable:!1,extraPayload:M}),je(this.deps,r,x,!1,{context:n,authored:!0,extraPayload:{code:cu,...M}}),i(new Error(x));return}let re=sn({run:Wb([{objectApiName:t.objectApiName,rows:t.records.length}],{threshold:st(this.deps).bulk.threshold,perCall:this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200),duplicateRules:ho(S)})+zb(0,dn(S)),...go(P?.planned),...cn(C.ofRun)},J);re.verdict==="unread"&&this.deps.log(`[WARN] seed:csv:execute ${r}: the daily API requests the org has left could not be read (${re.unread})`);let H=Xi(re,be(f,t.orgId));if(H){K(this.deps,{...d,outcome:"stopped",source:void 0,code:uo}),E(this.deps,"seed:csv:execute","seed:csv:error",e,new Error(H),{code:uo,retryable:!1}),je(this.deps,r,H,!1,{context:n,authored:!0,extraPayload:{code:uo}}),i(new Error(H));return}let j=!1;if(P||O){let Z=t.records.length,ve=await h.confirmRun({stage:"write",module:"seed",org:w,orgTier:Te(f),objects:[{objectApiName:t.objectApiName,rows:Z}],total:Z,storage:ln(gr({storageBytes:jn(t.objectApiName,{rows:Z})},_)),...po(re),...P?{checkpoint:P.planned}:{},...C.gate.confirmation});if(ve!=="confirmed"){let x=C.gate.stop;ve!=="declined"&&!P&&x?R(x.code,x.message):R(ve==="declined"?Io:yt.unanswered,ve==="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}j=O}if(d.details=Hr({read:C,accepted:j}).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),P)try{p=await As(this.beforeRunCheckpoints,P,r,o.signal,(Z,ve,x,M)=>{Le(this.deps,r,Z,ve,x,M),this.liveTracker?.updateProgress(r,Z,ve,x,M)})}catch(Z){if(!(Z instanceof Lt))throw Z;this.stoppedForCheckpoint(e,d,Z,n),i(Z.code===et?void 0:Z);return}c=!0;let N=st(this.deps),Y=this.deps.services?.getSandforgeSetting?.("seed.defaultBatchSize",200)??200;n.batchSize=Y,l=this.runCreations?.recorder({runId:r,targetOrgId:t.orgId,startedAt:new Date().toISOString(),origin:"csv"}),p&&l?.checkpoint?.(p),hr(l,()=>v.identity(),`seed:csv:execute ${r}`),l&&this.runningRuns.add(r);let Q=new un({connection:v,bulkExecutor:new en(N.bulk.threshold),bulkManager:ar(this.deps),retryConfig:N.retry,signal:o.signal,onProgress:(Z,ve,x)=>{let M=ve>0?Math.round(Z/ve*100):0;Le(this.deps,r,M,Z,ve,x),this.liveTracker?.updateProgress(r,M,Z,ve,x)},log:Z=>this.deps.log(Z),...l?{calls:Ja(l,Z=>{u+=Z})}:{}}),U=t.records.map(Z=>LT(Z,t.columnMappings)),G=o.signal.aborted,pe=[];if(!G){U.length>0&&(g=!0);try{pe=t.externalIdField?await Q.upsert(t.objectApiName,t.externalIdField,U,Y):await Q.insert(t.objectApiName,U,Y)}catch(Z){if(!(Z instanceof So))throw Z;G=!0,pe=Z.written}}let me=[],ne=0;for(let Z of pe)Z.success?ne++:me.length<MT&&me.push(Z.errors[0]??"Unknown insert error");let he=pe.length-ne,qe=he===0?"success":ne>0?"partial":"failure",Ie=!G&&qe==="failure"?me[0]??"No row could be imported.":void 0;c=!1;let ce=await fn(this.beforeRunCheckpoints,p,g,this.deps.log,`seed:csv:execute ${r}`);p=void 0,G&&pe.length===0?K(this.deps,{...d,outcome:"stopped",source:void 0,code:kv}):K(this.deps,{...d,outcome:G?"cancelled":qe,objects:[{...lt(t.objectApiName),...t.externalIdField?{upserted:ne}:{created:ne},failed:he}],...ce?.state==="taken"?{checkpointId:ce.checkpointId}:{}});let oe=await this.endKept(l,r,{status:G&&qe==="success"?"partial":qe,cancelled:G});l=void 0;let le={insertedCount:ne,failedCount:he,errors:me,...G?{cancelled:!0}:{},...oe&&u>0?{runId:r}:{},...ce?{checkpoint:ce}:{}};G?(this.registry?.abort(r),ge(this.deps,r,{aborted:!0,insertedCount:ne,failedCount:he}),this.liveTracker?.cancel(r)):(ge(this.deps,r,{status:qe,insertedCount:ne,failedCount:he}),Ie!==void 0?this.liveTracker?.fail(r,Ie):qe==="partial"?this.liveTracker?.partial(r):this.liveTracker?.complete(r));let Ae=T(this.deps,e,"seed:csv:execute:response",le);this.deps.broker.postToWebview(Ae),this.deps.log(`[TX] ${Ae.type} id=${Ae.id} inserted=${ne} failed=${he}`),i(Ie===void 0?void 0:new Error(Ie))}catch(h){let f=await fn(this.beforeRunCheckpoints,p,g,this.deps.log,`seed:csv:execute ${r}`);c&&K(this.deps,{...d,...f?.state==="taken"?{checkpointId:f.checkpointId}:{}}),await this.endKept(l,r,{status:"failure",cancelled:!1});let m=f?.state==="deleted"?`${A(h)} ${Fr}`:A(h);E(this.deps,"seed:csv:execute","seed:csv:error",e,h,{code:ro(h),retryable:!0,...f?{extraPayload:{checkpoint:f}}:{}}),je(this.deps,r,m,!0,{context:n}),this.liveTracker?.fail(r,m),i(h)}}};function LT(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]=FT(n))}return t}function FT(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 _T={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"])},UT=[{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 lu(s,e){let t=s.toLowerCase(),r=e.toLowerCase();if(t===r)return!0;let n=_T[t];return n?n.has(r):r==="string"}var ed=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&&Ov(a)){r.push({recordIndex:n,field:i.apiName,message:`Required field '${i.apiName}' is missing or empty`});continue}if(Ov(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=lu(o,i),d=UT.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"||!BT(e))return`Expected valid ${r} string`;break}}};function Ov(s){return s==null||s===""}function BT(s){let e=Date.parse(s);return!isNaN(e)}var td=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 uu=3e4,Iv=6e4,pu="Nothing was read or written.",qT="Nothing was read.",Av="the checkpoints of this window are not open to the Sync page",WT=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"]),Tv={insert:0,update:1,upsert:2,delete:3};function fu(s,e){let t=s.objects??[],r="insert";for(let o of t)Tv[o.operation]>Tv[r]&&(r=o.operation);s.mode==="delta"&&s.propagateDeletes===!0&&(r="delete");let n=t.map(o=>o.objectApiName);return{orgId:s.targetOrgId,orgTier:Te(e),operation:r,objectName:n.length>0?n.join(", "):"SyncData",recordCount:"unknown",module:"sync"}}function zT(s){return s.map(e=>{let t={...lt(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 GT=new Set(["direct","rename"]),gu=20,JT=V({fields:Se(V({name:L(),type:L(),createable:Je(),updateable:Je()}).loose())});function Ev(s,e,t){let r=JT.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 Pv(s){if(s==="ask")return{emailsLiftedBy:"Untick Mute automation to be asked about them and sync all the same"};let e=Oy();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 rd=class{constructor(e){this.deps=e;this.syncConfigStore=new Ct(e.configStore)}deps;activeOperationIds=new Set;dmlTracker=new vi;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-7YDNUBO5.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",_r);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):_r}readCap(){return ga(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=Pv(r),u=this.readCap(),p=Xb(e,async g=>{let{totalSize:h}=await t.query(g);return Math.min(h,u)});return Kb({readStorage:()=>new fe(uu).withTimeout("sync:limits",()=>pr(t)),readApiBudget:()=>new fe(uu).withTimeout("sync:limits",()=>Qt(t)),readAutomation:n??(g=>new fe(Iv).withTimeout("sync:automation",()=>d.read(e.targetOrgId,g))),readLimits:()=>new fe(uu).withTimeout("sync:limits",()=>fr(t)),readDeliverability:()=>Te(a)==="production"?Promise.resolve(Nt):$t(t),emails:{target:be(a,e.targetOrgId),accepted:l.emailsAccepted===!0,keepsAddresses:e.keepContactPoints===!0},confirmAboveRecords:this.confirmAboveRecords(),bulkThreshold:st(this.deps).bulk.threshold,...o?{checkpointFirst:o}:{},...i?{mutePlan:i}:{},...p?{countTarget:p}:{}},{policy:r,org:be(a,e.targetOrgId),orgTier:Te(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(Av);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(Av);let p=await o.take(a,i,{planned:u,...n?{signal:n.signal,onProgress:g=>{let h=lo(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: ${A(o)}`),n}}isRunning(e){return this.activeOperationIds.has(e)}async handle(e){if(!WT.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=Jo(t.objects);return i.length===0?!1:(E(this.deps,r,n,e,new Error(`${Vo(i)} ${o}`),{code:Yc,extraPayload:{rules:i}}),!0)}async handleConfigSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Ef,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(kg(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=D(ki,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=D(ki,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}: ${A(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=D(ki,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 uy(e.idMap(),t=>this.syncConfigStore.isSaved(t))}recordRun(e,t,r,n,o,i){let a=zT(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;K(this.deps,{action:"sync_execute",module:"sync",operationId:t,orgId:e.targetOrgId,outcome:c,...c==="stopped"?{code:et}:{},guard:n,objects:a,source:{origin:"org",orgId:e.sourceOrgId},details:{triggeredBy:o,...Dn(i)},...r.mutedAutomation?{muted:ot(r.mutedAutomation)}:{},...r.checkpoint?.state==="taken"?{checkpointId:r.checkpoint.checkpointId}:{}})}recordRefused(e,t,r){K(this.deps,{action:"sync_execute",module:"sync",operationId:e,orgId:t,outcome:"stopped",code:r})}recordStopped(e,t,r){K(this.deps,{action:"sync_execute",module:"sync",operationId:e,orgId:t,outcome:"stopped",guard:r})}buildGuardRequest(e){return fu(e,this.deps.orgManager.getOrg(e.targetOrgId))}async assertFieldTypesMatch(e,t,r,n){let o=new ed,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 fe(n),[g,h]=await Promise.all([p.withTimeout(`describe-source-${u}`,()=>Bt(e.sourceOrgId,u,()=>t.describe(u))),p.withTimeout(`describe-target-${u}`,()=>Bt(e.targetOrgId,u,()=>r.describe(u)))]),f=Ev(g,u,"source").map(a),m=Ev(h,u,"target").filter(w=>w.createable||w.updateable).map(a),y=Cb(l,{creatable:new Set(m.map(w=>w.apiName))}),b=bf(y.fieldMappings,y.excludedFields),v=[Object.fromEntries(f.filter(w=>!b.has(w.apiName.toLowerCase())).map(w=>[w.apiName,w.apiName])),...l.fieldMappings.filter(w=>GT.has(w.type)).map(w=>({[w.sourceField]:w.targetField}))];for(let w of v)for(let R of o.validateMapping(f,m,w).errors)i.push(`${u}.${R.sourceField} (${R.sourceType}) -> ${u}.${R.targetField} (${R.targetType})`)}if(i.length===0)return;let d=i.slice(0,gu).join("; "),c=i.length>gu?` and ${i.length-gu} 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=D(Pf,e,"sync:error",this.deps);if(!t)return;let r=st(this.deps);try{let n=await q(t.orgId,this.deps.orgRegistry,this.deps.orgManager),o=new fe(r.timeouts.describeGlobal),i=await o.withTimeout("describe-global",()=>n.describeGlobal());De(n.limitInfo,"sync:describe-global");let a=i.sobjects.filter(u=>u.queryable&&!Si(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());De(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=D(Cf,e,"sync:error",this.deps);if(!t)return;let r=t,n=st(this.deps);try{let o=await q(r.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),i=await q(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),a=new fe(n.timeouts.describe),[d,c]=await Promise.all([a.withTimeout("describe-source",()=>o.describe(r.objectApiName)),a.withTimeout("describe-target",()=>i.describe(r.objectApiName))]);De(o.limitInfo,`sync:describe-fields source ${r.objectApiName}`),De(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=D(cl,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=st(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 fe(o).withTimeout(`describe-target-${u}`,()=>Bt(r.targetOrgId,u,()=>n.describe(u)));i.set(u,$b(l,mr(p)))}catch{}}let{order:a}=Lb(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=Cn(cr(async a=>(await n.query(a)).records),a=>new fe(t).withTimeout(`describe-source-${a}`,()=>Bt(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=D(Tn,e,"sync:error",this.deps);t&&(this.refusedFieldless(e,t.config,"sync:execute","sync:error",pu)||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=D(cl,e,"sync:error",this.deps);if(!t||this.refusedFieldless(e,t.config,"sync:simulate","sync:error",qT))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){let i=st(this.deps),a={module:"sync",operation:e.type,...Mr(t.objects)};try{let d=await this.readersFor(t,n.signal),{DataSync:c}=await import("./chunk-ZVAED4QV.mjs"),{ConflictResolver:l}=await import("./chunk-CHCHAE4B.mjs"),{FieldMappingService:u}=await import("./chunk-3TJON4F3.mjs"),{TransformPipeline:p}=await import("./chunk-BGUEWRK2.mjs"),{toolingQueriesOver:g,toolingValidationRules:h}=await import("./chunk-7ABODJ4G.mjs"),{toolingRetrievesOver:f}=await import("./chunk-7YDNUBO5.mjs"),m=d.targetConn.tooling,y=async()=>{throw new Error("A simulation writes nothing: the write it reached was refused.")},b=new c({insert:y,update:y,upsert:y,delete:y,describeTargetFields:d.describeTargetFields});if(!this.deps.services)throw new Error("SyncOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let v=o?this.runCheckpointOf(t,r,o):void 0,w=this.deps.services.syncOrchestrator({dataSync:b,conflictResolver:new l,fieldMapping:new u,transformPipeline:new p,querySource:d.querySource,maskedSourceFields:d.maskedSourceFields,queryTarget:d.queryTarget,services:this.deps.services,signal:n.signal,findInTarget:d.findInTarget,describeTargetFields:d.describeTargetFields,readSourceIds:d.readSourceIds,countSource:d.countSource,countPersonAccounts:d.countPersonAccounts,writeGate:this.writeGateFor(t,d.targetConn,"ask",void 0,v?.gate),queryTargetRows:d.queryTargetRows,recordTypes:d.recordTypes,currencies:d.currencies,standardPricebooks:d.standardPricebooks,deltaStore:this.deltaStoreFor(),deltaReads:d.deltaReads,idMap:this.idMapFor(),files:d.files,readValidationRules:h(async O=>(await dr({query:async P=>m.query(P),queryMore:async P=>m.queryMore(P)},O)).records,g(d.targetConn),f(d.targetConn)),onSimulationProgress:(O,P,_)=>{let J=Math.round(O/P*100),B=`Simulating ${_}`;Le(this.deps,r,J,O,P,B),this.liveTracker?.updateProgress(r,J,O,P,B)}});await this.assertFieldTypesMatch(t,d.sourceConn,d.targetConn,i.timeouts.describe);let R=await w.simulate(t),k=v?.planned(),I=[...d.cutAtReadCap],S={...R,...k?{checkpoint:k}:{},readCap:d.readCap,...I.length>0?{cutAtReadCap:I}:{},operationId:r};S.cancelled?this.endCancelled(r):S.error?(this.liveTracker?.fail(r,S.error),je(this.deps,r,S.error,!0,{context:a})):(Le(this.deps,r,100,1,1,"Simulation complete"),ge(this.deps,r,{status:"success",simulated:!0}),this.liveTracker?.complete(r)),this.deps.log(`[sync] simulation ${r} ${S.cancelled?"stopped":"finished"}: `+S.objects.map(O=>`${O.objectApiName} insert=${O.insert} update=${O.update} delete=${O.delete} skipped=${O.skipped} refused=${O.refused} conflicts=${O.conflicts}`).join("; "));let C=T(this.deps,e,"sync:simulate:response",S);return this.deps.broker.postToWebview(C),this.deps.log(`[TX] ${C.type} id=${C.id}`),S}catch(d){return this.liveTracker?.fail(r,A(d)),E(this.deps,"sync:simulate","sync:error",e,d),je(this.deps,r,A(d),!0,{context:a}),null}}async handleRunControl(e,t){this.deps.log(`[RX] ${e.type} id=${e.id}`);let r=D(Tf,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=st(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 na({retryConfig:r.retry}),c=(O,P)=>async(_,J,B)=>{let re=gt(J.objectApiName),H="",j=is(J.where,B?.changedSince);j&&(H+=` WHERE ${j}`),J.orderBy&&(H+=` ORDER BY ${sl(J.orderBy)}`);let N=!1,Y=await d.execute(async()=>{N=!1;let U=(await O.describe(re)).fields.map(me=>me.name),G=U.length>0?U:["Id"],pe={query:async me=>O.query(me),queryMore:async me=>O.queryMore(me)};return os(`SELECT ${G.join(", ")} FROM ${re}${H}`,async me=>{let ne=await dr(pe,me,i);return N||=ne.truncated,ne.records})});if(!Y.success)throw Y.error??new Error("Query failed after retries");De(O.limitInfo,`sync:execute query ${re}`);let Q=Y.result??[];if(N){B?.onBoundReached?.();let U=Q.length>=i?`${i} records (sandforge.sync.maxRecordsPerObject)`:`${Math.max(500,Math.ceil(i/200))} pages`,G=P===e.sourceOrgId?"source":"target";G==="source"&&a.add(J.objectApiName);let pe=G==="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 ${re} (${G}): read stopped at ${Q.length} record(s) \u2014 bound: ${U}. ${pe}.`),ke(this.deps,"warning","Sync",`${re}: only ${Q.length} record(s) were read from the ${G} (bound: ${U}) \u2014 ${pe}. `+_b(G,i,Fb))}return Q},l=async(O,P,_)=>{let B=`SELECT COUNT() FROM ${gt(P.objectApiName)}`,re=is(P.where,_?.changedSince);re&&(B+=` WHERE ${re}`);let{totalSize:H}=await n.query(B);return Math.min(H,i)},u=async(O,P)=>{let _=gt(O.objectApiName),J=is(O.where,P?.changedSince),B=`SELECT COUNT() FROM ${_} WHERE IsPersonAccount = true`+(J?` AND (${J})`:"");try{return(await n.query(B)).totalSize}catch{return 0}},p=new Map,g=async O=>{let P=p.get(O);if(P)return P;let _=await o.describe(O),J=mr(_);return p.set(O,J),J},h=async O=>mr(await o.describe(O)),f=async O=>(await dr({query:async P=>o.query(P),queryMore:async P=>o.queryMore(P)},O)).records,m=mf({query:async O=>o.query(O),queryMore:async O=>o.queryMore(O)},t),y=async(O,P,_,J)=>{let B=await m(O,P,_,J);return De(o.limitInfo,`sync:simulate lookup ${P.objectApiName}`),B},b=Rf({query:async(O,P)=>n.query(O,P),queryMore:async O=>n.queryMore(O)},{query:async O=>o.query(O),queryMore:async O=>o.queryMore(O)},t),v=O=>({pages:{query:async P=>O.query(P),queryMore:async P=>O.queryMore(P)},transport:O,create:async(P,_)=>O.sobject(P).create(_,{headers:oi()})}),w=async(O,P)=>{let J=`SELECT Id FROM ${gt(O.objectApiName)}`,B=is(O.where,P);B&&(J+=` WHERE ${B}`),O.orderBy&&(J+=` ORDER BY ${sl(O.orderBy)}`);let{records:re}=await dr(v(n).pages,J,i);return re.flatMap(H=>typeof H.Id=="string"?[H.Id]:[])},R={copy:Ob({[e.sourceOrgId]:v(n),[e.targetOrgId]:v(o)}),sourceIds:w,store:this.fileStoreFor(),...e.files!==void 0&&kb(this.deps.infraServices?.productionGuard,e.targetOrgId,this.deps.orgManager.getOrg(e.targetOrgId))?{deleteFromTarget:async(O,P)=>Gm(await o.sobject(O).destroy(P),O).map(_=>({id:_.id,success:_.success,errors:_.errors}))}:{}},k=async()=>{let{readSyncRecordTypes:O}=await import("./chunk-BTWDMNN3.mjs");return O(v(n).pages,v(o).pages)},I=async()=>{let{readRunCurrencies:O}=await import("./chunk-QWT2C74M.mjs");return O(async P=>(await n.query(P)).records,async P=>(await o.query(P)).records,{source:async P=>(await n.tooling.query(P)).records,target:async P=>(await o.tooling.query(P)).records})},S=async()=>{let{readStandardPricebooks:O}=await import("./chunk-FGRG7ANU.mjs");return O(async P=>(await n.query(P)).records,async P=>(await o.query(P)).records)},C=Cn(cr(async O=>(await n.query(O)).records),O=>Bt(e.sourceOrgId,O,()=>n.describe(O)));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:k,currencies:I,standardPricebooks:S,findInTarget:y,readSourceIds:O=>w(O),countPersonAccounts:u,deltaReads:b,files:R,readCap:i,cutAtReadCap:a}}async rerunFromSnapshot(e,t){this.deps.log(`[RX] sync:history:rerun id=${e.id}`);let r=D(Tn,{...e,payload:{config:t}},"sync:history:error",this.deps);r&&(this.refusedFieldless(e,r.config,"sync:history:rerun","sync:history:error",pu)||await this.startExecution(e,r.config,"rerun"))}async executeScheduled(e,t="schedule"){let r=Tn.safeParse({config:e});if(!r.success)throw new Error(`Scheduled sync config failed validation: ${r.error.issues.map(m=>m.message).join("; ")}`);let n=Jo(r.data.config.objects);if(n.length>0)throw Object.assign(new Error(`${Vo(n)} ${pu}`),{code:Yc});let o=t==="pipeline"?An("sync:pipeline",crypto.randomUUID(),"sync:execute"):An("sync:schedule",crypto.randomUUID(),"sync:execute"),i=o.id,a=this.deps.services?.getSandforgeSetting?.("sync.defaultBatchSize",200)??200,d={...r.data.config,objects:r.data.config.objects.map(m=>({...m,batchSize:m.batchSize??a}))},c=this.deps.infraServices?.productionGuard;if(!c)throw this.recordRefused(i,d.targetOrgId,Re.code),bi();let{check:l,decision:u}=await Ye(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(v=>({...v,batchSize:v.batchSize??c}))};Object.assign(a,Mr(u.objects));let p=this.deps.infraServices?.productionGuard;if(!p){this.recordRefused(i,u.targetOrgId,Re.code),E(this.deps,"sync:execute","sync:error",e,new Error(Re.message),{code:Re.code}),je(this.deps,i,Re.message,!1,{context:a});return}let{check:g,decision:h}=await Ye(p,this.buildGuardRequest(u)),f=h;if((h==="refused"||h==="declined")&&this.recordStopped(i,u.targetOrgId,h),h==="refused")throw Qr(g.blockedReason??g.impactSummary);if(h==="declined"){let v="Operation cancelled by user (confirmation declined).";E(this.deps,"sync:execute","sync:error",e,new Error(v),{code:St.declined}),je(this.deps,i,v,!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}`)),je(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,b=this.executeSync(e,u,i,y,r,f,n,o);this.registry?this.registry.register(i,"sync",m,b,y):await b}catch(c){this.dmlTracker.markFailed(i),E(this.deps,"sync:execute","sync:error",e,c,{code:ro(c)}),je(this.deps,i,A(c),!0,{context:a})}finally{d?.release()}}answerCancelledBeforeStart(e,t,r){K(this.deps,{action:"sync_execute",module:"sync",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:r,code:ft});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),ge(this.deps,e,{aborted:!0}),this.liveTracker?.cancel(e)}async executeSync(e,t,r,n,o,i,a=!1,d){let c=t.id?t:{...t,id:r},l=st(this.deps),u,p,g=!1,h,f=k=>({measure:I=>k.measure(I),hold:async I=>{let S=await k.hold(I);return h=S.answer.emails,S}}),m=new td;this.pauseGates.set(r,m);let y=this.runCreations?.recorder({runId:r,configId:c.id,configName:c.name??"",sourceOrgId:c.sourceOrgId,targetOrgId:c.targetOrgId}),b=this.backupRecords,v=y&&b?ua({runId:r,orgId:c.targetOrgId,files:b,meta:this.deps.configStore}):void 0,w=d?this.runCheckpointOf(c,r,d,{signal:n.signal,...y?{recorder:y}:{}}):void 0,R=()=>{try{v?.close()}catch(k){this.deps.log(`[WARN] sync ${r}: the backup of what it wrote over could not be listed whole: `+A(k))}};try{let k=await this.readersFor(c,n.signal),{sourceConn:I,targetConn:S}=k;hr(y,()=>S.identity(),`sync ${r}`);let C=k.queryTargetRows,O=y&&v?pa({query:C,backup:v,recorder:y,describe:k.describeTargetFields,viewsEncrypted:cr(C)}):void 0,P=new en(l.bulk.threshold),_=ar(this.deps),J=new un({connection:S,bulkExecutor:P,bulkManager:_,retryConfig:l.retry,signal:n.signal,pauseGate:m,onProgress:(oe,le,Ae)=>{let Z=Math.round(oe/le*100);Le(this.deps,r,Z,oe,le,Ae),this.liveTracker?.updateProgress(r,Z,oe,le,Ae)},log:oe=>this.deps.log(oe),...y?{calls:ma(y,O)}:{}}),{DataSync:B}=await import("./chunk-ZVAED4QV.mjs"),{ConflictResolver:re}=await import("./chunk-CHCHAE4B.mjs"),{FieldMappingService:H}=await import("./chunk-3TJON4F3.mjs"),{TransformPipeline:j}=await import("./chunk-BGUEWRK2.mjs"),N=oe=>{oe.length>0&&(g=!0)},Y=new B({upsert:(oe,le,Ae,Z)=>(N(Ae),J.upsert(oe,le,Ae,Z)),insert:(oe,le,Ae)=>(N(le),J.insert(oe,le,Ae)),update:(oe,le,Ae)=>(N(le),J.update(oe,le,Ae)),delete:(oe,le,Ae)=>(N(le),J.delete(oe,le,Ae)),describeTargetFields:k.describeTargetFields}),Q=new re,U=new H,G=new j,pe={dataSync:Y,conflictResolver:Q,fieldMapping:U,transformPipeline:G,querySource:k.querySource,maskedSourceFields:k.maskedSourceFields,queryTarget:k.queryTarget,services:this.deps.services,grappeConfig:rs(this.deps.services),onGrappeEvent:oe=>Ri(this.deps,oe),countSource:k.countSource,countPersonAccounts:k.countPersonAccounts,describeTargetFields:k.describeTargetFields,describeTargetFieldsAgain:k.describeTargetFieldsAgain,leaseOfTheGate:()=>p?.lease(),queryTargetRows:C,readSourceIds:k.readSourceIds,findInTarget:k.findInTarget,writeGate:(()=>{let oe=o==="schedule"||o==="pipeline"?"unattended":"ask";if(!a)return f(this.writeGateFor(c,S,oe,void 0,w?.gate));let le=this.targetAutomation;return p=Qb((Z,ve)=>this.writeGateFor(c,S,oe,Z,w?.gate,ve),Z=>new fe(Iv).withTimeout("sync:automation",()=>le.read(c.targetOrgId,Z)),Z=>mt(async()=>Pt(S),Z,{...this.muteLeases,writes:Yb}),r,{target:be(this.deps.orgManager.getOrg(c.targetOrgId),c.targetOrgId),liftedBy:Pv(oe).emailsLiftedBy}),f(p.gate)})(),recordTypes:k.recordTypes,currencies:k.currencies,standardPricebooks:k.standardPricebooks,signal:n.signal,pauseGate:m,deltaStore:this.deltaStoreFor(),deltaReads:k.deltaReads,files:{...k.files,onProgress:(oe,le)=>{Le(this.deps,r,oe,0,0,le),this.liveTracker?.updateProgress(r,oe,0,0,le)}},...y?{creations:y}:{},idMap:this.idMapFor()};if(!this.deps.services)throw new Error("SyncOpsHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");let me=this.deps.services.syncOrchestrator(pe);await this.assertFieldTypesMatch(c,I,S,l.timeouts.describe),Le(this.deps,r,10,0,1,"Initializing sync");let ne=await me.execute(c).finally(async()=>{u=await p?.release()}),he=await this.settleRunCheckpoint(w,g,r),qe=[...k.cutAtReadCap],Ie={...ne,...qe.length>0?{status:ne.status==="success"?"partial":ne.status,readCap:k.readCap,cutAtReadCap:qe}:{},...u?{mutedAutomation:u}:{},...he?{checkpoint:he}:{}};if(await y?.end({status:Ie.status,cancelled:Ie.cancelled===!0}),R(),Ie.cancelled?this.endCancelled(r):(Le(this.deps,r,100,1,1,"Sync complete"),ge(this.deps,r,{status:Ie.status??"completed"}),Ie.status==="failure"?this.liveTracker?.fail(r,Ie.error??"No record could be synced."):Ie.status==="partial"?this.liveTracker?.partial(r):this.liveTracker?.complete(r)),this.dmlTracker.markCompleted(r),c.files){let oe=Ie.objectResults.flatMap(le=>le.files?[le.files]:[]);this.deps.log(`[sync] ${r} files: ${Ib(oe)}`)}De(I.limitInfo,"sync:execute completion (source)"),De(S.limitInfo,"sync:execute completion (target)");try{this.historyLogger?.logExecution(c,Ie,o)}catch(oe){this.deps.log(`[WARN] sync history logging failed: ${A(oe)}`)}this.recordRun(c,r,Ie,i,o,h);let ce=T(this.deps,e,"sync:execute:response",Ie);return this.deps.broker.postToWebview(ce),this.deps.log(`[TX] ${ce.type} id=${ce.id}`),Ie}catch(k){await y?.end({status:"failure"}),R(),this.dmlTracker.markFailed(r);let I=await this.settleRunCheckpoint(w,g,r),S=I?.state==="deleted";if(this.liveTracker?.fail(r,A(k)),k instanceof Nb){let _=w?.refusal(),J=S?`${k.message} ${Fr}`:k.message,B={..._?{checkpointRefusal:_.code}:{},...I?{checkpoint:I}:{}};return K(this.deps,{action:"sync_execute",module:"sync",operationId:r,orgId:c.targetOrgId,outcome:"stopped",guard:i,code:k.code,details:{triggeredBy:o,..._?{checkpointRefusal:_.code}:{},...Dn(h)}}),E(this.deps,"sync:execute","sync:error",e,k,{code:k.code,extraPayload:B}),je(this.deps,r,J,!1,{context:{module:"sync",operation:e.type,...Mr(c.objects)}}),{...k.result,configId:c.id,operationId:r,status:"failure",timestamp:new Date().toISOString(),error:J,...I?{checkpoint:I}:{}}}Zo(k)&&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}`):Zo(k)&&o==="rerun"&&this.deps.log(`[OFFLINE] sync replay failed again \u2014 not re-queued (replay outcomes surface via operation:failed): ${r}`);let C=S?new Error(`${A(k)} ${Fr}`):k;E(this.deps,"sync:execute","sync:error",e,k,{...I?{extraPayload:{checkpoint:I}}:{}}),je(this.deps,r,A(C),!0,{context:{module:"sync",operation:e.type,...Mr(c.objects)}});let P={...(k instanceof jb?k.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:A(C),...I?{checkpoint:I}:{}};try{this.historyLogger?.logExecution(c,P,o)}catch(_){this.deps.log(`[WARN] sync history logging failed: ${A(_)}`)}return this.recordRun(c,r,P,i,o,h),P}finally{this.pauseGates.delete(r),this.activeOperationIds.has(r)&&(this.deps.infraServices?.performanceTracker?.complete(r),this.activeOperationIds.delete(r))}}};var VT=new Set(["sync:history:list","sync:history:detail","sync:history:rerun","sync:history:export"]),nd=class{constructor(e,t,r){this.deps=e;this.historyStore=t;this.syncOps=r}deps;historyStore;syncOps;async handle(e){if(!VT.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=D(ll,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=D(Wf,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=D(ll,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 XT=1e4;async function Cv(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=>Et(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,XT),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 KT=new Set(["sync:removal:info","sync:removal:list","sync:remove","sync:remove:sweep","sync:remove:automation","sync:earlier-copies"]),YT=6e4,QT=12e4,Dv=6e4,ZT=6e4,xv="The run is still writing in another window: remove it once it has ended there.",od=class{constructor(e,t,r,n=io){this.deps=e;this.history=t;this.isRunning=r;this.self=n;this.configs=new Ct(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)&&Pn(e,this.self)}stillWriting(e){return this.isRunning(e.runId)||Pn(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-7YDNUBO5.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>q(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}async handle(e){if(!KT.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 Te(t)}infoOf(e,t=[]){let r=Et(e),n=fy(e,t),o=r.map(({objectApiName:m,ids:y})=>({objectApiName:m,count:y.length})),i=ao(e),a=this.keptBack(i),d=Sl(e),c=kl(e),l=gs(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:ps(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(b=>`${m}.${b}`))}:{},...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?Et(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 Dy(e,t=>this.deps.configStore.get(`backup:${t}`),Cy(this.deps.services))}removalStepsOf(e,t=!1){let r=o=>[...new Set(o.map(({objectApiName:i})=>i))],n=r(Et(e,t));return{bringBack:r(gs(e)),giveBack:r(this.keptBack(ao(e)).kept),setToDraft:Vt(n),delete:tn(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:xv};if(!this.deps.orgManager.getOrg(e.targetOrgId))return{code:"ORG_GONE",message:"The org the run wrote to is no longer connected: connect it again to remove the run."};let n=this.deps.infraServices?.productionGuard;if(!n)return{code:"NO_GUARD",message:Re.message};let o=n.check(this.guardRequestOf(e,t,r));return o.allowed?void 0:{code:"GUARD_BLOCKED",message:o.blockedReason??o.impactSummary}}async withJobAnswered(e){let t=this.creations;if(!t||(e.jobs??[]).length===0||this.stillWriting(e)||!this.deps.orgManager.getOrg(e.targetOrgId))return e;let r=`sync:removal of ${e.runId}`;try{let n=await new fe(ZT).withTimeout(r,async()=>{let o=await q(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=Xt(o,r);return oa(t,e,En(o),()=>i.serverTime())});for(let o of sa(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: ${A(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=D(Nf,e,"sync:remove:error",this.deps);if(t)try{let r=await this.runOf(t.runId),o=r!==void 0&&(Et(r).length>0||ao(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=D($f,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)&&(ps(d)>0||Sl(d)>0||kl(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=D(Lf,e,"sync:remove:error",this.deps);if(t)try{let r=this.creations,n=await Cv(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=gt(i),l=0;for(let u of ds(a.filter(Nr)))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=>!py.includes(l)))],a;try{a=await new fe(YT).withTimeout(`${r} automation`,()=>o.read(t.targetOrgId,i))}catch(l){a={error:A(l)}}let d=Xt(e,r),c=await aa(d,t.created,a,n,t.firstWrittenAt!==void 0?{at:t.firstWrittenAt,...t.lastWriteAt!==void 0?{lastAt:t.lastWriteAt}:{},serverTime:()=>d.serverTime()}:void 0,t.overwritten??[],{...t.runUserId?{runUserId:t.runUserId}:{},ties:{}});return bo({...c,ties:{...c.ties,...await ca(t,c.writtenBetween,await this.creations?.list().catch(()=>[])??[],this.otherModuleRuns)}},d)}async localRunsOn(e){return da(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=D(_f,e,"sync:remove:sweep:error",this.deps);if(!t)return;let r=(n,o)=>E(this.deps,"sync:remove:sweep","sync:remove:sweep:error",e,new Error(n),{code:o});try{let n=await this.runOf(t.runId);if(!n){r("Nothing this run created is kept: there is nothing to sweep after.","NOT_KEPT");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){r("The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}let o=await new fe(QT).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 mo(Ur(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=D(Uf,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=Ko(this.removalStepsOf(n,t.again===!0),t.sweptObjects??[]),i=[...new Set(Object.values(o).flat())],a=this.targetAutomation,d=await new fe(Dv).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 lr;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 Ro({input:async()=>{if(n instanceof Error)throw n;return n},org:Ur(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=wo(o,"");delete a.forgeId,K(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:vo(i)}:{},objects:yo(o),details:{...a,runId:r.runId}})},keepMade:async(o,i,a)=>{await this.creations?.updateRemoval(r.runId,d=>la(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: ${A(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={}){K(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=D(Ff,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,xv,"RUNNING");return}let o=t.again===!0;if(Et(n,o).length===0&&ao(n).length===0&&gs(n).length===0){let a=n.removal?.undo?.removedAt??n.removal?.restoredAt??n.removal?.undeletedAt;a!==void 0?this.refuse(e,`What this run created was removed already, on ${a}.`,"ALREADY_REMOVED"):this.refuse(e,"This run created nothing to remove.","NOTHING_TO_REMOVE");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){this.refuse(e,"The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}if(this.removing.has(n.runId)){this.refuse(e,"What this run created is being removed already.","DUPLICATE");return}this.removing.add(n.runId);let i=this.registry?.holdUntilStart(e.id);try{await this.removeRun(e,r,n,{includeChanged:t.includeChanged===!0,sweep:t.sweep===!0,sweepLate:t.sweep===!0&&t.sweepLate===!0,sweepUntied:t.sweep===!0&&t.sweepUntied===!0,again:o,muteAutomation:t.muteAutomation===!0},i)}finally{this.removing.delete(n.runId),i?.release()}}async removeRun(e,t,r,n,o){let{includeChanged:i,again:a}=n,d=Et(r,a),c=[...ao(r),...gs(r)],l=d.reduce((I,S)=>I+S.ids.length,0),u=c.reduce((I,S)=>I+S.ids.length,0),p=r.targetOrgId,g=this.deps.infraServices?.productionGuard;if(!g){this.recordNotRemoved(e,r,"stopped",{code:Re.code}),this.refuse(e,Re.message,Re.code);return}let{check:h,decision:f}=await Ye(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}`,St.blocked):this.refuse(e,"Operation cancelled by user (confirmation declined).",St.declined,!0);return}if(o?.signal.aborted){this.recordNotRemoved(e,r,"stopped",{guard:f,code:ft});let I={runId:r.runId,status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(T(this.deps,e,"sync:remove:response",{result:I,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`,b=new AbortController,v=()=>{},w=new Promise((I,S)=>{v=C=>C===void 0?I():S(C)});w.catch(()=>{}),ze(this.deps,m,"sync",y),this.registry?.register(m,"sync",y,w,b),this.liveTracker?.register(m,"sync",y,l+u);let R,k;try{let I=await q(p,this.deps.orgRegistry,this.deps.orgManager),S=n.sweep?await this.sweepInputOf(I,r,"sync:remove sweep",b.signal).catch(pe=>new Error(A(pe))):void 0;k=S?await this.sweepOfRemoval({conn:I,run:r,input:S,includeChanged:i,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,signal:b.signal,guard:g,operationId:m}):void 0;let C=k;await C?.ask();let O;if(n.muteAutomation===!0){let pe=Ko(this.removalStepsOf(r,a),C?.takes??[]),me=[...new Set(Object.values(pe).flat())],ne=this.targetAutomation,he=await new fe(Dv).withTimeout("sync:remove:automation",()=>ne.read(r.targetOrgId,me,{undeletes:!0})).catch(qe=>({unread:A(qe)}));O=await mt(async()=>Pt(I),he,{...this.muteLeases,writes:Yr(pe)})}let P,_=O?.muted,J=async()=>{let pe=O?.prepared;!pe||b.signal.aborted||(P=await pe.acquire(m),_=P.outcome)},B=Xt(I,"sync:remove"),re=await ia(B,r.created),{result:H,notes:j,earlierStamped:N}=await $i({run:r,org:B,includeChanged:i,...a?{again:a}:{},store:t,configs:this.configs,links:t.idMap(),...this.backups?{backups:this.backups}:{},earlierRuns:gy(r,await t.list().catch(()=>[])),undelete:pe=>I.soap.undelete(pe),...C?{sweep:pe=>C.first(pe),afterRemoval:pe=>C.afterRemoval(pe),automationMade:C.automationMade}:{},...r.runUserId?{runUserId:r.runUserId}:{},onUndeletable:xr(this.deps,p,"sync:remove"),beforeFirstWrite:J,signal:b.signal,onProgress:(pe,me,ne)=>{let he=Math.min(100,Math.round(pe/Math.max(me,1)*100));Le(this.deps,m,he,pe,me,ne),b.signal.aborted||this.registry?.updateProgress(m,he),this.liveTracker?.updateProgress(m,he,pe,me,ne)}}).finally(async()=>{P&&(_=await P.release())}),Y=await k?.settle(),Q=H.status==="cancelled"?{}:await re.take();for(let pe of[...j,...Q.note?[Q.note]:[]])this.deps.log(`[WARN] sync:remove ${m}: ${pe}`);for(let{runId:pe,records:me}of N??[])this.deps.log(`[INFO] sync:remove ${m}: ${me} record(s) given back hold the values of the earlier run ${pe} again, stamped on it`);let U={...H,objects:Q.object?[...H.objects,Q.object]:H.objects,status:oo(H.status,Y),...Y?{sweep:Y}:{},..._?{mutedAutomation:_}:{}};K(this.deps,{action:"cleanup_delete",module:"sync",operationId:m,orgId:p,outcome:so(H),guard:f,objects:Ni(rn(U.objects),U.restored??[],U.undeleted??[]),...U.leftBy?{leftBy:U.leftBy}:{},..._?{muted:ot(_)}:{},details:{runId:r.runId}});let G=T(this.deps,e,"sync:remove:response",{result:U,operationId:m});this.deps.broker.postToWebview(G),this.deps.log(`[TX] ${G.type} id=${G.id} status=${U.status}`),U.status==="cancelled"||U.sweep?.status==="cancelled"?(ge(this.deps,m,{aborted:!0}),this.liveTracker?.cancel(m)):(ge(this.deps,m,{status:U.status}),U.status==="failure"?(R=new Error("Nothing this run created could be removed."),this.liveTracker?.fail(m,"Nothing this run created could be removed.")):U.status==="partial"?this.liveTracker?.partial(m):this.liveTracker?.complete(m))}catch(I){R=I,await k?.settle().catch(()=>{});let S=kt(I)?I:void 0;this.recordNotRemoved(e,r,S?"stopped":"failure",{guard:f,...S?{code:S.code}:{}}),E(this.deps,"sync:remove","sync:remove:error",e,I,{code:S?.code??"REMOVE_ERROR",retryable:!0}),ge(this.deps,m,{status:"failure"}),this.liveTracker?.fail(m,A(I))}finally{v(R)}}};var eE=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,tE=/^[A-Za-z][A-Za-z0-9_]*$/;function sd(s,e,t){if(!eE.test(t)||!tE.test(e))return{ok:!1,reason:"not-a-record"};let r=pn(s);return r.ok?{ok:!0,url:new URL(`/lightning/r/${e}/${t}/view`,r.url.origin).toString()}:r}var rE=new Set(["seed:removal:info","seed:removal:list","seed:remove","seed:remove:sweep","seed:open-record"]),Mv=6e4,nE=12e4,oE=6e4,jv="The seed is still writing: remove it once it has ended.",Nv="The seed is still writing in another window: remove it once it has ended there.",id=class{constructor(e,t,r=()=>!1,n=io){this.deps=e;this.isRunning=r;this.self=n;this.externalBrowser=t??new wr}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)&&Pn(e,this.self)}setRunCreations(e){this.creations=e}setTargetAutomation(e){this.targetAutomation=e}ownReader(){return this.reader??=import("./chunk-7YDNUBO5.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 rE.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 Te(t)}infoOf(e){let t=Et(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:ps(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?Et(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-XUWL6ZPC.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:jv};if(this.elsewhere(e))return{code:"RUNNING",message:Nv};if(!this.deps.orgManager.getOrg(e.targetOrgId))return{code:"ORG_GONE",message:"The org the run wrote to is no longer connected: connect it again to remove the run."};let r=this.deps.infraServices?.productionGuard;if(!r)return{code:"NO_GUARD",message:Re.message};let n=r.check({orgId:e.targetOrgId,orgTier:this.tierOf(e.targetOrgId),operation:"delete",objectName:t.map(o=>o.objectApiName).join(", "),recordCount:t.reduce((o,i)=>o+i.ids.length,0),module:"seed"});return n.allowed?void 0:{code:"GUARD_BLOCKED",message:n.blockedReason??n.impactSummary}}async withJobAnswered(e){let t=this.creations;if(!t||(e.jobs??[]).length===0||this.isRunning(e.runId)||this.elsewhere(e)||!this.deps.orgManager.getOrg(e.targetOrgId))return e;let r=`seed:removal of ${e.runId}`;try{let n=await new fe(oE).withTimeout(r,async()=>{let o=await q(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),i=Xt(o,r);return oa(t,e,En(o),()=>i.serverTime())});for(let o of sa(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: ${A(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=D(Bf,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=D(uh,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=sd(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 "${be(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 fe(Mv).withTimeout(`${r} automation`,()=>o.read(t.targetOrgId,t.created.map(c=>c.objectApiName)))}catch(c){i={error:A(c)}}let a=Xt(e,r),d=await aa(a,t.created,i,n,void 0,[],{...t.runUserId?{runUserId:t.runUserId}:{},ties:{}});return bo({...d,ties:{...d.ties,...await ca(t,d.writtenBetween,await this.creations?.list().catch(()=>[])??[],this.otherModuleRuns)}},a)}async localRunsOn(e){return da(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=D(qf,e,"seed:remove:sweep:error",this.deps);if(!t)return;let r=(n,o)=>E(this.deps,"seed:remove:sweep","seed:remove:sweep:error",e,new Error(n),{code:o});try{let n=await this.runOf(t.runId);if(!n){r("Nothing this run created is kept: there is nothing to sweep after.","NOT_KEPT");return}if(!this.deps.orgManager.getOrg(n.targetOrgId)){r("The org the run wrote to is no longer connected: connect it again to remove the run.","ORG_GONE");return}let o=await new fe(nE).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 mo(Ur(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 Ro({input:()=>this.sweepInputOf(t,r,"seed:remove sweep",e.signal),org:Ur(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=wo(n,"");delete i.forgeId,K(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:vo(o)}:{},objects:yo(n),details:{...i,runId:r.runId}})},keepMade:async(n,o,i)=>{await this.creations?.updateRemoval(r.runId,a=>la(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: ${A(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={}){K(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=D(Hf,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(Et(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,jv,"RUNNING");return}if(this.elsewhere(n)){this.refuse(e,Nv,"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=Et(r,a),c=d.reduce((R,k)=>R+k.ids.length,0),l=r.targetOrgId,u=this.deps.infraServices?.productionGuard;if(!u){this.recordNotRemoved(e,r,"stopped",{code:Re.code}),this.refuse(e,Re.message,Re.code);return}let{check:p,decision:g}=await Ye(u,{orgId:l,orgTier:this.tierOf(l),operation:"delete",objectName:d.map(R=>R.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}`,St.blocked):this.refuse(e,"Operation cancelled by user (confirmation declined).",St.declined,!0);return}if(o?.signal.aborted){this.recordNotRemoved(e,r,"stopped",{guard:g,code:ft});let R={runId:r.runId,status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(T(this.deps,e,"seed:remove:response",{result:R,operationId:e.id}));return}let h=e.id,f=`Removing ${c} record(s) a Seed run created`,m=new AbortController,y=()=>{},b=new Promise((R,k)=>{y=I=>I===void 0?R():k(I)});b.catch(()=>{}),ze(this.deps,h,"seed",f),this.registry?.register(h,"seed",f,b,m),this.liveTracker?.register(h,"seed",f,c);let v,w;try{let R=await q(l,this.deps.orgRegistry,this.deps.orgManager);w=n.sweep?await this.sweepOfRemoval({conn:R,run:r,includeChanged:i,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,signal:m.signal,guard:u,operationId:h}):void 0;let k=w;await k?.ask();let I;if(n.muteAutomation===!0){let Y=[...new Set(d.map(me=>me.objectApiName))],Q=Ko({setToDraft:Vt(Y),delete:tn(Y)},k?.takes??[]),U=Q.delete??[],G=this.targetAutomation,pe=await new fe(Mv).withTimeout("seed:remove automation",()=>G.read(r.targetOrgId,U)).catch(me=>({unread:A(me)}));I=await mt(async()=>Pt(R),pe,{...this.muteLeases,writes:Yr(Q)})}let S,C=I?.muted,O=async()=>{let Y=I?.prepared;!Y||m.signal.aborted||(S=await Y.acquire(h),C=S.outcome)},P=Xt(R,"seed:remove"),_=await ia(P,r.created),{result:J,notes:B}=await $i({run:r,org:P,includeChanged:i,...a?{again:a}:{},store:t,...k?{sweep:Y=>k.first(Y),afterRemoval:Y=>k.afterRemoval(Y),automationMade:k.automationMade}:{},...r.runUserId?{runUserId:r.runUserId}:{},onUndeletable:xr(this.deps,l,"seed:remove"),beforeFirstWrite:O,signal:m.signal,onProgress:(Y,Q,U)=>{let G=Math.min(100,Math.round(Y/Math.max(Q,1)*100));Le(this.deps,h,G,Y,Q,U),m.signal.aborted||this.registry?.updateProgress(h,G),this.liveTracker?.updateProgress(h,G,Y,Q,U)}}).finally(async()=>{S&&(C=await S.release())}),re=await w?.settle(),H=J.status==="cancelled"?{}:await _.take();for(let Y of[...B,...H.note?[H.note]:[]])this.deps.log(`[WARN] seed:remove ${h}: ${Y}`);let j={runId:J.runId,status:oo(J.status,re),includeChanged:J.includeChanged,objects:H.object?[...J.objects,H.object]:J.objects,finishedAt:J.finishedAt,...J.leftBy?{leftBy:J.leftBy}:{},...re?{sweep:re}:{},...C?{mutedAutomation:C}:{}};K(this.deps,{action:"cleanup_delete",module:"seed",operationId:h,orgId:l,outcome:so(J),guard:g,objects:rn(j.objects),...j.leftBy?{leftBy:j.leftBy}:{},...C?{muted:ot(C)}:{},details:{runId:r.runId}});let N=T(this.deps,e,"seed:remove:response",{result:j,operationId:h});this.deps.broker.postToWebview(N),this.deps.log(`[TX] ${N.type} id=${N.id} status=${j.status}`),j.status==="cancelled"||j.sweep?.status==="cancelled"?(ge(this.deps,h,{aborted:!0}),this.liveTracker?.cancel(h)):(ge(this.deps,h,{status:j.status}),j.status==="failure"?(v=new Error("Nothing this run created could be removed."),this.liveTracker?.fail(h,"Nothing this run created could be removed.")):j.status==="partial"?this.liveTracker?.partial(h):this.liveTracker?.complete(h))}catch(R){v=R,await w?.settle().catch(()=>{});let k=kt(R)?R:void 0;this.recordNotRemoved(e,r,k?"stopped":"failure",{guard:g,...k?{code:k.code}:{}}),E(this.deps,"seed:remove","seed:remove:error",e,R,{code:k?.code??"REMOVE_ERROR",retryable:!0}),ge(this.deps,h,{status:"failure"}),this.liveTracker?.fail(h,A(R))}finally{y(v)}}};var ad="sync:history:all",$v="syncHistory";var dd=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(ad,n,$v)}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(ad,r,$v),!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(`
|
|
10
|
-
`)}clear(){this.configStore.delete(ad)}loadAll(){let e=this.configStore.get(ad);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 sE=/^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+:/;function iE(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))sE.test(r)||e.includes(r)?t++:e.push(r);return t===0?{...s,errors:e}:{...s,errors:e,refusalsDropped:(s.refusalsDropped??0)+t}}var cd=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(iE)},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 aE={Report:"ReportFolder",Dashboard:"DashboardFolder",EmailTemplate:"EmailTemplateFolder"},dE=new Set(["compare:execute","compare:permissions","compare:snapshots","compare:drift","compare:validate-deployment","compare:deploy"]),cE=5;function lE(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 ld=class{constructor(e,t={}){this.deps=e;this.options=t}deps;options;validations=new Map;async handle(e){if(!dE.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=D(vh,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-IZQZ6ZUF.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=D(Sh,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-IZQZ6ZUF.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});K(this.deps,{action:"metadata_deploy",module:"compare",operationId:e.id,orgId:r.targetOrgId,outcome:d.success?"success":"failure",guard:n,objects:lE(d),source:{origin:"org",orgId:r.sourceOrgId}}),this.post(T(this.deps,e,"compare:deploy:response",{report:d}),d)}catch(o){n&&K(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 Iy,i=this.deps.orgManager.getOrg(t),a={orgId:t,orgTier:Te(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 Ye(o,a);if((c==="refused"||c==="declined")&&K(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>cE;){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-IZQZ6ZUF.mjs");return e instanceof t?"STILL_RUNNING":"DEPLOY_ERROR"}async handleCompareStart(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(as,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,b=async R=>{t?.throwIfAborted();let k=await m.metadata.list(R);return De(m.limitInfo,`compare:metadata list ${String(f)}`),Array.isArray(k)?k:[]},v=aE[f],w=v?(await b([{type:v}])).map(R=>({type:f,folder:R.fullName})):[{type:f}];for(let R=0;R<w.length;R+=3)for(let k of await b(w.slice(R,R+3)))y.set(k.fullName,JSON.stringify(k));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=D(Oi,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 Tt(f,"SELECT Id, Name, Label, IsOwnedByProfile FROM PermissionSet WHERE IsOwnedByProfile = false");De(f.limitInfo,`compare:permissions ${m}`);let b=await Tt(f,"SELECT Id, Name FROM Profile");return De(f.limitInfo,`compare:permissions profiles ${m}`),{permSets:y,profiles:b}},[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=D(Oi,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();De(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=D(Oi,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 Tt(g,"SELECT Name, LanguageLocaleKey, DefaultLocaleSidKey, TimeZoneSidKey, FiscalYearStartMonth FROM Organization LIMIT 1");if(De(g.limitInfo,`compare:drift companyInfo ${h}`),m[0])for(let[y,b]of Object.entries(m[0]))y!=="attributes"&&y!=="Id"&&(f[`Organization.${y}`]=String(b));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 AE}from"node:crypto";function Lv(s,e,t){return s==="delete"?{...lt(e),deleted:t.done,failed:t.failed}:{...lt(e),updated:t.done,failed:t.failed}}async function ud(s,e,t){let r=crypto.randomUUID(),n=s.infraServices?.productionGuard;if(!n)return K(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,outcome:"stopped",code:Re.code}),{ran:!1,operationId:r,code:Re.code,message:Re.message};let o=s.orgManager.getOrg(e.orgId),{check:i,decision:a}=await Ye(n,{orgId:e.orgId,orgTier:Te(o),operation:e.operation,objectName:e.objectNames.join(", "),recordCount:e.recordCount,module:"dataops"}),d=a;if(a==="refused"||a==="declined")return K(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=Kt(t,r,"dataops",e.description,e.recordCount),g=[],h=0;try{let f=await e.run((b,v)=>{g.push({objectApiName:b,counts:v}),h+=v.done+v.failed;let w=Math.min(100,Math.round(h/Math.max(e.recordCount,1)*100)),R=`${b}: ${v.done} done, ${v.failed} refused`;Le(s,r,w,h,e.recordCount,R),p.progress(w,h,e.recordCount,R)},c.signal);await e.beforeEnd?.();let m=wl(f),y=c.signal.aborted;if(K(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,...y?m.done+m.failed>0?{outcome:"cancelled"}:{outcome:"stopped",code:et}:{outcome:m.status},...d?{guard:d}:{},objects:f.map(b=>Lv(e.operation,b.objectApiName,b.counts))}),y)return s.infraServices?.backgroundRegistry?.abort(r),ge(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(ge(s,r,{status:m.status,done:m.done,failed:m.failed}),m.status==="failure"){let b=`The org refused the ${m.failed} record(s)`;p.fail(b),l(new Error(b))}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=A(f);return K(s,{action:e.action,module:"dataops",operationId:r,orgId:e.orgId,outcome:"failure",...d?{guard:d}:{},objects:g.map(y=>Lv(e.operation,y.objectApiName,y.counts))}),je(s,r,m,!0,{context:{module:"dataops",operation:e.origin,objectName:e.objectNames.join(", ")}}),p.fail(m),l(f),{ran:!0,operationId:r,outcome:{...wl(g),status:"failure"},...d?{guard:d}:{},error:m}}}var Fv=100;async function pE(s,e,t){let r=new Map,n=[],o=t.map(a=>Fe(a.name)).filter(a=>a!=="Id"),i=[];for(let a=0;a<o.length;a+=Fv)i.push(o.slice(a,a+Fv));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 gE(s,e,t){let r,n;try{if(r=Jt.parse(await s.describe(Fe(t))),n=Fe(r.name),r.queryable===!1)throw new Error(`${n} cannot be queried.`)}catch(h){return{status:"failed",objectApiName:t,message:A(h)}}let o=fs(e,n,r.fields),i=new Set(o.map(h=>h.field.name)),a=r.fields.filter(h=>yy(h)&&wy(h)||i.has(h.name)),d=[],c;try{d=await pE(s,n,a)}catch(h){c=A(h)}let l=c?o:fs(e,n,r.fields,d),u=e.getPatterns(),p=l.map(h=>{let f=by(h.field),m=d.map(b=>b[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(Li).length,...y?{matched:m.filter(b=>typeof b=="string"&&y.test(b)).length}:{},...f?{searchedFor:f}:{}}}).sort((h,f)=>f.filled-h.filled||h.label.localeCompare(f.label)),g=Ry(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 _v(s,e,t,r=()=>new Date){let n=r().toISOString(),o=[];for(let i of t.objects)o.push(await gE(s,e,i));return{orgId:t.orgId,scannedAt:n,sampleSize:200,objects:o}}async function fE(s,e,t,r){let n=t.fields.filter(my).map(d=>d.name),o=await Zr(s,t.name,n,r),i=fs(e,t.name,t.fields,o),a=Sy(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 Uv(s,e,t,r){let n=[],o;for(let i of r){let a=Jt.parse(await s.describe(Fe(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 fE(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 Ti(s);let c=await Ei(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 pd(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 hE(s,e){return e.map(t=>({objectApiName:s,fieldApiName:t.field.name,method:t.method,config:{}}))}async function Bv(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 Pi(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,hE(i.objectApiName,d)),u=[],p=0;c.forEach((g,h)=>{let f={Id:g.Id};for(let m of d)Li(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 Wm(s,i.objectApiName,u,n),a.done+=p}o.push({objectApiName:i.objectApiName,counts:a}),r?.(i.objectApiName,a)}return o}var Hv="dataops:subject-requests",mE="audit",yE=V({objectApiName:L(),done:Me().int().nonnegative(),failed:Me().int().nonnegative()}),wE=Zs("kind",[V({kind:vt("searched"),at:L(),searchedBy:Se(Ke(["email","phone","name"])),objects:Se(V({objectApiName:L(),found:Me().int().nonnegative(),truncated:Je()}))}),V({kind:vt("exported"),at:L(),records:Me().int().nonnegative()}),V({kind:vt("erased"),at:L(),mode:Ke(["anonymize","delete"]),outcome:Ke(["success","partial","failure","stopped"]),operationId:L(),objects:Se(yE)})]),bE=V({requestId:L().min(1),orgId:L().min(1),openedAt:L(),events:Se(wE)}),gd=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(Hv);return Array.isArray(e)?e.flatMap(t=>{let r=bE.safeParse(t);return r.success?[r.data]:[]}):[]}write(e){this.configStore.set(Hv,e.slice(-this.limit),mE)}};function vE(s){return Xc(s).slice(-8)}function SE(s){return`%${s.split("").join("%")}%`}function qv(s,e){return typeof s=="string"&&s.trim().toLowerCase()===e.trim().toLowerCase()}function kE(s,e,t){let r=Fe(s.name);if(e==="email"&&t.email){let n=t.email.trim();return{field:s,kind:e,soql:`${r} = '${zt(n)}'`,matches:o=>qv(o,n)}}if(e==="phone"&&t.phone){let n=vE(t.phone);return{field:s,kind:e,soql:`${r} LIKE '${SE(n)}'`,matches:o=>typeof o=="string"&&Xc(o).includes(n)}}if(e==="name"&&t.name){let n=t.name.trim();return{field:s,kind:e,soql:`${r} = '${zt(n)}'`,matches:o=>qv(o,n)}}}async function OE(s,e,t){try{let r=Jt.parse(await s.describe(Fe(e))),n=Fe(r.name);if(r.queryable===!1)throw new Error(`${n} cannot be queried.`);let o=vy(r).flatMap(({field:g,kind:h})=>{let f=kE(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(Fe),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(!Nr(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:IE(A(r),t.identifiers)}}}function IE(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 Wv(s,e){let t=[];for(let r of e.objects)t.push(await OE(s,r,e));return t}var TE=6e4,EE=new Set(["dataops:pii-inventory","dataops:dsr:search","dataops:dsr:export","dataops:dsr:erase","dataops:dsr:log"]),PE=20;function CE(s){let e="payload"in s?s.payload:void 0;return typeof e=="object"&&e!==null&&"dryRun"in e?e.dryRun===!0:!1}function DE(s){return typeof s=="object"&&s!==null&&"success"in s&&s.success===!0}function xE(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)=>DE(i)?[r[a]?.Id]:[])),n}catch(n){throw Ty(n)==="may-have-written"&&e.wrote(t,r.map(o=>o.Id)),n}}}}function ME(s){return["email","name","phone"].filter(e=>s[e]!==void 0)}var fd=class{constructor(e,t){this.deps=e;this.saveDialog=t??new nn}deps;found=new Map;maskingKey=AE(32).toString("hex");saveDialog;writing=new Ey;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=xy;setDuplicatesSettle(e){this.duplicatesSettleMs=e}ownReader(){return this.reader??=import("./chunk-7YDNUBO5.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 gd(this.deps.configStore)}get detector(){return this.deps.infraServices?.piiDetector??new Fi}async session(e,t){let r=await q(e,this.deps.orgRegistry,this.deps.orgManager);return Ai(r,t)}async handle(e){if(!EE.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(CE(e)?void 0:Py(e,"orgId"),()=>this.handleErase(e)),!0;default:return this.handleLog(e),!0}}async handleInventory(e){let t=D(dh,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:pii-inventory"),n=await _v(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=D(ch,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 Wv(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:ME(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>PE;){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=D(lh,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=Jt.parse(await n.describe(u)),h=await Zr(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=D(ph,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((N,Y)=>{let Q=a.objects.get(Y.objectApiName);return N+Y.ids.filter(U=>!Q?.has(U)).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 Uv(c,this.detector,o,t.records),u=l.map(N=>N.plan),p=pd(u);if(i){let N=T(this.deps,e,"dataops:dsr:erase:response",{requestId:n,mode:o,dryRun:i,plan:u,written:p});this.deps.broker.postToWebview(N),this.deps.log(`[TX] ${N.type} id=${N.id} plan objects=${u.length}`);return}let g=u.filter(N=>!N.refused&&N.records>0),h=g.reduce((N,Y)=>N+Y.records,0);if(h===0){let N=u.flatMap(Y=>Y.refused?[Y.refused]:[]);throw new Error(N.length>0?`Nothing can be erased. ${N.join(" ")}`:"Nothing is left to erase: the records found are no longer in the org.")}let f=be(this.deps.orgManager.getOrg(r),r),m=await q(r,this.deps.orgRegistry,this.deps.orgManager),y=this.targetAutomation,b=await Lr({act:o==="delete"?"cleanup":"masking",target:f,objects:p,org:co(m,N=>new fe(TE).withTimeout("dataops automation",()=>y.read(r,N)),Te(this.deps.orgManager.getOrg(r))==="production"),accord:t,mayMute:!0,muteLeases:this.muteLeases,voice:"erasure"}),v=on(b.answer),w=v?{refused:v}:await xn(b,e.id,t.acceptEmails===!0,"erasure");if("refused"in w){let N=crypto.randomUUID();K(this.deps,{action:"subject_erase",module:"dataops",operationId:N,orgId:r,outcome:"stopped",code:w.refused.code}),this.requestLog.record(n,r,{kind:"erased",at:new Date().toISOString(),mode:o,outcome:"stopped",operationId:N,objects:[]}),E(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(w.refused.message),{code:w.refused.code,...v?Bi(v):{}});return}let R=w.held,k={},I=async()=>{if(!(!R||k.back)){k.back=await R.release();for(let N of Ut(k.back,f))this.deps.log(`[INFO] ${N}`)}},S=o==="anonymize"?jy({query:async N=>m.query(N),serverTime:async()=>(await m.soap.getServerTimestamp()).timestamp},My(b.answer.automation,p.map(N=>N.objectApiName)),{settleMs:this.duplicatesSettleMs}):void 0,C={},O=async()=>{await I(),!C.read&&(C.read=!0,C.duplicates=await S?.read())},P=()=>$y(C.duplicates,f,"erasure"),_=()=>R?{mutedAutomation:k.back??R.outcome}:{},J=new Hy(void 0,this.maskingKey),B=await ud(this.deps,{orgId:r,operation:o==="delete"?"delete":"update",objectNames:g.map(N=>N.objectApiName),recordCount:h,action:"subject_erase",description:`Erase ${h} record(s) of a subject request`,origin:"dataops:dsr:erase",run:(N,Y)=>Bv(S?xE(c,S):c,J,l,N,Y),beforeEnd:O},this.liveTracker).finally(I),re=new Date().toISOString();if(!B.ran){this.requestLog.record(n,r,{kind:"erased",at:re,mode:o,outcome:"stopped",operationId:B.operationId,objects:[]}),E(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(B.message),{...B.code?{code:B.code}:{},extraPayload:_()});return}this.requestLog.record(n,r,{kind:"erased",at:re,mode:o,outcome:B.outcome.status,operationId:B.operationId,objects:B.outcome.objects});let{duplicates:H}=C;if(B.error!==void 0){let N=P();E(this.deps,"dataops:dsr:erase","dataops:error",e,new Error(N?`${B.error} ${N}`:B.error),{...B.cancelled?{code:et}:{},extraPayload:{..._(),...H?{duplicates:H}:{}}});return}let j=T(this.deps,e,"dataops:dsr:erase:response",{requestId:n,mode:o,dryRun:i,plan:u,outcome:B.outcome,..._(),...H?{duplicates:H}:{}});this.deps.broker.postToWebview(j),this.deps.log(`[TX] ${j.type} id=${j.id} ${B.outcome.status} done=${B.outcome.done} failed=${B.outcome.failed}`),Ny(H)&&ke(this.deps,"warning","Erase",P())}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 jE=new Set(["User","Group","RecordType","BusinessHours","Profile","UserRole"]);function Xv(s){return s.type==="reference"&&_m(s)&&s.nillable===!0&&s.filterable===!0&&s.referenceTo?.length===1&&!jE.has(s.referenceTo[0])}function Kv(s,e){return e>0&&s/e>=.9}async function NE(s,e,t){let r,n,o;try{if(r=Jt.parse(await s.describe(Fe(e.objectApiName))),n=Fe(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:A(p)}}let i=r.fields.filter(yl).sort((p,g)=>p.label.localeCompare(g.label)),a=r.fields.filter(Xv),[d,c,l]=await Promise.all([Um(s,n,a,o),Bm(s,n,i,e.duplicateKey,o),qm(s,n,r.fields,t,o)]),u=d.fields.filter(p=>Kv(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 Yv(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 NE(s,o,e.staleDays));return{orgId:e.orgId,staleDays:e.staleDays,scannedAt:r,orphanThreshold:.9,bounds:{duplicateGroupLimit:$m,duplicateSample:Lm,singleFieldQueries:Fm},objects:n}}function $E(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 hu(s,e,t,r){let n=(s?.skip??0)+e;return e>0&&n<t?{skip:n,...r}:void 0}function Gv(s){return s.flatMap(e=>{let t=typeof e=="object"&&e!==null?e.Id:void 0;return Nr(t)?[t]:[]})}function LE(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 FE(s,e){let t=String(e??"");return typeof e=="string"&&s!=="date"?t.toLowerCase():t}var Jv=100,_E=2e3;async function UE(s,e,t,r){let n=Fe(e.name),o=Fe(t.name),i=await Hm(s,n,t.name),a=i.rows.reduce((u,p)=>u+p.count-1,0),d=i.rows.map(u=>LE(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+=Jv){let p=d.slice(u,u+Jv).join(", "),g=await s.query(`SELECT Id, ${o}${c?", LastModifiedDate":""} FROM ${n} WHERE ${o} IN (${p}) ORDER BY Id LIMIT ${_E}`),h=new Map;for(let f of g.records){if(typeof f!="object"||f===null)continue;let m=f;if(!Nr(m.Id))continue;let y=FE(t.type,m[t.name]),b=h.get(y)??[];b.push({id:m.Id,modified:typeof m.LastModifiedDate=="string"?m.LastModifiedDate:""}),h.set(y,b)}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 mu(s,e,t,r,n){let o=Jt.parse(await s.describe(Fe(e))),i=Fe(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?$E(n.modified):void 0,m=f!==void 0&&n?.id!==void 0&&Nr(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}`),b=Gv(y.records),v=y.records.at(-1),w=hu(n,b.length,h,{id:b.at(-1),...typeof v?.LastModifiedDate=="string"?{modified:v.LastModifiedDate}:{}});return{object:o,total:h,ids:b,truncated:(n?.skip??0)+b.length<h,...w?{next:w}:{}}}if(t.kind==="orphans"){let g=a(t.fieldApiName);if(!g||!Xv(g))throw new Error(`${t.fieldApiName} is not a lookup of ${o.label} that can leave a record without its parent.`);let h=Fe(g.name),f=(await s.query(`SELECT COUNT() FROM ${i}`)).totalSize,m=(await s.query(`SELECT COUNT() FROM ${i} WHERE ${h} = null`)).totalSize;if(!Kv(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&&Nr(n.id)?` AND Id > '${n.id}'`:"",b=await s.query(`SELECT Id FROM ${i} WHERE ${h} = null${y} ORDER BY Id LIMIT ${r}`),v=Gv(b.records),w=hu(n,v.length,m,{id:v.at(-1)});return{object:o,total:m,ids:v,truncated:(n?.skip??0)+v.length<m,...w?{next:w}:{}}}let d=a(t.keyField);if(!d||!yl(d))throw new Error(`${t.keyField} is not a field ${o.label} records can be grouped by.`);let c=n?.skip??0,l=await UE(s,o,d,c+r),u=l.ids.slice(c),p=hu(n,u.length,l.total,{});return{object:o,total:l.total,ids:u,truncated:c+u.length<l.total,...p?{next:p}:{}}}var BE=6e4,HE=new Set(["dataops:cleanup:scan","dataops:cleanup:export","dataops:cleanup:delete"]);function Zv(s){switch(s.kind){case"stale":return`stale-${s.days}d`;case"orphans":return`orphans-${s.fieldApiName}`;default:return`duplicates-${s.keyField}`}}var hd=class{constructor(e,t){this.deps=e;this.saveDialog=t??new nn}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-7YDNUBO5.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 Ai(r,t)}async handle(e){if(!HE.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=D(ah,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:cleanup:scan"),n=await Yv(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=D(gh,e,"dataops:error",this.deps);if(t)try{let r=await this.session(t.orgId,"dataops:cleanup:export"),n=await mu(r,t.objectApiName,t.recommendation,1e3,t.after),o=await Zr(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}-${Zv(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=D(fh,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 mu(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 I=await Ei(i,d,c,await Ti(i)),S={objectApiName:d.name,label:d.label,records:c.length,related:I.related,uncounted:I.uncounted},C=T(this.deps,e,"dataops:cleanup:delete:response",{objectApiName:t.objectApiName,dryRun:o,plan:S,truncated:a.truncated,written:pd([S])});this.deps.broker.postToWebview(C),this.deps.log(`[TX] ${C.type} id=${C.id} plan records=${c.length}`);return}if(c.length===0)throw new Error(`No ${d.label} record is left to delete for this recommendation.`);let l=await q(r,this.deps.orgRegistry,this.deps.orgManager),u=be(this.deps.orgManager.getOrg(r),r),p=this.targetAutomation,g=Ui(t),h=await Lr({act:"cleanup",target:u,objects:[{objectApiName:d.name,records:c.length}],org:co(l,I=>new fe(BE).withTimeout("dataops automation",()=>p.read(r,I)),Te(this.deps.orgManager.getOrg(r))==="production"),accord:t,mayMute:!0,muteLeases:this.muteLeases,...g?{voice:g}:{}}),f=on(h.answer);if(f){E(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(f.message),{code:f.code,...Bi(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,b={},v=async()=>{if(!(!y||b.back)){b.back=await y.release();for(let I of Ut(b.back,u))this.deps.log(`[INFO] ${I}`)}},w={objectApiName:d.name,label:d.label,records:c.length},R=await ud(this.deps,{orgId:r,operation:"delete",objectNames:[d.name],recordCount:c.length,action:"cleanup_delete",description:`Delete ${c.length} ${d.name} record(s): ${Zv(n)}`,origin:"dataops:cleanup:delete",run:async(I,S)=>{let C=await Pi(i,d.name,c,S);return I(d.name,C),[{objectApiName:d.name,counts:C}]},beforeEnd:v},this.liveTracker).finally(v);if(!R.ran){E(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(R.message),R.code?{code:R.code}:void 0);return}if(R.error!==void 0){E(this.deps,"dataops:cleanup:delete","dataops:error",e,new Error(R.error),R.cancelled?{code:et}:void 0);return}let k=T(this.deps,e,"dataops:cleanup:delete:response",{objectApiName:t.objectApiName,dryRun:o,plan:w,truncated:a.truncated,outcome:R.outcome,...y?{mutedAutomation:b.back??y.outcome}:{}});this.deps.broker.postToWebview(k),this.deps.log(`[TX] ${k.type} id=${k.id} ${R.outcome.status} deleted=${R.outcome.done} failed=${R.outcome.failed}`)}catch(i){E(this.deps,"dataops:cleanup:delete","dataops:error",e,i)}}};import{join as VP}from"node:path";async function eS(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=Xy(t,i),d=a.length>0?[...o,...await s.describe(a)]:o,c=Ky(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 tS(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 Ds="No record was read or deleted.",qE="Nothing was deleted.";function Cs(s,e){return{allowed:!1,refusal:{code:"PRODUCTION",message:`${s} is a production org, or cannot be told from one: ${e}. Emptying is for sandboxes, scratch orgs and Developer Edition orgs: SandForge never empties objects of a production org, and nothing lifts this. ${Ds}`}}}async function Fn(s,e){let{orgName:t,registered:r}=e;if(r===void 0)return Cs(t,"SandForge has no record of what kind of org it is");if(!Qn(r))return Cs(t,"SandForge has it registered as a production org");let n;try{n=await Zn(s)}catch(i){let a=Tg(i);return a!==void 0?{allowed:!1,refusal:{code:"ORG_UNTYPED",message:`${Eg(t,i,a)} SandForge empties no org it cannot tell from a production one. ${Ds}`}}:Cs(t,`it did not say what org it is (${A(i)})`)}if(Ag(n))return Cs(t,n.edition?`its Organization record says IsSandbox false, edition ${n.edition}`:"its Organization record says IsSandbox false, and no edition");let o=Te(r);return o==="production"?Cs(t,"SandForge has it registered as a production org"):o==="staging"&&e.mode==="org"?{allowed:!1,refusal:{code:"STAGING_ORG",message:`${t} is a sandbox marked Staging: it holds real data, and SandForge never empties the whole of it. Pick the objects to empty instead, which Production Guard asks about, or unmark it in Org Manager if it holds nobody's work. ${Ds}`}}:{allowed:!0,org:n,tier:o}}var rS=["PermissionsViewAllData","PermissionsModifyAllData","PermissionsBulkApiHardDelete"];async function xs(s){let e=async n=>(await s.query(`SELECT ${n.join(", ")} FROM UserPermissionAccess`)).records[0]??{},t,r;try{t=await e(rS)}catch(n){try{t=await e(rS.slice(0,2)),r=`whether the user has Bulk API Hard Delete could not be read: ${A(n)}`}catch(o){return{viewAllData:!1,modifyAllData:!1,hardDelete:!1,unread:A(o)}}}return{viewAllData:t.PermissionsViewAllData===!0,modifyAllData:t.PermissionsModifyAllData===!0,hardDelete:t.PermissionsBulkApiHardDelete===!0,...r!==void 0?{unread:r}:{}}}function yu(s){return{code:"HARD_DELETE_NOT_PERMITTED",message:"Deleting for good needs Bulk API Hard Delete, and the user SandForge deletes as "+(s.unread!==void 0?`could not be read to have it (${s.unread}). `:"doesn't have it: Salesforce refuses the job as it is opened. ")+"Give the user a permission set with Bulk API Hard Delete, or empty to the recycle bin, which Undo brings back. Nothing was deleted."}}var wu=60*6e4,nS=2e3,oS=/^005[A-Za-z0-9]{12}(?:[A-Za-z0-9]{3})?$/;async function bu(s,e,t,r){let n=t.filter(l=>oS.test(l)).map(l=>l.slice(0,15)),o=n.length>0?` AND LastModifiedById NOT IN (${n.map(l=>`'${l}'`).join(", ")})`:"",i=new Map,a=[],d=!1;for(let l of e){let u=Fe(l);try{let p=await s.query(`SELECT LastModifiedById, LastModifiedDate FROM ${u} WHERE LastModifiedDate >= ${r}${o} LIMIT ${nS}`);p.records.length>=nS&&(d=!0);for(let g of p.records){let{LastModifiedById:h,LastModifiedDate:f}=g;if(typeof h!="string"||!oS.test(h))continue;let m=h.slice(0,15),y=typeof f=="string"&&!Number.isNaN(Date.parse(f))?f:"",b=i.get(m);if(!b){i.set(m,{userId:h,records:1,lastChangedAt:y});continue}b.records+=1,y!==""&&(b.lastChangedAt===""||Date.parse(y)>Date.parse(b.lastChangedAt))&&(b.lastChangedAt=y)}}catch(p){a.push(`${l}: ${A(p)}`)}}let c=[...i.keys()].sort();return{people:c.map(l=>i.get(l).userId),...d?{atLeast:!0}:{},who:c.map(l=>i.get(l)),unread:a}}var WE=200;async function sS(s,e){let t=e.who.map(o=>o.userId).slice(0,WE);if(t.length===0)return e;let r;try{r=(await s.query(`SELECT Id, Name FROM User WHERE Id IN (${t.map(o=>`'${o}'`).join(", ")})`)).records}catch{return e}let n=new Map;for(let o of r){let{Id:i,Name:a}=o;typeof i=="string"&&typeof a=="string"&&a.trim()!==""&&n.set(i.slice(0,15),a.trim())}return{...e,who:e.who.map(o=>{let i=n.get(o.userId.slice(0,15));return i!==void 0?{...o,name:i}:o})}}function zE(s){let e;for(let t of s)t.lastChangedAt!==""&&(e===void 0||Date.parse(t.lastChangedAt)>Date.parse(e))&&(e=t.lastChangedAt);return e}function Ru(s,e,t={}){if(t.accepted===!0)return;let r=new Set((t.accepted??[]).map(l=>l.slice(0,15))),n=e.people.filter(l=>!r.has(l.slice(0,15)));if(n.length===0)return;let o=n.length,i=`${e.atLeast?"At least ":""}${o} ${o===1?"person":"people"}`,a=zE(e.who.filter(l=>n.includes(l.userId))),d=r.size>0?" the preview did not name":"",c=t.voice==="page"?"or tick the box that lets their work go, to empty all the same":"or add --accept-people-active to empty all the same";return{code:"PEOPLE_ACTIVE",message:`${i}${d} other than the user SandForge deletes as changed records of these objects in ${s} in the last hour${a!==void 0?`, the last at ${a}`:""}: emptying them would take their work. Empty once they have stopped, ${c}. `+qE}}var GE=1e4,aS={bulkDestroy:()=>Promise.reject(new Error("an estimate sends no job"))};function vu(s){return us(aS,s,1,"hard")}var dS=9,JE=25;function cS(s,e,t){let r=e>0&&us(aS,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/Mt),jobs:[],toTheBin:!0};let n=Math.ceil(e/ls),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 br(s,e){return{apiRequests:s,seconds:s*e}}function Ms(s){return s.reduce((e,t)=>({apiRequests:e.apiRequests+t.apiRequests,seconds:e.seconds+t.seconds}),{apiRequests:0,seconds:0})}function lS(s){return Math.max(1,Math.ceil(s/Il))}function uS(s){return s.notSent?{apiRequests:0,seconds:0}:Ms([br(lS(s.records),Mn),br(1,ws),br(s.restCalls,Vi),...s.jobs.map(e=>({apiRequests:Vm({stateReads:Km(e)}),seconds:Xm(e)}))])}function VE(s){return s<=0?{apiRequests:0,seconds:0}:Ms([br(1,ws),br(Math.ceil(s/Il),Mn),br(Math.ceil(s/Mt),Vi),br(Math.ceil(s/Mt),Mn)])}function XE(s){if(s<=0)return{apiRequests:0,seconds:0};let e=Math.ceil(s/Mt);return Ms([br(e,Vi),br(e,Mn)])}var KE=.05,iS={check:2,connect:3};function md(s,e,t,r=0){let n=t*iS.check+iS.connect,o=t*e+n+s.apiRequests+r,i=Math.ceil(o*KE);return{apiRequests:o+i,seconds:e*ws+s.seconds,requests:{reads:e,readings:t,passes:s.apiRequests,margin:i,connecting:n,...r>0?{mute:r}:{}}}}function pS(s){let e=s.passes.map(({objectApiName:d,records:c})=>cS(d,Math.max(0,c),s.mode)),t=Ms([VE(s.toDraft),br(s.draftReads??0,Mn),...e.map(uS),...(s.refused??[]).map(XE)]),r=md(t,Math.max(0,s.reads),s.readings??2),n=e.reduce((d,c)=>d+c.jobs.reduce((l,u)=>l+Math.ceil(u/GE),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*JE,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:sn(r.apiRequests,s.apiBudget),...a?{batches:s.bulkBatches?sn(n,s.bulkBatches):{verdict:"unread",estimate:n,unread:"the limits the org answered list no DailyBulkApiBatches"}}:{}}}function gS(s,e,t,r=0){let n=Ms(e.map(o=>{let i=cS(o.objectApiName,Math.max(0,o.records),s),a=uS(i);if(!o.idsRead||i.notSent)return a;let d=lS(i.records);return{apiRequests:a.apiRequests-d,seconds:a.seconds-d*Mn}}));return md(n,Math.max(0,t),1,Math.max(0,r)).apiRequests}var Su=3;function fS(s,e,t=0){return md({apiRequests:Math.max(0,s),seconds:0},Math.max(0,e),1,Math.max(0,t)).apiRequests}function hS(s,e,t,r=0){let n={apiRequests:s.requests.passes,seconds:s.seconds-s.requests.reads*ws},o=md(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:sn(o.apiRequests,i)}}var YE=Vy.extend({relationshipName:L().nullish(),polymorphicForeignKey:Je().optional()}),mS=zi.extend({deletable:Je().optional(),fields:Se(YE)});function ku(s){return Aw.has(s)}var yS={pricebook2:{field:"IsStandard",value:!0}};function wS(s){let e=yS[s.toLowerCase()];return e?`${e.field} = ${String(e.value)}`:void 0}function _n(s){let e=yS[s.toLowerCase()];return e?`${e.field} = ${String(!e.value)}`:void 0}var QE=new Set(["pricebook2","product2"]);function bS(s,e){return e!==void 0&&s.childSObject!==void 0&&s.field!==void 0&&Jy(s.childSObject,s.field,e)?"restricted":s.cascadeDelete===!0?"cascade":s.restrictedDelete===!0?"restricted":"lookup"}function Ou(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)?yd(s,i,o.field):void 0;RS(a,r)||t.push({parent:r,child:e(o.childSObject),field:o.field,kind:bS(o,r)})}return t}var js=5,ZE=8;function RS(s,e){if(s?.polymorphicForeignKey===!0)return!1;let t=s?.referenceTo??[];return t.length>0&&!t.some(r=>r.toLowerCase()===e.toLowerCase())}function eP(s,e,t){let r=yd(s,e,t);return(r?.referenceTo?.length??0)>1||r?.polymorphicForeignKey===!0}function Iu(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 b=o(m);if(!b){l.add(m);continue}for(let v of b.childRelationships??[]){if(bS(v,m)!=="cascade")continue;let w=n(v.childSObject),k=o(w)?.fields.find(O=>O.name.toLowerCase()===v.field.toLowerCase());if(RS(k,m))continue;let I=w.toLowerCase();if(!a.has(I)||I===m.toLowerCase()||y.some(O=>O.object.toLowerCase()===I))continue;let S=[{object:w,field:v.field,parent:m},...y],C=d.get(w)??[];if(S.length>1&&C.length>=ZE){u(w,m);continue}d.set(w,[...C,{object:w,steps:S,emptied:f}]),!(i.has(I)||S.length>=js)&&h.push({top:f,from:w,above:S})}}p=h}for(let h=!0;h;){h=!1;for(let[f,m]of d)for(let y of m)for(let[b,v]of y.steps.entries())b===0||!c.has(v.object)||y.steps.slice(0,b).some(R=>eP(t,R.object,R.field))||c.get(f)?.has(v.object)||(u(f,v.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 Ao(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 tP(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 yd(s,e,t){let r=t.toLowerCase();return s.get(e)?.fields.find(n=>n.name.toLowerCase()===r)}function wd(s,e,t=_n,r=()=>{}){let n=[],o=(i,a,d,c)=>tP({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=yd(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&&!QE.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>=js)return o(`${g} != null`,!1,g,a.parent);n.push(l)}}function vS(s,e,t){let r=[];for(let[n,o]of s.entries()){let i=e.has(o.object)?yd(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>=js)return;r.push(i.relationshipName)}}function Ns(s,e,t=_n,r){let n=s.map(a=>wd(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 SS(s,e,t,r,n,o=_n,i){let a={object:s,field:e,parent:t};if(r.emptied.has(t))return wd([a],n,o,i);let d=(r.routes.get(t)??[]).map(c=>({object:s,steps:[a,...c.steps],emptied:c.emptied}));return Ns(d,n,o,i)}var IS=4,kS=100,rP=/^[A-Za-z0-9]+$/;function OS(s,e){let t=_n(s);if(t!==void 0)return t;if(e&&s.toLowerCase()===sr.toLowerCase())return`${ys} = false`}var qn="stopped before the org was asked";function AS(s,e,t="COUNT()"){let r=ku(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 ${Fe(s)}${o}`,all:r}}var Hn=class{statements=new Map;answers=new Map;ask(e,t){let r=AS(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:qn});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:A(d)})}}),IS),r}answer(e){return this.answers.get(e)??{unread:qn}}},vd=class{statements=new Map;answers=new Map;ask(e,t){let r=AS(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:qn}});return}try{let i=await e.readIds(n,o),a=i.ids.filter(d=>rP.test(d));this.answers.set(n,{counted:{records:i.totalSize},...a.length===i.totalSize?{ids:a}:{}})}catch(i){this.answers.set(n,{counted:{unread:A(i)}})}}),IS),r}answer(e){return this.answers.get(e)??{counted:{unread:qn}}}};function Eu(s,e){return s.records===void 0?s:e.records===void 0?{unread:e.unread??qn}:{records:Math.max(0,s.records-e.records),...e.atMost?{atLeast:!0}:{}}}function Au(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 hn(s){return s.records===0&&s.atLeast!==!0}function Un(s){return s===void 0||s.records===void 0||s.records>0}function Rd(s){return{unread:`${s}: the lookup its records go by is hidden from the user`}}function Pu(s){return s.records===void 0?s:{...s,atLeast:!0}}function $s(s){return s.records===void 0?s:{...s,atMost:!0}}function Tu(s,e){let t=e.key?s.answer(e.key):Rd(e.objectApiName),r=e.going?Eu(t,s.answer(e.going)):t,n=(r.records??0)>0;return e.more&&n&&(r={...r,atLeast:!0}),e.under&&n&&(r=Pu(r)),e.over&&n&&(r=$s(r)),r}function Cu(s,e){return s.every(t=>e.get(t.emptied)!=="unnamed"&&t.steps.every(r=>e.get(r.parent)!=="unnamed"))}function nP(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 Bn(s){let e=s.filter(n=>n.records!==void 0);if(e.length===0)return s.length===0?{records:0}:{unread:s[0].unread??qn};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 bd="Pricebook2";function oP(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 TS(s,e,t=()=>!1,r={undo:!0}){let{affected:n,order:o,relations:i,describes:a}=s,d=o.passes.map(x=>x.objectApiName),c=a.get(sr)?.fields.some(x=>x.name===ys)===!0,l=x=>{let M=OS(x,c);if(!(x.toLowerCase()===sr.toLowerCase()&&n.emptied.has(eo)))return M},u=x=>{let M=l(x);return M===void 0?[]:[M]},p=new Map,g=x=>p.get(x),h=x=>g(x),f=x=>wd(x,a,l,h),m=x=>Ns(x,a,l,h),y=(x,M,F)=>SS(x,M,F,n,a,l,h),b=new Hn,v=new Map;for(let x of d)v.set(x,b.ask(x,u(x)));let w=await b.run(e,t),R=new Map(d.map(x=>[x,b.answer(v.get(x)??"")])),k=x=>[...Ao(x,n)].some(M=>Un(R.get(M))),I=x=>x.filter(M=>Un(R.get(M.emptied))),S=x=>!n.emptied.has(x)&&n.routesCut.has(x),C=new Hn,O=[];for(let{parent:x,child:M,field:F,kind:W}of i){if(W!=="restricted"||M===x||n.emptied.has(M)||!k(x))continue;let ae=y(M,F,x),z=n.routes.has(M)?m(I(n.routes.get(M)??[])):void 0;O.push({objectApiName:M,field:F,parent:x,...ae?{key:C.ask(M,[ae])}:{},...ae&&z?{going:C.ask(M,[z,ae])}:{},...z&&S(M)?{over:!0}:{},...n.emptied.has(x)&&!n.routes.has(M)?{naming:""}:{}})}for(let{child:x,field:M,parent:F,rows:W}of Ol){if(W===void 0||!k(F)||n.emptied.has(x)||!n.routes.has(x))continue;let z=a.get(x)?.fields.some($e=>$e.name===W.field)===!0?y(x,M,F):void 0;if(!z)continue;let ue=`${W.field} = ${String(W.value)}`;O.push({objectApiName:x,field:M,parent:F,key:C.ask(x,[ue,z]),along:!0,...n.emptied.has(F)?{naming:ue}:{}})}w=await C.run(e,t)||w;let P=new vd,_=new Map,J=new Map;O.forEach((x,M)=>{if(x.naming===void 0||x.key===void 0||(Tu(C,x).records??0)===0)return;let F=`Id IN (SELECT ${Fe(x.field)} FROM ${Fe(x.objectApiName)}${x.naming!==""?` WHERE ${x.naming}`:""})`;_.set(M,P.ask(x.parent,[...u(x.parent),F])),J.set(x.parent,[...J.get(x.parent)??[],F])}),w=await P.run(e,t)||w;for(let x of J.keys()){let M=[..._].filter(([W])=>O[W].parent===x).map(([,W])=>P.answer(W));if(M.every(W=>W.counted.records===0))continue;let F=new Set(M.flatMap(W=>W.ids??[]));p.set(x,M.every(W=>W.ids!==void 0)&&F.size<=kS?[...F]:"unnamed")}let B=x=>{let M={archived:new Map,kept:new Map,goneBefore:new Map,along:new Map,refusals:[],undoLost:[]};for(let z of o.passes){let ue=z.objectApiName;if(!Un(R.get(ue)))continue;let $e=u(ue);ku(ue)&&M.archived.set(ue,x.ask(ue,[...$e,"IsArchived = true"]));let Ne=wS(ue);Ne!==void 0&&M.kept.set(ue,x.ask(ue,[Ne]));let se=I(z.goneBefore);if(se.length>0){let xe=m(se);M.goneBefore.set(ue,xe?{key:x.ask(ue,[...$e,xe]),unreadable:!1}:{unreadable:!0})}let we=r.undo?I(z.sentBeforeTheirParent):[];for(let xe of we){let Xe=f(xe.steps),Ue=xe.steps[0],it=Xe?[...$e,Xe]:void 0;M.undoLost.push({objectApiName:ue,field:Ue.field,parent:Ue.parent,reason:"unordered",...it?{key:x.ask(ue,it),conditions:it}:{}})}}for(let z of n.along){let ue=I(n.routes.get(z)??[]);if(ue.length===0)continue;let $e=ue.map(se=>{let we=f(se.steps);return{route:se,...we?{key:x.ask(z,[we])}:{}}}),Ne=ue.length>1?m(ue):void 0;M.along.set(z,{...Ne?{total:x.ask(z,[Ne])}:$e[0].key?{total:$e[0].key}:{},via:$e})}let F=z=>o.passes.findIndex(ue=>ue.objectApiName===z);for(let z of r.undo?o.beforeParent:[]){if(z.reason==="customPrices"){if(!k(bd)||!k(z.parent)||F(bd)>F(z.parent))continue;let se=y(z.objectApiName,"Pricebook2Id",bd),we=y(z.objectApiName,z.field,z.parent),xe=se&&we?[se,we]:void 0;M.undoLost.push({objectApiName:z.objectApiName,field:z.field,parent:z.parent,reason:"restricted",...xe?{key:x.ask(z.objectApiName,xe),conditions:xe}:{},...S(bd)||S(z.parent)?{under:!0}:{}});continue}if(!k(z.objectApiName)||!k(z.parent))continue;let ue=y(z.objectApiName,z.field,z.parent),$e=[];if(!n.emptied.has(z.objectApiName)){let se=m(I(n.routes.get(z.objectApiName)??[]));se&&$e.push(se)}let Ne=S(z.objectApiName)||S(z.parent);M.undoLost.push({objectApiName:z.objectApiName,field:z.field,parent:z.parent,reason:"restricted",...ue?{key:x.ask(z.objectApiName,[...$e,ue]),conditions:[...$e,ue]}:{},...Ne?{under:!0}:{}})}for(let{child:z,field:ue,parent:$e,rows:Ne}of Ol){if(Ne===void 0||!k($e)||!n.emptied.has(z))continue;let we=a.get(z)?.fields.some(Xe=>Xe.name===Ne.field)===!0?y(z,ue,$e):void 0;if(!we||!r.undo||!Un(R.get(z)))continue;let xe=`${Ne.field} = ${String(Ne.value)}`;M.undoLost.push({objectApiName:z,field:ue,parent:$e,reason:"restricted",key:x.ask(z,[xe,we]),conditions:[xe,we],more:!0})}let W=(z,ue,$e,Ne=!1)=>{M.refusals.push({code:z,objectApiName:ue,key:x.ask(ue,$e),...Ne?{under:!0}:{}})};for(let z of o.toDraft){if(!k(z))continue;let ue="StatusCode != 'Draft'";if(n.emptied.has(z)){W("activatedOrder",z,[ue]);continue}let $e=I(n.routes.get(z)??[]),Ne=m($e);W(Cu($e,p)?"activatedOrder":"activatedOrderLeft",z,Ne?[Ne,ue]:[{soql:ue,exact:!1}],Ne!==void 0&&S(z))}for(let[z,ue]of M.kept)M.refusals.push({code:"standardPriceBook",objectApiName:z,key:ue});n.emptied.has(hi)&&Un(R.get(hi))&&(n.emptied.has(sr)||W("directContactRelation",hi,[{soql:"IsDirect = true",exact:!n.routes.has(sr)}]));let ae=a.get(sr);return n.emptied.has(sr)&&!n.emptied.has(eo)&&Un(R.get(sr))&&ae?.fields.some(z=>z.name===ys)===!0&&W("personAccountContact",sr,[`${ys} = true`]),M},re=new vd,H=new Map;if(p.size>0){let x=new Set;g=M=>(n.emptied.has(M)||x.add(M),p.get(M)),B(new Hn),g=M=>p.get(M);for(let M of[...x].sort()){let F=I(n.routes.get(M)??[]),W=F.filter(ue=>p.has(ue.emptied));if(W.length===0)continue;let ae=p.get(W[0].emptied),z=F.length===1&&Array.isArray(ae)?vS(F[0].steps,a,ae):void 0;z===void 0?p.set(M,"unnamed"):H.set(M,re.ask(M,[z]))}w=await re.run(e,t)||w;for(let[M,F]of H){let W=re.answer(F);p.set(M,W.ids!==void 0&&W.ids.length<=kS?W.ids:"unnamed")}}let j=new Hn,N=B(j);w=await j.run(e,t)||w;let Y=x=>Tu(j,x),Q=new Hn,U=new Map;for(let[x,M]of J)M.length===2&&p.get(x)==="unnamed"&&U.set(x,Q.ask(x,[...u(x),...M]));let G=new Map,pe=new Map;for(let x of N.undoLost)pe.set(x.objectApiName,[...pe.get(x.objectApiName)??[],x]);for(let[x,M]of pe){let F=M.filter(ae=>!hn(Y(ae)));if(F.length<2)continue;let W=F.map(ae=>ae.conditions);W.some(ae=>ae===void 0)||G.set(x,Q.ask(x,[nP(W)]))}w=await Q.run(e,t)||w;let me=O.map((x,M)=>{let F=_.get(M);return{objectApiName:x.objectApiName,field:x.field,parent:x.parent,records:Tu(C,x),...F!==void 0?{keeps:P.answer(F).counted}:{}}}).filter(x=>!hn(x.records)),ne=x=>{let M=me.flatMap(z=>z.parent===x&&z.keeps!==void 0?[z.keeps]:[]);if(M.length===0)return;let F=p.get(x);if(Array.isArray(F))return{records:F.length};let W=Bn(M),ae=U.get(x);return ae!==void 0?Au(W,Q.answer(ae)):M.length>1&&(W.records??0)>0?$s(W):W},he=me.filter(x=>!Array.isArray(p.get(x.parent))&&O.some(M=>M.along===!0&&M.objectApiName===x.objectApiName&&M.field===x.field&&M.parent===x.parent)),qe=me.filter(x=>O.some(M=>M.along===!0&&M.objectApiName===x.objectApiName&&M.field===x.field&&M.parent===x.parent)),Ie=o.passes.map(x=>{let M=x.objectApiName,F=OS(M,c),W=R.get(M)??{unread:qn};if(!Un(W))return{objectApiName:M,...F!==void 0?{rows:F}:{},records:W,sent:W};let ae=N.goneBefore.get(M),z=ae===void 0?W:ae.unreadable||ae.key===void 0?Rd(M):n.routesCut.has(M)?$s(Eu(W,j.answer(ae.key))):Eu(W,j.answer(ae.key)),ue=N.archived.get(M),$e=N.kept.get(M),Ne=ne(M);return{objectApiName:M,...F!==void 0?{rows:F}:{},records:W,sent:z,...ue?{archived:j.answer(ue)}:{},...$e?{kept:j.answer($e)}:{},...Ne&&!hn(Ne)?{blocked:Ne}:{}}}),ce=r.undo?Ie.filter(x=>a.get(x.objectApiName)?.undeletable===!1&&!hn(x.sent)).map(x=>({objectApiName:x.objectApiName,reason:"notRestorable",records:x.sent})):[],oe=[...N.along].map(([x,{total:M,via:F}])=>{let W=M?j.answer(M):Rd(x),ae=n.routesCut.get(x),z=he.filter(we=>we.objectApiName===x),ue=qe.filter(we=>we.objectApiName===x),$e=z.length>0?Bn(z.map(we=>we.records)):void 0,Ne=ue.length>0?Bn(ue.map(we=>we.records)):void 0,se=$e?Au(W,$e):W;return{objectApiName:x,records:ae?Pu(se):se,via:F.map(({route:we,key:xe})=>{let Xe=xe?j.answer(xe):Rd(x),Ue=we.steps[0],it=z.filter(Be=>Be.field===Ue.field&&Be.parent===Ue.parent);return{field:Ue.field,parent:Ue.parent,emptied:we.emptied,records:it.length>0?Au(Xe,Bn(it.map(Be=>Be.records))):Xe}}).filter(we=>!hn(we.records)),...Ne&&!hn(Ne)?{blocking:Ne}:{},...ae?{routesNotRead:[...ae]}:{}}}).filter(x=>!hn(x.records)),le=(x,M)=>x.map(F=>({...M(F),records:Y(F)})).filter(F=>!hn(F.records)),Ae=oP([...le(N.undoLost,x=>({objectApiName:x.objectApiName,...x.field!==void 0?{field:x.field}:{},...x.parent!==void 0?{parent:x.parent}:{},reason:x.reason})),...ce]),Z=new Map;for(let x of Ae)Z.set(x.objectApiName,[...Z.get(x.objectApiName)??[],x]);let ve=Bn([...Z].map(([x,M])=>{let F=G.get(x),W=M.filter(z=>z.reason==="notRestorable");if(F===void 0){let z=Bn(M.map(ue=>ue.records));return M.length>1&&(z.records??0)>0?$s(z):z}let ae=Q.answer(F);return M.some(z=>z.reason!=="notRestorable"&&z.records.atLeast)&&(ae.records??0)>0&&(ae=Pu(ae)),W.length>0?$s(Bn([ae,...W.map(z=>z.records)])):ae}));return{objects:Ie,along:oe,refusals:le(N.refusals,x=>({code:x.code,objectApiName:x.objectApiName})),blockers:me,undoLost:Ae,undoLostRecords:ve,kept:p,statements:b.size+C.size+P.size+re.size+j.size+Q.size,...w?{stopped:!0}:{}}}var CS={lookup:0,cascade:1,restricted:2,customPrices:2},ES="Pricebook2",Du="Product2",PS="PricebookEntry";function sP(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 Ao(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=Ao(i,s),l=s.emptied.has(i)?[i]:[...c],u=!1;for(let p of Ao(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(ES)&&s.emptied.has(Du)&&(t.push({first:ES,then:Du,reason:"customPrices"}),n(PS)&&r.push({objectApiName:PS,field:"Product2Id",parent:Du,reason:"customPrices"})),{constraints:t,beforeParent:r}}function iP(s){return Object.hasOwn(CS,s)}function DS(s,e){let{constraints:t,beforeParent:r}=sP(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=tf(n,i,({field:u})=>{let p=iP(u)?u:"lookup";return{first:p==="cascade"?"parent":"child",firmness:CS[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:aP(t.filter(({first:u,then:p})=>!c(u,p))),toDraft:Vt([...n,...s.along])}}function aP(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 dP(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 cP=(s,e,t)=>{let r=Ew(s,e,"empty",t.customSettings?{customSettings:Zg}:{});return{candidates:r.candidates,leftOut:r.leftOut.map(({objectApiName:n,reason:o,detail:i})=>({objectApiName:n,reason:dP(o),...i===void 0?{}:{detail:i}}))}},lP=new Set([Yg,Qg].map(s=>s.toLowerCase()));function xS(s,e){return s.objectApiName<e.objectApiName?-1:s.objectApiName>e.objectApiName?1:0}function uP(s,e){if(s.customSetting===!0&&e.customSettings!==!0)return"customSetting";if(lP.has(s.name.toLowerCase())&&e.files!==!0)return"files";if(ef(s.name)!==void 0&&e.managedPackages!==!0)return"managedPackage";if(s.undeletable===!1&&e.unrestorable!==!0)return"notRestorable"}function Sd(s,e,t,r=cP){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=uP(p,t);h===void 0?d.push(p.name):c.push({objectApiName:p.name,reason:h})}}return d.sort(),c.sort(xS),{mode:t.mode,objects:d,leftOut:c,worked:[...n.candidates].sort()}}function MS(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(xS)}}async function xu(s,e,t,r){await cs(e.map(n=>async()=>{try{t.set(n,mS.parse(await s.describe(n)))}catch(o){r.set(n,A(o))}}),6)}function gP(s,e){if(e!=="hard")return s;let t=s.objects.filter(r=>!vu(r));return t.length===0?s:{...s,objects:s.objects.filter(vu),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 Wn(s){return s.records}async function jS(s,e){let t=Sd(s.global,s.tooling,s.request,s.rule),r=new Map,n=new Map;await xu(e,t.objects,r,n);let o=gP(MS(t,r,n),s.deleteMode),i=new Map([...t.worked,...s.global.map(S=>S.name)].map(S=>[S.toLowerCase(),S])),a=S=>i.get(S.toLowerCase())??S,d=Iu(o.objects,t.worked,r);for(let S=0;S<js;S++){let C=d.undescribed.filter(O=>!r.has(O)&&!n.has(O));if(C.length===0)break;await xu(e,C,r,n),d=Iu(o.objects,t.worked,r)}let c=S=>d.emptied.has(S)||d.routes.has(S),l=[...new Set(Ou(r,a).filter(({kind:S,parent:C,child:O})=>S==="restricted"&&c(C)&&!c(O)).map(({child:S})=>S))].filter(S=>!r.has(S)&&!n.has(S));await xu(e,l,r,n);let u=Ou(r,a),p=DS(d,u),g=await TS({affected:d,order:p,relations:u,describes:r},e,s.stopped,{undo:s.deleteMode==="recycle"}),h=[...g.objects.filter(S=>Wn(S.records)===void 0),...g.along.filter(S=>Wn(S.records)===void 0)].map(S=>S.objectApiName),f=[...g.objects.map(S=>Math.max(0,(Wn(S.records)??0)-(S.blocked?.records??0))),...g.along.map(S=>Wn(S.records)??0)].filter(S=>S>0),m=f.reduce((S,C)=>S+C,0),y=g.along.some(S=>S.records.atLeast===!0)||g.objects.some(S=>S.blocked?.atMost===!0),b=g.refusals.filter(S=>S.code==="activatedOrder").reduce((S,C)=>S+(Wn(C.records)??0),0),v=p.toDraft.filter(S=>!d.emptied.has(S)).map(S=>{let C=d.routes.get(S)??[];if(!Cu(C,g.kept))return{objectApiName:S};let O=Ns(C,r,void 0,P=>g.kept.get(P));return{objectApiName:S,...O?{condition:O.soql}:{}}}),w=S=>S.records===void 0||S.records>0,R=g.objects.filter(S=>w(S.records)).length+g.along.filter(S=>w(S.records)).length,k=dS+r.size+n.size+g.statements+2*R,I=pS({mode:s.deleteMode,passes:g.objects.map(S=>({objectApiName:S.objectApiName,records:Wn(Vt([S.objectApiName]).length>0?S.records:S.sent)??0})),toDraft:b,deleted:m,reads:k,draftReads:v.filter(S=>S.condition!==void 0).length,refused:g.blockers.map(S=>Wn(S.records)??0),...s.apiBudget?{apiBudget:s.apiBudget}:{},...s.bulkBatches?{bulkBatches:s.bulkBatches}:{},...s.dataStorageMB===void 0?{}:{dataStorageMB:s.dataStorageMB}});return{mode:t.mode,deleteMode:s.deleteMode,passes: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:v,cost:I,total:{records:m,objects:f.length,uncounted:h,...y?{atLeast:!0}:{}},statements:g.statements,...g.stopped?{stopped:!0}:{}}}var fP=5,hP=ls,kd=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!==ey};this.refused.has(r)||this.refused.size<hP?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=[...ty(this.objectApiName,e),...ry(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,fP)}}};async function NS(s,e,t){let{mode:r}=t,n=()=>t.signal?.aborted===!0,o=t.splitting??Ci(),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(b=>b.objectApiName===f);m=new kd(f,y?.count??0),a.push(m)}return m},u=async(f,m)=>{await ji(s,c,{note:(b,v,w,R)=>l(b).note(w?Mi(b,v,R,c):v)});let y=a.map(b=>b.result(o,f));if(f)for(let{objectApiName:b,count:v}of e.objects)y.some(w=>w.objectApiName===b)||y.push({...new kd(b,v).result(o,!1),...v>0?{notReached:v}:{}});return{hard:r==="hard",objects:y,cancelled:f,...m!==void 0?{hardRefused:m}:{}}},p=(f,m)=>ny(s,f.objectApiName,m,{mode:r,stopped:n,splitting:o,...t.signal?{signal:t.signal}:{},...t.wait?{wait:t.wait}:{},settle:(y,b)=>{let v=f.deleted+f.gone+f.refused.size+f.refusedUnkept;f.settle(y,b),t.onSettled?.(f.objectApiName,y,b),d+=f.deleted+f.gone+f.refused.size+f.refusedUnkept-v,t.onProgress?.(d,i,f.objectApiName)}});if(r==="hard"&&s.bulkHardDestroy===void 0)return u(!0,Zm);if(t.toDraft!==!1){let f=await xi(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),b=us(s,f,m,r),v=[],w=async()=>{let R=v;return v=[],p(y,R)};for await(let R of e.pages(f)){if(n())return u(!0);if(v.push(...R),b&&v.length<ls)continue;let k=await w();if(k.stopped)return u(!0,k.hardRefused)}if(v.length>0){if(n())return u(!0);let R=await w();if(R.stopped)return u(!0,R.hardRefused)}}let g;if(await oy(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:b}=await sy([...f.refused.keys()],v=>Zr(s,f.objectApiName,[],v),()=>!0);for(let v of m)f.refused.delete(v),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`+(b?` \u2014 ${b}`:"."))}return u(!1)}function mP(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 yP(s){return/CreatedDate/.test(A(s))}function Mu(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 wP(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 bP(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 $S(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 Gi,d=new Map;if(s.resumed){for await(let j of e.lines())if(j.kind==="settled"){for(let N of[...j.deleted,...j.gone])a.add(N);d.set(j.objectApiName,(d.get(j.objectApiName)??0)+j.deleted.length+j.gone.length)}}let c=new AbortController,l=s.signal?AbortSignal.any([s.signal,c.signal]):c.signal,u=()=>l.aborted,p,g=!1,h=mP(r.readAt),f=new Map(r.passes.map(j=>[j.objectApiName,j])),m=j=>f.get(j)?.rows??_n(j),y=new Map,b=new Map,v=()=>r.passes.reduce((j,N)=>j+Math.max(0,(b.get(N.objectApiName)??N.sent??N.records??0)-(d.get(N.objectApiName)??0)),0),w=async(j,N)=>{let Y=async Q=>{let U=await Tw(t.ids,j,[{objectApiName:N.objectApiName,...Q!==void 0?{filter:Q}:{}}],{signal:l});return U.stopped?void 0:U.spool};try{let Q=await Y(Mu([N.filter,N.own,h]));return Q?{spool:Q,sinceRead:!0}:void 0}catch(Q){if(!yP(Q))throw Q;i.push(`${N.objectApiName} has no CreatedDate: its records were read whole, those made after the preview among them.`);let U=await Y(Mu([N.filter,N.own]));return U?{spool:U,sinceRead:!1}:void 0}},R=j=>{let N=y.get(j);if(N)return N;let Y=(async()=>{let Q=r.passes.findIndex(qe=>qe.objectApiName===j),U=e.idsDirOf(Q,j),G=o.spooled.get(j);if(s.resumed&&G)return b.set(j,G.count),{spool:await Ji.open(U,Qi),count:G.count,sinceRead:G.sinceRead};if(u())return;let pe=m(j),me=await w(U,{objectApiName:j,...pe!==void 0?{own:pe}:{}});if(!me)return;let ne=me.spool.count,he=f.get(j)?.records;if(he!==void 0&&ne>he){p={code:"ORG_CHANGED",message:`${j} now holds ${ne.toLocaleString("en-US")} records to delete, where the preview counted ${he.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:j,place:Q,count:ne,sinceRead:me.sinceRead}),b.set(j,ne),{spool:me.spool,count:ne,sinceRead:me.sinceRead}})();return y.set(j,Y),Y},k={objects:r.passes.map(j=>({objectApiName:j.objectApiName,count:j.sent??j.records??0})),pages:j=>({async*[Symbol.asyncIterator](){let N=await R(j);if(N)for await(let Y of N.spool.pages(j)){let Q=a.size>0?Y.filter(U=>!a.has(U)):Y;Q.length>0&&(yield Q)}}})},I=Promise.resolve(),S,C=(j,N,Y)=>{let Q=[],U=[];N.forEach((G,pe)=>{let me=Y[pe]?.kind;me==="deleted"?Q.push(G):me==="gone"&&U.push(G)}),Q.length>0&&(g=!0),Q.length+U.length!==0&&(I=I.then(async()=>{if(S===void 0)try{await e.settled(j,Q,U)}catch(G){S=A(G),c.abort()}}))},O=[];for(let[j,N]of r.toDraftAlong.entries()){if(N.condition===void 0||u())continue;let Y=e.idsDirOf(r.passes.length+j,N.objectApiName),Q=await w(Y,{objectApiName:N.objectApiName,filter:N.condition});if(!Q)break;let{drafted:U}=await xi(t.deletion,[{objectApiName:N.objectApiName}],Q.spool,()=>!0,u,async()=>new Set);O.push(...U)}let P=await NS(t.deletion,k,{mode:r.deleteMode,signal:l,...s.splitting?{splitting:s.splitting}:{},...s.wait?{wait:s.wait}:{},onSettled:C,onProgress:(j,N,Y)=>{let Q=Math.max(j,v());s.onProgress?.({percentage:Q>0?Math.min(99,Math.round(j/Q*100)):99,step:`${Y}: ${j.toLocaleString("en-US")} of about ${Q.toLocaleString("en-US")} settled`})}}).finally(async()=>{await I,await ji(t.deletion,O,{note:(j,N,Y,Q)=>i.push(Mi(j,N,Q,O))})});S!==void 0&&i.push(`The journal of this emptying could not be written (${S}): it stopped there, so that its Undo misses nothing it deleted.`);let _=new Map;for(let[j,N]of y)_.set(j,await N.catch(()=>{}));let J=P.objects.map(j=>wP(j,_.get(j.objectApiName),f.get(j.objectApiName)?.records,P.cancelled));if(!P.cancelled)for(let j of J){if(!_.get(j.objectApiName)?.sinceRead)continue;let Y=m(j.objectApiName),Q=h.replace("CreatedDate <","CreatedDate >=");try{let U=await t.deletion.query(`SELECT COUNT() FROM ${Fe(j.objectApiName)} WHERE ${Mu([Y,Q])}`);U.totalSize>0&&(j.madeSince=U.totalSize)}catch(U){i.push(`Whether ${j.objectApiName} records were made after the preview could not be read: `+A(U))}}let B=P.cancelled&&p===void 0&&S===void 0,re=p!==void 0||S!==void 0?g?"partial":"failure":bP(J,B,P.hardRefused,s.resumed&&o.deletedAny),H=J.reduce((j,N)=>j+N.refused,0);return s.resumed&&re==="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:re,hard:P.hard,passes:J,...P.hardRefused!==void 0?{hardRefused:P.hardRefused}:{},...p!==void 0?{changed:p}:{},deletedAny:g,notes:i}}var RP=/Entity is not in the recycle bin/,vP=/INSUFFICIENT_ACCESS/,SP=5,LS=5e4;function Od(s){return s.slice(0,15)}function ju(s){let e=new Set;for(let t of s){let r=t?.Id;typeof r=="string"&&e.add(Od(r))}return e}function kP(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 OP(s){return{objectApiName:s,planned:0,undeleted:0,alreadyBack:0,notInBin:0,othersDeletion:0,refused:0,reasons:[]}}function Ls(s,e){s.reasons.length<SP&&!s.reasons.includes(e)&&s.reasons.push(e)}async function*IP(s,e,t){let r=t?new Gi: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 Ji.open(s.idsDirOf(t.place,e),Qi);for await(let o of n.pages(e)){let i=o.filter(a=>!r.has(a));i.length>0&&(yield i)}}async function FS(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 _S(s,e){let t=s.spooledIn.get(e);return t!==void 0&&s.unendedAttempt!==void 0&&t.attempt===s.unendedAttempt?t:void 0}function AP(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 US(s){let e=await FS(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/Mt)*Su);let o=_S(e,r);o&&(n+=o.count,t+=Math.ceil(o.count/Mt)*Su);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)/Mt)}return t}async function BS(s){let{journal:e,org:t}=s,r=e.head,n=[],o=()=>s.signal?.aborted===!0,i=await FS(e),a=[],d=new Map,c=!1,l=[...r.passes].reverse();for(let[f,{objectApiName:m}]of l.entries()){let y=OP(m);a.push(y);let b=Fe(m),v=_S(i,m);for await(let w of IP(e,m,v)){y.planned+=w.length;for(let R=0;R<w.length;R+=Mt){let k=w.slice(R,R+Mt);if(c||o()){c=!0,y.notReached=(y.notReached??0)+k.length;continue}let[I]=ds(k,Mt),S,C;try{S=ju((await t.queryDeleted(`SELECT Id FROM ${b} WHERE Id IN (${I}) AND IsDeleted = true`)).records),C=ju((await t.query(`SELECT Id FROM ${b} WHERE Id IN (${I})`)).records)}catch(_){y.refused+=k.length,Ls(y,`The recycle bin could not be read: ${A(_)}`);continue}let O=k.filter(_=>S.has(Od(_)));for(let _ of k)S.has(Od(_))||(C.has(Od(_))?y.alreadyBack++:(y.notInBin++,Ls(y,"No longer in the recycle bin, nor in the org: emptied from the bin, or pushed out of it.")));if(O.length===0)continue;let P;try{let _=await s.undelete(O),J=Array.isArray(_)?_:[_];P=O.map((B,re)=>J[re]??{success:!1})}catch(_){let J=A(_);P=O.map(()=>({success:!1,errors:[J]}))}P.forEach((_,J)=>{if(_.success===!0){y.undeleted++;return}let B=kP(_);if(RP.test(B)){y.notInBin++;let re=d.get(m)??[];re.length<LS&&re.push(O[J]),d.set(m,re),Ls(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 vP.test(B)?(y.othersDeletion++,Ls(y,`Deleted by another user than the one bringing it back: only Modify All Data brings back another's deletions (${B})`)):(y.refused++,Ls(y,B))})}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 ${LS.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=Fe(f.objectApiName);try{let b=0;for(let w of ds(m,Mt)){let R=await t.query(`SELECT Id FROM ${y} WHERE Id IN (${w})`);b+=ju(R.records).size}let v=Math.min(b,f.notInBin);f.notInBin-=v,f.alreadyBack+=v}catch(b){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 (${A(b)}): they are counted as not back.`)}}let u=i.wentThrough?AP(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 er="Nothing was deleted.";function Ad(s){return{query:e=>s.query(e),queryMore:e=>s.queryMore(e)}}var Nu=V({Max:Me(),Remaining:Me()}).loose(),TP=V({DailyApiRequests:Nu.optional(),DailyBulkApiBatches:Nu.optional(),DataStorageMB:Nu.optional()}).loose();async function EP(s){try{let e=TP.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:A(e)}}}}async function qS(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 Fu(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 PP(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 CP(s,e){let t=[];for(let r of e)try{let n=zi.safeParse(await s.describe(r));n.success&&t.push(n.data)}catch{}return t}function WS(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. ${er}`}}function To(s,e={}){let[t,...r]=s;return{ran:!1,refusal:t,...r.length>0?{alsoRefused:r}:{},...e}}async function $u(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 yr)return;throw o}let n=await r.state();return n.open?{runId:t.runId,startedAt:n.head.startedAt,journal:r}:void 0}function zS(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. ${er}`}}function DP(s){return s.reason==="notRestorable"?`${s.objectApiName}, which Salesforce does not bring back`:`${s.objectApiName} before ${s.parent??"their parent"}`}function GS(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 xP(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=GS(s),r=`${t.atLeast?"at least ":""}${t.records.toLocaleString("en-US")}`,n=[...new Set(e.map(DP))],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. "+er}}function MP(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. ${er}`}),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. ${er}`}),t}function Id(s){return s.records}function jP(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=Id(o.records);if(!i){(a===void 0||a>0)&&t.push(`${o.objectApiName} is now emptied too`);continue}a===void 0&&Id(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=Id(o.records),d=i?Id(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=>GS(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 HS(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. ${er}`}}function Lu(s,e,t){let r=t.automation?Dr(t.automation,t.mutePlan,Yr(t.steps)):{firing:[]};return{module:"empty",written:Fu(e),running:{firing:r.firing},request:{},orgId:s.orgId,operationId:s.operationId}}async function JS(s,e){let{org:t,orgName:r}=s,n=s.requestsSent?.()??0,o=Ad(t),i=await Fn(o,{orgName:r,registered:s.registered,mode:e.request.mode});if(!i.allowed)return{previewed:!1,refusal:i.refusal};let a=await KS(s,e.request,e.deleteMode),d=await Lr({act:"empty",target:r,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{},...XS(a.preview)}),c=await $u(s.store,i.org.id),l=e.checkpointFirst===!0&&s.checkpoints?await s.checkpoints.scope(Lu(s,a.preview,d.answer),{operationId:s.operationId}):void 0,u=s.requestsSent!==void 0?s.requestsSent()-n:void 0,p=VS(a,u,2,$r(d.mute?.plan)),g={previewId:NP(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:$P(p.people),...l?{checkpoint:l}:{},...c?{openRun:{runId:c.runId,startedAt:c.startedAt}}:{}},h=await QS(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 VS(s,e,t,r){let n=e??s.preview.cost.requests.reads;return{...s,preview:{...s.preview,cost:hS(s.preview.cost,n,t,r)}}}function NP(s){return Jl(s).replace(/^em-/,"ep-")}function XS(s){let e=PP(s);return{objects:e.objects,writes:{steps:e.steps,written:e.written}}}async function KS(s,e,t){let{org:r}=s,n=Ad(r),o=await r.serverTime(),i=V({sobjects:Se(wi)}).loose().parse(await r.describeGlobal()).sobjects,a=await r.toolingObjects(),d=await EP(r),c=await jS({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 xs(n),u=Fu(c),p=new Set(i.filter(b=>b.customSetting===!0).map(b=>b.name)),g=await eS({permissions:l,objects:u,customSettings:u.filter(b=>p.has(b)),grants:async()=>Yy(n,()=>r.userId()),describe:b=>CP(r,b)}),h=await r.userId(),f=new Date(Date.parse(o)-wu).toISOString(),m=await bu(r,u,[h,...await qS(r)],f),y=s.voice==="page"?await sS(r,m):m;return{readAt:o,preview:c,permissions:l,access:g,people:y}}function $P(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 YS(s){return s.voice==="page"?"page":"flags"}async function QS(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(zS(s.orgName,r.open)),t.preview.stopped&&n.push({code:"PREVIEW_STOPPED",message:`The preview was stopped before every count was in: preview again. ${Ds}`}),r.deleteMode==="hard"&&!t.permissions.hardDelete&&n.push(yu(t.permissions));let i=Ru(s.orgName,t.people,{...r.peopleAccepted!==void 0?{accepted:r.peopleAccepted}:{},voice:YS(s)});i&&n.push(i);let a=r.acceptNoUndo?void 0:xP(t.preview);a&&n.push(a),n.push(...MP(t.preview,s.orgName)),r.checkpoint?.refusal&&n.push({...r.checkpoint.refusal});let d=on(r.automation);return d&&n.push({code:d.code,message:d.message},...d.alsoRefused),n}function LP(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 FP(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 _P(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 UP(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 BP(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 ZS(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=Ad(t),a=await Fn(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 $u(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. ${er}`}};if(c=l.journal,c.head.mode==="org"&&a.tier==="staging"){let O=await Fn(i,{orgName:r,registered:s.registered,mode:"org"});if(!O.allowed)return{ran:!1,refusal:O.refusal}}}else if(e.confirmed&&e.confirmed.organizationId.slice(0,15)!==d.slice(0,15))return{ran:!1,refusal:HS(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 KS(s,u.request,p);let O=[...jP(u.preview,h.preview),...tS(u.access,h.access).map(P=>`the user is no longer proven to see every record of ${P}`)];if(O.length>0&&g.push(HS(r,O)),h.preview.total.records===0&&h.preview.total.uncounted.length===0&&O.length===0)return{ran:!0,result:LP(n())};f=await Lr({act:"empty",target:r,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{},...XS(h.preview)}),e.checkpointFirst===!0&&(m=s.checkpoints?await s.checkpoints.scope(Lu(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. ${er}`})),h=VS(h,s.requestsSent!==void 0?s.requestsSent()-o:void 0,1,$r(f.mute?.plan)),g.push(...await QS(s,d,h,{deleteMode:p,acceptNoUndo:e.acceptNoUndo===!0,...e.acceptPeopleActive===!0?{peopleAccepted:(u.peopleActive.who??[]).map(P=>P.userId)}:{},automation:f.answer,...m?{checkpoint:m}:{},...l?{open:l.runId}:{}}))}else{let O=c.head,P=await xs(i);p==="hard"&&!P.hardDelete&&g.push(yu(P));let _=await s.runWriting?.(d);_!==void 0&&g.push({code:"RUN_WRITING",message:_});let J=O.passes.map(Q=>Q.objectApiName),B=await t.userId(),re=await t.serverTime(),H=await bu(t,J,[B,...await qS(t)],new Date(Date.parse(re)-wu).toISOString()),j=Ru(r,H,{...e.acceptPeopleActive===!0?{accepted:!0}:{},voice:YS(s)});j&&g.push(j);let N=O.passes.map(Q=>({objectApiName:Q.objectApiName,records:Q.sent??Q.records??0})).filter(Q=>Q.records>0);f=await Lr({act:"empty",target:r,objects:N,org:s.automation,accord:e.accord,mayMute:!0,...s.muteLeases?{muteLeases:s.muteLeases}:{},...s.voice?{voice:s.voice}:{}});let Y=on(f.answer);Y&&g.push({code:Y.code,message:Y.message},...Y.alsoRefused),y=gS(p,await UP(c),s.requestsSent!==void 0?s.requestsSent()-o:0,$r(f.mute?.plan))}if(g.length>0)return To(g);let b=u&&h?h.preview:void 0,v=b?b.total.records:c.head.passes.reduce((O,P)=>O+(P.records??0),0),w=b?Fu(b):c.head.passes.map(O=>O.objectApiName),R=await s.askGuard({operation:p==="hard"?"hardDelete":"delete",objectNames:w,recordCount:v});if(R.decision==="refused"||R.decision==="declined")return To([{code:"GUARD",message:R.decision==="refused"?`Production Guard refused the emptying: ${R.reason??"no reason given"}. ${er}`:`The emptying was declined at Production Guard's confirmation. ${er}`}],{guard:R.decision});let k=R.decision,I;if(m&&s.checkpoints&&b){let O=await s.checkpoints.take(Lu(s,b,f.answer),{operationId:s.operationId},{planned:m,...s.signal?{signal:s.signal}:{},onProgress:({percentage:P})=>s.onProgress?.(Math.round(P/10),`Taking the checkpoint first (${Math.round(P)}%)`)});if(!O.taken)return To(["stopped"in O?{code:"CANCELLED",message:`The emptying was stopped while its checkpoint was taken. ${er}`}:{code:O.refusal.code,message:O.refusal.message}],{guard:k});I=O.checkpoint}let S=async O=>{if(!I||I.state!=="taken"||!s.checkpoints)return I;try{return await s.checkpoints.settle(I,O)}catch{return I}},C=s.lock(d);if("busy"in C)return await S(!1),To([WS(r,C.busy)],{guard:k});try{let O=await $u(s.store,d);if(!c&&O)return await S(!1),To([zS(r,O.runId)],{guard:k});let P=await xn(f,s.operationId,e.accord.acceptEmails===!0,s.voice);if("refused"in P)return await S(!1),To([{code:P.refused.code,message:P.refused.message}],{guard:k});let _=P.held,J=n(),B=c??await s.store.begin(d,{runId:Jl(J),orgName:r,startedAt:J.toISOString(),readAt:u.readAt,previewId:u.previewId,mode:b.mode,deleteMode:p,request:FP(u.request),passes:b.passes.map(ne=>({objectApiName:ne.objectApiName,...ne.records.records!==void 0?{records:ne.records.records}:{},...ne.sent.records!==void 0?{sent:ne.sent.records}:{},...ne.rows!==void 0?{rows:ne.rows}:{}})),toDraftAlong:b.toDraftAlong,beforeParent:b.beforeParent,...p==="recycle"?{undoLost:_P(b)}:{}}),re=b&&b.cost.api.verdict!=="unread"?Di(b.cost.api).splitAllowance:void 0,H,j,N=[];try{H=await $S({org:{deletion:t,ids:t},journal:B,resumed:c!==void 0,...s.signal?{signal:s.signal}:{},splitting:Ci(re),now:n,onProgress:({percentage:ne,step:he})=>s.onProgress?.(ne,he)})}catch(ne){throw await B.ended("failure",[],n()).catch(()=>{}),ne}finally{let ne=t.lostJobs?.()??[];if(ne.length>0&&t.stillRunning){let he=await t.stillRunning(ne);he.length>0&&N.push(`${he.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.`)}_&&(j=await _.release(),N.push(...Ut(j,r).map(he=>he.trim())))}let Y=H.passes,Q=n();await B.ended(H.status,Y,Q,H.hardRefused);let U=await S(H.deletedAny),G=[];if(H.status==="success"||H.status==="partial")for(let ne of await s.store.runsOf(d))ne.runId>=B.head.runId||(await s.store.remove(d,ne.runId),G.push(ne.runId));let pe=await B.state();return{ran:!0,result:{runId:B.head.runId,status:H.status,hard:H.hard,passes:Y,totals:BP(Y),...H.hardRefused!==void 0?{hardRefused:H.hardRefused}:{},undo:H.hard?{offered:!1,why:"hard"}:pe.deletedAny?{offered:!0}:{offered:!1,why:"nothingDeleted"},...c?{resumed:!0}:{},notes:[...H.notes,...H.changed?[H.changed.message]:[],...N],...j?{mutedAutomation:j}:{},...U?{checkpoint:U}:{},...G.length>0?{removedRuns:G}:{},...s.requestsSent!==void 0?{requestsSent:s.requestsSent()-o}:{},...y!==void 0?{requestsEstimate:y}:{},startedAt:J.toISOString(),finishedAt:Q.toISOString()},guard:k}}finally{C.lock.release()}}async function ek(s,e){let{org:t,orgName:r}=s,n=s.now??(()=>new Date),o=s.requestsSent?.()??0,i=Ad(t),a=await Fn(i,{orgName:r,registered:s.registered,mode:"objects"});if(!a.allowed)return{ran:!1,refusal:a.refusal};let d=a.org.id,c=(w,R)=>({ran:!1,refusal:{code:w,message:`${R} Nothing was brought back.`}}),l;try{l=await s.store.open(d,e.runId)}catch(w){if(w instanceof yr)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 Lr({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=on(m.answer);if(y&&h.push({code:y.code,message:y.message},...y.alsoRefused),h.length>0){let[w,...R]=h;return{ran:!1,refusal:w,...R.length>0?{alsoRefused:R}:{}}}let b=fS(await US(l),s.requestsSent!==void 0?s.requestsSent()-o:0,$r(m.mute?.plan)),v=s.lock(d);if("busy"in v)return{ran:!1,refusal:WS(r,v.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 R,k;try{k=await BS({org:t,undelete:S=>t.undelete(S),journal:l,...s.signal?{signal:s.signal}:{},onProgress:({percentage:S,step:C})=>s.onProgress?.(S,C)})}finally{w.held&&(R=await w.held.release())}let I=n();return k.status!=="cancelled"&&await l.undone(k.status,I),{ran:!0,result:{runId:e.runId,status:k.status,objects:k.objects,notes:[...k.notes,...R?Ut(R,r).map(S=>S.trim()):[]],...R?{mutedAutomation:R}:{},...s.requestsSent!==void 0?{requestsSent:s.requestsSent()-o}:{},requestsEstimate:b,...k.previewedLost?{previewedLost:k.previewedLost}:{},finishedAt:I.toISOString()}}}finally{v.lock.release()}}function HP(s){let e=En(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=Jm(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 tk(s,e,t){let r=pi(s),n=Qm(s,t),o=HP(s),i=[],a=new db(async(l,u)=>(await En(s).bulk2.job("ingest",{id:u}).check()).state),d=l=>async(u,p,g)=>{try{return await Ym(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 qP,readFile as WP,rm as rk,stat as nk,writeFile as zP}from"node:fs/promises";import{join as Td}from"node:path";var sk=/^ep-\d{8}-\d{6}-[a-z0-9]{4}$/,GP=50;function Ed(s){return sk.test(s)}var ok=V({records:Me().optional(),unread:L().optional()}).loose(),JP=V({v:vt(1),orgId:L().min(1),kept:V({previewId:L().regex(sk),readAt:L(),orgName:L(),organizationId:L().min(15).max(18),request:V({mode:Ke(["objects","org"])}).loose(),preview:V({mode:Ke(["objects","org"]),deleteMode:Ke(["recycle","hard"]),passes:Se(V({objectApiName:L(),records:ok}).loose()),along:Se(V({objectApiName:L(),records:ok}).loose()),undoLost:Se(V({objectApiName:L()}).loose()),total:V({records:Me()}).loose()}).loose(),access:V({kind:Ke(["org","perObject"])}).loose(),peopleActive:V({people:Me(),who:Se(V({userId:L()}).loose()).optional()}).loose()}).loose()}),Pd=class{constructor(e,t=qi){this.root=e;this.keepMs=t}root;keepMs;async keep(e,t,r=Date.now()){if(!Ed(t.previewId))throw new Error(`Not a preview's id: ${t.previewId}`);await Wi(this.root),await zP(Td(this.root,`${t.previewId}.json`),JSON.stringify({v:1,orgId:e,kept:t}),{mode:Hi}),await this.sweep(r)}async read(e,t=Date.now()){if(!Ed(e))return;let r=Td(this.root,`${e}.json`);try{if((await nk(r)).mtimeMs+this.keepMs<=t)return;let n=JP.safeParse(JSON.parse(await WP(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){Ed(e)&&await rk(Td(this.root,`${e}.json`),{force:!0})}async sweep(e){let t;try{t=await qP(this.root)}catch{return}let r=t.filter(o=>o.endsWith(".json")&&Ed(o.slice(0,-5))).sort(),n=Math.max(0,r.length-GP);for(let[o,i]of r.entries()){let a=Td(this.root,i);try{(o<n||(await nk(a)).mtimeMs+this.keepMs<=e)&&await rk(a,{force:!0})}catch{}}}};var XP=6e4,KP=20,Eo="dataops",YP=new Set(["dataops:empty:scope","dataops:empty:preview","dataops:empty:run","dataops:empty:cancel","dataops:empty:undo"]),Wr=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 QP(s){return s.passes.filter(e=>e.deleted+e.refused+(e.notReached??0)>0).map(e=>({...lt(e.objectApiName),deleted:e.deleted,failed:e.refused,...(e.notReached??0)>0?{notSent:e.notReached}:{}}))}function ZP(s){return s.objects.filter(e=>e.undeleted+e.notInBin+e.othersDeletion+e.refused>0).map(e=>({...lt(e.objectApiName),created:e.undeleted,failed:e.notInBin+e.othersDeletion+e.refused,...(e.notReached??0)>0?{notSent:e.notReached}:{}}))}function eC(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 Cd=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)=>tk(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(!YP.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-7YDNUBO5.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=Gy({root:Wy()});if("refusal"in e)throw new Wr({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 Sa(Vl()),previews:new Pd(VP(Vl(),"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=be(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(pi(m))),p),h=Ui(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:co(a,async m=>{let y=await g();return new fe(XP).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:Re.message};let{check:b,decision:v}=await Ye(y,{orgId:e,orgTier:Te(i),operation:m.operation,objectName:m.objectNames.join(", "),recordCount:m.recordCount,module:Eo});return{decision:v,...v==="refused"?{reason:b.blockedReason??b.impactSummary}:{}}},operationId:t,tool:"panel",...n?{signal:n}:{},...o?{onProgress:o}:{}}}fail(e,t,r){if(t instanceof Wr){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=D(hh,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 Fn(i,{orgName:o.orgName,registered:o.registered,mode:n.mode});if(!a.allowed)throw new Wr(a.refusal);let d=V({sobjects:Se(wi)}).loose().parse(await o.org.describeGlobal()).sobjects,c=Sd(d,await o.org.toolingObjects(),n),l=await xs(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>KP;){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<=qi?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=D(mh,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 JS(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 Wr(o.refusal);await this.keep(t.orgId,o.kept),this.respond(e,"dataops:empty:preview:response",{...eC(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=D(wh,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,Eo,r),c?.register(d,Eo,r,p,l);let g=Kt(this.liveTracker,d,Eo,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}:{}}),ge(this.deps,d,{status:"refused",code:m.refusal.code}),g.fail(m.refusal.message),u(new Error(m.refusal.message)),new Wr(m.refusal,m.alsoRefused??[],m.mutedAutomation);let{result:y}=m;if(o(y.status,{result:y,...m.guard?{guard:m.guard}:{}}),await i(y),y.status==="cancelled")c?.abort(d),ge(this.deps,d,{aborted:!0}),g.cancel(),u();else if(y.status==="failure"){let b="Nothing the emptying set out to do went through: its result says why.";ge(this.deps,d,{status:y.status}),g.fail(b),u(new Error(b))}else ge(this.deps,d,{status:y.status}),y.status==="success"?g.complete():g.partial(),u()}catch(f){throw f instanceof Wr||(o("failure",{}),ge(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=D(yh,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 Wr({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=>ZS(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)=>K(this.deps,{action:"cleanup_delete",module:Eo,operationId:e.id,orgId:t.orgId,outcome:o,...i.guard?{guard:i.guard}:{},...i.code!==void 0?{code:i.code}:{},...i.result?{objects:QP(i.result)}:{},...i.result?.mutedAutomation?{muted:ot(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=D(bh,e,"dataops:error",this.deps);if(t)try{await this.writeAct(e,t.orgId,`Undoing the emptying ${t.runId}`,r=>ek(r,{runId:t.runId,accord:t}),(r,n)=>K(this.deps,{action:"empty_undo",module:Eo,operationId:e.id,orgId:t.orgId,outcome:r,...n.code!==void 0?{code:n.code}:{},...n.result?{objects:ZP(n.result)}:{},...n.result?.mutedAutomation?{muted:ot(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 YC}from"node:os";var ik=6e4,tC=2*6e4,rC=50,nC=2880*6e4,oC=60*6e4,sC=250,ak="pipeline-triggers",iC=V({cron:L().optional(),timezone:L().optional(),nextRunAt:Me().optional(),lastFiredAt:Me().optional(),lastOutcome:Ke(["started","missed"]).optional()});function Fs(s,e){return`pipeline-trigger:${s}:${e}`}var Dd=class{constructor(e){this.deps=e;this.now=e.now??(()=>Date.now()),this.newId=e.newId??(()=>globalThis.crypto.randomUUID())}deps;engine=new gR;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: ${A(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>=oC&&(this.lastPrune=e,this.deps.claims.prune(nC));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(Fs(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,rC),c=[a,...d.times],l=c[c.length-1],u=!n&&r-l<=tC?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=Fs(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=Fs(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:A(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(ak)))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?ik:this.soonest-this.now(),t=Math.min(Math.max(e,sC),ik);this.timer=setTimeout(()=>{this.look()},t),this.timer.unref?.()}triggersOf(e){return(Array.isArray(e.triggers)?e.triggers:[]).flatMap(r=>{let n=pR.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: ${A(t)}.`]}}read(e,t){let r=iC.safeParse(this.deps.store.get(Fs(e,t)));return r.success?r.data:{}}write(e,t,r){this.deps.store.set(Fs(e,t),r,ak)}};function Po(){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 MH=65*6e4;var dk=[{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."}]}];var ck="pipeline-rewind-grants",uk="pipeline:rewind-grant:",lk="pipeline:saved:",_u=V({pipelineId:L().min(1).max(200),stepId:L().min(1).max(200),organizationId:L().min(1).max(18),checkpointId:L().min(1).max(200),digest:L().regex(/^sha256:[0-9a-f]{64}$/),grantedAt:Wo.datetime(),grantedBy:L().max(80).optional(),takenBackAt:Wo.datetime().optional()}).strict();function Bu(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 Uu(s,e){return`${uk}${s}:${e}`}var _s=class{constructor(e){this.store=e}store;all(){return Object.values(this.store.getByCategory(ck)).flatMap(e=>{let t=_u.safeParse(e);return t.success?[t.data]:[]})}get(e,t){let r=_u.safeParse(this.store.get(Uu(e,t)));return r.success?r.data:void 0}write(e){this.store.set(Uu(e.pipelineId,e.stepId),_u.parse(e),ck)}revoke(e,t){return this.store.delete(Uu(e,t))}revokePipeline(e){let t=`${uk}${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&&Us(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(`${lk}${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(`${lk}${e}`)?{refusal:"never"}:r.takenBackAt!==void 0||Us(t.config)!==r.digest?{refusal:"changed"}:{grant:{organizationId:r.organizationId,checkpointId:r.checkpointId,digest:r.digest,grantedAt:r.grantedAt}}}};function Us(s){let e=_t.safeParse(s??{});return e.success?ci(e.data):void 0}function pk(s,e){return new _s(s).revokePipeline(e)}import{randomBytes as aC,randomUUID as Co}from"node:crypto";import{lstat as dC,rename as cC,rm as lC,stat as uC}from"node:fs/promises";import{hostname as pC}from"node:os";import{basename as Bs,dirname as yk,join as gC,sep as fC}from"node:path";var hC=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"]),Rr="checkpoint",mC=8,yC=6e4,zr="CANCELLED",wC={success:"success",partial:"partial",unstable:"partial",failure:"failure",cancelled:"cancelled"},bC={preview:"previewed",rewind:"rewound to",undo:"used",export:"exported"};function Hu(s){let{result:e,notes:t,deliverability:r}=s;return{done:!0,result:e,notes:t,...r!==void 0?{deliverability:r}:{}}}var RC=/\s*\b(?:No record was (?:read or )?written|Nothing was written)\./g;function qu(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:wk([n,...o])},alsoRefused:o}:{done:!1,refusal:n,alsoRefused:o}}function wk(s){let e=!1;return s.map(({message:t})=>{let r=t.replace(RC,"").trim();return e?r:(e=r!==t.trim(),t)}).join(" ")}var vC=new Set(["RUN_WRITING","API_BUDGET","EMAILS"]),zn=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 gk(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 SC(){let[s,e,t,r,n,o,i,a,d,c,l]=await Promise.all([import("./chunk-GSG7WZHM.mjs"),import("./chunk-CSBS5U5I.mjs"),import("./chunk-T62WNR54.mjs"),import("./chunk-DB7RBE5D.mjs"),import("./chunk-ADOAS63R.mjs"),import("./chunk-K327QKMD.mjs"),import("./chunk-IQXHJEYB.mjs"),import("./chunk-EHQ3FX6X.mjs"),import("./chunk-OPXCV2KL.mjs"),import("./chunk-IOIWJ3DJ.mjs"),import("./chunk-RMBPOTD7.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}}var Ce=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 fk(s){return s instanceof jt?s:s instanceof Ce?s.code===zr?new jt(s.message):new zn(s.code,s.alsoRefused.length>0?wk([s,...s.alsoRefused]):s.message,s.result,s.alsoRefused):s}async function hk(s){try{return(await uC(s)).isDirectory()}catch{return!1}}function tr(s,e){return s!==void 0&&e!==void 0&&s.length>=15&&s.slice(0,15)===e.slice(0,15)}var mk=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function xd(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 Ce("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 ht(s){return be(s)}function kC(s,e){let t=[...e].sort((n,o)=>o.length-n.length),r=s;for(let n of t)r=r.replaceAll(n,Bs(n));for(let n of t){let o=yk(n);o===n||o.length<=1||(r=r.replaceAll(`${o}${fC}`,"").replaceAll(o,Bs(o)))}return r}function OC(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}}function IC(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 Wu(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 Md=class{constructor(e,t={},r=io){this.deps=e;this.writers=t;this.self=r}deps;writers;self;loaded;store;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)}setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}setFreeBytes(e){this.freeBytes=e}rewindFromPreviewsAnswered(){this.previewsAnswered??=new Map}async handle(e){if(!hC.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: ${A(e)}`)}}async keptBefore(e){let t=e.previousOrganizationId??this.deps.sandboxRefreshes?.organizationIdOf(e.orgId);return t===void 0||!mk.test(t)?0:(await(await this.openedStore()).list({organizationId:t})).length}async latestUsableOf(e){let t=this.deps.orgManager.getOrg(e);if(!t||!Qn(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:${Co()}`,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;K(this.deps,{action:"checkpoint_take",module:Rr,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 ${ht(o)} before the run`,runWriting:this.beforeRunWriting(o,t),...r.signal?{signal:r.signal}:{},...r.onProgress?{onProgress:r.onProgress}:{}})}catch(h){if(h instanceof Ce&&h.code===zr)return l("cancelled"),{taken:!1,stopped:!0};if(h instanceof Ce&&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",_p.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,ht(e),"start this run","No record was read.",t)}async takeForPipeline(e,t){let r=`checkpoint:pipeline:${Co()}`;try{let n=Qo.safeParse(e.config);if(!n.success)throw new Ce("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 Ce(zr,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 ${ht(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 fk(n)}}async rewindForPipeline(e,t){let r=`checkpoint:pipeline:${Co()}`,{grant:n,origin:o}=e;try{let i=await this.modules(),a=_t.safeParse(e.config);if(!a.success)throw new Ce("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!==ci(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(!tr(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(!tr(p.orgId,u.org.organizationId)&&!tr(this.deps.sandboxRefreshes?.organizationIdOf(p.id),u.org.organizationId))throw new Ce("OTHER_ORG",`The checkpoint '${u.name}' is not of ${ht(p)}, the org the Rewind step "${o.step}" names. No record was read or written.`);let g=xd(u,d.objects),h=await this.connect(p),f=ht(p),m={operationId:r,pipeline:{origin:o,grantedAt:n.grantedAt}},y=()=>(this.audit(m,"rewind",p,u,"stopped",{code:ft}),new jt(new i.RewindStopped().message)),b=(_,J=[])=>(this.audit(m,"rewind",p,u,"stopped",{code:_.code}),this.refusalOf(_,J));if(t?.aborted)throw y();let v;try{v=await i.previewCheckpoint({org:i.takeOrgOf(h),store:c,readAutomation:_=>this.readAutomation(p.id,_),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(_){throw t?.aborted?y():_}if(!v.previewed)throw b(v.refusal);let w=g!==void 0?i.selectionDiff(v.diff,await i.planSelection({checkpoint:u,previewDir:i.previewDirOf(l,v.diff.previewId),readAt:v.diff.readAt,objects:new Set(g),acceptOutside:d.acceptOutside,heldRows:i.snapshotRowsOf(u,l),...t?{signal:t}:{}})):v.diff,R=d.muteAutomation&&v.automation?Fy(v.automation,Yr(i.rewindStepsOf(w))).automation:v.automation,k=await i.boundsRefusals({orgName:f,preview:{diff:w,...R?{automation:R}:{},...v.emails?{emails:v.emails}:{},...v.emailsUncounted!==void 0?{emailsUncounted:v.emailsUncounted}:{},...v.deliverability?{deliverability:v.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}),[I,...S]=[...v.refusal!==void 0?[v.refusal]:[],...k.filter(_=>_.code!==v.refusal?.code)];if(I!==void 0)throw b(I,S);if(t?.aborted)throw y();let C=[],O=[],P=await this.writeAct(m,"rewind",p,u,`Pipeline '${o.pipeline}': rewinding ${f} to '${u.name}'`,async(_,J)=>{let B=await i.rewindOrg({org:i.rewindOrgOf(h),undelete:re=>h.soap.undelete(re),store:c,readAutomation:re=>this.readAutomation(p.id,re),runWriting:this.runWriting(p.id,f,"rewind","No record was read or written."),onUndeletable:re=>(C.push(...re),this.deps.log(`[WARN] checkpoint:rewind ${r}: the user may not delete ${re.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:re,step:H})=>J(re,H),signal:_,...d.muteAutomation?{mute:this.muteOf(h)}:{}},{checkpoint:u,folder:l,orgName:f,registered:p,username:p.username,previewId:v.diff.previewId,reusesPreview:v.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 B.rewound?(O=B.notes,Hu(B)):qu(B.refusal,B.alsoRefused,re=>re,!1)},_=>_ instanceof i.RewindStopped,{...t?{signal:t}:{},acceptEmails:d.acceptEmails,refusalOf:_=>C.length>0?i.undeletableUnattendedRefusal(f,C,gk(_)):void 0});return{operationId:r,checkpointId:u.checkpointId,result:P,notes:O,estimate:v.estimate}}catch(i){throw fk(i)}}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 K(this.deps,{action:"checkpoint_export",module:Rr,operationId:Co(),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={})=>{K(this.deps,{action:"checkpoint_import",module:Rr,operationId:Co(),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:pC(),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=ht(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:ht(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)}: ${ht(i)} is another org now, and the checkpoint can no longer be rewound to. 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 Ce)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:A(e)}}async handleExport(e){let t=D(Ph,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 dC(c).then(()=>!0,()=>!1),u=l?gC(yk(c),`.${Bs(c)}.${aC(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 Ce(p.refusal.code,p.refusal.message);if(l)try{await cC(u,c)}catch(g){throw await lC(u,{force:!0}),g}this.respond(e,"checkpoint:export:response",{status:"saved",checkpointId:d,fileName:Bs(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=>tr(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 Ce(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:Bs(i),summary:OC(d),orgIds:c,...u?{keptHere:!0}:{}})}catch(r){this.fail(e,this.pathless(r,t,"IMPORT_ERROR"),"IMPORT_ERROR")}}async handleImport(e){let t=D(Ch,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 Ce("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 Ce("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 Ce(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 Ce(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 Ce("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=Co();this.importFiles.set(t,e);for(let r of this.importFiles.keys()){if(this.importFiles.size<=mC)break;this.importFiles.delete(r)}return t}pathless(e,t,r){let n=e instanceof Ce?e:new Ce(r,A(e));return new Ce(n.code,kC(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: ${A(t)}`)}}modules(){return this.loaded??=SC(),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 Ce("STORE_REFUSED",IC(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 Ce){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 Ce(e.code,e.message,vC.has(e.code),void 0,e,t)}registeredOrg(e){let t=this.deps.orgManager.getOrg(e);if(!t)throw new Ce("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 Pg&&t.code==="SCRATCH_ORG_EXPIRED"?new Ce("SCRATCH_EXPIRED",`${ht(e)} is a scratch org that has expired: its checkpoints can only be deleted. `+Wc):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:ht(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||Pn(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||tr(e.targetOrganizationId,r)||tr(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(tr(o,e))return n.detectedAt}}organizationIdsOf(e){let t=this.deps.sandboxRefreshes,r=[this.deps.orgManager.getOrg(e)?.orgId,t?.organizationIdOf(e),...t?.refreshesOf(e).map(o=>o.previousOrganizationId)??[]],n=[];for(let o of r)o===void 0||!mk.test(o)||n.some(i=>tr(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)}orgOfCheckpoint(e){let t=e.org.organizationId,r=this.deps.orgManager.getAllOrgs(),n=r.filter(a=>tr(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=>tr(i?.organizationIdOf(a.id),t))}async checkpointOf(e,t){let r=await e.read(t);if(r===void 0)throw new Ce("NOT_FOUND",`No checkpoint ${t} is kept on this machine.`,!1);if(r.checkpoint===void 0)throw new Ce("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=be(t.org);if(t.status!=="ready")throw new Ce(t.status==="taking"?"TAKING":"FAILED",t.status==="taking"?`The checkpoint '${t.name}' is being taken, or its take never ended: it can be ${bC[r]} once taken, or deleted.`:`The take of checkpoint '${t.name}' failed: it can only be deleted.`);let o=this.refreshedAt(t.org.organizationId);if(o!==void 0)throw new Ce("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. It can only be deleted.`);if(e.scratchOrgExpired(t.org,Date.now()))throw new Ce("SCRATCH_EXPIRED",`${n} is a scratch org that has expired: its checkpoints can only be deleted. `+Wc)}connectedOrgOf(e,t){let r=this.orgOfCheckpoint(e);if(!r){let n=be(e.org);throw new Ce("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 Ce("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;K(this.deps,{action:t==="rewind"?"checkpoint_rewind":"checkpoint_undo",module:Rr,operationId:e.operationId,orgId:r.id,outcome:o,...a?{objects:Ni(rn(a.deleted),a.restored,a.undeleted)}:{},...d!==void 0?{code:d}:{},...l?{muted:ot(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=D(kh,e,"checkpoint:error",this.deps);if(t!==null)try{let r=await this.openedStore(),n=t?.orgId===void 0?await r.list({refreshedAt:o=>this.refreshedAt(o)}):await this.listOfOrg(r,t.orgId);this.respond(e,"checkpoint:list:response",{checkpoints:n})}catch(r){this.fail(e,r,"LIST_ERROR")}}async handleScope(e){let t=D(Oh,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,ht(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=D(Ih,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 Ce(zr,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=ht(o),c=a.description??`Taking a checkpoint of ${d}`,l=this.deps.infraServices?.backgroundRegistry,u=new AbortController,p=()=>{},g=new Promise((y,b)=>{p=v=>v===void 0?y():b(v)});g.catch(()=>{}),ze(this.deps,e,Rr,c),l?.register(e,Rr,c,g,u);let h=Kt(this.liveTracker,e,Rr,c),f=y=>{let{percentage:b,processedObjects:v,totalObjects:w,step:R}=y;Le(this.deps,e,b,v,w,R),u.signal.aborted||l?.updateProgress(e,b),h.progress(b,v,w,R),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 ge(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:R}of y.notChecked)this.deps.log(`[WARN] checkpoint:take ${e}: what moved in ${w} while it was read was not checked: ${R}`);let{checkpoint:b}=y,v={checkpoint:b,...y.requests?{requests:y.requests}:{},estimate:y.estimate};return a.kept?.(v),this.checkpointsChanged(),ge(this.deps,e,{status:"success",objects:b.objects.length,records:b.objects.reduce((w,R)=>w+R.records,0)}),h.complete(),p(),v}catch(y){throw y instanceof Ce?y:y instanceof t.CheckpointTakeStopped?(l?.abort(e),ge(this.deps,e,{aborted:!0}),h.cancel(),p(),new Ce(zr,y.message,!0)):(ge(this.deps,e,{status:"failure"}),h.fail(A(y)),p(y),y)}finally{a.signal?.removeEventListener("abort",m)}}async handlePreview(e){let t=D(Ah,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=xd(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,ht(d),"rewind","No record would be read or written."),...t.muteAutomation===!0?{mute:this.muteOf(c)}:{}},{checkpoint:i,folder:o,orgName:ht(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=D(Eh,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=xd(i,t.objects)??[],d=r.previewDirOf(o,t.previewId),c=this.previewReads.get(t.previewId);if(c?.checkpointId!==i.checkpointId||!await hk(d))throw new Ce("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=D(Th,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=xd(d,t.objects);if(!await hk(o.previewDirOf(a,t.previewId)))throw new Ce("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:ft}),new Ce(zr,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=ht(l);await this.writeAct(p,"rewind",l,d,`Rewinding ${f} to '${d.name}'`,async(m,y)=>{let b=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:xr(this.deps,l.id,"checkpoint:rewind"),onProgress:({percentage:w,step:R})=>y(w,R),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(b.rewound)return Hu(b);let v=t.fromPage===!0;return qu(b.refusal,b.alsoRefused,w=>v?o.pageEmailsRefusal(w,"rewind",f):w,v)},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=D(Dh,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:ft,rewindId:t.rewindId}),new Ce(zr,new o.UndoStopped().message,!0);let p=ht(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:xr(this.deps,c.id,"checkpoint:undo"),onProgress:({percentage:y,step:b})=>h(y,b),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 Hu(f);let m=t.fromPage===!0;return qu(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)=>mt(async()=>Pt(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((v,w)=>{g=R=>R===void 0?v():w(R)});h.catch(()=>{}),ze(this.deps,c,Rr,o),u?.register(c,Rr,o,h,p);let f=Kt(this.liveTracker,c,Rr,o),m=l!==void 0?{rewindId:l}:{},y=(v,w)=>{Le(this.deps,c,v,0,0,w),p.signal.aborted||u?.updateProgress(c,v),f.progress(v,0,0,w)},b=()=>{u?u.abort(c):p.abort()};d.signal?.addEventListener("abort",b,{once:!0}),d.signal?.aborted&&b();try{let v=await i(p.signal,y);if(!v.done)throw this.audit(e,t,r,n,"stopped",{code:v.refusal.code,...m}),ge(this.deps,c,{status:"refused",code:v.refusal.code}),f.fail(v.refusal.message),g(new Error(v.refusal.message)),this.refusalOf(v.refusal,v.alsoRefused);let{result:w,notes:R,deliverability:k}=v,I={...k!==void 0?{deliverability:k}:{},...d.acceptEmails===!0?{acceptEmails:!0}:{}};for(let C of R)this.deps.log(`[WARN] checkpoint:${t} ${c}: ${C}`);for(let C of w.removedJournals??[])this.deps.log(`[INFO] Removed the journal of rewind ${C.rewindId} of checkpoint '${C.name}': Undo reaches the last rewind of the org alone`);let S=d.refusalOf?.(w);if(S!==void 0)throw this.audit(e,t,r,n,gk(w)?"partial":"stopped",{result:w,code:S.code,...I}),ge(this.deps,c,{status:"refused",code:S.code}),f.fail(S.message),g(new Error(S.message)),new Ce(S.code,S.message,!1,w);if(this.audit(e,t,r,n,wC[w.status],{result:w,...I}),e.respond?.(`checkpoint:${t}:response`,{result:w,operationId:c}),w.status==="cancelled")u?.abort(c),ge(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.`;ge(this.deps,c,{status:w.status}),f.fail(C),g(new Error(C))}else ge(this.deps,c,{status:w.status}),w.status==="success"?f.complete():f.partial(),g();return w}catch(v){if(v instanceof Ce)throw v;if(a(v))throw u?.abort(c),ge(this.deps,c,{aborted:!0}),f.cancel(),g(),this.audit(e,t,r,n,"stopped",{code:zr,...m}),new Ce(zr,A(v),!0);let w=ms(v);throw this.audit(e,t,r,n,"failure",{...m,...w?{muted:w}:{}}),this.unreleased(e,t,r,w),ge(this.deps,c,{status:"failure"}),f.fail(A(v)),g(v),v}finally{d.signal?.removeEventListener("abort",b)}}unreleased(e,t,r,n){n?.released===!1&&this.deps.log(`[WARN] checkpoint:${t} ${e.operationId}: `+Ut(n,ht(r)).map(o=>o.trim()).join("; "))}readAutomation(e,t){let r=this.targetAutomation;return new fe(yC).withTimeout("checkpoint:preview automation",()=>r.read(e,t,{undeletes:!0}))}ownReader(){return this.reader??=import("./chunk-7YDNUBO5.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=D(xh,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 ${Wu(i)}`);if(n.length===0&&o.length>0)throw new Ce("RUN_WRITING",`The checkpoint was not deleted: ${Wu(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=D(Mh,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=D(jh,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=D(Nh,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=D($h,e,"checkpoint:error",this.deps);if(t!==null)try{let r=await this.openedStore(),{readRewindLedgers:n}=await import("./chunk-IGYH7GMA.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=>tr(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 Ce("RUN_WRITING",`The checkpoint was not changed: ${Wu(d)}. Change it once that has ended.`,!0);let c;try{c=await n(i)}catch(l){throw l instanceof o.CheckpointStoreError?new Ce(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 kk={apiLimits:"apiLimits",storage:"storage",recentErrors:"recentErrors",failedJobs:"activeJobs"},zu=Object.keys(kk),bk={apiLimits:{variable:Yo.apiLimits,read:s=>s.percent},storage:{variable:Yo.storage,read:s=>s.percent},recentErrors:{variable:Yo.recentErrors,read:s=>s.count},failedJobs:{variable:Yo.failedJobs,read:s=>s.count}},Ok=500,Ik=V({orgId:vf,checks:Se(Ke(["apiLimits","storage","recentErrors","failedJobs"])).min(1).refine(s=>new Set(s).size===s.length)}),Ak=V({message:L().trim().min(1).max(Ok)});function Ot(s,e){return`${s} ${e}${s===1?"":"s"}`}function Sr(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 wt(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 vr(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 Xu(s){return Array.isArray(s)&&s.length>0?s:void 0}function AC(s){return e=>{let t=`Backup step "${e.name}"`,r=e.config??{},n=vr(s,t,r.orgId,"the org it backs up");if(n)return n;let o=Xu(r.objects);if(!o)return`${t} names no object: list the API names of the objects it backs up.`;let i=o.filter(a=>!Sf.safeParse(a).success);if(i.length>0)return`${t} names what is not an object API name: ${i.map(String).join(", ")}.`;if(!fl.safeParse({orgId:r.orgId,objects:o}).success)return`${t} backs up more objects than one backup takes: at most 100.`}}function TC(s){return e=>{let t=`Compare step "${e.name}"`,r=e.config??{},n=vr(s,t,r.sourceOrgId,"the org it compares from")??vr(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=Xu(r.types);if(!o)return`${t} names no component type: choose what it compares.`;if(!as.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 EC(s){return e=>{let t=`Pre-check step "${e.name}"`,r=e.config??{},n=vr(s,t,r.orgId,"the org it checks");if(n)return n;let o=Xu(r.checks);if(!o)return`${t} names no check: choose what it checks (${zu.join(", ")}).`;let i=o.filter(a=>typeof a!="string"||!zu.includes(a));if(i.length>0)return`${t} names checks SandForge does not have: ${i.map(String).join(", ")}. It can check ${zu.join(", ")}.`;if(!Ik.safeParse({orgId:r.orgId,checks:o}).success)return`${t} names the same check twice.`}}function PC(s){return e=>{let t=`Notification step "${e.name}"`;if(!s.notify)return`${t} cannot show a notification: there is no VS Code window to show it in.`;let r=(e.config??{}).message;if(typeof r!="string"||r.trim()==="")return`${t} has no message: write what the notification says.`;if(!Ak.safeParse({message:r}).success)return`${t} has a message longer than ${Ok} characters.`}}function CC(s){return async(e,t)=>{let r=new Date().toISOString(),{orgId:n,objects:o}=fl.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 ${Ot(i.totalRecords,"record")} of ${Ot(i.objects.length,"object")} from ${a}`+(d.length>0?`; only part of ${d.join(", ")}: the org holds more rows than one backup reads.`:".");return Sr(e,r,{operationId:i.operationId,orgId:n,objects:i.objects,totalRecords:i.totalRecords,partial:i.partial},c)}}function DC(s){return async(e,t)=>{let r=new Date().toISOString(),{sourceOrgId:n,targetOrgId:o,types:i}=as.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 Sr(e,r,{sourceOrgId:n,targetOrgId:o,types:i,summary:a.summary,content:a.content,variables:{[hg]:String(d+c+l)}},`Compared ${Ot(i.length,"component type")} of ${g} with ${h}: ${c} only in ${g}, ${d} only in ${h}, ${l} modified, ${u} unchanged, ${p} not compared.`)}}function Rk(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 xC(s){return async e=>{let t=new Date().toISOString(),{orgId:r,checks:n}=Ik.parse({orgId:e.config.orgId,checks:e.config.checks}),o=s.orgName(r)??r,i=await s.readOrgHealth(r,n.map(u=>kk[u])),a=n.map((u,p)=>({check:u,signal:i[p]})),d={};for(let{check:u,signal:p}of a){let g=p?bk[u].read(p):void 0;g!==void 0&&p.status!=="unknown"&&(d[bk[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?wt(e,t,c,`Pre-check "${e.name}" failed on ${o}: ${l.map(({check:u,signal:p})=>p?Rk(p):`${u} was not read`).join("; ")}.`):Sr(e,t,c,`${a.length===1?"The check":`${a.length} checks`} passed on ${o}: ${a.map(({signal:u})=>Rk(u)).join("; ")}.`)}}function MC(s){return async(e,t)=>{let r=new Date().toISOString(),{message:n}=Ak.parse({message:e.config.message});return s.notify?(s.notify(t.pipelineName?`${t.pipelineName}: ${n}`:n),Sr(e,r,{message:n},"Showed a notification in VS Code.")):wt(e,r,{},`Notification step "${e.name}" cannot show a notification: there is no VS Code window to show it in.`)}}function jC(s){return e=>{let t=`Approval step "${e.name}"`;if(!s.askApproval)return`${t} cannot ask anyone: there is no VS Code window to ask in.`;switch(Rg(e.config)){case"timeout":return`${t} waits for a time it cannot keep: set a whole number of minutes from 1 to ${yg} (a day).`;case"message":return`${t} has a message that is not text, or is longer than ${wg} characters.`;default:return}}}function vk(s){return s.via==="page"?" on the Automation page":s.via==="notification"?" in the VS Code notification":""}function NC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Approval step "${e.name}"`;if(!s.askApproval)return wt(e,r,{},`${n} cannot ask anyone: there is no VS Code window to ask in.`);let o=bg(e.config)??mg,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{...Sr(e,r,c,`Approved${vk(d)} at ${d.at}.`),approval:d};case"rejected":return{...wt(e,r,c,`${n} was rejected${vk(d)} at ${d.at}.`),approval:d};case"timedOut":return{...wt(e,r,c,`${n} was not approved in time: nobody answered within ${Ot(o,"minute")}.`),approval:d};case"cancelled":return{...wt(e,r,c,`${n} was stopped before anyone answered.`),approval:d}}}}function Tk(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=Tn.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 Ek(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(!Tn.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 Pk(s){return s===void 0||s.steps.slice(0,s.index).some(e=>e.type==="approval")}function $C(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=Tk(s,e);if("problem"in n)return n.problem;let{config:o}=n,i=vr(s,r,o.sourceOrgId,"the source org of its configuration")??vr(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"&&!Pk(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 Ku(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 LC(s){return async(e,t)=>{let r=new Date().toISOString(),n=Tk(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,Ku(t),t.signal);if(a.cancelled)throw new jt(`Sync step "${e.name}" was cancelled: ${a.error??"the run stopped before it synced every object."}`);let d=s.orgName(o.targetOrgId)??o.targetOrgId,c=a.summary,l={configId:o.id,configName:i,operationId:a.operationId,status:a.status,totalProcessed:a.totalProcessed,totalSuccess:a.totalSuccess,totalFailed:a.totalFailed,totalSkipped:a.totalSkipped,objects:a.objectResults.map(p=>({objectApiName:p.objectApiName,operation:p.operation,processed:p.processed,success:p.success,failed:p.failed,skipped:p.skipped})),...typeof c=="object"&&c!==null?{summary:c}:{}},u=`${Ot(a.totalSuccess,"record")} written, ${a.totalFailed} failed and ${a.totalSkipped} skipped of ${a.totalProcessed} read`;if(a.status!=="success"){let p=[a.error,fa(a)].filter(g=>g!==void 0&&g!=="");return wt(e,r,l,`Sync step "${e.name}" ran "${i}" into ${d} and did not complete: ${u}`+(p.length>0?`; ${p.join("; ")}`:"."))}return Sr(e,r,l,`Synced "${i}" into ${d}: ${u}.`)}}function mn(s){return typeof s=="string"&&s.trim()!==""?s.trim():void 0}function Yu(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 FC(s,e){return s!==void 0&&e!==void 0&&s.length>=15&&s.slice(0,15)===e.slice(0,15)}function jd(s){return s.pipelineName??s.pipelineId}function Ck(s,e,t,r,n){let o=s.orgName(t)??t,i=li(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"&&!Pk(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 Dk(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 xk(s){if(s instanceof jt)return;let e=s?.code;return typeof e=="string"?e:void 0}function _C(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=vr(s,r,n.orgId,"the org it seeds");if(o)return o;let i=mn(n.templateId);if(i===void 0)return`${r} names no Seed template: choose the one it seeds with.`;let a=String(n.orgId),d=Ba(a,i,c=>s.savedSeedTemplate?.(c));return"refusal"in d?`${r}: ${d.refusal.message}`:Dk(e,r,"a second try would write a second set of records")??Ck(s,r,a,"seeds",t)}}function UC(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}=vg.parse({orgId:e.config.orgId,templateId:mn(e.config.templateId)}),a=s.orgName(o)??o,d;try{d=await s.seed({orgId:o,templateId:i,pipeline:{name:jd(t)},answer:Ku(t)},t.signal)}catch(g){let h=xk(g);if(h===void 0)throw g;return wt(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=Ot(c.totalRecordsCreated,"record"),p="take them back from Seed's Recent runs";if(c.cancelled)throw new jt(`${n} was cancelled: it had created ${u} in ${a}, which stay there; ${p}.`);return c.status!=="success"?wt(e,r,l,`${n} seeded ${a} and did not complete: ${u} created, ${c.totalRecordsFailed} refused; ${p}.`):Sr(e,r,l,`Seeded ${u} into ${a}: ${p}.`)}}function Mk(s){let e=(s.listSeedTemplates?.()??[]).map(n=>({raw:n,builtIn:!1})),t=ni.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=no.safeParse(n);return[{id:i,name:d,builtIn:o,valid:c.success,usesAi:c.success&&nu(c.data).length>0}]})}function BC(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 jk(s){return(s.maskingTemplates?.()??[]).map(e=>({id:e.id,name:e.name,builtIn:e.builtIn,objects:BC(e)}))}function HC(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=vr(s,r,n.orgId,"the org it masks");if(o)return o;let i=mn(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=mn(n.object),l=mn(n.where),u=By({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=el.safeParse({orgId:a,templateId:i,...Nk(n)});return p.success?Ck(s,r,a,"masks",t):`${r} does not read (${Yu(p.error)}).`}}function Nk(s){return Object.fromEntries(["acceptAutomation","acceptEmails","muteAutomation"].flatMap(e=>s[e]===void 0?[]:[[e,s[e]]]))}var Sk=3;function qC(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-Sk;return`, refused by the org: ${e.slice(0,Sk).join("; ")}`+(t>0?`; and ${Ot(t,"other reason")}`:"")}function WC(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=mn(e.config.object),i=mn(e.config.where),{orgId:a,templateId:d,acceptAutomation:c,acceptEmails:l,muteAutomation:u}=el.parse({orgId:e.config.orgId,templateId:mn(e.config.templateId),...o!==void 0?{object:o}:{},...i!==void 0?{where:i}:{},...Nk(e.config)}),p=s.orgName(a)??a,g=R=>R?` ${Ut(R,p).map(k=>k.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:jd(t)},answer:Ku(t)},t.signal)}catch(R){let k=xk(R);if(k===void 0)throw R;let I=R.snapshot,S=ms(R);return wt(e,r,{orgId:a,templateId:d,code:k,...I!==void 0?{snapshot:I}:{},...S?{mutedAutomation:S}:{}},`${n}: ${R.message}`+(typeof I?.operationId=="string"?` The snapshot ${I.operationId} it took keeps the values it wrote over, in clear, until it is deleted on the DataOps page.`:"")+g(S))}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}:{}},b=g(f.mutedAutomation);if(f.cancelled)throw new jt(`${n} was cancelled: it masked ${Ot(f.recordsProcessed,"record")} in ${p} before the stop, and ${f.recordsNotMasked} still hold their values; ${m}.`+b);let v=f.objects.filter(R=>R.notMasked>0);if(f.recordsNotMasked>0){let R=`${v.map(k=>`${k.notMasked} of ${k.objectApiName}`).join(", ")} still hold their values${qC(f)}`;return wt(e,r,y,`${n} masked ${p} and did not complete: ${R}; ${m}.${b}`)}let w=o!==void 0?i!==void 0?`the ${o} rows where ${i}`:`every ${o} row`:`every row of ${f.objects.map(R=>R.objectApiName).join(", ")}`;return Sr(e,r,y,`Masked ${Ot(f.recordsProcessed,"record")} in ${p}, ${w}; ${m}.${b}`)}}function zC(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=vr(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=Qo.safeParse(r);if(!i.success)return`${t} does not read (${Yu(i.error)}).`}}function GC(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 JC(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=Qo.parse(e.config),i=s.orgName(o.orgId)??o.orgId,a;try{a=await s.takeCheckpoint({config:o,origin:{pipeline:jd(t),step:e.name,trigger:s.trigger??"manual"}},t.signal)}catch(l){if(!(l instanceof zn))throw l;return wt(e,r,{orgId:o.orgId,code:l.code},l.message)}let d=a.movedWhileTaken,c=d.changed+d.deleted+d.created;return Sr(e,r,{orgId:o.orgId,operationId:a.operationId,checkpointId:a.checkpointId,name:a.name,records:a.records,objects:a.objects,bytes:a.bytes,movedWhileTaken:d},`Took the checkpoint '${a.name}' of ${i}: ${Ot(a.records,"record")} of ${Ot(a.objects,"object")}, ${GC(a.bytes)} on this machine, `+(o.keepDays===0?"kept until it is deleted":`kept ${Ot(o.keepDays,"day")}`)+(c>0?`; ${Ot(c,"record")} changed while it was taken.`:"."))}}var VC={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, and the checkpoint can only be deleted. Take a checkpoint of it again, and choose it",scratchExpired:"of a scratch org that has expired: it can only be deleted"};function $k(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}, ${VC[a]}.`}}let i=s.organizationIdsOf?.(t)??[];if(n.organizationId!==void 0&&!i.some(a=>FC(a,n.organizationId)))return{why:"otherOrg",problem:`${e} rewinds ${s.orgName(t)??t} to the checkpoint ${o}, which was taken of another org.`}}function XC(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=vr(s,t,r.orgId,"the org it rewinds");if(n)return n;let o=String(r.orgId);if((s.orgTier?.(o)??"production")==="production")return`${t} writes to ${s.orgName(o)??o}, a production org or one SandForge cannot tell is not: SandForge rewinds none.`;let i=_t.safeParse(r);if(!i.success)return`${t} does not read (${Yu(i.error)}).`;let a=Dk(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?Bu(e.name,d.refusal):$k(s,t,o,i.data.checkpointId)?.problem}}function Vu(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 Gu(s){let e=Vu(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 Ju(s){return s.undo?`Undo on the Checkpoints page takes it back until ${s.undo.until}`:"it wrote nothing Undo would take back"}function KC(s){return async(e,t)=>{let r=new Date().toISOString(),n=`Rewind step "${e.name}"`;if(!s.rewind||!s.rewindGrant)throw new Error(`${n} cannot run here: Checkpoints are not available in this window.`);let o=_t.parse(e.config),i=s.rewindGrant(t.pipelineId,e);if("refusal"in i)return wt(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:"NOT_CONFIRMED"},Bu(e.name,i.refusal));let a=s.orgName(o.orgId)??o.orgId,d=h=>h?` ${Ut(h,a).map(f=>f.trim()).join("; ")}.`:"",c;try{c=await s.rewind({config:o,grant:i.grant,origin:{pipeline:jd(t),step:e.name,trigger:s.trigger??"manual"}},t.signal)}catch(h){let f=(h instanceof zn?h.result?.mutedAutomation:void 0)??ms(h);if(!(h instanceof zn)){if(!f||h instanceof jt)throw h;return wt(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,mutedAutomation:f},`${A(h)}${d(f)}`)}return wt(e,r,{orgId:o.orgId,checkpointId:o.checkpointId,code:h.code,...h.alsoRefused.length>0?{alsoRefused:[...h.alsoRefused]}:{},...h.result?{status:h.result.status,...Vu(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,...Vu(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 jt(`${n} was stopped part way in ${a}: ${Gu(l)}; ${Ju(l)}.${g}`);return l.status!=="success"?wt(e,r,p,`${n} rewound ${a} and did not complete (${l.status}): ${Gu(l)}; ${Ot(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`:"")+`; ${Ju(l)}.${g}`):Sr(e,r,p,`Rewound ${a} to the checkpoint ${c.checkpointId}: ${Gu(l)}, with ${Ot(l.apiRequests.used,"API request")}; ${Ju(l)}.${g}`)}}function Lk(s,e,t,r){let n=r?{granted:{at:r.grantedAt,digestMatches:r.matches}}:{},o=_t.safeParse(e.config??{});if(!o.success)return{stepId:e.id,valid:!1,why:"config",...n};let{orgId:i,checkpointId:a}=o.data,d=$k({...s,checkpointKept:()=>t},"The step",i,a);return{stepId:e.id,checkpointId:a,valid:d===void 0,...d?{why:d.why}:{},...n}}function Fk(s,e){s.registerHandler("backup",CC(e),AC(e)),s.registerHandler("compare",DC(e),TC(e)),s.registerHandler("precheck",xC(e),EC(e)),s.registerHandler("notification",MC(e),PC(e)),s.registerHandler("approval",NC(e),jC(e)),s.registerHandler("sync",LC(e),$C(e)),s.registerHandler("seed",UC(e),_C(e)),s.registerHandler("anonymize",WC(e),HC(e)),s.registerHandler("checkpoint",JC(e),zC(e)),s.registerHandler("rewind",KC(e),XC(e))}function Qu(s,e){return`${s}\0${e}`}var Nd=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=Qu(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=l==="approve"?"approved":"rejected";this.answer(e.operationId,e.stepId,u,"notification")||this.deps.tooLate?.(o)},()=>{})})}answer(e,t,r,n){let o=this.waiting.get(Qu(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(Qu(e,t))}};var _k=50,Bk={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 QC(s,e){return`Pipeline "${s}" is already running: the run started ${Bk[e.triggeredBy]} at ${e.startedAt} has not ended. A pipeline runs once at a time.`}function ZC(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 eD={approved:"success",rejected:"stopped",timedOut:"stopped",cancelled:"cancelled"};function Uk(){try{return of(YC().username)}catch{return}}function tD(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}}}function Zu(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 rD=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","marketplace:list","marketplace:install"]),$d=class{constructor(e){this.deps=e}deps;pipelineMarketplace;stepRunners;claims=Po();scheduler;reportTrigger=()=>{};approvalGate;unreadableSaid=new Map;liveTracker;setLiveOperationTracker(e){this.liveTracker=e}approvals(){let e=this.deps.services;return this.approvalGate??=new Nd({...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:Uk}),this.approvalGate}async askApproval(e,t,r){r.holdBudget(!0);try{let n=await this.approvals().ask({...e,operationId:r.operationId},t);return 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 _s(this.deps.configStore)}async runSyncUntimed(e,t,r,n,o){o.holdBudget(!0);try{return await e(t,r,n)}finally{o.holdBudget(!1)}}recordApproval(e,t,r){try{if(!(this.deps.services?.getSandforgeSetting?.("safety.auditLogging",!0)!==!1))return;new to(this.deps.configStore).append({id:crypto.randomUUID(),action:"pipeline_approval",module:"automation",operationId:r,outcome:eD[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 ${A(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 Dd({pipelines:()=>this.savedPipelines(),problems:e=>this.pipelineProblems(e),org:e=>{let t=this.deps.orgManager.getOrg(e);return t?{name:be(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=ml.safeParse(o);return i.success?[i.data]:(t.set(n,Nm(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=`${ng}${crypto.randomUUID()}`;return{started:!0,run:this.runPipeline(e,{},t,n).catch(i=>{throw this.deps.log(`[ERR] ${t} run of "${e.name}": ${A(i)}`),je(this.deps,n,A(i),!1,{context:{module:"automation",operation:"pipeline:execute"}}),i}).finally(()=>r.release())}}async handle(e){if(!rD.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"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=D(Am,e,"pipeline:error",this.deps);if(!t)return;let r=t,n=e.id,o={module:"automation",operation:e.type},i=r.pipeline,a=typeof i.id=="string"&&i.id!==""?this.claims.hold(i.id,{startedAt:new Date().toISOString(),triggeredBy:"manual"}):{release:()=>{}};if("busy"in a){E(this.deps,"pipeline:execute","pipeline:error",e,new Error(QC(i.name,a.busy)),{code:"PIPELINE_RUNNING",retryable:!0});return}try{let d=await this.runPipeline(i,r.variables??{},"manual",n),c=T(this.deps,e,"pipeline:run:response",d);this.deps.broker.postToWebview(c),this.deps.log(`[TX] ${c.type} id=${c.id}`)}catch(d){E(this.deps,"pipeline:execute","pipeline:error",e,d),je(this.deps,n,A(d),!1,{context:o})}finally{a.release()}}handlePipelineApproval(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Pm,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 Zu(e.steps)){let o=_t.safeParse(n.config);if(!(!o.success||t.has(o.data.checkpointId)))try{t.set(o.data.checkpointId,await r(o.data.checkpointId))}catch(i){this.deps.log(`[WARN] checkpoint ${o.data.checkpointId} not read for a check: ${A(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: ${A(e)}`)}}savedPipeline(e){let t=ml.safeParse(this.deps.configStore.get(`pipeline:saved:${e}`));return t.success?t.data:void 0}async describeRewindStep(e,t){let r=this.stepRunners,n=_t.safeParse(t.config),o=n.success&&r?.readCheckpoint?await r.readCheckpoint(n.data.checkpointId):void 0,i=this.rewindGrants().get(e,t.id),a=i?{grantedAt:i.grantedAt,matches:i.takenBackAt===void 0&&Us(t.config)===i.digest}:void 0;return r?{info:Lk(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=D(Cm,e,"pipeline:error",this.deps);if(t)try{let r=this.savedPipeline(t.pipelineId),n=[];for(let i of Zu(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=D(Dm,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=Zu(d?.steps??[]).find(f=>f.id===n);if(!c)return a("NOT_SAVED");let l=_t.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!==be(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=Uk();this.rewindGrants().write({pipelineId:r,stepId:n,organizationId:g.organizationId,checkpointId:l.data.checkpointId,digest:Us(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 ${be(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=D(xm,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?Mk(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?jk(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?Ek(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){let{PipelineBuilder:r}=await import("./chunk-4HW535YJ.mjs"),{TriggerEngine:n}=await import("./chunk-2YIV2OB2.mjs"),{StepLibrary:o}=await import("./chunk-RPI7LRTW.mjs"),{StepExecutor:i}=await import("./chunk-BY2HJFFG.mjs"),{ConditionalRouter:a}=await import("./chunk-FXXLX4O6.mjs"),{PipelineHistory:d}=await import("./chunk-ZHJP7L3K.mjs"),c=new i,l=e??{operationId:"",holdBudget:()=>{}};if(c.wrapHandler("delay",u=>(p,g)=>this.untimed(()=>u(p,g),l)),this.stepRunners){let{runSync:u,seed:p,anonymize:g,takeCheckpoint:h,rewind:f,backup:m}=this.stepRunners,y=await this.checkpointsOf(t),b=this.rewindGrants();Fk(c,{...this.stepRunners,...t?.id?{pipelineId:t.id}:{},...l.triggeredBy?{trigger:l.triggeredBy}:{},rewindGrant:(v,w)=>b.verify(v,w),checkpointKept:v=>y.get(v),...u?{runSync:(v,w,R)=>this.runSyncUntimed(u,v,w,R,l)}:{},backup:(v,w)=>this.untimed(()=>m(v,w),l),...p?{seed:(v,w)=>this.untimed(()=>p(v,w),l)}:{},...g?{anonymize:(v,w)=>this.untimed(()=>g(v,w),l)}:{},...h?{takeCheckpoint:(v,w)=>this.untimed(()=>h(v,w),l)}:{},...f?{rewind:(v,w)=>this.untimed(()=>f(v,w),l)}:{},...this.approvals().canAsk?{askApproval:(v,w)=>this.askApproval(v,w,l)}:{}})}if(!this.deps.services)throw new Error("AutomationHandler: composition-root services not injected. Wire ExtensionHandlersDeps.services in extension.ts.");return 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})}async runPipeline(e,t,r,n){let o={module:"automation",operation:"pipeline:execute"},i=this.deps.services?.getSandforgeSetting?.("pipeline.timeout",3e5)??3e5,a=new AbortController,d=!1,c=tD(i,()=>{d=!0,a.abort()}),l=await this.buildOrchestrator({operationId:n,holdBudget:R=>R?c.hold():c.resume(),triggeredBy:r},e);this.deps.infraServices?.performanceTracker?.start(n,"automation");let u=`Pipeline: ${e.name}`;ze(this.deps,n,"automation",u);let p=Kt(this.liveTracker,n,"automation",u,e.steps.length),g=R=>d&&R.status==="stopped"?{...R,status:"failed"}:R,h=(R,k)=>{let I=k,S=l.getActiveRuns(),C=e.steps.length,O=S[0]?.stepResults.length??0,P=Math.round(O/C*100),_=`Step: ${I.stepResult.stepName} (${I.stepResult.status})`;Le(this.deps,n,P,O,C,_),p.progress(P,O,C,_)},f=(R,k)=>{let{stepId:I}=k;this.postStepUpdate({operationId:n,stepId:I,status:"running"})},m=(R,k)=>{let I=g(k.stepResult);this.postStepUpdate({operationId:n,stepId:I.stepId,status:I.status==="failed"||I.status==="skipped"||I.status==="stopped"?I.status:"completed",...I.duration!==void 0?{duration:I.duration}:{},...I.summary!==void 0?{summary:I.summary}:{},...I.error!==void 0?{error:I.error}:{}})};l.on("stepCompleted",h),l.on("stepStarted",f),l.on("stepCompleted",m),l.on("stepSkipped",m),c.start();let y=()=>{};this.deps.infraServices?.backgroundRegistry?.register(n,"automation",u,new Promise((R,k)=>{y=I=>I?k(I):R()}),a);let b;try{b=await l.execute(e,t,r,a.signal)}catch(R){throw y(new Error(A(R))),p.fail(A(R)),R}finally{c.end(),l.off?.("stepCompleted",h),l.off?.("stepStarted",f),l.off?.("stepCompleted",m),l.off?.("stepSkipped",m)}let v=d&&b.status==="cancelled",w=v?{...b,status:"failed",error:`Pipeline ran out of time: sandforge.pipeline.timeout stopped it after ${i} ms.`,stepResults:b.stepResults.map(g)}:b;return y(w.status==="failed"?new Error(w.error??"Pipeline failed"):void 0),w.status==="failed"?p.fail(w.error??"Pipeline failed"):w.status==="cancelled"?p.cancel():w.status==="completed_with_warnings"?p.partial():p.complete(),this.deps.infraServices?.performanceTracker?.complete(n),this.recordRun(w,e),w.status==="failed"?je(this.deps,n,w.error??"Pipeline failed",v,{context:o}):ge(this.deps,n,{status:w.status,stepResults:w.stepResults.length}),w}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(ZC)},{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: ${A(r)}`)}}trimHistory(){let e=Object.entries(this.deps.configStore.getByCategory("pipeline-history"));if(e.length<=_k)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-_k))this.deps.configStore.delete(r)}handlePipelineTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=T(this.deps,e,"pipeline:templates:response",{templates:dk});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(([i,a])=>({key:i,...a})),n=await this.triggerScheduler().statuses();await this.revokeVoidGrants();let o=T(this.deps,e,"pipeline:list:response",{pipelines:r,triggers:n});this.deps.broker.postToWebview(o),this.deps.log(`[TX] pipeline:list:response (${r.length} pipelines)`)}catch(t){E(this.deps,"pipeline:list","pipeline:error",e,t)}}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}).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=D(Tm,e,"pipeline:error",this.deps);if(!t)return;let r=t,n=r.id||crypto.randomUUID(),o=`pipeline:saved:${n}`;this.deps.configStore.set(o,{...r.config,id:n,savedAt:new Date().toISOString()},"pipelines");let i=Array.isArray(r.config.steps)?r.config.steps:[],a=this.rewindGrants().revokeChanged(n,i.map(c=>({...typeof c.id=="string"?{id:c.id}:{},...c.type==="rewind"?{type:"rewind"}:{},config:typeof c.config=="object"&&c.config!==null?c.config:{}})));for(let c of a)this.deps.log(`[INFO] pipeline:save ${n}: the confirmation of Rewind step ${c} was taken back, since the save changed what it does`);this.scheduler?.reload();let d=T(this.deps,e,"pipeline:save:response",{success:!0,id:n});this.deps.broker.postToWebview(d),this.deps.log(`[TX] pipeline:save:response id=${n}`)}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=D(Em,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 ${Bk[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=D(Mm,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: ${A(t)}`);let r=T(this.deps,e,"marketplace:list:response",{success:!1,error:A(t)});this.deps.broker.postToWebview(r)}}handleMarketplaceInstall(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(jm,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: ${A(n)}`);let o=T(this.deps,e,"marketplace:install:response",{success:!1,error:A(n)});this.deps.broker.postToWebview(o)}}};var Do=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 Gn(s,e){return e.aborted?(s.catch(()=>{}),Promise.reject(Hk())):new Promise((t,r)=>{let n=()=>r(Hk());e.addEventListener("abort",n,{once:!0}),s.then(o=>{e.removeEventListener("abort",n),t(o)},o=>{e.removeEventListener("abort",n),r(o)})})}function Hk(){return Object.assign(new Error("Stopped before its answer came."),{code:"CANCELLED"})}var qk=200,ep=50,tp="ai.enabled",rp="ai.errorResolution",Wk="ai:conversations:index",zk="ai",Ld="ai.anthropic.key",nD=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"]),Fd=class{constructor(e){this.deps=e}deps;aiAssistant;asking=new Do;setAIAssistant(e){this.aiAssistant=e}async handle(e){if(!nD.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(Wk)??[]}saveIndex(e){this.deps.configStore.set(Wk,e,zk)}loadConversation(e){return this.deps.configStore.get(this.conversationKey(e))}saveConversation(e){this.deps.configStore.set(this.conversationKey(e.id),e,zk),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<=ep)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-ep).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 (${ep} 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<=qk)return e;let t=e.filter(o=>o.role==="system"),r=e.filter(o=>o.role!=="system"),n=qk-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=D(Vh,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=A(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=D(Ii,e,"ai:error",this.deps);t&&this.asking.abort(t.conversationId)}handleConversationCreate(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Xh,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=D(Ii,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=D(Ii,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(Ld),r=T(this.deps,e,"ai:status:response",{enabled:!!this.aiAssistant&&t,provider:this.aiAssistant?Xp:"none",model:this.aiAssistant?Yp(this.deps.services?.getSandforgeSetting?.("ai.model",Kp.MODEL)):"",budget:this.aiAssistant?this.deps.services?.sessionBudget?.getState():void 0,hasKey:t,errorResolution:this.deps.services?.getSandforgeSetting?.(rp,!0)??!0});this.deps.broker.postToWebview(r),this.deps.log("[TX] ai:status:response")}async enableAIFeature(){await this.writeSetting("ai:save-key",tp,!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: ${A(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: ${A(r)}`)}}async handleSaveKey(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Kh,e,"ai:error",this.deps);if(!t)return;let{apiKey:r,errorResolution:n}=t;try{let o=await this.deps.secretVault.hasSecret(Ld);await this.deps.secretVault.storeSecret(Ld,r),(!o||n!==void 0)&&await this.writeSetting("ai:save-key",rp,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=A(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=D(Yh,e,"ai:error",this.deps);if(!t)return;let r=[];t.errorResolution!==void 0&&r.push([rp,t.errorResolution]),t.enabled!==void 0&&r.push([tp,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(Ld);let t=this.deleteAllConversations();await this.writeSetting("ai:remove-key",tp,!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=A(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 oD=new Set(["ai:anomaly-scan"]),_d=class{constructor(e){this.deps=e}deps;ruleModules;setRuleModules(e){this.ruleModules=e}async handle(e){return oD.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=D(Qh,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=gt(n),d=o??Xr.anomalyScan,c=`SELECT FIELDS(ALL) FROM ${a} LIMIT ${d}`,l=await uf(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: ${A(i)}`);let a=T(this.deps,e,"ai:anomaly-scan:response",{success:!1,error:A(i)});this.deps.broker.postToWebview(a)}}};function Gk(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"")}function sD(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 iD(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=Gk(r);n&&!e.has(n)&&e.set(n,t.name)}return e}function Jk(s,e,t=5){if(t<=0)return[];let r=iD(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=sD(Gk(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 aD={sync:"Sync",seed:"Seed",dataops:"DataOps"};function Vk(s){if(s.code==="STEP_NOT_RUNNABLE")return`A pipeline cannot run a ${s.stepType} step, so the draft leaves it out.`;let e=aD[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 dD=new Set(["WHERE","USING","WITH","GROUP","ORDER","LIMIT","OFFSET","FOR","UPDATE"]),cD=new Set(["WITH","GROUP","ORDER","LIMIT","OFFSET","FOR","UPDATE"]),lD=new Set(["AND","OR","NOT","WHERE"]),uD=/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/,pD=/^([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)(?:\s+[A-Za-z_]\w*)?$/,gD=/^[A-Za-z_]\w*\s*\(([^()]*)\)(?:\s+[A-Za-z_]\w*)?$/,fD=/([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*)\s*(?:!=|<>|<=|>=|=|<|>|\bNOT\s+IN\b|\bIN\b|\bLIKE\b|\bINCLUDES\b|\bEXCLUDES\b)/gi;function hD(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 Xk=/\(\s*SELECT\b/iy;function mD(s){let e="",t=0;for(;t<s.length;){if(Xk.lastIndex=t,s[t]!=="("||!Xk.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 yD(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 wD(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 bD(s){let e=pD.exec(s);if(e)return e[1];let t=gD.exec(s);if(t){let r=t[1].trim();return uD.test(r)?r:null}return null}function RD(s){let e=mD(hD(s)).replace(/\bTYPEOF\b[\s\S]*?\bEND\b/gi,"()"),t=yD(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&&!dD.has(d)&&!c.includes(",")&&i.add(d);let l=[],u=e.slice(t[0].end,t[n].start);for(let f of wD(u)){let m=bD(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,b)=>b>p&&cD.has(r(b)??"")),m=e.slice(t[p].end,f<0?e.length:t[f].start);for(let y of m.matchAll(fD))lD.has(y[1].toUpperCase())||l.push(y[1])}let g=new Set,h=[];for(let f of l){let[m,...y]=f.split("."),b=y.length>0&&i.has(m.toUpperCase())?y.join("."):f,v=b.toUpperCase();g.has(v)||(g.add(v),h.push(b))}return{objectApiName:o,fieldRefs:h}}async function Kk(s,e){let t=RD(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:A(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:A(l)})}return{rootObject:n.name,rootLabel:o.label||n.label,fieldsChecked:t.fieldRefs.length,problems:d}}function np(s){return kD().text(s)}var SD=new Set;function kD(){let s=Zb(),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=eR({text:o},SD,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 Dt=Vc,Ft=Vc.text,Yk="{firstName}, {lastName}, {company}, {email} and {caseSubject}";var cW=[`- "id" and each topic's "key": lower-case letters and digits in words joined by single hyphens, starting with a letter, ${Dt.maxKeyLength} characters at most.`,`- "name": at most ${Ft.name} characters. "businessContext": what the company does and who its customers are, in two or three sentences, at most ${Ft.businessContext} characters.`,`- "customers": "count" is 10 unless the scenario asks for another number, at least the number of topics and at most ${Dt.maxCustomers}; "industry" is the customers' industry as an Account Industry value of Salesforce (Retail, Telecommunications, Technology...), at most ${Ft.industry} characters.`,`- "topics": ${Dt.topics.min} to ${Dt.topics.max}, five unless the scenario calls for more or fewer: the subjects customers write to support about. "label": at most ${Ft.label} characters.`,`- "utterances": ${Dt.utterances.min} to ${Dt.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 ${Ft.utterance} characters. They may name the customer and the case with ${Yk}, 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 ${Ft.articleTitle} characters, "summary" at most ${Ft.articleSummary}, "body" plain-text paragraphs of 600 to 1,500 characters. No placeholder.`,`- "outOfScope": ${Dt.outOfScope.min} to ${Dt.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 ${Ft.utterance} characters. No placeholder.`,"- No word in braces but the placeholders named here, where they are allowed."];var lW=[`- "article": what the agent answers the topic from. "title" at most ${Ft.articleTitle} characters and none of the titles above; "summary" at most ${Ft.articleSummary}; "body" plain-text paragraphs of 1,200 to 3,000 characters, at most ${Ft.articleBody}: the policy or the procedure, with the figures, delays and conditions customers ask about. No placeholder in the article.`,`- "facts": ${Dt.facts.min} to ${Dt.facts.max}, each a sentence of the body copied word for word, at most ${Ft.fact} characters: what an answer drawn from the article has to say.`,`- "caseTemplates": ${Dt.caseTemplates.min} to ${Dt.caseTemplates.max}, two unless the topic needs more: cases customers open on the topic. "subject" at most ${Ft.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" ${Dt.resolutionSteps.min} to ${Dt.resolutionSteps.max} steps, each a comment of the agent who resolved the case, under 400 characters. "description", "followUp" and "resolution" may name ${Yk}.`,"- No word in braces but the placeholders named here, where they are allowed."];var OD=new Set(["ai:forge-plan","ai:generate-pipeline","ai:scenario-draft","ai:tool:cancel"]),op={success:!1,code:"CANCELLED"},Qk="AI not configured. Set your API key in Settings > AI.";function ID(s){switch(s){case"Production":return"production";case"Sandbox":return"sandbox";case"Developer":return"developer";case"Scratch":return"scratch";default:return"production"}}var Ud=class{constructor(e){this.deps=e}deps;aiModules;drafting=new Do;describeGlobalCache=new vs({defaultTtl:5*6e4,maxSize:16,maxSizeBytes:50*1024*1024});describeCache=new vs({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(!OD.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=D(tm,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=D(Zh,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:Qk}));return}let a=await Gn(this.connect(r),o.signal),d=await Gn(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 Gn(Kk(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",{...op})),this.deps.log("[TX] ai:forge-plan:response cancelled");return}this.deps.log(`[ERR] ai:forge-plan: ${A(i)}`),this.deps.broker.postToWebview(T(this.deps,e,"ai:forge-plan:response",{success:!1,error:A(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=Jk(t,o),d=await Gn(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 Gn(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}: ${A(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=D(em,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:ID(u?.orgType)}}),{suggestions:a=[],...d}=await Gn(this.aiModules.pipelineGenerator.generatePipeline(r,i,{signal:o.signal}),o.signal);if(d.steps.length===0&&a.length>0){let l=a.map(Vk).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",{...op})),this.deps.log("[TX] ai:generate-pipeline:response cancelled");return}this.deps.log(`[ERR] ai:generate-pipeline: ${A(i)}`);let a=T(this.deps,e,"ai:generate-pipeline:response",{success:!1,error:A(i)});this.deps.broker.postToWebview(a)}finally{o.end()}}async handleScenarioDraft(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(rm,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:np(t.text)});return}let n=this.aiModules?.scenarioDrafter;if(!n){r({success:!1,code:"AI_NOT_CONFIGURED",error:Qk,sentText:np(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(AD(i))}catch(i){this.deps.log(`[ERR] ai:scenario-draft: ${A(i)}`),r({success:!1,error:A(i)})}finally{o.end()}}};function AD(s){switch(s.kind){case"complete":return{success:!0,sentText:s.sentText,pack:s.pack};case"stopped":return{...op,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 TD=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"]),Bd=class{chatHandler;analysisHandler;toolsHandler;subHandlers;constructor(e){this.chatHandler=new Fd(e),this.analysisHandler=new _d(e),this.toolsHandler=new Ud(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(!TD.has(e.type))return!1;for(let t of this.subHandlers)if(await t.handle(e))return!0;return!1}};function Zk(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 eO(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 ED=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"]),PD=10,sp=3e4,rO=6e4;function nO(s){return`autopilot:${s}`}var ip=(s,e)=>e==="insert"||e==="update",Hd={code:"AUTOPILOT_NOT_READY",message:"Autopilot module is not initialized."},xo={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."},CD=new Set(["autopilot:pause","autopilot:resume","autopilot:skip-node"]),qd=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-7YDNUBO5.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!==nO(r))}async handle(e){if(!ED.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(Hd.message),{code:Hd.code}),CD.has(e.type)&&ke(this.deps,"error","Autopilot",Hd.message,{code:Hd.code})}resolveCurrentOperation(){return this.currentOperationId!==void 0?this.operations.get(this.currentOperationId):void 0}evictOldOperations(){for(;this.operations.size>PD;){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=D(Lh,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=D(Fh,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=D(_h,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),ke(this.deps,"error","Autopilot",`Schema scan failed: ${A(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){ke(this.deps,"error","Autopilot","No schema scan result available. Run scan-schema first.");return}let r=D(Uh,e,"autopilot:error",this.deps);if(!r)return;let n=r;try{let o=n.complianceFramework!=="none"&&t.scanResult?Cw(this.deps.infraServices?.piiDetector??new Fi,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),ke(this.deps,"error","Autopilot",`Plan generation failed: ${A(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,jl(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 (${A(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 Bw(t,r,()=>this.readTargetApiBudget(e),n);return Zk(t,gr(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=D(Hh,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,fo.NO_PLAN,"No execution plan available. Run generate-plan first.");return}let{targetOrgId:c}=n;if(this.writingTargets.has(c)){this.refuseFit(e,xo.code,xo.message);return}try{let l=await this.readTargetAutomation(c,o),u=r.muteAutomation===!0?await this.planMute(c,l).catch(b=>{if(!kt(b))throw b}):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=Iw({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:go(g&&"estimate"in g?g.estimate:void 0)});if("unread"in h){this.refuseFit(e,fo.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 b=>Fw((await m.describe(b)).fields)})}catch(b){let v=A(b);this.refuseFit(e,fo.READ_REFUSED,`The plan could not be fitted: the source refused a read of it (${v}).`,{reason:v});return}if(n.plan!==o||this.currentOperationId!==n.id||this.writingTargets.has(c)){this.refuseFit(e,fo.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,fo.NO_PLAN,"No execution plan available. Run generate-plan first.");return}if(this.writingTargets.has(t.targetOrgId)){this.refuseFit(e,xo.code,xo.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){ke(this.deps,"error","Autopilot","No execution plan available. Run generate-plan first.");return}let r=D(Bh,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){K(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:Re.code}),E(this.deps,"autopilot:execute","autopilot:error",e,new Error(Re.message),{code:Re.code});return}if(this.writingTargets.has(t.targetOrgId)){E(this.deps,"autopilot:execute","autopilot:error",e,new Error(xo.message),{code:xo.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((U,G)=>U+G,0),u=a?eO(a.report,l,[...t.scanResult?.recordCounts.values()??[]].reduce((U,G)=>U+G,0)):void 0,p=new AbortController,g=()=>{},h=new Promise((U,G)=>{g=pe=>pe===void 0?U():G(pe)});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:Te(f),operation:"insert",objectName:r.waves[0]?.objects[0]??"AutopilotData",recordCount:l,module:"autopilot"},{check:y,decision:b}=await Ye(c,m),v=b;if((b==="refused"||b==="declined")&&K(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:b,...u?{fit:u}:{}}),b==="refused"){let U=Qr(y.blockedReason??y.impactSummary);E(this.deps,"autopilot:execute","autopilot:error",e,U,{code:St.blocked}),g(U);return}if(b==="declined"){let U="Operation cancelled by user (confirmation declined).";E(this.deps,"autopilot:execute","autopilot:error",e,new Error(U),{code:St.declined}),g(new Error(U));return}let w=jl(r,i.recordCounts,i.personAccounts),R,k;if(d.muteAutomation===!0)try{({mute:R,read:k}=await this.runMute(t.targetOrgId,r))}catch(U){if(!kt(U))throw U;K(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:v,...u?{fit:u}:{},code:U.code}),E(this.deps,"autopilot:execute","autopilot:error",e,U,{code:U.code}),g(U);return}let I;if(d.checkpointFirst!==void 0&&w.totalRows>0){k??=await this.readTargetAutomation(t.targetOrgId,r);let U=await this.checkpointFirstOf(e,t.targetOrgId,r,d.checkpointFirst,{read:k,mute:R},p.signal);if("refused"in U){K(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:v,...u?{fit:u}:{},code:Rs.CHECKPOINT_REFUSED});let G=new Error(U.refused);E(this.deps,"autopilot:execute","autopilot:error",e,G,{code:Rs.CHECKPOINT_REFUSED}),g(G);return}I=U}w.totalRows>0&&(k??=await this.readTargetAutomation(t.targetOrgId,r));let S=await this.targetEmails(t.targetOrgId,r,w,R?R.automation:k),C=new Set(w.objects.map(({objectApiName:U})=>U)),O=(U,G)=>C.has(U)&&ip(U,G),P=be(f,t.targetOrgId),_=k?await Yt({read:k,...R?.plan?{plan:R.plan}:{},writes:O,readDeliverability:async()=>m.orgTier==="production"?Nt:$t(await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager)),accepted:!1,target:P,run:"autopilot",keepsAddresses:d.keepContactPoints===!0}):void 0,J=await Hw({plan:w,storage:await this.readTargetDataStorage(t.targetOrgId),readApiBudget:()=>this.readTargetApiBudget(t.targetOrgId),confirmAboveRecords:this.confirmAboveRecords(),emails:S.checks,...S.unread!==void 0?{emailsUncounted:S.unread}:{},org:P,orgTier:m.orgTier,confirm:U=>c.confirmRun(U),...I?{checkpointFirst:I}:{},readBack:Uw(w),mute:$r(R?.plan),..._?{runEmails:_}:{}});if(!J.go){K(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:v,...u?{fit:u}:{},code:J.code,details:Dn(J.emails)});let U=new Error(J.message);E(this.deps,"autopilot:execute","autopilot:error",e,U,{code:Rs[J.code],...await this.fitOffer(t,J,w,I)}),g(U);return}this.liveTracker?.register(e.id,"autopilot","Autopilot run",l),this.executingOperations.add(t.id);let B=new Map,re=!1,H=R?.muted,j=J.checkpoint,N,Y=!1,Q=U=>{re||(re=!0,K(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:U,guard:v,objects:[...B.values()],source:{origin:"org",orgId:t.sourceOrgId},...U==="stopped"?{code:et}:{},...H?{muted:ot(H)}:{},...N?.state==="taken"?{checkpointId:N.checkpointId}:{},...u?{fit:u}:{},details:Dn(J.emails)}))};try{d.grappeThreshold&&this.deps.log(`[GRAPPE] autopilot threshold set to ${d.grappeThreshold}`);for(let M of r.waves)for(let F of M.objects)this.sendNodeProgress(e,String(F),"processing",M.order);let U=new Map;for(let M of r.waves)for(let F of M.objects)U.set(String(F),M.order);let G=R?.prepared?await R.prepared.acquire(e.id).catch(M=>{if(!kt(M))throw M;return M}):void 0;if(kt(G)){j&&(N=await this.settleCheckpoint(j,!1)),re=!0,K(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:v,...u?{fit:u}:{},code:G.code}),this.liveTracker?.fail(e.id,G.message),E(this.deps,"autopilot:execute","autopilot:error",e,G,{code:G.code,...N?{extraPayload:{checkpoint:N}}:{}}),g(G);return}G&&(H=G.outcome);let pe=G?_?.afterLease(G.outcome,J.emails?.accepted===!0):void 0;if(G&&pe){H=await G.release(),j&&(N=await this.settleCheckpoint(j,!1)),re=!0,K(this.deps,{action:"autopilot_execute",module:"autopilot",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",guard:v,code:pe.code,muted:ot(H),details:Dn(J.emails)});let M=Uy(pe.message,"autopilot","Untick Mute automation to be asked about them and run it all the same"),F=new Error(M);this.liveTracker?.fail(e.id,M),E(this.deps,"autopilot:execute","autopilot:error",e,F,{code:Rs.EMAILS_NOT_ACCEPTED,...N?{extraPayload:{checkpoint:N}}:{}}),g(F);return}Y=!0;let ne=await this.orchestrator.executePlan(r,n,o,i.recordCounts,M=>{let F=String(M.objectApiName);B.set(F,{...lt(F),...M.type==="node-completed"?{created:M.successCount,failed:M.failureCount}:{created:M.partialSuccessCount,failed:M.failureCount??0}});let W=[...B.values()].reduce((ae,z)=>ae+z.created+z.failed,0);this.liveTracker?.updateProgress(e.id,l>0?Math.round(W/l*100):0,W,l,F),M.type==="node-completed"?this.sendNodeProgress(e,F,"completed",U.get(F)??0,{recordCount:M.successCount,failureCount:M.failureCount,linkedCount:M.linkedCount,refusals:M.refusals,apiCallsUsed:M.apiCallsUsed}):this.sendNodeProgress(e,F,"failed",U.get(F)??0,{recordCount:M.partialSuccessCount,failureCount:M.failureCount,linkedCount:M.linkedCount,refusals:M.refusals,error:M.errors[0]??`Execution failed for ${F}`})},p.signal,i.parentIds,{...d.keepContactPoints===!0?{keepContactPoints:!0}:{},...G?{lease:{assigned:G.outcome.assigned.length,giveBack:()=>G.release()}}:{},...a?{fit:a.run}:{}}).finally(async()=>{G&&(H=await G.release())});j&&(N=await this.settleCheckpoint(j,ne.totalSuccess>0));let he=new Set(ne.completedObjects),qe=new Set(ne.failedObjects),Ie=new Set(ne.skippedObjects),ce=new Set(ne.stoppedObjects??[]),oe=[],le=0,Ae=[],Z=[];for(let M of r.waves)for(let F of M.objects){let W=String(F),ae=ne.objectOutcomes?.[W],z=ne.statuses?.[W],ue=ne.lookups?.[W],$e=(ae?.leftToThePlatform??[]).reduce((Ue,it)=>Ue+it.count,0),Ne={...ae?{recordCount:ae.written,failureCount:ae.failed,linkedCount:ae.linked,refusals:ae.refusals,...$e>0?{leftToThePlatform:$e}:{},...ae.currenciesReplaced?{currenciesReplaced:ae.currenciesReplaced}:{},...ae.pricesSettled?{pricesSettled:ae.pricesSettled}:{},...ae.recordTypeGiven?{recordTypeGiven:ae.recordTypeGiven}:{},...ae.cutSinceFit!==void 0?{cutSinceFit:ae.cutSinceFit}:{},...ae.sentAgainForALock?{sentAgainForALock:ae.sentAgainForALock}:{}}:{},...z?{statusesApplied:z.applied,statusRefusals:z.refusals}:{},...ue?{lookupsFilled:ue.filled,lookupRefusals:ue.refusals}:{}};if(he.has(W))this.sendNodeProgress(e,W,"completed",M.order,{recordCount:i.recordCounts.get(W)??0,failureCount:0,...Ne});else if(qe.has(W))this.sendNodeProgress(e,W,"failed",M.order,{...Ne,error:ne.nodeErrors?.[W]??`Execution failed for ${W}`});else if(Ie.has(W)){let Ue=i.recordCounts.get(W)??0;B.set(W,{...lt(W),skipped:"counted",...Ue>0?{notSent:Ue}:{}}),this.sendNodeProgress(e,W,"skipped",M.order,{recordCount:0,failureCount:0,...Ue>0?{notSent:Ue}:{}})}else if(ce.has(W)){let Ue=ae?.notSent??0;le+=ae?.heldForTheirTask??0,B.set(W,{...lt(W),created:ae?.written??0,failed:ae?.failed??0,...Ue>0?{notSent:Ue}:{}}),this.sendNodeProgress(e,W,"stopped",M.order,{...Ne,recordCount:ae?.written??0,failureCount:ae?.failed??0,...Ue>0?{notSent:Ue}:{}})}let se=()=>B.get(W)??{...lt(W),created:ae?.written??0,failed:ae?.failed??0},we=ae?.lookupsLeftEmpty??0,xe=ae?.statusesNotGivenBack??0;if(we+xe>0){let Ue={...we>0?{lookupsLeftEmpty:we}:{},...xe>0?{statusesNotGivenBack:xe}:{}};oe.push({objectApiName:W,...Ue}),B.set(W,{...se(),...Ue})}ue?.leftEmpty!==void 0&&(Ae.push({objectApiName:W,records:ue.leftEmpty,refusals:ue.refusals}),B.set(W,{...se(),lookupsNotFilled:ue.leftEmpty}));let Xe=z?.leftDraft??0;z&&Xe>0&&(Z.push({objectApiName:W,records:Xe,refusals:z.refusals}),B.set(W,{...se(),statusesNotApplied:Xe}))}let ve=Lw(ne);Q(ne.stopped?ne.totalSuccess+ne.totalFailure>0?"cancelled":"stopped":ve);let x=T(this.deps,e,"autopilot:completed",{status:ve,totalRecords:ne.totalSuccess+ne.totalFailure+ne.totalSkipped,totalSuccessCount:ne.totalSuccess,totalFailureCount:ne.totalFailure,totalElapsedMs:ne.elapsedMs,totalApiCalls:0,...H?{mutedAutomation:H}:{},...N?{checkpoint:N}:{},...ne.cutSinceFit!==void 0?{cutSinceFit:ne.cutSinceFit}:{},...Ae.length>0?{lookupsNotFilled:Ae}:{},...Z.length>0?{statusesNotApplied:Z}:{},...ne.stopped?{stopped:!0,notWritten:ne.stoppedObjects??[],...oe.length>0?{leftByStop:oe}:{},...le>0?{emailsHeldForTheirTask:le}:{}}:{}});this.deps.broker.postToWebview(x),ne.stopped?this.liveTracker?.cancel(e.id):ve==="failure"?this.liveTracker?.fail(e.id,ne.fatalError??"No record could be written."):ve==="partial"?this.liveTracker?.partial(e.id):this.liveTracker?.complete(e.id),g()}catch(U){this.liveTracker?.fail(e.id,A(U)),g(U),j&&N===void 0&&(N=await this.settleCheckpoint(j,Y)),Q("failure"),E(this.deps,"autopilot:execute","autopilot:error",e,U,N?{extraPayload:{checkpoint:N}}:void 0),ke(this.deps,"error","Autopilot",`Execution failed: ${A(U)}`)}finally{this.executingOperations.delete(t.id)}}maxRecordsPerObject(){let e=this.deps.services?.getSandforgeSetting?.("forge.maxRecordsPerObject",5e4);return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.floor(e),di):5e4}confirmAboveRecords(){let e=this.deps.services?.getSandforgeSetting?.("safety.confirmAboveRecords",_r);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):_r}async readTargetDataStorage(e){try{let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return await new fe(sp).withTimeout("autopilot:limits",()=>pr(t))}catch(t){return{unread:A(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 mt(async()=>Pt(await q(e,this.deps.orgRegistry,this.deps.orgManager)),t,{...this.muteLeases,writes:ip})}async readTargetAutomation(e,t){let r=this.targetAutomation;return new fe(rO).withTimeout("autopilot:automation",()=>r.read(e,Zi(t))).catch(n=>({unread:A(n)}))}async checkpointFirstOf(e,t,r,n,o,i){let a=this.beforeRunCheckpoints;if(!a)return{refused:ur(new Error("SandForge's checkpoints are not set up in this window"))};let{read:d,mute:c}=o,l="objects"in d?Dr(d,c?.plan,ip):{firing:[]},u={module:"autopilot",orgId:t,operationId:e.id,written:Zi(r),running:l,request:n},p={operationId:nO(e.id)};try{return{estimate:await a.scope(u,p),take:h=>a.take(u,p,{planned:h,signal:i})}}catch(g){return{refused:ur(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 (${A(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:be(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 (${A(c)})`),{extraPayload:d}}}async readTargetApiBudget(e){let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return new fe(sp).withTimeout("autopilot:limits",()=>Qt(t))}async targetEmails(e,t,r,n){let o=this.targetAutomation,i=await _w({plan:r,objects:Zi(t),readAutomation:a=>n?"objects"in n?Promise.resolve(n):Promise.reject(new Error(n.unread)):new fe(rO).withTimeout("autopilot:automation",()=>o.read(e,a)),readLimits:async()=>{let a=await q(e,this.deps.orgRegistry,this.deps.orgManager);return new fe(sp).withTimeout("autopilot:limits",()=>fr(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()){ke(this.deps,"warning","Autopilot","No autopilot execution in progress.");return}try{this.orchestrator.pause();for(let t of this.runningRequests)this.liveTracker?.pause(t);ke(this.deps,"info","Autopilot","Execution paused.")}catch(t){E(this.deps,"autopilot:pause","autopilot:error",e,t),ke(this.deps,"error","Autopilot",`Pause failed: ${A(t)}`)}}handleResume(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}if(!this.hasExecutingOperation()){ke(this.deps,"warning","Autopilot","No autopilot execution in progress.");return}try{this.orchestrator.resume();for(let t of this.runningRequests)this.liveTracker?.resume(t);ke(this.deps,"info","Autopilot","Execution resumed.")}catch(t){E(this.deps,"autopilot:resume","autopilot:error",e,t),ke(this.deps,"error","Autopilot",`Resume failed: ${A(t)}`)}}handleSkipNode(e){if(this.deps.log(`[RX] ${e.type} id=${e.id}`),!this.orchestrator){this.refuseNotReady(e);return}let t=D(qh,e,"autopilot:error",this.deps);if(!t)return;let r=t;if(!this.hasExecutingOperation()){ke(this.deps,"warning","Autopilot","No autopilot execution in progress.");return}try{this.orchestrator.skip(r.objectApiName),ke(this.deps,"info","Autopilot",`Skipped node: ${r.objectApiName}`)}catch(n){E(this.deps,"autopilot:skip-node","autopilot:error",e,n),ke(this.deps,"error","Autopilot",`Skip failed: ${A(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){ke(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),ke(this.deps,"error","Autopilot",`Report generation failed: ${A(r)}`)}}};import{dirname as pO}from"node:path";import{AsyncLocalStorage as DD}from"node:async_hooks";var xD=new DD;async function oO(s){let e=new Map;return{result:await xD.run(e,s),sent:e}}function sO(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 ap from"node:path";var Wd="forge:imported-templates",MD=10,iO="forge",jD=V({folder:L().min(1),templates:Se(Xn()),replacing:Se(L())});function Gr(s){if(typeof s!="object"||s===null||Array.isArray(s))return!1;let{id:e}=s;return typeof e=="string"&&e.length>0}function Hs(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 dp(s,e){return ap.resolve(s)===ap.resolve(e)}function cp(s){let e=s.get(Wd);if(!Array.isArray(e))return[];let t=[];for(let r of e){let n=jD.safeParse(r);if(!n.success)continue;let{folder:o,templates:i,replacing:a}=n.data;t.push({folder:o,templates:i.filter(Gr),replacing:a})}return t}function zd(s,e){return cp(s).find(t=>dp(t.folder,e))}function aO(s,e,t,r){if(t.length===0)return;let n=cp(s),o=n.findIndex(d=>dp(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(Wd,n.slice(-MD),iO)}function dO(s,e){let t=cp(s).filter(r=>!dp(r.folder,e));t.length>0?s.set(Wd,t,iO):s.delete(Wd)}function ND(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}:{},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}))}:{},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 cO(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:ND(i)}:{},...n.length>0?{leftOutCounts:n}:{},...c?{idRemapWithTheirRecord:c}:{}}}var lO="SELECT Id, Name, Username FROM User WHERE IsActive = true AND UserType = 'Standard' ORDER BY Name LIMIT 2001";function uO(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 gp=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/,$o=L().min(1).max(128),LD=V({recordId:L().regex(gp,"Invalid Salesforce record ID"),orgId:$o}),Rn=Hp.superRefine((s,e)=>{if(s.inputMode!=="org"&&s.depth!=="all"&&s.sample===void 0)return;let t=zc(s);t!==void 0&&e.addIssue({code:"custom",message:t,path:["inputMode"]});let r=FD(s.sample);r!==void 0&&e.addIssue({code:"custom",message:r.message,path:r.path})});function FD(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 _D=V({config:Rn}),UD=V({graph:Tr,config:Rn,anonymizationRules:ti.optional(),files:Wp.optional(),retryOf:L().min(1).max(200).optional(),reviewSkipped:Je().optional(),muteAutomation:Je().optional(),checkpointFirst:Of.optional()}).superRefine((s,e)=>{let t=qp(s.config,s.files);t!==void 0&&e.addIssue({code:"custom",message:t,path:["files"]})});function BD(s,e){let t=s.check(e);return{check:t,decision:t.allowed?"allowed":"refused"}}var gO="FILES_NOT_ACCEPTED",fO="RETRY_UNAVAILABLE",HD="GRAPH_WITHOUT_EDGES",qD="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.",WD="WHOLE_ORG_DIRECT",zD="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.",GD="WHOLE_ORG_REHEARSAL",JD="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.",VD="A clone of the whole org keeps its journal on disk, which could not be opened. Nothing was written.",lp="JOURNAL_UNAVAILABLE",XD="RESUME_TARGET_UNREAD",bn=class extends Error{constructor(t,r){super(r);this.code=t;this.name="ForgeRunRefusal"}code};function hO(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:A(s),lift:t}}function KD(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 Jd="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.",Mo="JOURNAL_GONE",yn=`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. ${Jd}`,jo="RUN_NOT_IN_HISTORY",mO="REMOVAL_RUNNING",YD="VERIFY_RUNNING",yO="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.",QD="RESUME_UNAVAILABLE",wO="remove the records it created (Forge \u2192 Recent runs), then run the clone again. Nothing was read or written.",bO="RESUME_TARGET_CHANGED",up="RESUME_CHANGED",ZD=V({forgeId:L().min(1).max(200),graph:Tr.optional(),config:Rn.optional(),muteAutomation:Je().optional()}).strict(),RO=new Set(["cancelled","failure","interrupted"]),wn="Forge execution was aborted before it started. Nothing was written.",pp="FORGE_RUNNING",ex="FORGE_STOP_AMBIGUOUS",tx={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.`}},rx=V({requestId:L().min(1).max(200).optional()}).optional(),nx=V({template:Gc}),ox=V({forgeId:L().min(1).max(200),includeChanged:Je().optional(),sweep:Je().optional(),again:Je().optional(),muteAutomation:Je().optional(),sweepLate:Je().optional(),sweepUntied:Je().optional()}),sx=V({forgeId:L().min(1).max(200),again:Je().optional(),sweptObjects:kf.optional()}),ix=V({forgeId:L().min(1).max(200)}),ax=V({forgeId:L().min(1).max(200),recordId:L().regex(gp,"Invalid Salesforce record ID")}).strict(),dx=V({forgeId:L().min(1).max(200)}).strict(),cx=V({forgeId:L().min(1).max(200)}).strict(),lx=5e3,ux=V({templateId:L().min(1).max(200)}),px=V({graph:Tr,config:Rn}),gx=V({framework:L().min(1).max(50),graph:Tr,config:Rn,anonymizationRules:ti.optional()}),fx=V({sourceOrgId:$o,targetOrgId:$o,objectApiNames:Se(L().regex(/^[A-Za-z][A-Za-z0-9_]*$/).max(80)).max(100)}),hx=V({graph:Tr,config:Rn,anonymizationRules:ti.optional()}),mx=V({targetOrgId:$o,graph:Tr}),yx=V({graph:Tr,config:Rn}),wx=V({orgId:$o}),bx=V({targetOrgId:$o,objectApiNames:Se(L().min(1).max(255)).max(5e3)}),Rx=V({graph:Tr,config:Rn,muteAutomation:Je().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"]}),vx="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.",Sx=16;function vO(s){let e=s.fit();return e?{fit:e}:{}}function Gd(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 kx(){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 D(s,e,t,r)}function Ox(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 SO(s){return s.successCount+s.updatedCount>0}function kO(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 Ix(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 Ax(s,e){let t=s.remap.createdByObject.reduce((d,c)=>d+c.sourceIds.length,0),r=Object.keys(s.remap.table).length,n=Ix(s),o=new Set(s.remap.withTheirRecord??[]),i=s.remap.linked.filter(d=>o.has(d)),a=r>ta?{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 Tx=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"]),OO=3e4,Ex=3e4,Px=6e4,qs=6e4,Cx=12e4;function IO(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 AO="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.",Dx=6e4,xx=10*6e4,Mx=8,jx=8,No=3e4,Nx=3e4,TO="forge:templates",EO="forge:history";function $x(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 Lx(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:jO(i.writtenBetween,i),...c.length>0?{wrote:c}:{},...d.length>0?{linked:d}:{}}]})}function jO(s,e){return s?{runStartedAt:new Date(s.first),runEndedAt:new Date(s.last)}:{runDurationMs:e.duration,runRecordedAt:new Date(e.timestamp)}}function Fx(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=tn(r.objects,n),i=t.filter(a=>o.includes(a));return i.length>0?[{forgeId:r.forgeId,objects:i}]:[]})}function _x(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 Ux(s){return(s.mayHaveBeenWritten??[]).reduce((e,{sourceIds:t})=>e+t.length,0)}function Bx(s,e){if(!e||e.calls===0)return Ux({mayHaveBeenWritten:s});let t=e.lookedFor??new Set,r=(s??[]).reduce((n,{sourceIds:o})=>n+o.filter(i=>!t.has(i)).length,0);return Fl(e)+r}function Hx(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 qx(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 PO="forge";function Wx(s){let e={...s};return delete e.sourceOrgId,delete e.targetOrgId,e}function zx(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:Gx(e)}:{},...s.failedReads?.length?{failedReads:s.failedReads}:{}}}function Gx(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 Jx(s,e){let t=s.nodes.filter(d=>d.included),r=t.map(d=>d.objectApiName).join(", ")||"ForgeData",n=Ay,o=e.inputMode==="org"?void 0:e.maxRecordsPerObject,i=e.inputMode==="record"&&typeof e.recordId=="string",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 Vx(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 CO(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 DO(s,e){let t=(e.nodes??[]).map(r=>r.objectApiName).sort();return JSON.stringify([s.sourceOrgId,s.targetOrgId,t])}function Xx(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 xO(s,e){return s.apiCalls===void 0?s:{...s,apiCalls:s.apiCalls+e}}function MO(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 Kx(s){return s instanceof Error&&s.name==="ForgeAbortedError"}var Vd=class extends Error{constructor(t,r){super(r);this.code=t;this.name="RehearsalStoppedError"}code};function Yx(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 Xd=class s{constructor(e,t,r){this.deps=e;this.externalBrowser=t??new wr,this.saveDialog=r??new nn}deps;abortController=null;stops=new cb;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;describeGlobalCache=new vs({defaultTtl:5*6e4,maxSize:16,maxSizeBytes:50*1024*1024});dmlTracker=new vi;removing=new Set;trials=new fb;simulations=new ew;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)}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(!Tx.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;default:return!1}}async loadTemplates(){if(!this.templateStore){let e=this.deps.configStore.get(TO);return{templates:Array.isArray(e)?e.filter(Gr):[]}}return this.withImportedTemplates(this.templateStore)}async withImportedTemplates(e){let t=zd(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=A(n);return de.warn(`Imported forge templates not written into .sandforge/: ${o}`),{templates:await e.list(),importNotMerged:o}}return dO(this.deps.configStore,e.workspacePath),de.info("Merged an imported set of forge templates into .sandforge/"),{templates:r}}async saveTemplates(e){if(!this.templateStore){this.deps.configStore.set(TO,e,PO);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(EO)??[]}saveHistory(e){this.deps.configStore.set(EO,e,PO)}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(LD,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();De(o.limitInfo,"forge:preview describeGlobal"),a=w.sobjects.map(R=>({name:R.name,label:R.label,keyPrefix:R.keyPrefix??null})),this.describeGlobalCache.set(n,a)}let d=a.find(w=>w.keyPrefix===i),c=be(this.deps.orgManager.getOrg(n),n),l=(w,R)=>{this.deps.broker.postToWebview(T(this.deps,e,"forge:preview:error",{code:w,orgName:c,message:R}))};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 lf(o,d.name,`SELECT FIELDS(STANDARD) FROM ${d.name} WHERE Id = '${zt(r)}' LIMIT 1`);if(De(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,R])=>({name:w,value:String(R)})),f=await o.describe(d.name);De(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 b=y*.001,v=T(this.deps,e,"forge:preview:response",{objectApiName:d.name,objectLabel:d.label,recordId:r,fields:h,estimatedRecordCount:y,totalFieldCount:m,estimatedSize:b});this.deps.broker.postToWebview(v)}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(_D,e,"forge:discover:error",this.deps);if(!t)return;let{config:r}=t,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=Gd(u=>{let p=T(this.deps,e,"forge:discover:progress",u);this.deps.broker.postToWebview(p)},100);try{de.info("Forge discover started");let u=this.orchestrator,{result:p,sent:g}=await oO(()=>u.discover(r,{...r.inputMode==="org"?{}:{maxNodes:r.maxNodes},signal:n.signal,onProgress:y=>{l(y)}}));if(l.flush(),n.signal.aborted){ge(this.deps,o,{aborted:!0}),this.answerStoppedDiscovery(e,i);return}let h=sO(g,r),f=DO(r,p);this.discoverySent.delete(f),h&&this.discoverySent.set(f,h);for(let y of this.discoverySent.keys()){if(this.discoverySent.size<=jx)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),ge(this.deps,o,{nodeCount:p.nodes?.length??0}),de.info("Forge discover finished",{objects:p.nodes?.length??0,records:p.totalRecords})}catch(u){if(l.flush(),n.signal.aborted){ge(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}),je(this.deps,o,A(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}=tx[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(UD,e,"forge:execute:error",this.deps);if(!r)return;let{graph:n,config:o,anonymizationRules:i,files:a,reviewSkipped:d,muteAutomation:c}=r,l=t?t.forgeId:r.retryOf,u=l!==void 0?Ox(l,this.loadHistory()):void 0,p=l===void 0?r.checkpointFirst:void 0;l!==void 0&&r.checkpointFirst!==void 0&&de.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=o.dryRun===!0,h=Ul(n,o),f=Zy(o),m=new hb(o,{reviewSkipped:d===!0,...this.trials.before(h)}),y=o.inputMode==="org",b=y&&o.sample!==void 0,v=(_e,He)=>{g||K(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:o.targetOrgId,outcome:"stopped",code:_e,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(He),{code:_e})};if(n.withoutEdges===!0){v(HD,qD);return}if(y&&d===!0){v(WD,zD);return}let w=y?sb(n):void 0;if(w){v(w.code,w.message);return}let R=a?Up(o.anonymizePII,a.acceptedAsIs):null;if(R){K(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:o.targetOrgId,outcome:"stopped",code:gO,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(R),{code:gO});return}let k,I;if(l!==void 0&&!t){let _e=await this.runToRetry(l,o.targetOrgId);if("refused"in _e){K(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:o.targetOrgId,outcome:"stopped",code:fO,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(_e.refused),{code:fO});return}k=_e.written,I=_e.journalId!==void 0?{journalId:_e.journalId}:{}}let S=this.deps.infraServices?.productionGuard;if(!S){K(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:o.targetOrgId,outcome:"stopped",code:Re.code,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(Re.message),{code:Re.code});return}let C=this.deps.orgManager.getOrg(o.targetOrgId),O=Te(C),P=be(C,o.targetOrgId);if(O==="production"){this.refuseAtGate(e,o.targetOrgId,new ut("PRODUCTION_TARGET",`${P} 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 _=await this.ownerMapRefusal(o);if(_){g||K(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:o.targetOrgId,outcome:"stopped",code:_.code,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,_,{code:_.code,retryable:!0});return}let J={orgId:o.targetOrgId,orgTier:O,operation:"insert",...Jx(n,o),module:"forge"},B=new AbortController,re=this.stops.awaitGuard(e.id,B),{check:H,decision:j}=g?BD(S,J):await Ye(S,J).finally(re);g&&re();let N=j;if(H.warnings.length>0&&de.warn("Forge run: Production Guard warnings",{warnings:H.warnings}),(j==="refused"||j==="declined")&&K(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:o.targetOrgId,outcome:"stopped",guard:j,context:m.context()}),j==="refused"){E(this.deps,"forge:execute","forge:execute:error",e,new Error(`Operation blocked by Production Guard: ${H.blockedReason??H.impactSummary}`),{code:"GUARD_BLOCKED"});return}if(j==="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(B.signal.aborted){K(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:o.targetOrgId,outcome:"stopped",guard:j,code:ft,context:m.context()}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(wn),{code:ft,retryable:!0});return}let Y=`${o.sourceOrgId}:${o.targetOrgId}:${o.recordId??""}`,Q=n.nodes?.map(_e=>_e.objectApiName).join(",")??"",U=`forge:${Y}:${Q}:${n.totalRecords??0}`+(l!==void 0?`:${t?"resume":"retry"}:${l}`:""),G=this.dmlTracker.isDuplicate(U)?this.dmlTracker.get(U):void 0,pe=this.lastWriteAt.get(U),me=pe!==void 0&&Date.now()-pe<s.DUPLICATE_COOLDOWN_MS;if(G?.status==="pending"||me){de.warn("Duplicate forge execution detected",{operationId:U}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(`Duplicate forge operation: ${U}`),{code:"DUPLICATE"});return}if(this.executeOperationId!==null){K(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:o.targetOrgId,outcome:"stopped",guard:j,code:pp,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:pp,retryable:!0});return}let ne=n.totalRecords??0;G?(G.status="pending",G.recordCount=ne,G.registeredAt=new Date().toISOString()):this.dmlTracker.register(U,"forge","upsert",ne),this.abortController=B;let he=`forge-execute-${this.deps.nextId()}`,qe=g?"Simulating forge operation":"Executing forge operation";ze(this.deps,he,"forge",qe);let Ie=this.trackRun(he,qe,B,!0);this.liveTracker?.register(he,"forge",qe),this.executeOperationId=he,this.writingTo=g?null:o.targetOrgId,this.stops.beginRun(e.id,B);let ce=Date.now(),oe,le,Ae,Z,ve,x=!1,M=()=>{x||!le||(x=!0,le.close())},F={keep:!1},W=!1,ae=async()=>{if(!oe||W)return;W=!0;let _e=oe,He=F;M(),await(He.keep?this.runJournal?.stop(_e,He.status,He.forgeId):this.runJournal?.end(_e))?.catch(tt=>{de.warn(`Forge run journal not ${He.keep?"kept":"dropped"}: ${A(tt)}`)}),this.journalsRunning.delete(_e)},z={requests:0},ue,$e=()=>{let _e=this.requestsSent?.();return _e===void 0||ue===void 0?void 0:z.requests+_e-ue},Ne,se=!1,we=[],xe,Xe=0,Ue,it,Be,Uo,rr=[],Bo,Sn=()=>(Bo??=this.jobsStillRunning(o.targetOrgId,Uo,z).then(_e=>{rr=_e}),Bo),Jn,Or={firing:[]},Xs,Ht,Ks,Ir,Ho=!1,bt,kn,qo=Gd(_e=>{let He=T(this.deps,e,"forge:progress",_e);this.deps.broker.postToWebview(He)},100),Vn=Gd(_e=>{this.deps.broker.postToWebview(T(this.deps,e,"forge:sampling:progress",{..._e}))},100),Bc=this.liveProgressOf(he,n),Ys=kx(),Ar=this.orchestrator.on("forge:progress",_e=>{let He=Ys(_e),tt=$e(),rt=tt===void 0?He:{...He,apiCalls:tt};Bc(rt);let ct=rt.status;if(ct==="done"||ct==="error"||ct==="skipped"||ct==="stopped"){qo.flush();let Qe=T(this.deps,e,"forge:progress",rt);this.deps.broker.postToWebview(Qe);return}qo(rt)});try{de.info("Forge execute started",{source:be(this.deps.orgManager.getOrg(o.sourceOrgId),"unknown org"),target:be(this.deps.orgManager.getOrg(o.targetOrgId),"unknown org")});let _e=this.maxRecordsPerObject(),He=Dl(n,{leftOut:new Set(n.nodes.filter(ai).map(ee=>ee.objectApiName)),retry:l!==void 0}),tt=new Set(He.map(ee=>ee.objectApiName)),rt=(ee,te)=>te==="insert"||te==="update"&&tt.has(ee);if(g){if(p!==void 0||y||b){let ee=await this.automationBeforeTheRun(o.targetOrgId,n);if("automation"in ee){let te=c===!0?await mt(()=>this.muteOrg(o.targetOrgId),ee.automation,{...this.muteLeases,writes:rt}).then(Ee=>Ee.plan,Ee=>{de.warn(`Forge simulation: the mute could not be planned (${A(Ee)})`)}):void 0;Or=Dr(ee.automation,te,rt),Xs=te}}}else{let ee=await this.automationBeforeTheRun(o.targetOrgId,n);Xe=dn("automation"in ee?ee.automation:ee);let te=ee,Ee;if(c===!0){let Ge=await mt(()=>this.muteOrg(o.targetOrgId),"automation"in ee?ee.automation:ee,{...this.muteLeases,writes:rt});it=Ge.prepared,Be=Ge.muted,Ee=Ge.plan,"automation"in ee&&Ge.automation&&(te={...ee,automation:Ge.automation})}if((p!==void 0||b||y)&&"automation"in ee&&(Or=Dr(ee.automation,Ee,rt)),xe=te,"automation"in te&&(we=pg(te.automation)),B.signal.aborted)throw se=!0,new Error(wn);if(m.automationRead(te,He),Ir=await Yt({read:"automation"in ee?ee.automation:ee,...Ee?{plan:Ee}:{},writes:rt,applyAssignmentRules:o.applyAssignmentRules===!0,readDeliverability:()=>this.readDeliverability(o.targetOrgId,B.signal),accepted:!1,target:P,run:"clone",keepsAddresses:o.keepContactPoints===!0}),z.requests+=Ir.ofRun.read?.requests??0,B.signal.aborted)throw se=!0,new Error(wn);m.emailsRead(Ir.gate.audit);let Pe=await this.confirmAutomation(S,{orgId:o.targetOrgId,org:P,orgTier:O,username:C?.username},te,He,d===!0,Ir.gate.confirmation);Pe==="confirmed"&&(m.confirm("automation"),Ir.gate.verdict==="asks"&&(Ho=!0,m.confirm("emails"))),N=hs(N,Pe);let at=y?[]:Qy(n,o.maxRecordsPerObject,_e);if(at.length>0){if(B.signal.aborted)throw se=!0,new Error(wn);let Ge=await this.confirmReadCeiling(S,{org:P,orgTier:O,source:be(this.deps.orgManager.getOrg(o.sourceOrgId),o.sourceOrgId)},at,_e);Ge==="confirmed"&&m.confirm("volume"),N=hs(N,Ge)}}if(B.signal.aborted)throw se=!0,new Error(wn);let ct=g?void 0:this.runUserOf(o.targetOrgId),Qe=await this.loadRecordTypeMappings(o,B.signal,z);if(B.signal.aborted)throw se=!0,new Error(wn);Ae=await ct,ce=Date.now(),ue=this.requestsSent?.(),Uo=this.lostBulkJobs?.count;let pt=g?void 0:this.runJournal,nr;if(pt){let ee=t?.journalId??`forge-run-${ce}`;oe=ee,this.journalsRunning.add(ee);let te=Pe=>new bn(XD,`${P} could not be read for the insert calls the run had under way when it stopped (${A(Pe)}): taken up without them, the run would write their records twice. Reconnect ${P} on Organizations if its session expired, then resume the run again. Nothing was written.`);if(le=await(t?pt.resuming(ee).then(async()=>{let Pe=await q(o.targetOrgId,this.deps.orgRegistry,this.deps.orgManager).catch(At=>{throw te(At)}),at={},Ge=await pt.reconcile(ee,KD($l(Pe),at)).catch(At=>{throw at.err!==void 0?te(at.err):At});for(let At of Ll(Ge,P))de.info(`Forge resume: ${At.trim()}`);Z=Ge.uncertain,ve=Ge.underway;let Wt=this.loadHistory().find(At=>At.forgeId===t.forgeId);Wt&&Ge.found.length>0&&await this.withRowsFoundAfterStop(Wt,Ge.found)}):pt.begin(ee,o.targetOrgId,new Date(ce),{...this.resumeHeadOf(n,o,i,_e),...c===!0?{muteAutomation:!0}:{},...a?{files:a}:{}},Ae)).then(()=>pt.open(ee)).catch(Pe=>{de.warn(`Forge run journal not started: ${A(Pe)}`),nr={err:Pe}}),t&&!le){let Pe=nr?.err;if(Pe instanceof bn)throw Pe;let{reason:at,lift:Ge}=hO(Pe);throw new bn(lp,`The journal of the run to resume, in ${pO(pt.pathOf(ee))}, could not be opened (${at}). ${Ge}, then resume it again. Nothing was written.`)}}if(y&&!g&&!le){if(!pt||!oe||nr===void 0)throw new bn(lp,VD);let{reason:ee,lift:te}=hO(nr.err);throw new bn(lp,`A clone of the whole org keeps its journal on disk, in ${pO(pt.pathOf(oe))}, which could not be opened (${ee}). ${te}, then run it again. Nothing was written.`)}if(b&&(bt=await this.sampleOf({graph:n,config:o,anonymizationRules:i,readCeiling:_e,dryRun:g,...oe!==void 0?{journalId:oe}:{},resumes:t!==void 0,...I?{retried:I}:{},volumeCase:f,target:P,lookup:z,room:()=>Ml(Or,rt).perRecord,onProgress:Vn})),B.signal.aborted)throw se=!0,new Error(wn);let qt,or=y?nb(o):void 0,xt=this.writeGate({guard:S,targetOrgId:o.targetOrgId,org:P,orgTier:O,lookup:z,emailsPerInsert:we,...xe!==void 0?{automation:xe}:{},...cn(Ir?.ofRun),sentBefore:Xe+(this.discoverySent.get(DO(o,n))?.target??0),mute:$r(it?.plan??Xs),mayBeInTarget:Z,...ve&&ve.length>0?{jobsUnderway:ve}:{},...g?{}:{simulated:this.simulations.of(f)},updatedAfterInsert:[...tt],...y?{automationRoom:()=>Ml(Or,rt).perRecord}:{},...y?{wholeOrg:{source:be(this.deps.orgManager.getOrg(o.sourceOrgId),o.sourceOrgId),sourceOrgId:o.sourceOrgId,graph:n,anonymizePII:o.anonymizePII,...or?{carried:or}:{}}}:{},...p!==void 0?{checkpoint:{ask:{module:"forge",orgId:o.targetOrgId,operationId:he,running:Or,request:p},own:{operationId:he},signal:B.signal,onEstimate:ee=>{Ks=ee},onTaken:ee=>{Ht=ee,pt&&oe&&le&&pt.keepCheckpoint(oe,ee).catch(te=>{de.warn(`Forge run journal: the checkpoint taken first not named (${A(te)})`)})},onProgress:ee=>{let te=lo(ee);Le(this.deps,he,ee,0,0,te),this.liveTracker?.updateProgress(he,ee,0,0,te)}}}:{},onSimulated:ee=>{Ue=ee},...b?{sampled:ee=>{Vn.flush();let te=bt?.drawnAgain,Ee=te||bt?.ofTheRunRetried?{...ee,plan:{...ee.plan,...te?{drawnAgain:te}:{},...bt?.ofTheRunRetried?{ofTheRunRetried:!0}:{}}}:ee;return m.sampled(Ee),Ee}}:y?{onSampleOffer:ee=>{kn=ee}}:{},onConfirmed:()=>{N=hs(N,"confirmed"),m.confirm("volume")}}),It=await this.orchestrator.execute(n,o,{recordTypeMappings:Qe,anonymizationRules:i,files:a,writtenBefore:k,stream:{ceiling:_e,...le?{store:le,summaryBound:ta}:{},...bt?{sample:bt.stream}:{}},...Ae?{runUserId:Ae}:{},beforeWrite:async ee=>{let te=await xt(ee);if(!it||ee.dryRun||qt)return te;let Ee=await it.acquire(he);qt=Ee,Be=Ee.outcome;let Pe=Ir?.afterLease(Ee.outcome,Ho);if(Pe)throw new ut(Pe.code,Pe.message);return{...te,lease:{assigned:Ee.outcome.assigned.length,giveBack:async()=>(await Sn(),Ee.release())}}}}).catch(ee=>{if(!ib(ee))throw ee;return Jn=ee.dryRun,Vx(n,ce,ee.dryRun)}).finally(M).finally(async()=>{qt&&(await Sn(),Be=await qt.release())}),Rt=MO(xO(It,z.requests),bt),Jr=Rt.remapInJournal&&le&&oe?{journalId:oe,journalPart:Math.max(0,le.partCount-1)}:{},Qs=Be?{mutedAutomation:Be,...rr.length>0?{bulkJobsPastMute:rr,errors:[...Rt.errors??[],..._l(rr)]}:{}}:{},Vr=g?Ks:Ht?await this.settleCheckpoint(Ht,(Rt.createdCount??Rt.idRemapCount-(Rt.linkedExistingCount??0))+(Rt.updatedCount??0)>0):u,$=Vr?{checkpoint:Vr}:{},X=t&&!g&&le&&oe?await this.wroteToEarlierPartsOf(Rt,oe,le.partCount-1):{},ie=l!==void 0?{...Rt,...Jr,...Qs,...$,retryOf:l,...t?{resumed:!0}:{},...X}:{...Rt,...Jr,...Qs,...$};"journalId"in Jr&&!g&&(F={keep:!0,status:"success",forgeId:ie.forgeId});let Oe=ie.createdCount??ie.idRemapCount-(ie.linkedExistingCount??0);ie.status!=="failure"&&Oe>0&&this.noteForgeWrite(U),ie.status==="failure"&&(Ne=new Error("Forge execution finished with a failure status.")),g?(this.trials.note("simulation",h),Ue&&this.simulations.note(f,Ue),bt&&Jn?.sample&&this.noteSampleSimulation(f,bt.fingerprint)):(K(this.deps,{action:"forge_execute",module:"forge",operationId:he,orgId:o.targetOrgId,outcome:ie.status,guard:N,objects:al(ie),source:{origin:"org",orgId:o.sourceOrgId},carried:dl(ie),...ns(ie.contactPoints),...vO(m),context:m.context(ie.decisionsApplied),...Be?{muted:ot(Be)}:{},...Vr?.state==="taken"?{checkpointId:Vr.checkpointId}:{}}),this.addToHistory(ie,o)),de.info("Forge execute finished",zx(ie)),await ae(),Vn.flush();let ye=T(this.deps,e,"forge:execute:response",{result:ie,operationId:he,...Jn?{wholeOrgDryRun:Jn}:{},...kn?{sampleOffer:kn}:{}});this.deps.broker.postToWebview(ye),this.dmlTracker.markCompleted(U),ge(this.deps,he,{status:ie.status}),ie.status==="failure"?this.liveTracker?.fail(he,"Forge execution finished with a failure status."):ie.status==="partial"?this.liveTracker?.partial(he):this.liveTracker?.complete(he)}catch(_e){Vn.flush();let He=uw(_e,t?"resume":"draw")??_e,tt=Sw(He)?He:kw(He),rt=kt(He)?He:void 0;(tt?.code==="AUTOMATION_DECLINED"||tt?.code==="READ_DECLINED"||tt?.code==="WRITE_DECLINED")&&(N=hs(N,"declined"));let ct=se||Kx(He)||tt!==void 0||rt!==void 0;ct||(Ne=He);let Qe=tt||rt?void 0:Gw(He),pt=Qe?df(Qe):void 0,nr=pt?al(pt):[],qt=se||tt||rt?"stopped":ct?cf(Qe,nr):"failure",or=tt?tt.code:rt?rt.code:se?ft:qt==="stopped"?et:He instanceof bn?He.code:void 0,xt=Ht?await this.settleCheckpoint(Ht,Qe?SO(Qe):!(se||tt||rt)):u;de.info("Forge execute stopped",{outcome:qt,...or?{code:or}:{},...Qe?{created:Qe.successCount,linked:Qe.linkedCount,failed:Qe.failedCount}:{}});let It=Qe&&!g?this.keepStoppedRun(MO(Qe,bt),n,o,{startedAt:ce,cancelled:ct,retryOf:l,resumed:t!==void 0,callsBefore:z.requests,...le&&oe?{journalId:oe,journalPart:Math.max(0,le.partCount-1)}:{},...xt?{checkpoint:xt}:{},...Ae?{runUserId:Ae}:{},...rr.length>0?{bulkJobsPastMute:rr}:{},...t&&le&&oe?await this.wroteToEarlierPartsOf({idRemapTable:Qe.remapTable,idRemapCreated:Qe.createdByObject,...Qe.remapInJournal?{remapInJournal:!0}:{}},oe,le.partCount-1):{}}):void 0;le&&oe&&It?F={keep:!0,status:ct?"cancelled":"failure",forgeId:It.forgeId}:t&&(F={keep:!0,...t.end}),g||K(this.deps,{action:"forge_execute",module:"forge",operationId:he,orgId:o.targetOrgId,outcome:qt,...or?{code:or}:{},guard:N,...pt?{objects:nr,source:{origin:"org",orgId:o.sourceOrgId},carried:dl(pt)}:{},...ns(Qe?.contactPoints),...vO(m),context:m.context(Qe?.decisionsApplied),...Be?{muted:ot(Be)}:{},...xt?.state==="taken"?{checkpointId:xt.checkpointId}:{}}),this.dmlTracker.markFailed(U),this.lastWriteAt.delete(U),bt?.adoptedFrom!==void 0&&oe!==void 0&&!F.keep&&!(Qe&&SO(Qe))&&await this.giveThePlanBack(oe,bt.adoptedFrom),await ae();let Rt=Ht&&xt?{checkpoint:xt}:{};E(this.deps,"forge:execute","forge:execute:error",e,He,{code:or??(ct?et:"EXECUTE_ERROR"),retryable:!0,...It?{extraPayload:{result:F.keep?{...It,resumable:!0}:It}}:tt?.stop?{extraPayload:{gate:tt.stop,...Rt,...kn?{sampleOffer:kn}:{}}}:Ht?{extraPayload:Rt}:{}}),ct?(this.deps.infraServices?.backgroundRegistry?.abort(he),ge(this.deps,he,{aborted:!0}),this.liveTracker?.cancel(he)):(je(this.deps,he,A(He),!0),this.liveTracker?.fail(he,A(He))),F.keep&&this.liveTracker?.offerResume(he,F.forgeId)}finally{await ae(),Ie(Ne),this.executeOperationId===he&&(this.executeOperationId=null,this.writingTo=null),this.stops.endRun(e.id),Ar(),qo.flush(),this.abortController=null}}addToHistory(e,t){let r={...t.inputMode==="org"?cO(e):e,config:Wx(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=xO(af(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??[],..._l(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(Pr(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<=ta?{wroteToEarlierParts:i}:{}}catch(i){return de.warn(`Forge run journal not read for what the part wrote: ${A(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 zw(t,async n=>(await r.query(n)).records)}catch(r){de.warn(`Forge run: the users its owners are mapped to could not be read first (${A(r)})`);return}}runUserOf(e){return gb(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 de.warn(`Forge run: the checkpoint '${e.name}' taken before it is kept, as it could not be settled (${A(n)})`),e}}async runToRetry(e,t){let r=this.loadHistory(),n=r.find(d=>d.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 d=i.retryOf;i=d===void 0?void 0:r.find(c=>c.forgeId===d)}let a=await this.withIdsOf(n);return"gone"in a?{refused:a.gone}:{written:a.entry.idRemapTable??{},...n.journalId!==void 0?{journalId:n.journalId}:{}}}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),de.info("Forge paused")}handleResume(e){this.orchestrator?.resume(),this.executeOperationId&&this.liveTracker?.resume(this.executeOperationId),de.info("Forge resumed")}handleAbort(e){let t=nt(rx,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"){de.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:ex});return}de.info("Forge stopped",{what:r.stops.kind})}refuseAtGate(e,t,r,n,o){K(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=CO(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<=Mx)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([...tn(t,n,{userKept:o}),...r])],d=i?await new fe(qs).withTimeout("forge:undo-automation",()=>i.read(e,a)).catch(l=>({unread:A(l)})):{unread:"no reader of the target org's automation is set up"},c=new Set(Vt(t));return mt(()=>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):Pt(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(CO(e,t));if(o&&Date.now()-o.at<xx)try{return{automation:Xx(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(ai).map(d=>d.objectApiName));try{return{automation:await new fe(qs).withTimeout("forge:automation",()=>i.readForGraph(e,t,a)),reused:!1}}catch(d){return{unread:A(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?Pl(a):[],l=a?Cl(a,d):[],u=a?xl(a):[{part:"automation",reason:"unread"in r?r.unread:""}];de.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?gg(a):[],h=i.deliverability!==void 0;if(p&&!h&&!(o&&g.length>0))return"allowed";let f=a&&!p?Rw(a,d):[],m=await e.confirmRun({stage:"automation",org:t.org,orgTier:t.orgTier,fired:c,firedOnUpdate:l,updateSteps:bw(n.filter(y=>l.some(b=>b.objectApiName===y.objectApiName))),unread:u,bypass:f,assign:a&&!p?vw(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 ut("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 ut("CONFIRMATION_UNAVAILABLE","Forge execution needed a confirmation of what the target org runs as it inserts and updates the records, and there was no one to ask. Nothing was read or written.")}async confirmReadCeiling(e,t,r,n){de.info("Forge read past the ceiling",{ceiling:n,objects:Object.fromEntries(r.slice(0,20).map(i=>[i.objectApiName,i.rows]))});let o=await e.confirmRun({stage:"read",org:t.org,orgTier:t.orgTier,source:t.source,objects:r,ceiling:n});if(o==="confirmed")return"confirmed";throw o==="declined"?new ut("READ_DECLINED","Forge execution was cancelled at the confirmation of the tables it reads with no cap per object. Nothing was read or written.",void 0,n):new ut("CONFIRMATION_UNAVAILABLE","Forge execution needed a confirmation of the tables it reads with no cap per object, and there was no one to ask. Nothing was read or written.")}maxRecordsPerObject(){let e=this.deps.services?.getSandforgeSetting?.("forge.maxRecordsPerObject",Al);return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.min(Math.floor(e),di):Al}confirmAboveRecords(){let e=this.deps.services?.getSandforgeSetting?.("safety.confirmAboveRecords",_r);return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):_r}async readTargetEmailLimits(e){try{let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return await new fe(No).withTimeout("forge:limits",()=>fr(t))}catch(t){return{unread:A(t)}}}async readTargetDataStorage(e){try{let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return await new fe(No).withTimeout("forge:limits",()=>pr(t))}catch(t){return{unread:A(t)}}}async readTargetApiBudget(e){try{let t=await q(e,this.deps.orgRegistry,this.deps.orgManager);return await new fe(No).withTimeout("forge:limits",()=>Qt(t))}catch(t){return{unread:A(t)}}}async readSourceApiBudget(e,t){t.requests++;try{let r=await q(e.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager);return await new fe(No).withTimeout("forge:limits",()=>Qt(r))}catch(r){return{unread:A(r)}}}limitsTransportOf(e,t){return{request:async r=>{t.requests++;let n=await q(e,this.deps.orgRegistry,this.deps.orgManager);return new fe(No).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[];de.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&&de.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(vx);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 Jw))throw f};if(e.dryRun||e.journalId===void 0)i=Vw(r,n);else if(e.retried&&!e.resumes){i=ea(r,e.journalId);let f=e.retried.journalId,m=f!==void 0?await Nl.open(ea(r,f),{fingerprint:n}).catch(u):void 0;m?(a=await Qw(m,r,e.journalId),c=!0):d="planGone"}else if(i=ea(r,e.journalId),!e.resumes){let f=await Xw(r,n,o);if(f instanceof Nl)a=await Kw(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 Zw(r,o).catch(f=>{de.warn(`Forge sample: the plans of past simulations were not swept (${A(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=cw({storage:f,bounds:g!==void 0?{withinMB:g}:{},target:e.target});if(m)throw ut.of(m);let y=ra({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 Yw(r,e,t).catch(n=>{de.warn(`Forge sample: the plan of the simulation was not put back (${A(n)})`)})}noteSampleSimulation(e,t){this.sampleSimulations.delete(e),this.sampleSimulations.set(e,t);for(let r of this.sampleSimulations.keys()){if(this.sampleSimulations.size<=Sx)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=El(n.objects,i);e.onSimulated?.(H);let j=r(H),N;t&&j&&this.beforeRunCheckpoints&&H.totalRows>0&&(N=await this.beforeRunCheckpoints.scope(j,t.own).then(Q=>(t.onEstimate(Q),Q),Q=>{de.warn(`Forge simulation: ${ur(Q)}`)}));let Y=await dw({objects:n.objects,measures:i,graph:o.graph,anonymizePII:o.anonymizePII,...e.updatedAfterInsert?{updatedAfterInsert:e.updatedAfterInsert}:{},...N?{checkpoint:N}:{},...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&&Y.storage.verdict==="exceeds"){let Q=ra({storage:Y.storage});Q&&e.onSampleOffer?.(Q.budget)}throw de.info("Forge write gate: the dry run of a clone of the whole org",{records:Y.totalRows,objects:Y.wouldInsert.length,targetRequests:Y.targetRequests.estimate,sourceRequests:Y.sourceRequests.estimate,...Y.bulkBatches?{bulkBatches:Y.bulkBatches.estimate}:{},wouldBeRefused:Y.wouldBeRefused.map(Q=>Q.code)}),new ob(Y)}if(n.dryRun){let H=Tl(n.objects);e.onSimulated?.(H);let j=r(H);return t&&j&&this.beforeRunCheckpoints&&H.totalRows>0&&await this.beforeRunCheckpoints.scope(j,t.own).then(t.onEstimate,N=>{de.warn(`Forge simulation: ${ur(N)}`)}),{}}let d=i?ow(i.readWholeOver):void 0;if(d)throw ut.of(d);let c=i?El(n.objects,i):Tl(n.objects);if(c.totalRows===0)return{};e.lookup.requests++;let l=await this.readTargetDataStorage(e.targetOrgId),u=gr(c,l,o&&e.automationRoom?aw(c,e.automationRoom()):0);if(a){let H=lw({sample:a,storage:l,target:e.org});if(H)throw ut.of(H)}let p=this.confirmAboveRecords(),g=p>0&&c.totalRows>p?p:void 0,h=ky(e.orgTier),f=h!==void 0&&c.totalRows>h?h:void 0;de.info("Forge write gate",{records:c.totalRows,objects:Object.fromEntries(c.objects.slice(0,20).map(H=>[H.objectApiName,H.rows])),storageEstimateMB:bs(u.estimateMB),...u.verdict==="unread"?{storageUnread:u.unread}:{storageRemainingMB:u.remainingMB,storageMaxMB:u.maxMB},storage:u.verdict});let m=Ow(u,e.org);if(m&&u.verdict==="exceeds"){if(o&&!a&&!("unread"in l)){let H=ra({storage:l});H&&e.onSampleOffer?.(H.budget)}throw new ut("STORAGE_EXCEEDED",`${m} Nothing was written.`,{estimateMB:Number(bs(u.estimateMB)),remainingMB:u.remainingMB})}u.verdict==="near"?de.warn("Forge write gate: the records take more than 80 % of the data storage the target has left"):u.verdict==="unread"&&de.warn("Forge write gate: the data storage the target has left could not be read"),f!==void 0&&de.warn(`Forge write gate: more than ${f} records, a large volume`);let y=i?sw(i.files,l,e.org):void 0;if(y?.stop)throw ut.of(y.stop);let b;"unread"in l?(e.lookup.requests++,b=await this.readTargetApiBudget(e.targetOrgId)):b=l.dailyApiRequests;let v=r(c),w;if(t&&v){let H=this.beforeRunCheckpoints;if(!H)throw new ut(an,ur(new Error("SandForge's checkpoints are not set up in this window")));w=await H.scope(v,t.own).catch(j=>{throw new ut(an,ur(j))})}let R=o?await this.readSourceApiBudget(o,e.lookup):void 0,k=iw({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:b,target:e.org,...o&&i?{wholeOrg:{measures:i,bulkBatches:"unread"in l?l:l.dailyBulkApiBatches,sourceBudget:R,source:o.source}}:{}});if(de.info("Forge write gate: API requests",{estimate:k.api.estimate,verdict:k.api.verdict,...k.api.verdict==="unread"?{unread:k.api.unread}:{remaining:k.api.remaining,max:k.api.max},...k.api.parts?{parts:k.api.parts}:{}}),k.stop)throw ut.of(k.stop);let I=Di(k.api),S=o&&i&&k.wholeOrg?ab({run:o,measures:i,plan:c,budget:{api:k.api,wholeOrg:k.wholeOrg},...y?.files?{files:y.files}:{},...a?{sample:a,now:Date.now()}:{}}):void 0;S&&de.info("Forge write gate: a clone of the whole org",{sourceRequests:k.wholeOrg?.source.estimate,sourceApi:k.wholeOrg?.source.verdict,jobs:S.bulk?.jobs??0,...k.wholeOrg?.bulkBatches?{bulkBatches:k.wholeOrg.bulkBatches.estimate}:{},durationSeconds:Math.round(S.durationSeconds),managedPackages:S.managedPackages?.length??0,personalAsIs:S.personalAsIs?.length??0});let C=async()=>{let H=this.beforeRunCheckpoints;if(!t||!v||!w||!H)return;let j=w,N=await Yi(()=>H.take(v,t.own,{planned:j,signal:t.signal,onProgress:({percentage:Y})=>t.onProgress?.(Y)}));if("stop"in N)throw N.stop.code===an?ut.of({...N.stop,code:an}):Object.assign(new Error(N.stop.message),{name:"ForgeAbortedError"});t.onTaken(N.checkpoint)},O=[],P=[];if(e.emailsPerInsert.length>0){e.lookup.requests++;for(let H of pw(c,e.emailsPerInsert,await this.readTargetEmailLimits(e.targetOrgId)))H.verdict==="exceeds"?O.push(hw(H)):H.verdict==="unread"&&P.push(mw(H));P.length>0&&de.warn("Forge write gate: a daily email limit of the target could not be read",{limits:P.map(({limit:H,emails:j})=>({limit:H,emails:j}))}),O.length>0&&de.warn("Forge write gate: the records take the target past a daily email limit",{limits:O.map(({limit:H,emails:j,remaining:N})=>({limit:H,emails:j,remaining:N}))})}let _=e.automation===void 0?void 0:"automation"in e.automation?fw(e.automation.automation,gw(c)):`the target's automation: ${e.automation.unread}`;_!==void 0&&de.warn("Forge write gate: what of the target sends emails could not all be read, and its emails were not counted");let J=(e.mayBeInTarget??[]).filter(({rows:H})=>H>0),B=e.simulated?tw(e.simulated,c.totalRows):void 0;if(B?.farAbove&&de.warn("Forge write gate: far more records than the last simulation of the case",{records:c.totalRows,simulated:B.total}),g===void 0&&u.verdict==="fits"&&O.length===0&&P.length===0&&_===void 0&&J.length===0&&B?.farAbove!==!0&&!k.asks)return await C(),I;let re=await e.guard.confirmRun({stage:"write",org:e.org,orgTier:e.orgTier,objects:c.objects.map(({objectApiName:H,rows:j})=>({objectApiName:H,rows:j})),total:c.totalRows,...g!==void 0?{aboveRecords:g}:{},...f!==void 0?{largeVolume:f}:{},storage:ln(u),...c.leftOut?{leftOut:c.leftOut}:{},...n.objects.some(H=>H.counted)?{counted:!0}:{},...O.length>0?{emails:O}:{},...P.length>0?{emailsUnread:P}:{},..._!==void 0?{emailsUncounted:_}:{},...rw(c),...nw(c),...J.length>0?{mayBeInTarget:J.map(({objectApiName:H,rows:j})=>({objectApiName:H,rows:j}))}:{},...J.length>0&&e.jobsUnderway&&e.jobsUnderway.length>0?{jobsUnderway:_x(e.jobsUnderway)}:{},...n.capped?{capped:n.capped}:{},...B?{simulated:B}:{},...S?{wholeOrg:S,...k.confirmation.checkpoint?{checkpoint:k.confirmation.checkpoint}:{}}:k.confirmation});if(re==="confirmed")return e.onConfirmed(),await C(),I;throw re==="declined"?new ut("WRITE_DECLINED","Forge execution was cancelled before it wrote the records it had read. Nothing was written."):new ut("CONFIRMATION_UNAVAILABLE","Forge execution needed a confirmation before it wrote the records it had read, and there was no one to ask. Nothing was written.")}}async loadRecordTypeMappings(e,t,r){let n=()=>{},o=new Promise(i=>{n=()=>i(void 0),t.addEventListener("abort",n,{once:!0})});try{let i=new fe(Nx).withTimeout("forge:record-types",()=>this.readRecordTypeMappings(e,r));return await Promise.race([i,o])}catch(i){de.warn(`[forge] Record types could not be read from both orgs (${A(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 dr({query:async d=>(t.requests++,i.query(d)),queryMore:async d=>(t.requests++,i.queryMore(d))},xw);return Mw(a)}));for(let o of jw(r,n))de.warn(`[forge] ${Nw(o)}`);return new $w().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=>Gc.safeParse(o).success),...r===void 0?{}:{importNotMerged:r}});this.deps.broker.postToWebview(n)}async handleSaveTemplate(e){let t=nt(nx,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(ux,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){de.warn(`Forge removal plans could not be read: ${A(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)&&Cr(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=nt(ox,e,"forge:undo:error",this.deps);if(!t)return;let{forgeId:r}=t,n=t.includeChanged===!0,o=t.sweep===!0,i=t.again===!0,a=t.muteAutomation===!0,d=o&&t.sweepLate===!0,c=o&&t.sweepUntied===!0,l=(w,R)=>this.refuseUndo(e,w,R),u=this.loadHistory().find(w=>w.forgeId===r),p=u?void 0:await this.keptRemovalPlan(r),g,h={},f=u?.targetOrgId??p?.targetOrgId,m=u?u.journalId:p?.inJournal?.journalId;if(f&&m&&(!u||u.idRemapCreated)){if(this.removing.has(r)){l("The records of this run are being removed already: its result shows under the run once it ends.",mO);return}this.removing.add(r);try{let w=await this.callsLookedForBeforeRemoval({forgeId:r,targetOrgId:f,journalId:m,removedBefore:(u??p)?.undo!==void 0});if("unread"in w){l(w.unread,"IN_FLIGHT_UNREAD");return}g=w.reconciled,h=w,g&&g.found.length>0&&(u?u=await this.withRowsFoundAfterStop(u,g.found):p&&(p=await this.planWithRowsFoundAfterStop(p,g.found)))}finally{this.removing.delete(r)}}let y,b,v=()=>{};if(u){let w=Date.parse(u.timestamp);if(!u.idRemapCreated||!u.targetOrgId||Number.isNaN(w)){l(`This run was recorded before Forge kept what a run created: its records cannot be removed from the history. ${Jd}`,"NOT_RECORDED");return}let R=u.remapInJournal&&u.journalId&&u.journalPart!==void 0?{journalId:u.journalId,part:u.journalPart}:void 0,k=Hx(u.mayHaveBeenWritten,{...h,reconciled:g});if(y={...u,targetOrgId:u.targetOrgId,unreachable:Bx(u.mayHaveBeenWritten,g),...k?{notLookedFor:k}:{},...R?{inJournal:R}:{}},u.remapInJournal){if(b=[],i||Kr(u).length>0){let I=await this.journalRecordsOf(R,u.undo,i);if("gone"in I){l(I.gone,Mo);return}b=I.records,v=I.close}}else b=i?Pr(u):Xo(u)}else if(p){if(o){l(AO,"SWEEP_UNAVAILABLE");return}y={...p,unreachable:g&&g.calls>0?Fl(g):p.mayHaveBeenWritten??0,...h.callsNotLookedFor?{notLookedFor:{callsAfterRemoval:h.callsNotLookedFor}}:{}};let{inJournal:w}=p;if(w&&(i||Cr(p).length>0)){let R=await this.journalRecordsOf(w,p.undo,i);if("gone"in R){l(R.gone,Mo);return}b=R.records,v=R.close}else b=i?p.objects.map(({objectApiName:R,ids:k})=>({objectApiName:R,ids:[...k]})):Qc(p)}else{l("This run is no longer in the Forge history.",jo);return}try{let w=bl(b),R=o&&y.undo!==void 0;if(w===0&&!R){y.undo?l(`The records this run created were already removed, on ${y.undo.removedAt}.`,"ALREADY_REMOVED"):l("This run created no record to remove.","NOTHING_TO_REMOVE");return}if(this.removing.has(r)){l("The records of this run are being removed already: its result shows under the run once it ends.",mO);return}this.removing.add(r);let k=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(e.id);try{await this.removeRun(e,y,b,{includeChanged:n,again:i,muteAutomation:a,sweepLate:d,sweepUntied:c,...!o&&u?.config?.inputMode==="org"?{wholeOrgNotSwept:!0}:{}},o?u:void 0,k)}finally{this.removing.delete(r),k?.release()}}finally{v()}}async journalRecordsOf(e,t,r=!1){let n=this.runJournal;if(!n||!e)return{gone:yn};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 de.warn(`Forge run journal could not be read: ${A(o)}`),{gone:yn}}}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 de.warn(`Forge run journals could not be listed: ${A(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){de.warn(`Forge run journals could not be dropped: ${A(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:yn};try{let n=await r.idsOf(e.journalId,e.journalPart);if(!n)return{gone:yn};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 de.warn(`Forge run journal could not be read: ${A(n)}`),{gone:yn}}}async planRecordsOf(e,t=!1){let r=this.runJournal;if(!r)return{gone:yn};try{let{journalId:n,part:o}=e.inJournal,i=await r.idsOf(n,o);if(!i)return{gone:yn};let a={idRemapTable:i.table,idRemapExisting:i.existing,idRemapCreated:i.createdByObject};if(t)return{records:Pr(a)};let d=await r.leftOf(n,o);return{records:Xo({...a,...e.undo?{undo:e.undo}:{},...d?{removalLeft:d}:{}})}}catch(n){return de.warn(`Forge run journal could not be read: ${A(n)}`),{gone:yn}}}async keptRemovalPlan(e){try{return await this.removalPlans?.get(e)}catch(t){de.warn(`Forge removal plans could not be read: ${A(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=be(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,$l(i));for(let d of Ll(a,o,"removal"))de.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 (${A(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){de.warn(`Forge run not dated from its journal: ${A(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=qx(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=ii(d);return c&&await this.removalPlans?.put(c).catch(l=>{de.warn(`Forge removal plan not kept: ${A(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=>{de.warn(`Forge removal plan not kept: ${A(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)){let n=r.resume?.startedWith;if(!n){let o=eb.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=Ax(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){de.warn(`Forge run journals could not be read: ${A(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||!RO.has(o.status))continue}catch{continue}kO(n,e)===void 0&&t.add(n.forgeId)}return t}async runToResume(e){let t=this.loadHistory(),r=t.find(l=>l.forgeId===e);if(!r)return{refused:"The run to resume is no longer in the history: what it wrote and where it stopped are not known. Run the clone again from Review. Nothing was read or written."};let n=r.targetOrgId,o=this.runJournal;if(!r.journalId||!o)return{refused:`This run kept no journal to take it up from: ${wO}`,targetOrgId:n};if(this.journalsRunning.has(r.journalId))return{refused:"This run is being taken up already.",targetOrgId:n};let i=await o.lastEnd(r.journalId);if(!i||i.forgeId!==r.forgeId||!RO.has(i.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 a=kO(r,t);if(a!==void 0)return{refused:`The records ${a===r?"this run created":"a part of this run created"} were removed on ${a.undo?.removedAt}: there is nothing to resume against.`,targetOrgId:n};let d=await o.head(r.journalId),c=d?.resume?.startedWith;return!d?.resume||!c||d.targetOrgId!==n?{refused:`The journal of this run does not say how it was set up: ${wO}`,targetOrgId:n}:{entry:r,journalId:r.journalId,head:{...d.resume,startedWith:c},targetOrgId:d.targetOrgId,end:i}}async handleResumeRun(e){let t=nt(ZD,e,"forge:execute:error",this.deps);if(!t)return;let r=(y,b,v)=>{v&&K(this.deps,{action:"forge_execute",module:"forge",operationId:e.id,orgId:v,outcome:"stopped",code:y}),E(this.deps,"forge:execute","forge:execute:error",e,new Error(b),{code:y})},n=await this.runToResume(t.forgeId);if("refused"in n){r(QD,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(bO,"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(bO,`${be(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=zc(p);if(h!==void 0){r(up,`${h}. Nothing was read or written.`,d);return}let f=this.maxRecordsPerObject(),m=y=>rb(a.fingerprint,y.graph,this.runSetupOf(y.config,g,f,a.targetSalesforceOrgId));if(!m({graph:u,config:p})){r(up,"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:t.config})){r(up,"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&&gp.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 tb(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=ii(e),o=[...n?[r.put(n)]:[],...t.flatMap(i=>{let a=ii(i);return a&&Cr(a).length>0?[r.putIfAbsent(a)]:[]})];Promise.all(o).catch(i=>{de.warn(`Forge removal plan not kept: ${A(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(ax,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.",jo);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,Mo);return}let i=t.recordId.slice(0,15),a;for(let{objectApiName:l,ids:u}of Pr(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(yO,"ORG_NOT_FOUND");return}let c=sd(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 "${be(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(dx,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.",jo);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. ${Jd}`,"NOT_RECORDED");return}let a=o;if(o.remapInJournal&&Kr(o).length>0){let l=await this.withIdsOf(o,!0);if("gone"in l){n(l.gone,Mo);return}a=l.entry}let d=o.remapInJournal&&a===o?[]:Xo(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(yO,"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.",YD);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 wb({target:Bl(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:vb(o.writtenWithoutFields??[]),...o.lookupsLeftEmptyByFilter?{leftEmptyByFilter:o.lookupsLeftEmptyByFilter}:{},leftEmptyByTheRun:Rb(o.config?.inputMode==="org"),...a.idRemapWithTheirRecord?{withTheirRecord:a.idRemapWithTheirRecord}:{}});this.saveHistory(this.loadHistory().map(f=>f.forgeId===r?{...f,verification:g}:f)),K(this.deps,{action:"forge_verify",module:"forge",operationId:c,orgId:i,outcome:g.verdict==="verified"?"success":"partial",verdict:g.verdict,details:{forgeId:r,...bb(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){K(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(cx,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.",jo);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,Mo);return}i=dg(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(cg([]));let g=0,h=[];for(let f of i)h.push(f),!(h.length<lx)&&(await p(`
|
|
11
|
-
${Zc(h)}`),g+=h.length,h=[]);return h.length>0&&await p(`
|
|
12
|
-
${Zc(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){de.warn(`Forge run journal could not be read: ${A(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 Bl(t,"forge:verify source")}catch(t){return{unavailable:`The org this run read from could not be reached: ${A(t)}`}}}async removeRun(e,t,r,n,o,i){let{includeChanged:a,again:d}=n,{forgeId:c,targetOrgId:l}=t,u=bl(r),p=(O,P)=>this.refuseUndo(e,O,P),g=this.deps.infraServices?.productionGuard;if(!g){K(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:l,outcome:"stopped",code:Re.code}),p(Re.message,Re.code);return}let h=this.deps.orgManager.getOrg(l),f=Te(h),{check:m,decision:y}=u>0?await Ye(g,{orgId:l,orgTier:f,operation:"delete",objectName:Rl(r).join(", "),recordCount:u,module:"forge"}):{check:void 0,decision:"allowed"};if(m&&(y==="refused"||y==="declined")){K(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){K(this.deps,{action:"cleanup_delete",module:"forge",operationId:e.id,orgId:l,outcome:"stopped",guard:y,code:ft});let O={forgeId:c,status:"cancelled",includeChanged:a,objects:[],finishedAt:new Date().toISOString()};this.deps.broker.postToWebview(T(this.deps,e,"forge:undo:response",{result:O,operationId:e.id}));return}let b=e.id,v=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,b,"forge",v);let R=this.trackRun(b,v,w);this.liveTracker?.register(b,"forge",v,u);let k,I,S,C;try{let O=await q(l,this.deps.orgRegistry,this.deps.orgManager),{inJournal:P}=t,_=t.writtenBetween??await this.datedByItsJournal({journalId:t.journalId??P?.journalId,part:t.journalPart??P?.part},O),J={...t.removalStamps,...P?await this.runJournal?.stampsOf(P.journalId,P.part).catch(F=>(de.warn(`Forge removal stamps not read: ${A(F)}`),{})):{}};u>0&&(I=await this.otherPartsOf(c,l,O));let B=vl(t.removalSpans,I?.spans);o&&(S=await this.sweepOfRemoval({conn:O,entry:o,includeChanged:a,sweepLate:n.sweepLate===!0,sweepUntied:n.sweepUntied===!0,removalSpans:B,signal:w.signal,guard:g,orgTier:f,operationId:b,muted:()=>u===0?C:void 0}));let re=S;await re?.ask();let H=re?.takes??[],j=n.muteAutomation===!0&&(u>0||H.length>0)?await this.removalMute(l,Rl(r),H,I?.parts.flatMap(F=>F.objects)??[],t.runUserId!==void 0&&u>0):void 0,N;C=j?.muted;let Y=async()=>{let F=j?.prepared;!F||w.signal.aborted||(N=await F.acquire(b),C=N.outcome)},U=await(u===0?(async()=>(await Y(),await re?.first(),await re?.afterRemoval(),ay))():dy(Xt(O,"forge:undo"),r,{..._?{runStartedAt:new Date(_.first),runEndedAt:new Date(_.last)}:{runDurationMs:t.duration,runRecordedAt:new Date(t.timestamp)},...Object.keys(J).length>0?{removalStamps:J}:{},...B.length>0?{removalSpans:B}:{},...I&&I.laterParts.length>0?{laterParts:I.laterParts}:{},...re?{sweep:F=>re.first(F),afterRemoval:F=>re.afterRemoval(F),automationMade:re.automationMade}:{},...t.runUserId?{runUserId:t.runUserId}:{},...I&&I.parts.length>0?{otherParts:I.parts.map(F=>F.alongside)}:{},includeChanged:a,onUndeletable:xr(this.deps,l,"forge:undo"),beforeFirstWrite:Y,signal:w.signal,onProgress:(F,W,ae)=>{let z=Math.min(100,Math.round(F/Math.max(W,1)*100));Le(this.deps,b,z,F,W,ae),w.signal.aborted||this.deps.infraServices?.backgroundRegistry?.updateProgress(b,z),this.liveTracker?.updateProgress(b,z,F,W,ae)}})).finally(async()=>{N&&(C=await N.release())});I&&await this.keepOtherPartStamps(I.parts,U.otherPartStamps??[]);let G=await S?.settle(),pe=d?void 0:t.undo?.removedAt,me=t.unreachable,ne=I?Fx(U.objects,I.parts):[],he=(I?.parts??[]).flatMap(F=>F.undo&&F.records>0?[{forgeId:F.forgeId,records:F.records}]:[]),qe={forgeId:c,status:cy(U.objects,U.cancelled),includeChanged:a,objects:U.objects,finishedAt:new Date().toISOString(),...pe?{leftBy:pe}:{},...me>0?{mayHaveBeenWritten:me}:{},...t.notLookedFor?{notLookedFor:t.notLookedFor}:{},...C?{mutedAutomation:C}:{},...ne.length>0?{heldByOtherParts:ne}:{},...he.length>0?{otherPartsLeft:he}:{}};u>0&&K(this.deps,{action:"cleanup_delete",module:"forge",operationId:b,orgId:l,outcome:so(qe),guard:y,objects:rn(qe.objects),...pe?{leftBy:pe}:{},...C?{muted:ot(C)}:{}});let Ie={...qe,status:oo(qe.status,G),...G?{sweep:G}:{},...n.wholeOrgNotSwept?{wholeOrgNotSwept:!0}:{}};n.wholeOrgNotSwept&&de.info("Forge removal: a clone of the whole org removed without its sweep; what the target\u2019s automation created during the run stays");let ce=ly(Ie,u,t.undo,d),oe=G&&pb(G,new Date().toISOString(),o?.sweep),le=Object.keys(U.stamps).length>0,Ae=U.span,Z,ve;if(P)(U.objects.some(W=>W.deleted+W.alreadyGone>0)||d&&ce!==void 0)&&(ve=await this.runJournal?.keepLeftPages(P.journalId,P.part,U.left()).catch(W=>{de.warn(`Forge removal left not kept: ${A(W)}`)})),le&&await this.runJournal?.keepStamps(P.journalId,P.part,U.stamps).catch(W=>{de.warn(`Forge removal stamps not kept: ${A(W)}`)});else if((U.gone.length>0||d&&ce)&&!iy(r)){let F=new Set(U.gone);Z=r.flatMap(({ids:W})=>W.filter(ae=>!F.has(ae)))}if(ce||le||Ae||Z||ve||oe){let F=W=>({...W,...ce?{undo:ce}:{},...oe?{sweep:oe}:{},...le&&!P?{removalStamps:{...W.removalStamps,...U.stamps}}:{},...Ae?{removalSpans:[...W.removalSpans??[],Ae]}:{},...Z?{removalLeft:Z}:{}});this.saveHistory(this.loadHistory().map(W=>W.forgeId===c?{...F(W),...ve?{removalLeftByObject:ve}:{}}:W)),await this.removalPlans?.update(c,W=>{let ae={...F(W),...W.inJournal&&ve?{inJournal:{...W.inJournal,left:ve}}:{}};return Cr(ae).length>0?ae:void 0}).catch(W=>{de.warn(`Forge removal plan not updated: ${A(W)}`)})}let x=T(this.deps,e,"forge:undo:response",{result:Ie,operationId:b});this.deps.broker.postToWebview(x);let M=Ie.status==="failure"?"No record this run created could be removed.":u===0&&G&&G.status!=="success"?G.refusal??"The sweep left records in the org.":void 0;Ie.status==="cancelled"||G?.status==="cancelled"?(ge(this.deps,b,{aborted:!0}),this.liveTracker?.cancel(b)):(ge(this.deps,b,{status:M&&u===0?"failure":Ie.status}),M?(k=new Error(M),this.liveTracker?.fail(b,M)):Ie.status==="partial"?this.liveTracker?.partial(b):this.liveTracker?.complete(b))}catch(O){k=O,await S?.settle().catch(_=>{de.warn(`Forge sweep not recorded: ${A(_)}`)});let P=kt(O)?O:void 0;K(this.deps,{action:"cleanup_delete",module:"forge",operationId:b,orgId:l,outcome:P?"stopped":"failure",guard:y,...P?{code:P.code}:{}}),E(this.deps,"forge:undo","forge:undo:error",e,O,{code:P?.code??"UNDO_ERROR",retryable:!0}),ge(this.deps,b,{status:"failure"}),this.liveTracker?.fail(b,A(O))}finally{I?.close(),R(k)}}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=>Lx(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:vl(...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?Kr(d):c?Cr(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}=$x(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=>(de.warn(`Forge run journal parts not read: ${A(u)}`),[])))}}async keptRemovalPlans(){try{return await this.removalPlans?.list()??[]}catch(e){return de.warn(`Forge removal plans could not be read: ${A(e)}`),[]}}async otherPartFromEntry(e,t,r,n){if(e.targetOrgId!==t||!e.idRemapCreated||this.removing.has(e.forgeId)||Kr(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=Xo(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:Kr(e).map(c=>c.objectApiName),records:Kr(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)||Cr(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=Qc(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:Cr(e).map(c=>c.objectApiName),records:Cr(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:jO(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=>{de.warn(`Forge removal stamps of another part not kept: ${A(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=>{de.warn(`Forge removal plan not updated: ${A(a)}`)})}}sweepOfRemoval(e){let{conn:t,entry:r}=e,n=r.targetOrgId??"";return Ro({input:async()=>{let o=await this.sweepInputOf(r,t,e.signal);return"gone"in o?{refused:o.gone}:o},org:Ur(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();K(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:vo(i)}:{},objects:yo(o),details:wo(o,r.forgeId),...a?{muted:ot(a)}:{}})},keepMade:async(o,i,a)=>{await this.removalPlans?.keepMade(r.forgeId,o,i,a).catch(d=>{de.warn(`Forge sweep finds not kept: ${A(d)}`)})}})}async sweepInputOf(e,t,r){let n=await this.withIdsOf(e);if("gone"in n)return n;let o=n.entry,i=Pr(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 fe(qs).withTimeout("forge:undo-sweep automation",()=>c.read(l,i.map(p=>p.objectApiName)))}catch(p){u={error:A(p)}}return bo({writtenBetween:e.writtenBetween,created:i,remap:d,automation:ub(u),...e.runUserId?{runUserId:e.runUserId}:{},ties:await this.tiesOf(e),...a.length>0?{otherParts:a}:{},...r?{signal:r}:{}},Xt(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=Pr(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=Pb(e.removalSpans),i=await this.removalPlans?.madeOf(e.forgeId).catch(()=>[]),a=await this.removalPlans?.lateOf(e.forgeId).catch(()=>[]);return{otherRuns:Ab(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(!Tb(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=IO(d);i.push(d.remapInJournal?await a(c,async()=>{let l=await this.withIdsOf(d);return"gone"in l?void 0:Pr(l.entry)}):{ids:Pr(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=IO(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}async handleUndoSweep(e){let t=nt(ix,e,"forge:undo-sweep:error",this.deps);if(!t)return;let r=(i,a)=>E(this.deps,"forge:undo-sweep","forge:undo-sweep:error",e,new Error(i),{code:a}),n=this.loadHistory().find(i=>i.forgeId===t.forgeId);if(!n){r(AO,jo);return}let o=n.targetOrgId;if(!n.idRemapCreated||!o){r("This run was recorded before Forge kept what a run created: nothing of it can be swept. "+Jd,"NOT_RECORDED");return}try{let i=await new fe(Cx).withTimeout("forge:undo-sweep",async()=>{let a=await q(o,this.deps.orgRegistry,this.deps.orgManager),d=await this.sweepInputOf(n,a);return"gone"in d?d:mo(Ur(a,"forge:undo-sweep"),d,n.removalSpans??[])});if("gone"in i){r(i.gone,Mo);return}this.deps.broker.postToWebview(T(this.deps,e,"forge:undo-sweep:response",{forgeId:t.forgeId,listing:i}))}catch(i){let a=i instanceof lr;E(this.deps,"forge:undo-sweep","forge:undo-sweep:error",e,i,{code:a?"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(px,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{de.info("Forge plan generation started");let i=await this.readPersonalFields(r,n),a=await new fe(OO).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),ge(this.deps,o,{waveCount:a.waves?.length??0})}catch(i){let a=i instanceof lr;E(this.deps,"forge:plan","forge:plan:error",e,i,{code:a?"TIMEOUT":"PLAN_ERROR",retryable:a}),ge(this.deps,o,{status:"failure"})}}async readPersonalFields(e,t){let r=this.orchestrator;if(!r)return e;try{return await new fe(OO).withTimeout("forge:plan:personal-fields",n=>r.readPersonalFields(e,t,n))}catch(n){return de.warn(`Forge personal fields not read: ${A(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(gx,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{de.info("Forge compliance report generation started");let d=await new fe(Ex).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),ge(this.deps,a,{framework:r})}catch(d){let c=d instanceof lr;E(this.deps,"forge:compliance","forge:compliance:error",e,d,{code:c?"TIMEOUT":"COMPLIANCE_ERROR",retryable:c}),ge(this.deps,a,{status:"failure"})}}async handleMetadataDiffRequest(e){if(!this.metadataDiff){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(fx,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{de.info("Forge metadata diff started");let a=await new fe(Px).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),de.info("Forge metadata diff finished",{objects:o.length,differences:a.length,objectsMissing:a.filter(c=>c.issue==="object_missing").length}),ge(this.deps,i,{objectCount:o.length})}catch(a){let d=a instanceof lr;E(this.deps,"forge:metadata-diff","forge:metadata-diff:error",e,a,{code:d?"TIMEOUT":"METADATA_DIFF_ERROR",retryable:d}),ge(this.deps,i,{status:"failure"})}}async handleRehearseRequest(e){let t=this.rehearser,r=(I,S,C=!1)=>E(this.deps,"forge:rehearse","forge:rehearse:error",e,I,{code:S,retryable:C});if(!t){r(new Error("Forge rehearsal is not initialized"),"NOT_INITIALIZED");return}let n=nt(hx,e,"forge:rehearse:error",this.deps);if(!n)return;let{graph:o,config:i,anonymizationRules:a}=n;if(i.inputMode==="org"){r(new Error(JD),GD);return}let d=(I,S,C={})=>K(this.deps,{action:"forge_rehearse",module:"forge",operationId:I,orgId:i.targetOrgId,outcome:S,...C}),c=(I,S,C=!1)=>{d(e.id,"stopped",{code:S}),r(I,S,C)},l=this.deps.infraServices?.productionGuard;if(!l){c(new Error(Re.message),Re.code);return}let u=this.deps.orgManager.getOrg(i.targetOrgId),p=Te(u),g=be(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."),pp,!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 b,v=!1,w=I=>this.deps.broker.postToWebview(T(this.deps,e,"forge:rehearse:progress",{...I})),R=I=>{if(I.phase!=="rehearsing"||!I.call||!I.calls)return;let S=Math.min(100,Math.round((I.call-1)/I.calls*100));m.signal.aborted||this.deps.infraServices?.backgroundRegistry?.updateProgress(h,S),this.liveTracker?.updateProgress(h,S,I.call-1,I.calls,`call ${I.call} of ${I.calls}`)},k=Gd(w,100);try{let I=await this.automationBeforeTheRun(i.targetOrgId,o),S="automation"in I?I.automation:void 0,C=await this.loadRecordTypeMappings(i,new AbortController().signal,{requests:0}),O=await t.rehearse(o,i,{recordTypeMappings:C,anonymizationRules:a,signal:m.signal,onProgress:P=>{if(P.phase==="reading"){k(P);return}k.flush(),w(P),R(P)},confirm:async P=>{let _=await l.confirmRun({stage:"rehearsal",org:g,orgTier:p,rows:P.rows,sampled:P.sampled,updates:P.updates.reduce((J,B)=>J+B.updates,0),calls:P.calls,maxCalls:P.maxCalls,fired:S?Pl(S):[],firedOnUpdate:S?Cl(S,P.updates.map(J=>J.objectApiName)):[],unread:S?xl(S):[{part:"automation",reason:"unread"in I?I.unread:""}]});if(_==="confirmed"){v=!0;return}throw new Vd(_==="declined"?"REHEARSAL_DECLINED":"CONFIRMATION_UNAVAILABLE",_==="declined"?"The rehearsal was cancelled at its confirmation. Nothing was sent to the target.":"The rehearsal needed a confirmation, and there was no one to ask. Nothing was sent to the target.")}});this.deps.broker.postToWebview(T(this.deps,e,"forge:rehearse:response",{rehearsal:O})),this.trials.note("rehearsal",Ul(o,i)),de.info("Forge rehearsal",{rows:O.rows,sampled:O.sampled,judged:O.judged,passed:O.passed,notJudged:O.notJudged,calls:O.calls,plannedCalls:O.plannedCalls,codes:[...new Set(O.gaps.flatMap(P=>typeof P.detail?.statusCode=="string"?[P.detail.statusCode]:[]))]}),d(h,"success",{guard:v?"confirmed":"allowed",details:Yx(O)}),ge(this.deps,h,{status:"success"}),this.liveTracker?.complete(h)}catch(I){let S=I instanceof Vd?I:void 0,C=I instanceof yb?I:void 0,O=I instanceof mb?I:void 0,P=A(I);if(r(I instanceof Error?I:new Error(P),S?.code??(C?"REHEARSAL_CANCELLED":"REHEARSAL_ERROR"),!0),S||C){let _=S?.code==="REHEARSAL_DECLINED"?"declined":v?"confirmed":void 0;d(h,"stopped",{code:S?.code??"REHEARSAL_CANCELLED",..._?{guard:_}:{},...C?{details:{calls:C.calls}}:{}}),ge(this.deps,h,{aborted:!0}),this.liveTracker?.cancel(h)}else b=I,d(h,"failure",{...v?{guard:"confirmed"}:{},...O?{code:"REHEARSAL_NOT_ROLLED_BACK",details:{recordsLeft:O.ids.length},objects:O.objects.map(({objectApiName:_,created:J})=>({objectApiName:_,created:J,updated:0,deleted:0,failed:0}))}:{}}),je(this.deps,h,P,!0),this.liveTracker?.fail(h,P)}finally{k.flush(),y(b),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(mx,e,"forge:automation:error",this.deps);if(!t)return;let{targetOrgId:r,graph:n}=t,o=`forge-automation-${this.deps.nextId()}`;ze(this.deps,o,"forge","Reading the target org's automation");try{let i=new fe(qs).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})),de.info("Forge target automation read",{objects:a.objectsRead.length,objectsWithAutomation:a.objects.length,flows:a.objects.reduce((d,c)=>d+c.flows.length,0),triggers:a.objects.reduce((d,c)=>d+c.triggers.length,0),conditionsNotRead:a.conditionsNotRead,unread:a.unread.map(d=>d.part),requests:a.requests}),ge(this.deps,o,{objectCount:a.objectsRead.length})}catch(i){let a=i instanceof lr;E(this.deps,"forge:automation","forge:automation:error",e,i,{code:a?"TIMEOUT":"AUTOMATION_ERROR",retryable:a}),ge(this.deps,o,{status:"failure"})}}async readDeliverability(e,t){let r=()=>{},n=new Promise((o,i)=>{r=()=>i(new Error(wn)),t?.addEventListener("abort",r,{once:!0})});try{return await Promise.race([new fe(Ly).withTimeout("forge:deliverability",async()=>$t(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=Dl(t,{leftOut:new Set(t.nodes.filter(ai).map(d=>d.objectApiName))}),i=new Set(o.map(d=>d.objectApiName)),{ofRun:a}=await Yt({read:r,writes:(d,c)=>c==="insert"||c==="update"&&i.has(d),readDeliverability:()=>Te(n)==="production"?Promise.resolve(Nt):this.readDeliverability(e),accepted:!1,target:be(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(sx,e,"forge:undo-automation:error",this.deps);if(!t)return;let r=(d,c)=>E(this.deps,"forge:undo-automation","forge:undo-automation:error",e,d,{code:c}),n=this.targetAutomation;if(!n){r(new Error("Target automation reader not configured"),"NOT_INITIALIZED");return}let o=this.loadHistory().find(d=>d.forgeId===t.forgeId);if(!o?.targetOrgId){r(new Error("This run is no longer in the Forge history."),jo);return}let i=(t.again===!0?ag(o):Kr(o)).map(d=>d.objectApiName),a=o.targetOrgId;try{let d=await this.otherPartObjectsOf(t.forgeId,a),c=[...new Set([...tn(i,d,{userKept:o.runUserId!==void 0}),...t.sweptObjects??[]])],l=await new fe(qs).withTimeout("forge:undo-automation",()=>n.read(a,c));this.deps.broker.postToWebview(T(this.deps,e,"forge:undo-automation:response",{forgeId:t.forgeId,automation:l,drafted:Vt(i)}))}catch(d){let c=d instanceof lr;E(this.deps,"forge:undo-automation","forge:undo-automation:error",e,d,{code:c?"TIMEOUT":"AUTOMATION_ERROR",retryable:c})}}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(yx,e,"forge:gaps:error",this.deps);if(!t)return;let{graph:r,config:n}=t,o=this.targetGaps,i=`forge-gaps-${this.deps.nextId()}`;ze(this.deps,i,"forge","Reading what the target org holds against the rows");try{let a=await new fe(Dx).withTimeout("forge:gaps",()=>o.read(n.sourceOrgId,n.targetOrgId,r,n));this.deps.broker.postToWebview(T(this.deps,e,"forge:gaps:response",{gaps:a})),de.info("Forge target gaps read",{gaps:a.gaps.length,blocking:a.gaps.filter(d=>d.severity==="blocking").length,kinds:[...new Set(a.gaps.map(d=>d.kind))],unread:a.unread.map(d=>d.part),requests:a.requests}),ge(this.deps,i,{objectCount:r.nodes.length})}catch(a){let d=a instanceof lr;E(this.deps,"forge:gaps","forge:gaps:error",e,a,{code:d?"TIMEOUT":"GAPS_ERROR",retryable:d}),ge(this.deps,i,{status:"failure"})}}async handleUsersRequest(e){let t=nt(wx,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(lO);De(r.limitInfo,"forge:users query");let{users:o,truncated:i}=uO(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(bx,e,"forge:target-records:error",this.deps);if(t)try{let r=await q(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),n=await new fe(No).withTimeout("forge:target-records",()=>r.request(`/services/data/v${r.version}/limits/recordCount`)),o=Pw(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(Rx,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=lb({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"})}}};import{randomUUID as Qx}from"node:crypto";import*as LO from"node:os";import*as kr from"node:path";var NO=50*1024*1024,Zx=new Set(["migration:pick-file","migration:import-sfdmu","migration:save-sync-config"]),eM="Saved from the SandForge Migration page",tM=new Set([".json"]);function rM(s,e,t){if(typeof s!="string"||s.trim().length===0)throw new Error("Invalid import path: path is empty.");if(!kr.isAbsolute(s))throw new Error(`Invalid import path: "${s}" is not absolute. Pick a file inside the workspace or your home directory.`);let r=kr.resolve(s),n=kr.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=kr.resolve(i);if(process.platform==="win32"){let d=r.toLowerCase(),c=a.toLowerCase();return d===c||d.startsWith(c+kr.sep)}return r===a||r.startsWith(a+kr.sep)}))throw new Error("Invalid import path: the file must be inside an open workspace folder or your home directory.");return r}async function $O(s,e){let t=await s.statSize(e);if(t>NO){let r=(t/1048576).toFixed(1),n=NO/(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 Kd=class{constructor(e){this.deps=e}deps;fileReader;setFileReader(e){this.fileReader=e}async handle(e){if(!Zx.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=D(om,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 Ct(this.deps.configStore);if(Sg(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=>Si(u));if(a.length>0){r({success:!1,code:"SYNC_CANNOT_COPY",objects:a});return}let d=new Date().toISOString(),c=If.safeParse({...t.config,id:Qx(),name:n,description:eM,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?.()??[],LO.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=D(nm,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=rM(r,tM,this.getAllowedBaseDirs());await $O(n,o);let{SfdmuImporter:i,SfdmuRefusal:a}=await import("./chunk-YAZO75G2.mjs"),d=new i({readFile:async c=>(c!==o&&await $O(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: ${A(n)}`);let o=T(this.deps,e,"migration:import-sfdmu:response",{success:!1,error:A(n)});this.deps.broker.postToWebview(o)}}};import*as Lo from"node:fs/promises";var BO="settings",FO=V({version:L(),exportedAt:L(),exportedBy:L().optional(),categories:Se(Ke(["syncMappings","forgePlans","pipelines","anonymizationTemplates",BO])),data:ei(L(),Xn())});function _O(s){return s!==BO}var fp={syncMappings:"sync:config:",forgePlans:"forge:templates",pipelines:"pipeline:saved:",anonymizationTemplates:"anonymization:"},UO={syncMappings:"syncConfigs",forgePlans:"forge",pipelines:"pipelines",anonymizationTemplates:"anonymizationTemplates"},Ws="forge:templates";function nM(s){return typeof s.name=="string"&&s.name.length>0?s.name:s.id}var Yd=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?{[Ws]:l}:{},n+=l.length;continue}let a=fp[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=FO.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(_O),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=fp[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,UO[c]),d++,c==="pipelines"){let h=pk(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=FO.safeParse(t);return r.success?{valid:!0,categories:r.data.categories.filter(_O)}:{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(fp)){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(Ws);return Array.isArray(r)?r.filter(Gr):[]}let e=await this.workspace.readTemplates(),t=zd(this.configStore,this.workspace.folder);return t?Hs(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!==Ws){r.push(`Key "${c}" does not match expected prefix "${Ws}" 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(!Gr(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 "${nM(u)}" already exists, skipped.`);continue}d.push(u.id)}a.push(u)}}}return this.workspace?aO(this.configStore,this.workspace.folder,a,d):a.length>0&&this.configStore.set(Ws,Hs(n,a,new Set(d)),UO.forgePlans),a.length}};import*as hp from"node:path";var Qd=class{deps;filePath;constructor(e){this.deps=e,this.filePath=hp.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(Gr):[]}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=Hs(r,e.filter(Gr),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=hp.join(this.deps.workspacePath,".sandforge");await this.deps.mkdir(t).catch(()=>{}),await this.deps.writeFile(this.filePath,JSON.stringify(e,null,2))}};var oM=new Set(["config:export","config:import","config:categories","config:validate"]);function sM(s){let e=s.services?.getWorkspaceFolders?.()[0];if(!e)return;let t=new Qd({workspacePath:e,readFile:r=>Lo.readFile(r,"utf-8"),writeFile:(r,n)=>Lo.writeFile(r,n,"utf-8"),mkdir:r=>Lo.mkdir(r,{recursive:!0}).then(()=>{})});return{folder:e,readTemplates:()=>t.list()}}var Zd=class{constructor(e){this.deps=e;this.profileManager=new Yd(e.configStore,sM(e))}deps;profileManager;async handle(e){if(!oM.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=D(um,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=D(pm,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=D(gm,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 iM=V({metric:L(),operator:Ke(["gt","gte","lt","lte","eq","neq"]),threshold:Me(),warningThreshold:Me().optional()}),aM=V({id:L(),name:L(),description:L(),category:Ke(["security","performance","compliance","custom"]),condition:iM,remediation:L(),enabled:Je()}),zs=V({id:L(),name:L(),description:L(),rules:Se(aM),createdAt:L(),updatedAt:L()});function HO(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 ec=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";HO(a,n,o)?d="fail":i!==void 0&&HO(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 tc="governance:policy:",dM="governance",Gs=class{constructor(e){this.configStore=e}configStore;getAll(){let e=this.configStore.getKeysByPrefix(tc),t=[];for(let r of e){let n=this.configStore.get(r);if(n){let o=zs.safeParse(n);o.success&&t.push(o.data)}}return t}getById(e){let t=this.configStore.get(`${tc}${e}`);if(!t)return;let r=zs.safeParse(t);return r.success?r.data:void 0}save(e){this.configStore.set(`${tc}${e.id}`,e,dM)}delete(e){return this.configStore.delete(`${tc}${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 cM={apiUsagePercent:"DailyApiRequests",storageUsagePercent:"DataStorageMB"},lM=new Set(["governance:policies:list","governance:policy:save","governance:policy:delete","governance:evaluate","governance:templates"]),rc=class{constructor(e,t){this.deps=e;this.store=new Gs(e.configStore),this.engine=new ec,this.alertEngine=t}deps;store;engine;alertEngine;async handle(e){if(!lM.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=D(am,e,"governance:error",this.deps);if(t)try{let r=zs.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=D(im,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=D(dm,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/${Yn}/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(cM))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=Gs.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 nc=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 uM=new Set(["OpportunityId","CaseId","ContractId","OrderId"]),oc=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)||Kg(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 uM.has(e)?"masterDetail":"lookup"}};var sc=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 ic=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 lu(e,t)}inferType(e,t){return e.apiName===t.apiName&&e.type===t.type?"direct":e.apiName!==t.apiName?"rename":"direct"}};var pM=new Set(["quicksync:suggest-objects","quicksync:detect-relationships","quicksync:preview","quicksync:execute"]),Js={direction:"source_to_target",mode:"full",conflictStrategy:"source_wins",operation:"insert",batchSize:200},ac=class{constructor(e){this.deps=e}deps;suggester=new nc;relationshipDetector=new oc;previewEstimator=new sc;autoFieldMapper=new ic;async handle(e){if(!pM.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=D(Wh,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=D(zh,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=D(Gh,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=ga(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=D(Jh,e,"quicksync:error",this.deps);if(!t)return;let r=t;try{let n=zp.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([Bt(n.sourceOrgId,p,()=>o.describe(p)),Bt(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})),b=this.autoFieldMapper.suggest(m,y),v=this.autoFieldMapper.toMappings(b);d.push({objectApiName:p,operation:Js.operation,fieldMappings:v,transformRules:[],excludedFields:[],batchSize:Js.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:Js.direction,mode:Js.mode,objects:d,conflictStrategy:Js.conflictStrategy,enableRollback:!1};ke(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 qO=6e4,gM=2880*6e4,fM=60*6e4,dc=class{deps;schedules=new Map;checkInterval;lastTickTime=0;claims;lastPrune=0;running=new Set;constructor(e){this.deps=e,this.claims=e.claims??Po()}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()},qO),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+uR)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*qO&&this.deps.log(`[SyncScheduleExecutor] sleep-wake detected (elapsed ${Math.round(t/1e3)}s)`),this.lastTickTime=e,e-this.lastPrune>=fM&&(this.lastPrune=e,this.claims.prune(gM));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=fa(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=ba(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 mp="schedule:sync:",WO="syncSchedules",cc=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${mp}${e.id}`,e,WO)}load(e){return this.configStore.get(`${mp}${e}`)}list(){let e=this.configStore.getByCategory(WO);return Object.values(e).sort((r,n)=>n.createdAt.localeCompare(r.createdAt))}delete(e){return this.configStore.delete(`${mp}${e}`)}loadAll(){return this.list()}};var hM=new Set(["sync:schedule:list","sync:schedule:upsert","sync:schedule:toggle","sync:schedule:delete"]),lc=class{constructor(e){this.deps=e}deps;executor;executeBridge;inFlight=0;claims=Po();async handle(e){if(!hM.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 dc({scheduleStore:new cc(this.deps.configStore),configStore:new Ct(this.deps.configStore),onExecute:t=>this.executeDue(t),notificationCenter:{notify:(t,r,n)=>{this.deps.log(`[SyncSchedule] ${t}: ${r} \u2014 ${n}`),ke(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=D(zf,e,"sync:schedule:error",this.deps);if(!t)return;let r=t.schedule.configId;if(!new Ct(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=ba(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=D(Gf,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=D(Jf,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 mM=new Set(["direct","rename"]);function zO(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=Jo([a]);if(d.length>0)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" cannot be applied. ${Vo(d)}`);let c=sg([a]);if(c.length>0)throw new Error(`${s.objectApiName}: the saved Sync configuration "${i.name}" cannot be applied. ${ig(c)}`);let l=a.externalIdField?.trim()||"Id",u=a.fieldMappings.find(p=>p.targetField===l&&mM.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 yM=V({entityName:L().min(1),changeType:L().min(1),recordIds:Se(L()),commitTimestamp:Me(),commitUser:L().optional(),transactionKey:L().optional(),changeOrigin:L().optional(),changedFields:Se(L()).optional(),nulledFields:Se(L()).optional()}).loose(),wM=V({event:V({replayId:Me()}).loose(),payload:V({ChangeEventHeader:yM}).loose()}).loose(),uc="ChangeEvent";function JO(s){return`/data/${s.endsWith("__c")?s.slice(0,-1):s}${uc}`}function VO(s){if(!s.endsWith(uc)||s===uc)return null;let e=s.slice(0,-uc.length);return e.endsWith("__")?`${e}c`:e}function XO(s,e){return s.endsWith("__c")?`${s.slice(0,-3)}__${e}__s`:s.endsWith("Address")?`${s.slice(0,-7)}${e}`:e}function GO(s){let e=s.indexOf(".");return e<0?s:XO(s.slice(0,e),s.slice(e+1))}function bM(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}function KO(s,e){let t=wM.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(bM(a))for(let[d,c]of Object.entries(a))o[XO(i,d)]=c;else o[i]=a;for(let i of r.nulledFields??[])o[GO(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(GO),values:o}}var yp="SandForgeRealtime";function YO(s){return s.changeOrigin.split(";").some(e=>e.trim()===`client=${yp}`)}var Fo=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 RM(s){return s instanceof Error?s.message:typeof s=="object"&&s!==null&&"message"in s?String(s.message):String(s)}function QO(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 Fo(a,t.get(a)??RM(p)))})})},onDown(a){r.push(a)},disconnect(){n=!0,i.disconnect()}}}var ZO="SELECT EventChannel, SelectedEntity FROM PlatformEventChannelMember";function eI(s){let e=new Map;for(let t of s){let r=typeof t.SelectedEntity=="string"?t.SelectedEntity:"",n=VO(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 tI(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: ${A(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 gc=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}},vn=200,rI=new Set(["int","double","currency","percent","long"]),vM="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 SM(s){return s==="DELETE"||s==="GAP_DELETE"}function nI(s){return s==="CREATE"||s==="UNDELETE"}function pc(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 oI(s){return Object.fromEntries(Object.entries(s).filter(([e])=>e!=="attributes"))}function sI(s){return s==null||s===""}function wp(s){return String(s).toLowerCase()}var fc=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:vn,insertOrder:0}}plan;deps;mapping=new wf;transforms=new yf;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:vM});return}if(i.recordIds.length===0){t[a].push({outcome:"failed",error:"The change named no record."});return}let d=SM(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||nI(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:nI(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=A(c);for(let u of a)d(u,{outcome:"failed",error:l})}}return{results:t.map(kM),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:A(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"&&rI.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(wp(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),b=this.recordFor(g,h,o,!0),v=pc(m.LastModifiedDate);if(!(v!==null&&v>g.commitTimestamp&&!this.deps.ownWrites.wrote(y,v))){c.push({change:g,record:b,targetId:y});continue}switch(this.deps.conflictStrategy){case"source_wins":c.push({change:g,record:b,targetId:y});break;case"merge":{let R=Object.fromEntries(Object.entries(b).filter(([k,I])=>I!==null||k===this.plan.keyField));Object.keys(R).length>1?c.push({change:g,record:R,targetId:y}):t(g,{outcome:"kept-target"});break}case"manual":r.push(this.held(g,"upsert",b,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(wp(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=pc(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(pc(n.LastModifiedDate)??0).toISOString()}}async keysOf(e,t,r){let{keySource:n}=this.plan,o=e.filter(a=>n!=="Id"&&sI(a.values[n])&&!(n in a.values&&a.full));if(o.length>0){let a=await this.readSource(o.map(d=>d.recordId),`Id, ${Fe(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(sI(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?[]:yi(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={...oI(o),...n.values},n.full=!0}}async readSource(e,t,r){let n=gt(this.plan.objectApiName),o=new Map;for(let i=0;i<e.length;i+=vn){let d=e.slice(i,i+vn).map(u=>`'${zt(u)}'`).join(", "),c=t==="FIELDS(ALL)"?` LIMIT ${vn}`:"",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=gt(this.plan.objectApiName),o=Fe(this.plan.keyField),i=rI.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+=vn){let p=e.slice(l,l+vn).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(Fe).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=wp(f[this.plan.keyField]);c.set(m,[...c.get(m)??[],oI(f)])}}return c}async rememberWrites(e){if(e.length===0)return;let t=gt(this.plan.objectApiName);try{for(let r=0;r<e.length;r+=vn){let n=e.slice(r,r+vn).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=pc(i.LastModifiedDate);a!==null&&this.deps.ownWrites.record(String(i.Id),a)}}}catch{}}};function kM(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 hc=class{constructor(e){this.deps=e}deps;async open(e){let t={subscribed:[],refused:[],notes:[]};for(let r of e){let n=JO(r),o=a=>{let d;try{d=KO(n,a)}catch(c){this.deps.onUnreadable(n,A(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 Fo&&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:iI(d)})}else t.refused.push({objectApiName:r,reason:iI(a)})}}return t}close(){this.deps.transport.disconnect()}};function iI(s){return s instanceof Fo?s.answer:A(s)}var AM=[2e3,1e4,3e4],TM=6e4,mc=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=A(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<TM);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 hc({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 AM){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: ${A(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: ${A(t)}`)}}}async process(e){let t=e.map(()=>({outcome:"watched"})),r=new Map;e.forEach((i,a)=>{YO(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=A(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)=>EM(i,t[a]))),this.deps.replayStore.save(o)}};function EM(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 PM="realtime:replay:",CM="realtime",Vs=class{constructor(e,t){this.configStore=e;this.sourceOrgId=t}configStore;sourceOrgId;get key(){return`${PM}${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)},CM)}forget(){this.configStore.delete(this.key)}};function bp(s){return s.eventsFailed===0?"success":s.eventsApplied>0?"partial":"failure"}function aI(s){return s.slice(0,15)}function dI(s){let e=s.store.recorder({runId:s.sessionId,configId:`realtime:${s.sessionId}`,configName:"",sourceOrgId:s.sourceOrgId,targetOrgId:s.targetOrgId,realtime:!0});s.identity&&hr(e,s.identity,`realtime ${s.sessionId}`);let t=s.backups?ua({runId:s.sessionId,orgId:s.targetOrgId,files:s.backups,meta:s.meta}):void 0,r=d=>s.target.query(d),n=t?pa({query:r,backup:t,recorder:e,describe:async d=>mr(await s.target.describe(d)),viewsEncrypted:cr(r)}):void 0,o=new Set,i=(d,c,l,u)=>{if(c==="insert"||c==="upsert"){for(let g of ha(c,u))o.add(aI(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(aI(f))?[f]:[]});p.length>0&&e.deleted?.(d,p)},a;return{runId:s.sessionId,calls:ma(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 DM=new Set(["realtime:start","realtime:stop","realtime:status","realtime:metrics","realtime:objects","realtime:resolve-conflict"]);function xM(s){let e=r=>q(r,s.orgRegistry,s.orgManager),t=st(s);return{async openTransport(r){let{streaming:n}=await e(r);return QO({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 dr({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 Bt(r,n,()=>o.describe(n))).fields}}}},writer(r,n){return async(o,i,a)=>{let d=await e(r),c=await $g(d,yp),l=new un({connection:c,bulkExecutor:new en(t.bulk.threshold),bulkManager:ar(s),retryConfig:t.retry,onProgress:()=>{},log:p=>s.log(p),...n?{calls:n}:{}});return new Mb({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=>mr(await Bt(r,p,()=>d.describe(p))),...a?{contactPoints:a}:{}}).write(o,i)}},async tooling(r,n){let o=await e(r),{records:i}=await dr({query:async a=>o.tooling.query(a),queryMore:async a=>o.tooling.queryMore(a)},n);return i}}}var yc=class{constructor(e,t){this.deps=e;this.syncConfigs=new Ct(e.configStore),this.access=t??xM(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(!DM.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 Vs(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&&K(this.deps,{action:"realtime_sync",module:"sync",operationId:e.operationId,orgId:e.targetOrgId,outcome:bp(this.lastMetrics),guard:e.guard,source:{origin:"org",orgId:e.sourceOrgId}}),t>0&&ke(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=D(Mf,e,"realtime:error",this.deps);if(t)try{let r=await this.access.tooling(t.sourceOrgId,ZO),n=this.access.reader(t.targetOrgId),o=await tI(eI(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=Ig(A(r));E(this.deps,"realtime:objects","realtime:error",e,r,n?{code:n}:void 0)}}async handleStart(e){let t=D(Df,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(O=>zO(O,P=>this.syncConfigs.load(P),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 gc,d=this.access.reader(t.sourceOrgId),c=this.access.reader(t.targetOrgId),l=crypto.randomUUID(),u=o&&this.runCreations?dI({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:O=>this.deps.log(O)}):void 0,p=u?u.write(this.access.writer(t.targetOrgId,u.calls)):this.access.writer(t.targetOrgId),g=new Dw,h=Cn(cr(O=>d.query(O)),O=>d.describe(O)),f=new Map(n.map(O=>[O.objectApiName,new fc(O,{source:d,target:c,write:p,conflictStrategy:t.conflictStrategy,ownWrites:a,contactPoints:g,maskedSourceFields:h})])),m,y=()=>{},b=new Promise((O,P)=>{y=_=>{_?m?.fail(_):i.signal.aborted?m?.cancel():m?.complete(),_?P(new Error(_)):O()}});b.catch(()=>{});let v=async()=>{if(!u)return;let O=await u.end({status:bp(w.metrics()),cancelled:i.signal.aborted}).catch(P=>A(P));this.openRuns.delete(u.runId),O!==void 0&&ke(this.deps,"warning","Real-time sync",`What the session wrote could not all be kept (${O}): removing it may leave some of it in the target.`)},w=new mc({sessionId:l,watchedObjects:t.watchedObjects,appliers:f,flushIntervalMs:t.flushIntervalMs,maxBatchSize:t.maxBatchSize},{openTransport:()=>this.access.openTransport(t.sourceOrgId),replayStore:new Vs(this.deps.configStore,t.sourceOrgId),sink:{events:O=>this.pushEvents(O),conflict:O=>this.pushConflict(O),status:O=>{if(O.status!=="error"){this.pushStatus(O);return}y(O.error),v().then(()=>this.pushStatus(O))}},log:O=>this.deps.log(O)}),R={session:w,abort:i,operationId:e.id,sourceOrgId:t.sourceOrgId,targetOrgId:t.targetOrgId,guard:o,finish:O=>y(O),detach:()=>{},endRun:v};this.current=R,this.lastMetrics=null,u&&this.openRuns.add(u.runId);let k;try{k=await w.start()}catch(O){throw await v(),O}let I=w.snapshot();if(k.subscribed.length>0){let O=`Real-time sync of ${k.subscribed.length} object(s)`;this.registry?.register(w.sessionId,"sync",O,b,i),m=Kt(this.liveTracker,w.sessionId,"realtime",O);let P=()=>{this.current?.session===w&&this.stopCurrent().then(_=>{_&&this.pushStopped(_,"cancelled")})};i.signal.addEventListener("abort",P,{once:!0}),R.detach=()=>i.signal.removeEventListener("abort",P)}else y(),await v();let S=new Set(k.subscribed),C=(await Promise.all(n.filter(O=>S.has(O.objectApiName)).map(async O=>({objectApiName:O.objectApiName,fields:[...await h(O.objectApiName)].sort()})))).filter(O=>O.fields.length>0);C.length>0&&(R.encryptedLeftOut=C),this.post(T(this.deps,e,"realtime:started",{success:k.subscribed.length>0,sessionId:w.sessionId,watchedObjects:k.subscribed,refused:k.refused,notes:k.notes,...C.length>0?{encryptedLeftOut:C}:{},...I.error?{error:I.error}:{}}))}catch(n){r(A(n))}}async passesProductionGuard(e,t,r){let n=this.deps.infraServices?.productionGuard;if(!n)throw K(this.deps,{action:"realtime_sync",module:"sync",operationId:e.id,orgId:t,outcome:"stopped",code:Re.code}),bi();let o={orgId:t,orgTier:Te(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 Ye(n,o);if(i==="refused"||i==="declined"){K(this.deps,{action:"realtime_sync",module:"sync",operationId:e.id,orgId:t,outcome:"stopped",guard:i});return}return i}async handleStop(e){let t=D(xf,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=D(jf,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||ke(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 MM=new Set(["file:save"]),wc=class{constructor(e,t){this.deps=e;this.saveDialog=t??new nn}deps;saveDialog;async handle(e){return MM.has(e.type)?(await this.handleSave(e),!0):!1}async handleSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=Af.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 jM=new Set(["reports:list","reports:audit","reports:lineage"]),NM="forge:history",$M="sync:history:all",cI=50;function LM(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 FM(s){let e=s.graph?.nodes??[];return e.filter(t=>!lg(t)).length+ug(s,e).length}var bc=class{constructor(e){this.deps=e}deps;async handle(e){if(!jM.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=D(cm,e,"reports:error",this.deps);if(t===null)return;let r=new to(this.deps.configStore).list(t??{});this.deps.log(`[ReportsHandler] audit trail: ${r.entries.length} of ${r.total} entries`),this.deps.broker.postToWebview(T(this.deps,e,"reports:audit:response",{...r}))}handleLineage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(lm,e,"reports:error",this.deps);if(t===null)return;let r=new nf(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?cI:Math.min(Math.floor(t),500)}build(e=cI){let t=this.deps.configStore.get(NM)??[],r=this.deps.configStore.get($M)??[],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:UM(n)}}forgeReport(e){let t=FM(e),r=LM(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 _M(s){let e=s.sections[0]?.content?.status;return e==="failure"||e==="failed"||e==="partial"}function UM(s){let e=s.length;if(e===0)return{totalOperations:0,successRate:0,avgDuration:0,errorRate:0};let t=s.filter(_M).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 lI(s){return Object.values(s).every(e=>e<50)}var Rc=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(Pp.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=lI(t),a=n!==void 0&&!lI(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 HM(s,e){return`smart-action:${s}:${e??""}`}var qM=300*1e3,WM=new Set(["smart-action:analyze"]),vc=class{constructor(e){this.deps=e;this.analyzer=new Rc({getConnection:t=>q(t,e.orgRegistry,e.orgManager)})}deps;analyzer;cache=new Map;async handle(e){return WM.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=D(Im,e,"smart-action:error",this.deps);if(t)try{let r=t.targetOrgId,n=t.sourceOrgId,o=HM(r,n),i=this.cache.get(o);if(i&&Date.now()-i.fetchedAt<qM){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 zM=new Set(["execution:abort"]),Sc=class{constructor(e,t){this.deps=e;this.registry=t}deps;registry;async handle(e){return zM.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=D(sm,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 GM}from"node:fs/promises";import{join as JM}from"node:path";var Rp=new Map;function uI(s,e){let t=JM(s,`${e}.json`),r=Rp.get(t);if(r)return r;let n=GM(t,"utf-8").then(o=>JSON.parse(o));return Rp.set(t,n),n.catch(()=>Rp.delete(t)),n}var VM=new Set(["i18n:locale"]),kc=class{constructor(e,t){this.deps=e;this.localesDir=t}deps;localesDir;async handle(e){return VM.has(e.type)?(await this.handleLocaleRequest(e),!0):!1}async handleLocaleRequest(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=D(Om,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 uI(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}): ${A(n)}`);let o=T(this.deps,e,"i18n:locale:response",{lng:r,error:A(n)});this.deps.broker.replyToRequester(o)}}};import{AsyncLocalStorage as XM}from"node:async_hooks";function gI(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 pI=new XM;async function fI(s,e,t,r){let n=Symbol("pipeline sync"),o,i=s.registry?.onEvent((d,c,l)=>{c!=="started"||l.module!=="sync"||pI.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{return await pI.run(n,()=>_i(t,()=>s.execute(e)))}finally{i?.(),r?.removeEventListener("abort",a)}}var KM=V({setting:L().regex(/^sandforge(?:\.[A-Za-z][A-Za-z0-9]*)+$/)}),Oc=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 ka({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:Jc,bulkManager:new rf(Jc.bulk.maxConcurrentJobs),nextId:()=>this.nextId(),sandboxRefreshes:this.refreshDetector},this.orgHandler=new Aa(this.handlerDeps),this.settingsHandler=new Ta(this.handlerDeps),this.monitorHandler=new Ua(this.handlerDeps),this.seedHandler=new za(this.handlerDeps),this.seedCloneHandler=new Xa(this.handlerDeps),this.seedCsvHandler=new Za(this.handlerDeps),this.seedRemovalHandler=new id(this.handlerDeps,void 0,r=>this.seedHandler.isRunning(r)||this.seedCsvHandler.isRunning(r)||this.seedCloneHandler.isRunning(r)),this.syncHandler=new rd(this.handlerDeps),this.syncHistoryStore=new dd(e.configStore),this.syncHandler.setHistoryLogger(new cd(this.syncHistoryStore)),this.syncHistoryHandler=new nd(this.handlerDeps,this.syncHistoryStore,this.syncHandler),this.syncRemovalHandler=new od(this.handlerDeps,this.syncHistoryStore,r=>this.syncHandler.isRunning(r)||this.realtimeHandler.isRunning(r)),this.compareHandler=new ld(this.handlerDeps),this.dataOpsHandler=new qy(this.handlerDeps),this.complianceHandler=new fd(this.handlerDeps),this.cleanupHandler=new hd(this.handlerDeps),this.emptyHandler=new Cd(this.handlerDeps),this.automationHandler=new $d(this.handlerDeps),this.aiHandler=new Bd(this.handlerDeps),this.autopilotHandler=new qd(this.handlerDeps),this.forgeHandler=new Xd(this.handlerDeps),this.frozenHandler=new hR(this.handlerDeps),this.frozenHandler.setSaltKeeper(fR(e.secretVault));let t=()=>[this.forgeHandler,this.frozenHandler,this.dataOpsHandler,this.complianceHandler,this.emptyHandler,this.autopilotHandler,this.realtimeHandler];this.checkpointHandler=new Md(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 Kd(this.handlerDeps),this.configHandler=new Zd(this.handlerDeps),this.governanceHandler=new rc(this.handlerDeps,this.monitorHandler.getAlertEngine()),this.quickSyncHandler=new ac(this.handlerDeps),this.syncScheduleHandler=new lc(this.handlerDeps),this.realtimeHandler=new yc(this.handlerDeps),this.fileHandler=new wc(this.handlerDeps),this.reportsHandler=new bc(this.handlerDeps),this.smartActionHandler=new vc(this.handlerDeps),this.i18nHandler=new kc(this.handlerDeps,e.localesDir),this.automationHandler.setStepRunners({orgName:r=>{let n=e.orgManager.getOrg(r);return n?be(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 Ct(e.configStore).load(r),listSyncConfigs:()=>new Ct(e.configStore).list(),syncGuard:r=>gI(this.handlerDeps.infraServices?.productionGuard,fu(r,e.orgManager.getOrg(r.targetOrgId))),runSync:(r,n,o)=>fI({execute:i=>this.syncHandler.executeScheduled(i,"pipeline"),registry:this.backgroundRegistry},r,n,o),orgTier:r=>{let n=e.orgManager.getOrg(r);return n?Te(n):void 0},organizationIdsOf:r=>[e.orgManager.getOrg(r)?.orgId,this.refreshDetector.organizationIdOf(r)].filter(n=>typeof n=="string"&&n!==""),savedSeedTemplate:r=>new $n(e.configStore).load(r),listSeedTemplates:()=>new $n(e.configStore).list(),seed:(r,n)=>this.seedHandler.seedForPipeline(r,n),maskingTemplates:()=>[...sf.map(r=>({...r,builtIn:!0})),...new hy(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)}),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){gi().remove(e),TR(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.syncHandler.setBackupRecordStore(e),this.syncRemovalHandler.setBackupRecordStore(e),this.realtimeHandler.setBackupRecordStore(e)}otherModuleRuns(e,t){return async(r,n)=>{let o=e==="forge"?this.forgeHandler:e==="frozen"?this.frozenHandler:void 0,i=new to(this.handlerDeps.configStore).list({orgId:r,limit:Fp}).entries,a=[...e==="forge"?[]:await this.forgeHandler.localRunsOn(r,n),...e==="sync"?[]:await this.syncRemovalHandler.localRunsOn(r),...e==="seed"?[]:await this.seedRemovalHandler.localRunsOn(r),...Eb(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-GSG7WZHM.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 Sc(this.handlerDeps,e)}async replayQueuedOperation(e){let t=An("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","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"],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=KM.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?`
|
|
13
|
-
${n.stack}`:""))})}nextId(){return`ext-${++this.idCounter}`}};var Ic=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 YM=100,QM=1e3,ZM=3,ej=1e3;function tj(s){return typeof s=="object"&&s!==null&&"protocolVersion"in s&&"payload"in s&&typeof s.payload=="object"}var hI=500;function rj(s){let e=s.map(t=>`${t.path.map(String).join(".")}: ${t.message}`).join("; ");return e.length<=hI?e:`${e.slice(0,hI)}\u2026(+${s.length} issues)`}var Tc=class{handlers=new Map;panels=new Set;rateLimiter;telemetry;fixSuggestionNotifier;mismatchCount=0;webviewSeen=!1;firstWebviewCallbacks=[];senders=new Map;constructor(e){this.rateLimiter=new Ic(e?.rateLimitMax??YM,e?.rateLimitWindowMs??QM),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=A(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(!tj(e)){this.logFn?.("[MessageBroker] Received malformed message: not an envelope");return}let r=Np.safeParse(e);if(!r.success){let o=rj(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;Cp(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>=ZM&&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>ej){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 Ec=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 Pc=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 Cc=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=A(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 Dc=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){de.warn("OrgManager listener threw",{error:A(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 _o="org.",xc="org-cred.",vp="orgs",mI=1e4;function nj(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 oj(e)}function oj(s){if(s.orgType===og(s.orgType,s.metadata?.edition))return s;let{safetyTier:e,color:t}=Er("Developer");return{...s,orgType:"Developer",safetyTier:e,appearance:{...s.appearance,color:s.appearance.color===Kc?t:s.appearance.color}}}var Mc=class{constructor(e,t,r){this.configStore=e;this.secretVault=t;this.orgManager=r}configStore;secretVault;orgManager;loadAll(){let e=this.configStore.getByCategory(vp),t=new Map,r=[];for(let[n,o]of Object.entries(e)){if(!n.startsWith(_o))continue;let i=nj(o),a=i.orgId??i.id,d=n.slice(_o.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(_o.length);this.secretVault.deleteSecret(`${xc}${o}`).catch(()=>{}),this.orgManager.removeOrg(o),de.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=`${_o}${e.id}`,n=this.configStore.get(r),i=n!==void 0&&Te(n)==="production"&&Qn(e)&&n.appearance?.color===Kc?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,vp),this.orgManager.addOrg(a),t&&await this.secretVault.storeObject(`${xc}${e.id}`,t)}async removeOrg(e){this.configStore.delete(`${_o}${e}`),await this.secretVault.deleteSecret(`${xc}${e}`),this.orgManager.removeOrg(e)}async getCredentials(e){let t=this.secretVault.getObject(`${xc}${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 ${mI} ms for org "${e}" \u2014 the OS keyring may be locked or unavailable.`))},mI)})])}finally{r!==void 0&&clearTimeout(r)}}updateOrgMetadata(e){this.configStore.set(`${_o}${e.id}`,e,vp),this.orgManager.addOrg(e)}};import{mkdtemp as sj,readFile as ij,rm as aj}from"node:fs/promises";import{tmpdir as dj}from"node:os";import{join as Sp}from"node:path";async function yI(s){let e=await sj(Sp(dj(),"sandforge-sf-"));try{let t={stdout:Sp(e,"stdout.json"),stderr:Sp(e,"stderr.txt")},r;try{await s(t)}catch(o){r=o}let n=o=>ij(o,"utf8").catch(()=>"");return{stdout:await n(t.stdout),stderr:await n(t.stderr),...r!==void 0?{failure:r}:{}}}finally{await aj(e,{recursive:!0,force:!0}).catch(()=>{})}}var vI=10*1024*1024,cj=3e4,jc=3e4,Ap=6e4,wI=12e4,bI=3e4,lj=4,uj=2e3,pj=/["%!\u0000-\u001f\u007f]/,RI=/^[A-Za-z0-9._-]+={0,2}$/;async function Tp(s,e){let{exec:t}=await import("child_process"),{promisify:r}=await import("util"),n=await r(t)(s,{maxBuffer:vI,windowsHide:!0,env:rl(),...e});return{stdout:String(n.stdout),stderr:String(n.stderr)}}function SI(s,e){if(pj.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 Nc(s,e){let{exec:t,execFile:r}=await import("child_process");return new Promise(n=>{let o={encoding:"utf8",maxBuffer:vI,windowsHide:!0,timeout:e.timeoutMs,env:rl()},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=>SI(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+uj),l.stdin?.once("error",()=>{}),l.stdin?.end(e.input??"")})}var gj=V({status:Me().optional(),result:Xn().optional(),message:L().optional(),name:L().optional()}).loose();function kI(s){try{let e=gj.safeParse(JSON.parse(II(s.stdout)));return e.success?e.data:void 0}catch{return}}function OI(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 fj=V({id:L().min(1),username:L().min(1),instanceUrl:L().min(1),accessToken:L().nullish(),alias:L().nullish(),connectedStatus:L().nullish(),apiVersion:L().nullish(),devHubId:L().nullish(),status:L().nullish(),expirationDate:L().nullish(),edition:L().nullish()}).loose(),hj=V({username:L().min(1),orgId:L().min(1),instanceUrl:L().min(1)}).loose();function kp(s,e,t=Ap){let r=kI(s);if(s.failure||r?.status!==0)throw OI(s,r,e,t);let n=hj.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 Op(s){let e=ui(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 II(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 mj(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 yj(s,e){let t=s;return t.killed===!0?`its ${e/1e3} s limit`:typeof t.code=="number"?`exit code ${t.code}`:nl(A(s))??"an error that says nothing"}async function wj(s,e){let t=Date.now(),r=o=>process.platform==="win32"?SI(o,"temporary folder path"):mj(o),n=!1;try{let o=await yI(async a=>{let d=`${s} > ${r(a.stdout)} 2> ${r(a.stderr)}`;n=!0,await Tp(d,{timeout:e})}),i=o.failure===void 0?void 0:n?yj(o.failure,e):A(o.failure);return{ran:n,stdout:o.stdout,stderr:o.stderr,ms:Date.now()-t,...i?{failure:es(i)}:{}}}catch(o){return{ran:n,stdout:"",stderr:"",ms:Date.now()-t,failure:es(A(o))}}}function AI(s){if(!s.ran)return`could not be made (${(s.failure??"").slice(0,200)})`;let e=Lc(s.stderr);return`ended with ${s.failure??"exit code 0"} after ${Ep(s.ms)} s, with ${s.stdout.length} chars in its stdout file and ${s.stderr.length} in its stderr file${e?` ("${e}")`:""}`}function Lc(s){let e=nl(s);return e===void 0?void 0:es(e).slice(0,200)}function Ep(s){return(s/1e3).toFixed(1)}function TI(s,e){return s.ms>=e-500}function bj(s,e,t,r,n){let o=Lc(s.stderr),i=a=>a.length>0?a.join(" | "):"none";return[`first run: ${Ep(s.ms)} s of the ${n/1e3} s allowed`+(TI(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: ${AI(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: ${es(process.cwd())}`,`variables ${Cg()}`].join("; ")}function Rj(s,e,t,r,n){let o=Lc(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 ${Ep(s.ms)} s${TI(s,n)?`, its ${n/1e3} s limit,`:""} and exited with code 0. Run again with its output sent to a file, it ${AI(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 Ip(s){return s.connectedStatus!==void 0?s.connectedStatus==="Connected":s.isScratch===!0&&s.status==="Active"&&s.isExpired!==!0}function vj(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 Sj(s){let e=await xg({instanceUrl:s.instanceUrl,accessToken:s.accessToken,...s.apiVersion?{version:s.apiVersion}:{}});return Zn(e)}async function kj(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 $c=class{constructor(e=Ng,t=Sj){this.readToken=e;this.readKind=t}readToken;readKind;versionAnswer;async isCliAvailable(){try{let{stdout:e}=await Tp("sf --version",{timeout:cj});return this.versionAnswer=Lc(e)??"",!0}catch{return!1}}async listOrgs(e){let t=await this.readOrgEntries(),r=this.dedupeByOrgId(t.filter(a=>Ip(a))),n=new Set(r.map(a=>a.orgId));for(let a of this.dedupeByOrgId(t.filter(d=>!Ip(d))))n.has(a.orgId)||e?.({username:a.username,...a.alias?{alias:a.alias}:{},orgId:a.orgId,reason:vj(a),why:"notConnected"});let o=await kj(r.map(a=>async()=>{try{return{entry:await this.withUsableToken(a)}}catch(d){return{entry:a,reason:A(d)}}}),lj),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||!Ip(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}: ${A(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 Nc([{value:"org",role:"command"},{value:"display",role:"command"},{value:"--target-org",role:"flag"},{value:e,role:"username"},{value:"--json",role:"flag"}],{timeoutMs:bI}),r=kI(t);if(r?.name==="NamedOrgNotFoundError")return;if(t.failure||r?.status!==0)throw OI(t,r,"sf org display",bI);let n=fj.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:Op(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"}),kp(await Nc(t,{timeoutMs:Ap}),"sf org login jwt")}async loginWithRefreshToken(e){if(!RI.test(e.clientId))throw new Error("The consumer key holds characters the Salesforce CLI does not accept.");if(!RI.test(e.refreshToken))throw new Error("Salesforce issued a refresh token the Salesforce CLI cannot store (unexpected characters).");let t=new URL(Op(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}
|
|
14
|
-
`;return kp(await Nc(r,{timeoutMs:Ap,input:n}),"sf org login sfdx-url")}async readOrgEntries(){let e="sf org list --json",t=Date.now(),r,n="";try{let a=await Tp(e,{timeout:jc});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=II(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 wj(e,jc),n=await Dg(),o=bj(t,r,n,this.versionAnswer,jc);if(r.stdout.trim()!=="")return de.warn(`${e} printed nothing on its pipe; what it wrote to a file was read instead. ${o}`),r.stdout;throw de.warn(`${e} printed nothing, on its pipe or to a file. ${o}`),new Error(Rj(t,r,n,this.versionAnswer,jc))}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:Op(t),role:"login URL"}];return e&&r.push({value:"--alias",role:"flag"},{value:e,role:"alias"}),r.push({value:"--json",role:"flag"}),kp(await Nc(r,{timeoutMs:wI}),"sf org login web",wI)}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(ol(e.accessToken))return e;let t=await this.readToken(e.username);if(!ol(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=In({isScratch:e.isScratch,isSandbox:e.isSandbox,edition:e.orgEdition}),{safetyTier:r,color:n}=Er(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??Kn.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 Oj(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 Fc=class{deps;results=new Map;constructor(e){this.deps=e}async execute(e,t){let r=Date.now(),{items:n,managedLeftOut:o}=await Oj(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 Ij(){return globalThis.crypto.randomUUID()}function EI(s){return{stepId:s.id,stepName:s.name,stepType:s.type,status:"skipped"}}function Aj(s,e){let t={};for(let r of s.variables)r.defaultValue!==void 0&&(t[r.name]=r.defaultValue);return{...t,...e}}function Tj(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 PI(s){return`Validation failed: ${s.join(", ")}`}function Ej(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 _c=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=PI(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=Aj(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,Tj(m)),l[fg]=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 b=p.getNextStep(f,m),v=b?u.findIndex((w,R)=>R>h&&w.id===b):-1;v!==-1&&(y=v)}for(let b of u.slice(h+1,y)){let v=EI(b);a.stepResults.push(v),this.emit("stepSkipped",{runId:a.id,stepResult:v})}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 ${A(i)}.`}}if(!o)return EI(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?[PI(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)??Ej(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:Ij(),pipelineId:e.id,pipelineName:e.name,status:"queued",triggeredBy:r,stepResults:[],variables:t,startTime:new Date().toISOString()}}};var Uc=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 Dj=3e4;function xj(s,e){let t=In({isSandbox:e.isSandbox,edition:e.orgType}),{safetyTier:r,color:n}=Er(t);return{id:e.orgId,alias:s.alias,username:e.username||s.username,instanceUrl:s.instanceUrl,orgId:e.orgId,orgType:t,authMethod:"sfdx_import",safetyTier:r,appearance:{color:n,icon:"cloud",position:0},metadata:{apiVersion:Kn.DEFAULT_API_VERSION,edition:e.orgType,features:[]},status:"connected",lastConnected:new Date().toISOString(),tags:[]}}function Mj(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 jj(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 Nj(s,e){return{compareOrchestrator:r=>new Fc(r),automationOrchestrator:r=>new _c(r),seedOrchestrator:r=>new Bb(r),syncOrchestrator:r=>new Ub(r),getSandforgeSetting:(r,n)=>n,isAIEnabled:()=>!1,configStore:s,showNotification:r=>e(` notification: ${r}`)}}function xX(s){let{log:e}=s,t=s.waitMs??5*6e4,r=tl();jg("command line");let n=qw(Cj(s.storeDir,"configStore.json")),o=new Map,i=new Cc({get:v=>Promise.resolve(o.get(v)),store:(v,w)=>(o.set(v,w),Promise.resolve()),delete:v=>(o.delete(v),Promise.resolve())}),a=new Dc,d=new Mc(n,i,a),c=new $c,l=new lR;l.setSfdxBridge(c);let u=new Tc;u.setLogFunction(e);let p=new Ec(u),g=Nj(n,e),h=new Oc({log:e,broker:u,stateSync:new Pc(u),orgManager:a,orgRegistry:d,configStore:n,secretVault:i,authProvider:l,sfdxBridge:c,services:g});h.setLiveOperationTracker(new Uc),s.compose?.({handlers:h,configStore:n,orgRegistry:d,orgManager:a,services:g,log:e}),h.registerAll(p);let f=[],m=new Set,y,b={webview:{postMessage:v=>{f.push(v);let w=jj(v);w&&e(` ${w}`),s.onPost?.(v);for(let R of[...m])R(v);return Promise.resolve(!0)},onDidReceiveMessage:v=>(y=v,{dispose:()=>{y=void 0}})}};return u.registerPanel(b),{posted:f,async connect(v){let w=await Fg(v),R=await l.validateConnection(w.accessToken,w.instanceUrl),k=xj(w,R);return await d.saveOrg(k,{loginUrl:w.instanceUrl,instanceUrl:w.instanceUrl,accessToken:w.accessToken,username:w.username}),k},connectingRequests:()=>tl()-r,request(v){let w=y;if(!w)return Promise.reject(new Error("No panel is registered with the broker."));let R=v.responseType??`${v.type}:response`,k=v.timeoutMs??Dj,I={id:`wv-${Pj()}`,type:v.type,timestamp:Date.now(),...v.payload!==void 0?{payload:v.payload}:{}},S=Date.now();return new Promise(C=>{let O=J=>{m.delete(P),clearTimeout(_),C(J)},P=J=>{let B=Mj(J,I.id,R);if(!B)return;let re=Date.now()-S;O({outcome:B,message:J,elapsedMs:re,late:re>k})},_=setTimeout(()=>O({outcome:"unanswered",elapsedMs:Date.now()-S,late:!0}),Math.max(t,k));m.add(P),w({protocolVersion:1,payload:I})})}}}export{DI as a,Ds as b,Gl as c,Vl as d,Sa as e,xX as f};
|