sandforge 1.84.1 → 1.86.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/lib/{chunk-S42RBRH2.mjs → chunk-22L43JMK.mjs} +1 -1
- package/lib/{chunk-Y2DRK37K.mjs → chunk-2LSGWTWX.mjs} +1 -1
- package/lib/{chunk-24RFOFYT.mjs → chunk-2YJJTQNC.mjs} +1 -1
- package/lib/chunk-34SMB5PA.mjs +10 -0
- package/lib/chunk-35B73566.mjs +7 -0
- package/lib/{chunk-3TZSBHEY.mjs → chunk-35IJ4WEU.mjs} +1 -1
- package/lib/chunk-3EHPAFKV.mjs +7 -0
- package/lib/{chunk-6YL7BNYD.mjs → chunk-3HAVVEXF.mjs} +1 -1
- package/lib/{chunk-6JWWSDM6.mjs → chunk-3I6FXFCN.mjs} +1 -1
- package/lib/{chunk-WUUKFE2U.mjs → chunk-3KJCSYXY.mjs} +1 -1
- package/lib/{chunk-2HVOZUM4.mjs → chunk-3L6DVNCR.mjs} +1 -1
- package/lib/chunk-3LRFPGYZ.mjs +7 -0
- package/lib/{chunk-GWZRR3MM.mjs → chunk-3MVWGL5A.mjs} +1 -1
- package/lib/{chunk-KGU4SVIT.mjs → chunk-4CSBZZAL.mjs} +1 -1
- package/lib/{chunk-JE6SCT6R.mjs → chunk-4NSXPONF.mjs} +1 -1
- package/lib/{chunk-UIOMAX56.mjs → chunk-4VLP6RHC.mjs} +1 -1
- package/lib/{chunk-YA6ATMTB.mjs → chunk-4XROG5CT.mjs} +1 -1
- package/lib/chunk-54V4FVEY.mjs +7 -0
- package/lib/chunk-55OJJT2Q.mjs +7 -0
- package/lib/{chunk-6QE6R6RL.mjs → chunk-5EHHQ5UX.mjs} +1 -1
- package/lib/{chunk-FITPY3L4.mjs → chunk-5JMQXHJ2.mjs} +1 -1
- package/lib/{chunk-W6PN6TJG.mjs → chunk-65AMXOQU.mjs} +1 -1
- package/lib/{chunk-3Q353S2R.mjs → chunk-6HHSAPIM.mjs} +1 -1
- package/lib/chunk-6KVBCFVS.mjs +7 -0
- package/lib/chunk-6NG7C2U3.mjs +476 -0
- package/lib/chunk-6ROL3KBM.mjs +7 -0
- package/lib/{chunk-2JDAOWUW.mjs → chunk-72AWCN7U.mjs} +1 -1
- package/lib/{chunk-JLSIWO4Z.mjs → chunk-7KHA5UIQ.mjs} +1 -1
- package/lib/chunk-7O6EFNQS.mjs +10 -0
- package/lib/{chunk-WWTCWWZI.mjs → chunk-A2CH2QGX.mjs} +1 -1
- package/lib/chunk-A2TXLAC3.mjs +276 -0
- package/lib/chunk-ALWVNR34.mjs +7 -0
- package/lib/{chunk-D4GF4FAB.mjs → chunk-ATBQIE2V.mjs} +1 -1
- package/lib/{chunk-NED4MBIM.mjs → chunk-ATQML7ZK.mjs} +1 -1
- package/lib/chunk-AVY742BJ.mjs +7 -0
- package/lib/{chunk-YWEQQL3C.mjs → chunk-AXTB2HJS.mjs} +1 -1
- package/lib/chunk-BBZUGKBZ.mjs +10 -0
- package/lib/chunk-BIDXK7KA.mjs +7 -0
- package/lib/{chunk-O677VOGO.mjs → chunk-BLMJ4WVI.mjs} +1 -1
- package/lib/{chunk-RE7RYF3B.mjs → chunk-BNHJCJJM.mjs} +1 -1
- package/lib/{chunk-5M5FQ7RP.mjs → chunk-BNPQEQXC.mjs} +1 -1
- package/lib/chunk-C5AUNG6T.mjs +37 -0
- package/lib/{chunk-ETDCBLGU.mjs → chunk-C5EQ7GFC.mjs} +1 -1
- package/lib/{chunk-MJZU3U5O.mjs → chunk-C7CKDZMC.mjs} +61 -61
- package/lib/{chunk-HCGXK7G7.mjs → chunk-CB4U22NR.mjs} +1 -1
- package/lib/chunk-CJAWKLAL.mjs +7 -0
- package/lib/chunk-CL75DEMQ.mjs +9 -0
- package/lib/{chunk-VCUXCK36.mjs → chunk-CLUNF4FK.mjs} +1 -1
- package/lib/chunk-CSMGP53U.mjs +7 -0
- package/lib/{chunk-7YNM6KFZ.mjs → chunk-CT324C7I.mjs} +1 -1
- package/lib/{chunk-7UVKIWKV.mjs → chunk-CZXDJXQP.mjs} +1 -1
- package/lib/{chunk-43TOMFV4.mjs → chunk-D2X6U3MS.mjs} +1 -1
- package/lib/{chunk-M6K34KGF.mjs → chunk-DAUX63UB.mjs} +1 -1
- package/lib/chunk-DB7JNALQ.mjs +10 -0
- package/lib/chunk-DDNCJVZ2.mjs +17 -0
- package/lib/{chunk-FP7CYB2F.mjs → chunk-DLSU66MY.mjs} +1 -1
- package/lib/{chunk-JKJ74BX5.mjs → chunk-DO6PSHQZ.mjs} +1 -1
- package/lib/{chunk-MDMPJEV3.mjs → chunk-DUBECLZV.mjs} +1 -1
- package/lib/{chunk-KZTZDC7H.mjs → chunk-DYHF6DNT.mjs} +1 -1
- package/lib/chunk-E5FSPXYH.mjs +930 -0
- package/lib/{chunk-Q7GIJBCD.mjs → chunk-EGL3I3IX.mjs} +1 -1
- package/lib/chunk-EIYMQPMG.mjs +7 -0
- package/lib/{chunk-RHNTHGNU.mjs → chunk-EUIALBMX.mjs} +1 -1
- package/lib/{chunk-NCZKWSC7.mjs → chunk-FI3R5ZOQ.mjs} +1 -1
- package/lib/{chunk-PAXNWTYK.mjs → chunk-FM4QCTO7.mjs} +1 -1
- package/lib/{chunk-HV7VPEXP.mjs → chunk-FRSIEASH.mjs} +1 -1
- package/lib/{chunk-QAFPQ3YB.mjs → chunk-FV6MOSHD.mjs} +1 -1
- package/lib/chunk-FYG47CNA.mjs +7 -0
- package/lib/chunk-GB6W4Q56.mjs +7 -0
- package/lib/chunk-GEV2DCMK.mjs +7 -0
- package/lib/{chunk-NSQWI7ZY.mjs → chunk-GFB2DNCB.mjs} +1 -1
- package/lib/chunk-GFGMGFSH.mjs +7 -0
- package/lib/{chunk-RGUQOSBU.mjs → chunk-GIFQXB2Q.mjs} +1 -1
- package/lib/{chunk-JAEDM4SI.mjs → chunk-GP5J3DGS.mjs} +1 -1
- package/lib/chunk-GQZEX7LH.mjs +231 -0
- package/lib/{chunk-JSAJS3MY.mjs → chunk-GYDTM62J.mjs} +1 -1
- package/lib/{chunk-OPMO6I45.mjs → chunk-GYFIXUJG.mjs} +1 -1
- package/lib/chunk-GZW2GNFK.mjs +7 -0
- package/lib/chunk-H6BHWAX7.mjs +8 -0
- package/lib/{chunk-EAC5QCE3.mjs → chunk-HDDJ3CVN.mjs} +1 -1
- package/lib/{chunk-5SMWFNE7.mjs → chunk-HDWB4ZOG.mjs} +1 -1
- package/lib/chunk-HGVPBJR6.mjs +7 -0
- package/lib/{chunk-BBRWFKS5.mjs → chunk-HLROVOR6.mjs} +1 -1
- package/lib/{chunk-LKTNQEBS.mjs → chunk-HUOR4M2L.mjs} +1 -1
- package/lib/chunk-HZCS6EED.mjs +8 -0
- package/lib/{chunk-36JOHEJL.mjs → chunk-HZUI56KZ.mjs} +1 -1
- package/lib/chunk-IAB5H7WN.mjs +7 -0
- package/lib/{chunk-X4BXESMQ.mjs → chunk-IQ5UKRHU.mjs} +1 -1
- package/lib/{chunk-54WZUS7J.mjs → chunk-IRQ4WANV.mjs} +1 -1
- package/lib/{chunk-5IZTFMJM.mjs → chunk-IT3DGX37.mjs} +1 -1
- package/lib/chunk-J347SPU6.mjs +49 -0
- package/lib/{chunk-QO53K5W2.mjs → chunk-JANBNTR5.mjs} +1 -1
- package/lib/chunk-JFXQZPRY.mjs +9 -0
- package/lib/{chunk-KAZS5Z6W.mjs → chunk-JRLYWVF4.mjs} +1 -1
- package/lib/{chunk-GKY2JMHY.mjs → chunk-JSNMUTY6.mjs} +1 -1
- package/lib/chunk-JTNJKSAA.mjs +7 -0
- package/lib/{chunk-7WATA4SB.mjs → chunk-JV2LAKWQ.mjs} +1 -1
- package/lib/{chunk-WAPSSYMT.mjs → chunk-JV7K2ZHK.mjs} +1 -1
- package/lib/{chunk-ZBAWJUG2.mjs → chunk-K4TQ7YHX.mjs} +1 -1
- package/lib/chunk-K5PUMHZU.mjs +7 -0
- package/lib/chunk-KH4KLCYG.mjs +7 -0
- package/lib/{chunk-OLCVHL7I.mjs → chunk-KQVLZVOP.mjs} +1 -1
- package/lib/chunk-KWUS7UAV.mjs +19 -0
- package/lib/{chunk-JGZPD4IM.mjs → chunk-L6G73FXM.mjs} +1 -1
- package/lib/{chunk-BAWCOKRW.mjs → chunk-LG466Q5H.mjs} +1 -1
- package/lib/{chunk-GMIGWR6U.mjs → chunk-LHNAR6FC.mjs} +1 -1
- package/lib/chunk-LT4GHEI2.mjs +7 -0
- package/lib/{chunk-EC72TIEG.mjs → chunk-MR262Y3B.mjs} +1 -1
- package/lib/{chunk-LA4KIATH.mjs → chunk-NCCHOV2N.mjs} +1 -1
- package/lib/chunk-NICRSGLS.mjs +7 -0
- package/lib/chunk-NV5QA2HY.mjs +7 -0
- package/lib/{chunk-PR3XCSPO.mjs → chunk-O3GIN5TU.mjs} +1 -1
- package/lib/chunk-O6FHK6NQ.mjs +13 -0
- package/lib/{chunk-M4BLK6HJ.mjs → chunk-O7YIEFG7.mjs} +1 -1
- package/lib/chunk-OCUVAA5E.mjs +7 -0
- package/lib/chunk-OLCS7JCT.mjs +14 -0
- package/lib/chunk-ON7Y63FK.mjs +9 -0
- package/lib/{chunk-N4WPCWJO.mjs → chunk-OO2WY3UB.mjs} +1 -1
- package/lib/{chunk-MSIEU5MR.mjs → chunk-OT2NHL2V.mjs} +1 -1
- package/lib/{chunk-6WX5ZU7Q.mjs → chunk-P2M5ZXWU.mjs} +1 -1
- package/lib/{chunk-GNRSF65U.mjs → chunk-P4YOHLZ4.mjs} +1 -1
- package/lib/chunk-PBHDPTT6.mjs +343 -0
- package/lib/chunk-PE7CHD2W.mjs +7 -0
- package/lib/{chunk-PBY2O6OF.mjs → chunk-PIQ2I67B.mjs} +1 -1
- package/lib/chunk-PKYDNZJK.mjs +7 -0
- package/lib/chunk-PVZ72OOQ.mjs +7 -0
- package/lib/chunk-QACFTHJM.mjs +8 -0
- package/lib/{chunk-J3DND3BC.mjs → chunk-QGVL5EW3.mjs} +1 -1
- package/lib/chunk-QHE2RUWX.mjs +7 -0
- package/lib/{chunk-QKEKG2LD.mjs → chunk-RCW5BZNW.mjs} +1 -1
- package/lib/{chunk-4JE4BYXK.mjs → chunk-RJ6HHG7J.mjs} +1 -1
- package/lib/{chunk-ZQWIVYVM.mjs → chunk-RPTEEI4R.mjs} +1 -1
- package/lib/chunk-RQW5S67A.mjs +7 -0
- package/lib/chunk-RTCMYMED.mjs +7 -0
- package/lib/chunk-RWVX7XSD.mjs +7 -0
- package/lib/{chunk-WY5V5PR3.mjs → chunk-RZOINFNL.mjs} +1 -1
- package/lib/chunk-SOOTWGMQ.mjs +7 -0
- package/lib/chunk-STQ2JMIZ.mjs +7 -0
- package/lib/{chunk-6PD6K7LP.mjs → chunk-SUIPDW5O.mjs} +1 -1
- package/lib/{chunk-TNT27RBG.mjs → chunk-SZOJ7BEJ.mjs} +1 -1
- package/lib/{chunk-4EOHEDFP.mjs → chunk-T542Z54E.mjs} +1 -1
- package/lib/chunk-TAN2CIRI.mjs +21 -0
- package/lib/{chunk-A3MYSOOC.mjs → chunk-TCNBINOG.mjs} +1 -1
- package/lib/chunk-TFDF3DBN.mjs +7 -0
- package/lib/chunk-TICZXC53.mjs +9 -0
- package/lib/chunk-TLX45X5U.mjs +7 -0
- package/lib/{chunk-QTG6LUZT.mjs → chunk-TMIV3IWH.mjs} +1 -1
- package/lib/chunk-TQ6HEJ73.mjs +11 -0
- package/lib/chunk-TTU5EQZ6.mjs +7 -0
- package/lib/chunk-TYUYPFDJ.mjs +7 -0
- package/lib/chunk-TZXYVMZC.mjs +7 -0
- package/lib/chunk-UCUFLFNK.mjs +7 -0
- package/lib/chunk-UK3QLBHW.mjs +7 -0
- package/lib/{chunk-IZGCEOYO.mjs → chunk-UM2B4GR7.mjs} +1 -1
- package/lib/chunk-UZFTTNOP.mjs +7 -0
- package/lib/chunk-V3AXSKSU.mjs +7 -0
- package/lib/chunk-VA6EEI6X.mjs +21 -0
- package/lib/{chunk-OFTT7J2M.mjs → chunk-VFKG2G37.mjs} +1 -1
- package/lib/chunk-VJNEW5MQ.mjs +7 -0
- package/lib/{chunk-L53JWJ3S.mjs → chunk-VKREON6Q.mjs} +1 -1
- package/lib/{chunk-NOBQTEQD.mjs → chunk-VNNDYPBL.mjs} +1 -1
- package/lib/{chunk-ZJW6YOMV.mjs → chunk-VRBETPHY.mjs} +1 -1
- package/lib/{chunk-EPFCERGL.mjs → chunk-VT6P3X6R.mjs} +1 -1
- package/lib/{chunk-ZV7ZFQQC.mjs → chunk-VUTQY76O.mjs} +1 -1
- package/lib/chunk-WF5S4FW5.mjs +7 -0
- package/lib/{chunk-Z4LKKOFY.mjs → chunk-WJGK6VGU.mjs} +1 -1
- package/lib/{chunk-5CRLRHOJ.mjs → chunk-WJHMB3SL.mjs} +1 -1
- package/lib/{chunk-OUZQPYT3.mjs → chunk-WQCXOZEJ.mjs} +1 -1
- package/lib/{chunk-L2E5WBGD.mjs → chunk-WVVFR4E3.mjs} +1 -1
- package/lib/{chunk-PWRJRL5U.mjs → chunk-XBYXT74L.mjs} +1 -1
- package/lib/chunk-XJE3LJHP.mjs +7 -0
- package/lib/{chunk-CPQIZGG5.mjs → chunk-XV4CVZYD.mjs} +1 -1
- package/lib/chunk-Y37ED7AS.mjs +7 -0
- package/lib/{chunk-YTLUYSMF.mjs → chunk-YGBNZYT4.mjs} +1 -1
- package/lib/{chunk-4CVUUVGJ.mjs → chunk-YGTOX7IL.mjs} +1 -1
- package/lib/{chunk-OMNMLKDT.mjs → chunk-YJ27WHKR.mjs} +1 -1
- package/lib/chunk-YRULC27A.mjs +7 -0
- package/lib/{chunk-RMFU4BAL.mjs → chunk-YSVAHT4Q.mjs} +4 -4
- package/lib/chunk-YTOTMJTY.mjs +15 -0
- package/lib/{chunk-B63POIPQ.mjs → chunk-YZKZC62O.mjs} +1 -1
- package/lib/{chunk-DPMRIMUC.mjs → chunk-YZQN7BRB.mjs} +1 -1
- package/lib/{chunk-7SQSWVAU.mjs → chunk-Z5IUK2QO.mjs} +1 -1
- package/lib/{chunk-M2ABR4JM.mjs → chunk-ZEGSMW5A.mjs} +1 -1
- package/lib/{chunk-PR42EZSR.mjs → chunk-ZIKLQZBG.mjs} +1 -1
- package/lib/chunk-ZVU7MD2S.mjs +7 -0
- package/lib/sandforge-autopilot.mjs +33 -27
- package/lib/sandforge-backup.mjs +19 -19
- package/lib/sandforge-checkpoint.mjs +1 -1
- package/lib/sandforge-cleanup.mjs +1 -1
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +32 -14
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +11 -13
- package/lib/sandforge-env.mjs +105 -105
- package/lib/sandforge-frozen.mjs +1 -1
- package/lib/sandforge-mcp.mjs +2 -2
- package/lib/sandforge-monitor.mjs +1 -1
- package/lib/sandforge-pipeline.mjs +13 -13
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge-users.mjs +13 -15
- package/lib/sandforge.mjs +1 -1
- package/lib/sf/sandforge/dataops.mjs +2 -2
- package/lib/sfPlugin.mjs +1 -1
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
- package/lib/chunk-23SEDORH.mjs +0 -11
- package/lib/chunk-26POJDIT.mjs +0 -7
- package/lib/chunk-2AZQHBEF.mjs +0 -7
- package/lib/chunk-2METQHGG.mjs +0 -7
- package/lib/chunk-2WFIVO4F.mjs +0 -13
- package/lib/chunk-2YHZBUZE.mjs +0 -7
- package/lib/chunk-326AJTIU.mjs +0 -272
- package/lib/chunk-3PVRGTVK.mjs +0 -7
- package/lib/chunk-5XTUSN72.mjs +0 -8
- package/lib/chunk-6I6TWNV5.mjs +0 -7
- package/lib/chunk-6O222PW6.mjs +0 -7
- package/lib/chunk-6ZLKIT3H.mjs +0 -7
- package/lib/chunk-7QYHEHMA.mjs +0 -9
- package/lib/chunk-B3FBHVNN.mjs +0 -21
- package/lib/chunk-BEA27DLS.mjs +0 -7
- package/lib/chunk-BRY3PLIZ.mjs +0 -7
- package/lib/chunk-CBH3TOWK.mjs +0 -341
- package/lib/chunk-CVHNXJH3.mjs +0 -7
- package/lib/chunk-DGDRQRCW.mjs +0 -7
- package/lib/chunk-DUN2EPRC.mjs +0 -7
- package/lib/chunk-E3A3LOCY.mjs +0 -7
- package/lib/chunk-F2424IKX.mjs +0 -7
- package/lib/chunk-F3AQW6IU.mjs +0 -7
- package/lib/chunk-FNJ4SGWO.mjs +0 -7
- package/lib/chunk-GOOVPVWX.mjs +0 -7
- package/lib/chunk-H2BHESDA.mjs +0 -9
- package/lib/chunk-H4CGM6YO.mjs +0 -7
- package/lib/chunk-HIDW7FNV.mjs +0 -9
- package/lib/chunk-HSBXRQTI.mjs +0 -7
- package/lib/chunk-HUZPBE47.mjs +0 -7
- package/lib/chunk-I6E6T6YY.mjs +0 -7
- package/lib/chunk-IUM4NFKI.mjs +0 -10
- package/lib/chunk-IVFVNNGB.mjs +0 -37
- package/lib/chunk-JCFBFF4Y.mjs +0 -7
- package/lib/chunk-JTJK2D36.mjs +0 -7
- package/lib/chunk-KB4ZHM4Q.mjs +0 -10
- package/lib/chunk-KJWFYBMU.mjs +0 -15
- package/lib/chunk-LC3NDW4N.mjs +0 -7
- package/lib/chunk-OM5NORJG.mjs +0 -7
- package/lib/chunk-OVNMB6Q2.mjs +0 -7
- package/lib/chunk-PEDQPM2P.mjs +0 -926
- package/lib/chunk-PH7SP4YK.mjs +0 -21
- package/lib/chunk-PMN4PAC3.mjs +0 -19
- package/lib/chunk-PMWAFDUB.mjs +0 -48
- package/lib/chunk-PPLVFX6N.mjs +0 -7
- package/lib/chunk-PZBZ7MNC.mjs +0 -7
- package/lib/chunk-QROPNEGY.mjs +0 -14
- package/lib/chunk-RGBGUCJA.mjs +0 -156
- package/lib/chunk-RKTFFCNS.mjs +0 -7
- package/lib/chunk-ROV3QXEF.mjs +0 -475
- package/lib/chunk-RT47RKLY.mjs +0 -7
- package/lib/chunk-SI267LYR.mjs +0 -8
- package/lib/chunk-SRPWW4A2.mjs +0 -10
- package/lib/chunk-T3G6VZNS.mjs +0 -7
- package/lib/chunk-T63U4OZJ.mjs +0 -7
- package/lib/chunk-TEIBWMJM.mjs +0 -7
- package/lib/chunk-TW3N6W5Z.mjs +0 -7
- package/lib/chunk-UBIKR5VO.mjs +0 -7
- package/lib/chunk-UI3JQVRU.mjs +0 -8
- package/lib/chunk-UX3BVH2Y.mjs +0 -7
- package/lib/chunk-VINGECAJ.mjs +0 -10
- package/lib/chunk-VOXJHJIE.mjs +0 -7
- package/lib/chunk-WB2RIVO3.mjs +0 -7
- package/lib/chunk-WXDLQT2O.mjs +0 -10
- package/lib/chunk-XBQGZGWR.mjs +0 -7
- package/lib/chunk-XGGOUNPP.mjs +0 -7
- package/lib/chunk-XKWW3GKF.mjs +0 -7
- package/lib/chunk-YHR4WQPR.mjs +0 -7
- package/lib/chunk-ZQQXSCVI.mjs +0 -7
- package/lib/chunk-ZRUDYB7O.mjs +0 -7
package/lib/chunk-KJWFYBMU.mjs
DELETED
|
@@ -1,15 +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 wn}from"./chunk-Z4LKKOFY.mjs";import{a as Ar,b as es}from"./chunk-XCA5AONB.mjs";import{a as xt,b as bn,c as Xn}from"./chunk-66NMFCWX.mjs";import{a as Yn,e as br,i as kr}from"./chunk-WB2RIVO3.mjs";import{Aa as lr,Ac as mr,Ba as ur,Dc as Zn,Fc as Ir,Hc as is,Ic as $t,Jc as as,Kc as Bt,Lc as ds,Mc as en,Oc as Tr,Pc as jr,Qc as Cr,b as Qt,d as Kn,e as Hn,f as qn,j as ke,k as hn,l as Yt,m as Mt,n as Qe,o as q,pa as er,qa as tr,ra as nr,s as pe,sa as sr,ta as rr,ua as or,va as ir,wa as kn,wc as je,xa as ar,ya as dr,za as cr}from"./chunk-XGGOUNPP.mjs";import{d as fr}from"./chunk-L53JWJ3S.mjs";import{a as Et,b as Zs}from"./chunk-CE6ZDGBB.mjs";import{a as Rr,b as ts,c as Sr,d as ns,e as ss,f as Zt,g as Jt,h as Nr,i as rs,j as Or,k as yn,l as os}from"./chunk-OFTT7J2M.mjs";import{l as yr,s as Pr,t as Mr}from"./chunk-VINGECAJ.mjs";import{d as wr}from"./chunk-T63U4OZJ.mjs";import{a as Jn}from"./chunk-YYZL7UGV.mjs";import{a as gr,c as hr}from"./chunk-FP7CYB2F.mjs";import{b as Vn,c as zt,d as Qn,h as pr}from"./chunk-JAEDM4SI.mjs";import{a as tt}from"./chunk-5LFSFYFJ.mjs";import{r as We}from"./chunk-MSIEU5MR.mjs";import{c as Gn,s as $r}from"./chunk-KB4ZHM4Q.mjs";import{f as Vt,i as be,j as gn}from"./chunk-23SEDORH.mjs";import{b as vr}from"./chunk-VV3B6IC3.mjs";import{d as Xs,e as Vs,g as Qs,h as Ys}from"./chunk-INIT2UKJ.mjs";import{B as Js}from"./chunk-YA6ATMTB.mjs";import{q as se,r as Xt,u as mn}from"./chunk-TNT27RBG.mjs";import{a as Gs,f as Gt,h as bt}from"./chunk-TZE3Y7IQ.mjs";import{b as P}from"./chunk-CA5NAXSU.mjs";import{Ee as qs,Uc as xe,Zc as Un,a as Re,dd as Pt,fb as Ws,gb as Us,hb as Ks,hd as Hs,id as fn,vc as Wn,x as _s,y as ht}from"./chunk-PMWAFDUB.mjs";import{b as ie,e as Ls,f as Ds,k as vt,l as gt,q as Fs,v as _n}from"./chunk-WZQEK4WT.mjs";var Ro={defaultQueryLimit:500,previewQueryLimit:200,exportQueryLimit:1e3},So={defaultQueryLimit:2e3,previewQueryLimit:2e3,exportQueryLimit:5e3};function An(i){return i==="production"?{...Ro}:{...So}}function In(i){return i?"sandbox":"production"}var Lt="IsPersonAccount",vo=new Set(["FirstName","LastName","MiddleName","Suffix","Salutation","Phone","Fax"]);function $o(i){if(vo.has(i))return i;if(i.endsWith("__c"))return`${i.slice(0,-3)}__pc`;if(/^[A-Za-z][A-Za-z0-9]*$/.test(i))return`Person${i}`}function cs(i){let e=(s,r)=>s.fieldPattern.toLowerCase().startsWith(`${r.toLowerCase()}.`)?s.fieldPattern.slice(r.length+1):void 0,t=new Set(i.flatMap(s=>{let r=e(s,se);return r===void 0?[]:[r.toLowerCase()]})),n=[];for(let s of i){let r=e(s,Xt),o=r===void 0?void 0:$o(r);o===void 0||t.has(o.toLowerCase())||(t.add(o.toLowerCase()),n.push({...s,fieldPattern:`${se}.${o}`}))}return n}function Er(i){if(i.objectApiName.toLowerCase()!==se.toLowerCase()||!i.fields.some(l=>l.name===Lt))return;let e=new Map(i.fields.map(l=>[l.name.toLowerCase(),l])),t=new Set(i.kept.map(l=>l.fieldApiName.toLowerCase())),n=[],s=new Set,r=[],o=(l,p)=>{t.add(p.name.toLowerCase()),s.add(p.name),n.push({...l,objectApiName:se,fieldApiName:p.name})};for(let l of i.derived){let p=e.get(l.fieldApiName.toLowerCase());if(!p){r.push(l.fieldApiName);continue}t.has(p.name.toLowerCase())||o(l,p)}let a=i.fields.filter(l=>Hs(l.name)&&l.updateable===!0&&l.calculated!==!0&&!t.has(l.name.toLowerCase())),d=new Map,c=a.map(l=>{let p=zr(l.name);return d.set(p,l),{...l,name:p,label:l.label??l.name,type:l.type??"string"}});for(let l of br(i.detector,Xt,c)){let p=d.get(l.field.name);!p||t.has(p.name.toLowerCase())||o({objectApiName:se,fieldApiName:p.name,method:kr({...l.field,name:p.name}),config:{}},p)}return{rules:n,personOnly:s,unseen:r}}function xr(i,e){let t=new Set((e??[]).map(n=>n.name.toLowerCase()));return i.filter(n=>!t.has(zr(n).toLowerCase()))}function zr(i){return i.endsWith("__pc")?`${i.slice(0,-4)}__c`:i.startsWith("Person")&&!i.includes("__")?i.slice(6):i}function Br(i,e,t,n){if(i.toLowerCase()!==se.toLowerCase())return[...t];let s=mn(e,!1);return t.filter(r=>!fn(se,r.fieldApiName,s)&&(s==="person"||!n.has(r.fieldApiName)))}var Lr=200,No=48,Oo=64;function Rn(i,e){return Math.max(1,Math.ceil(i/e))}function Dr(i,e,t){let n=Math.max(1,Math.ceil(i/e)),s=t.masking?Math.ceil(i/Lr):0;return n+1+s+(t.duplicateRule?2:0)}function ls(i,e,t,n){let s=0,r=0,o=0,a=0,d=[],c=[];for(let l of i){let p=Rn(l.rows,e);p>ht&&c.push(l.objectApiName);let g=Math.floor(l.rows/e),u=l.rows-g*e;s+=g*Math.ceil(e/t)+Math.ceil(u/t)+1,n==="masking"&&(r+=Math.ceil(l.rows/Lr)),o+=p+(l.duplicateRule&&n==="masking"?2*p:0)+2,a+=l.rows*(No+Oo*l.fields),d.push({objectApiName:l.objectApiName,size:e,slices:p,...l.approximate?{approximate:!0}:{}})}return{objects:d,requests:s+r+o,parts:{snapshots:s,updates:r,reads:o},diskBytes:a,seconds:Math.round(s*Pr+r*Mr),tooMany:c}}function Sn(i){return Math.ceil(i*1.1)}function us(i){let e=["bytes","KB","MB","GB","TB"],t=i,n=0;for(;t>=1024&&n<e.length-1;)t/=1024,n++;return n===0?`${i} bytes`:`${t.toFixed(t<10?1:0)} ${e[n]}`}import{createHash as To}from"node:crypto";import{mkdir as jo,readFile as Co,rm as Po,writeFile as Mo}from"node:fs/promises";import*as ps from"node:path";function vn(i){if(!/^[A-Za-z0-9_-]{1,200}$/.test(i))throw new Error(`Not a set id: "${i}".`);return i}var Fr=/^[0-9a-f]{64}$/;function Pi(i){return{save:async(e,t)=>{await i.storeSecret(`dataops.runKey.${vn(e)}`,t)},load:async e=>{let t=await i.getSecret(`dataops.runKey.${vn(e)}`);return t!==void 0&&Fr.test(t)?t:void 0},delete:async e=>{await i.deleteSecret(`dataops.runKey.${vn(e)}`)}}}var Eo=384,xo=448;function Mi(i){let e=ps.join(i,"keys"),t=n=>ps.join(e,`${vn(n)}.key`);return{save:async(n,s)=>{await jo(e,{recursive:!0,mode:xo}),await Mo(t(n),s,{encoding:"utf8",mode:Eo})},load:async n=>{try{let s=(await Co(t(n),"utf8")).trim();return Fr.test(s)?s:void 0}catch{return}},delete:async n=>{await Po(t(n),{force:!0})}}}function fs(i){return To("sha256").update(`sandforge-slice-key:${i}`).digest("hex").slice(0,16)}import{randomBytes as Qo}from"node:crypto";import{statfs as Yo}from"node:fs/promises";import*as mo from"node:path";var tn=[{id:"tpl-gdpr-standard",name:"GDPR Standard",description:"Standard GDPR compliance: anonymize personal data fields across common Salesforce objects.",complianceFramework:"gdpr",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace with fake first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace with fake last name."},{fieldPattern:"Contact.Email",ruleType:"fake",description:"Replace with fake email address."},{fieldPattern:"Contact.Phone",ruleType:"mask",description:"Mask phone number (keep last 4 digits).",config:{maskKeepLast:4}},{fieldPattern:"Contact.MailingStreet",ruleType:"fake",description:"Replace with fake street address."},{fieldPattern:"Contact.MailingCity",ruleType:"fake",description:"Replace with fake city."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"mask",description:"Mask postal code."},{fieldPattern:"Lead.FirstName",ruleType:"fake",description:"Replace with fake first name."},{fieldPattern:"Lead.LastName",ruleType:"fake",description:"Replace with fake last name."},{fieldPattern:"Lead.Email",ruleType:"fake",description:"Replace with fake email address."},{fieldPattern:"Lead.Phone",ruleType:"mask",description:"Mask phone number."},{fieldPattern:"Lead.Street",ruleType:"fake",description:"Replace with fake street address."},{fieldPattern:"Account.BillingStreet",ruleType:"fake",description:"Replace with fake address."},{fieldPattern:"Account.Phone",ruleType:"mask",description:"Mask phone number."}]},{id:"tpl-ccpa-california",name:"CCPA California",description:"CCPA compliance: anonymize consumer personal information per California privacy regulations.",complianceFramework:"ccpa",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace consumer first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace consumer last name."},{fieldPattern:"Contact.Email",ruleType:"hash",description:"Hash email for pseudonymization."},{fieldPattern:"Contact.Phone",ruleType:"nullify",description:"Nullify phone number."},{fieldPattern:"Contact.MailingStreet",ruleType:"nullify",description:"Nullify street address."},{fieldPattern:"Contact.MailingCity",ruleType:"nullify",description:"Nullify city."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"nullify",description:"Nullify postal code."},{fieldPattern:"Contact.Birthdate",ruleType:"nullify",description:"Remove date of birth."},{fieldPattern:"Lead.Email",ruleType:"hash",description:"Hash email for pseudonymization."},{fieldPattern:"Lead.Phone",ruleType:"nullify",description:"Nullify phone number."}]},{id:"tpl-hipaa-health",name:"HIPAA Health Data",description:"HIPAA compliance: de-identify protected health information (PHI) in healthcare Salesforce orgs.",complianceFramework:"hipaa",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Replace patient first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Replace patient last name."},{fieldPattern:"Contact.Email",ruleType:"hash",description:"Hash email address."},{fieldPattern:"Contact.Phone",ruleType:"mask",description:"Mask phone number."},{fieldPattern:"Contact.Birthdate",ruleType:"nullify",description:"Remove date of birth (PHI)."},{fieldPattern:"Contact.MailingStreet",ruleType:"nullify",description:"Remove address (PHI)."},{fieldPattern:"Contact.MailingCity",ruleType:"nullify",description:"Remove city (PHI)."},{fieldPattern:"Contact.MailingState",ruleType:"nullify",description:"Remove state (PHI)."},{fieldPattern:"Contact.MailingPostalCode",ruleType:"truncate",description:"Truncate to first 3 digits.",config:{truncateLength:3,truncateKeep:"first"}},{fieldPattern:"Account.Name",ruleType:"fake",description:"Replace facility name."},{fieldPattern:"Account.Phone",ruleType:"mask",description:"Mask facility phone."}]},{id:"tpl-sandbox-scrub",name:"Sandbox Data Scrub",description:"General-purpose sandbox data scrubbing: mask all PII for safe development use.",complianceFramework:"custom",rules:[{fieldPattern:"Contact.FirstName",ruleType:"fake",description:"Fake first name."},{fieldPattern:"Contact.LastName",ruleType:"fake",description:"Fake last name."},{fieldPattern:"Contact.Email",ruleType:"preserve_format",description:"Replace keeping email format."},{fieldPattern:"Contact.Phone",ruleType:"preserve_format",description:"Replace keeping phone format."},{fieldPattern:"Lead.FirstName",ruleType:"fake",description:"Fake first name."},{fieldPattern:"Lead.LastName",ruleType:"fake",description:"Fake last name."},{fieldPattern:"Lead.Email",ruleType:"preserve_format",description:"Replace keeping email format."},{fieldPattern:"Lead.Company",ruleType:"fake",description:"Fake company name."},{fieldPattern:"Account.Name",ruleType:"fake",description:"Fake account name."},{fieldPattern:"Account.Website",ruleType:"constant",description:"Replace with placeholder URL.",config:{constantValue:"https://example.com"}},{fieldPattern:"Opportunity.Name",ruleType:"fake",description:"Fake opportunity name."}]}];var $n=class{operations=new Map;ttlMs;nowFn;constructor(e=36e5,t=Date.now){this.ttlMs=e,this.nowFn=t}isDuplicate(e){return this.pruneExpired(),this.operations.has(e)}register(e,t,n,s){if(this.pruneExpired(),this.operations.has(e))throw new Error(`Duplicate DML operation detected: ${e}`);let r={operationId:e,objectApiName:t,dmlType:n,recordCount:s,registeredAt:new Date(this.nowFn()).toISOString(),status:"pending"};return this.operations.set(e,r),r}markCompleted(e){let t=this.operations.get(e);t&&(t.status="completed")}markFailed(e){let t=this.operations.get(e);t&&(t.status="failed")}get(e){return this.operations.get(e)}get size(){return this.operations.size}clear(){this.operations.clear()}pruneExpired(){let e=this.nowFn()-this.ttlMs;for(let[t,n]of this.operations)new Date(n.registeredAt).getTime()<e&&this.operations.delete(t);if(this.operations.size>1e4){let t=Array.from(this.operations.entries()),n=t.length-1e4;for(let s=0;s<n;s++)this.operations.delete(t[s][0])}}};var zo=3e3;function Ye(i){return i.slice(0,15)}function Bo(i,e){let t=i??null,n=e??null;return t===n?!0:t===null||n===null?!1:typeof t=="object"||typeof n=="object"?JSON.stringify(t)===JSON.stringify(n):String(t)===String(n)}function Lo(i){let e=[],t=[],n=0;for(let s of i)t.length>0&&n+s.length+2>zo&&(e.push(t),t=[],n=0),t.push(s),n+=s.length+2;return t.length>0&&e.push(t),e}async function _r(i,e,t){let n=t.map(a=>a.Id).filter(zt),s=[...new Set(t.flatMap(a=>Object.keys(a)))].filter(a=>a.toLowerCase()!=="id");if(n.length===0||s.length===0)return{write:[...t],unchanged:0};let r=new Map;try{for(let a of Lo(s))for(let d of await pr(i,e,a,n))typeof d.Id=="string"&&r.set(Ye(d.Id),{...r.get(Ye(d.Id)),...d})}catch(a){return{write:[...t],unchanged:0,unread:P(a)}}let o=t.filter(a=>{let d=zt(a.Id)?r.get(Ye(a.Id)):void 0;return d?Object.keys(a).some(c=>c.toLowerCase()!=="id"&&!Bo(a[c],d[c])):!0});return{write:o,unchanged:t.length-o.length}}async function Wr(i,e,t,n){let s=bt(e),r=new Set,o=t.filter(zt);for(let a=0;a<o.length;a+=Vn){let d=o.slice(a,a+Vn),[c]=Qn(d,d.length),l=new Set,p=await i.query(`SELECT Id, LastModifiedDate FROM ${s} WHERE Id IN (${c})`);for(let S of p.records){if(typeof S.Id!="string")continue;l.add(Ye(S.Id)),Date.parse(String(S.LastModifiedDate??""))<=n||r.add(Ye(S.Id))}let g=d.filter(S=>!l.has(Ye(S)));if(g.length===0)continue;let[u]=Qn(g,g.length),f=await i.query(`SELECT Id FROM ${s} WHERE Id IN (${u}) AND IsDeleted = true`,{scanAll:!0});for(let S of f.records)typeof S.Id=="string"&&r.add(Ye(S.Id))}return r}function Ur(i,e){return{async*[Symbol.asyncIterator](){for await(let t of i){let n=t.filter(s=>!(zt(s.Id)&&e.has(Ye(s.Id))));n.length>0&&(yield n)}}}}function ms(i,e){let t=0;return{batches:{async*[Symbol.asyncIterator](){let n=new Map,s=[],r=0;for await(let a of i)for(let d of a){if(r++,!zt(d.Id)){s.push({...d});continue}let c=n.get(Ye(d.Id));if(!c){n.set(Ye(d.Id),{...d});continue}for(let[l,p]of Object.entries(d))l in c||(c[l]=p)}t=r;let o=[...n.values(),...s];for(let a=0;a<o.length;a+=e)yield o.slice(a,a+e)}},lines:()=>t}}var gs="anonymization:template:",Kr="anonymizationTemplates",Hr=gt({id:ie().min(1).max(100),name:ie().trim().min(1).max(Ws),description:ie().max(500),complianceFramework:_n("custom"),rules:vt(Fs(Ks,gt({description:ie().max(500)}))).min(1).max(Us),saved:_n(!0),createdAt:ie()}),Nn=class{constructor(e){this.configStore=e}configStore;save(e){this.configStore.set(`${gs}${e.id}`,e,Kr)}load(e){let t=Hr.safeParse(this.configStore.get(`${gs}${e}`));return t.success?t.data:void 0}list(){let e=[];for(let t of Object.values(this.configStore.getByCategory(Kr))){let n=Hr.safeParse(t);n.success&&e.push(n.data)}return e.sort((t,n)=>t.createdAt.localeCompare(n.createdAt))}delete(e){return this.configStore.delete(`${gs}${e}`)}};import{createHash as qr}from"node:crypto";var Fo="anonymization:checkpoint:",_o="anonymizationCheckpoints",Nt=2e3,hs=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,Wo=ie().min(1).max(255),Uo=gt({id:ie().regex(hs),fields:vt(Wo).min(1).max(800),digest:ie().regex(/^[0-9a-f]{64}$/)}),Ko=gt({objectApiName:ie().min(1).max(255),done:Ds(),afterId:ie().regex(hs).optional(),refused:vt(ie().regex(hs)).max(Nt),unconfirmed:vt(Uo).max(Nt).optional(),slice:gt({setId:ie().min(1).max(200),index:Ls().int().positive()}).optional()}),Ho=gt({id:ie().min(1).max(200),orgId:ie().min(1).max(200),templateId:ie().min(1).max(200),fingerprint:ie().regex(/^[0-9a-f]{64}$/),savedAt:ie(),objects:vt(Ko),namesGiven:ie().max(6e4).regex(/^[A-Za-z0-9+/]*={0,2}$/).optional(),setId:ie().min(1).max(200).optional()});function sn(i,e,t,n){let s=i.map(o=>[o.fieldPattern,o.ruleType,o.config??null]),r=t?.trim();return qr("sha256").update(JSON.stringify({rules:s,objects:e,...r?{where:r}:{},...n!==void 0?{slices:n}:{}})).digest("hex")}function qo(i){return i==null||i===""?null:typeof i=="string"?i.trim():typeof i=="number"||typeof i=="boolean"?String(i):JSON.stringify(i)}function bs(i,e){let t=[...e].sort().map(n=>[n,qo(i[n])]);return qr("sha256").update(JSON.stringify(t)).digest("hex")}function nn(i){return i.reduce((e,t)=>e+t.refused.length,0)}var nt=class{constructor(e){this.configStore=e}configStore;load(e,t,n){let s=Ho.safeParse(this.configStore.get(this.key(e,t)));if(!s.success)return;let r=s.data;if(!(r.orgId!==e||r.templateId!==t||r.fingerprint!==n))return r}save(e){if(nn(e.objects)>Nt)throw new Error(`A checkpoint keeps at most ${Nt} refused records; this run left ${nn(e.objects)}.`);this.configStore.set(this.key(e.orgId,e.templateId),e,_o)}clear(e,t){this.configStore.delete(this.key(e,t))}key(e,t){return`${Fo}${e}:${t}`}};async function Go(i){let{open:e,rename:t,rm:n}=await import("node:fs/promises"),{randomBytes:s}=await import("node:crypto"),r=`${i}.${s(4).toString("hex")}.partial`,o=await e(r,"w"),a=!1;return{write:async d=>{let c=Buffer.from(d,"utf8");for(let l=0;l<c.length;){let{bytesWritten:p}=await o.write(c,l,c.length-l,null);l+=p}},close:async()=>{a=!0,await o.close(),await t(r,i)},abort:async()=>{a||await o.close().catch(()=>{}),a=!0,await n(r,{force:!0})}}}function Xo(i){let e=[];return{write:async t=>{e.push(t)},close:async()=>{await i(new TextEncoder().encode(e.join("")))},abort:async()=>{e.length=0}}}var On=class i{host;constructor(e){this.host=e??null}async defaultHost(){let e=await import("vscode");return{showSaveDialog:t=>e.window.showSaveDialog(t),writeFile:(t,n)=>e.workspace.fs.writeFile(t,n),fileUri:t=>e.Uri.file(t),openFile:async t=>t.scheme==="file"?Go(t.fsPath):Xo(n=>e.workspace.fs.writeFile(t,n))}}static filtersOf(e,t){let n=e.includes(".")?e.split(".").pop():void 0;return t?.length?{[t.join("/").toUpperCase()]:t}:n?{[n.toUpperCase()]:[n]}:void 0}static ask(e,t,n){let s=i.filtersOf(t,n);return e.showSaveDialog({saveLabel:"Save",defaultUri:e.fileUri(t),...s?{filters:s}:{}})}async save(e,t,n){let s=this.host??await this.defaultHost();try{let r=await i.ask(s,e,n);return r?(await s.writeFile(r,new TextEncoder().encode(t)),{status:"saved",path:r.fsPath}):{status:"cancelled"}}catch(r){return{status:"error",message:r instanceof Error?r.message:String(r)}}}async saveStream(e,t,n){let s=this.host??await this.defaultHost(),r;try{let o=await i.ask(s,e,n);if(!o)return{status:"cancelled"};let a=await s.openFile(o);r=a;let d=await t(c=>a.write(c));return await a.close(),r=void 0,{status:"saved",path:o.fsPath,result:d}}catch(o){return await r?.abort().catch(()=>{}),{status:"error",message:o instanceof Error?o.message:String(o)}}}};function rn(i,e,t,n,s=0){i?.register(e,t,n,s);let r=!1,o=a=>{r||(r=!0,a())};return{progress:(a,d,c,l)=>{r||i?.updateProgress(e,a,d,c,l)},complete:()=>o(()=>i?.complete(e)),partial:()=>o(()=>i?.partial(e)),fail:a=>o(()=>i?.fail(e,a)),cancel:()=>o(()=>i?.cancel(e))}}var Ue={orgUnknown:"ORG_NOT_FOUND",production:"PIPELINE_WRITE_REFUSED",needsApproval:"PIPELINE_WRITE_NEEDS_APPROVAL",retries:"PIPELINE_WRITE_NO_RETRIES",filterNeedsObject:"MASKING_FILTER_NEEDS_OBJECT",invalid:"INVALID_PAYLOAD",templateMissing:"TEMPLATE_NOT_FOUND",fieldsUnseen:"MASKING_FIELDS_UNSEEN",masksNothing:"MASKING_MASKS_NOTHING"};function st(i,e){return Object.assign(new Error(e),{code:i})}function Gr(i,e,t){let n=qs(i);if(n==="refused")return st(Ue.production,`${t} is a production org, or one SandForge cannot tell is not: a pipeline never masks one, whatever an Approval step answers. Mask a sandbox, a scratch org or a Developer Edition org. Nothing was masked.`);if(n==="needsApproval"&&!e.approved)return st(Ue.needsApproval,`${t} is a sandbox marked Staging, which a pipeline masks only once an Approval step before the masking has approved the run, and none did: put an Approval step before it. Nothing was masked.`)}function ks(i,e){if(i.retries!==void 0&&i.retries>0)return{refusal:st(Ue.retries,"A masking step is never tried again: a second try masks again what the first one masked \u2014 an address it hashed is hashed once more, and no longer gives the same pseudonym on Contact and on Lead. Set its retries to 0. Nothing was masked.")};let t=i.where?.trim();if(t&&i.object===void 0)return{refusal:st(Ue.filterNeedsObject,"A masking condition filters the rows of one object: name the object it holds, or remove the condition. Nothing was masked.")};let n=kn.safeParse({orgId:i.orgId,templateId:i.templateId,...i.object!==void 0?{objects:[i.object]}:{},...t?{where:t}:{},snapshot:!0});if(!n.success){let s=n.error.issues[0];return{refusal:st(Ue.invalid,`The masking step is not one the DataOps page would run (${s.path.join(".")}: ${s.message}). Nothing was masked.`)}}return e(n.data.templateId)?{asked:n.data}:{refusal:st(Ue.templateMissing,`No masking template is shipped or saved under ${n.data.templateId}: it was deleted on the DataOps page. Choose another. Nothing was masked.`)}}var Vo=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function Xr(i){if(!Vo.test(i))throw new Error(`Not a record id: "${i}".`);return i}function ws(i,e){let t=i?.trim();return[...t?[`(${Gt(t)})`]:[],...e.createdSince!==void 0?[`CreatedDate >= ${Js(e.createdSince)}`]:[],...e.afterId!==void 0?[`Id > '${Xr(e.afterId)}'`]:[],...e.untilId!==void 0?[`Id <= '${Xr(e.untilId)}'`]:[]]}function ys(i){return i.length===0?"":` WHERE ${i.join(" AND ")}`}function Vr(i,e,t,n,s){if(!Number.isInteger(s)||s<=0)throw new Error(`Not a slice size: ${s}.`);return`SELECT ${e} FROM ${bt(i)}${ys(ws(t,n))} ORDER BY Id LIMIT ${s}`}function As(i,e,t,n){return`SELECT COUNT() FROM ${bt(i)}`+ys(ws(e,{...n,createdSince:t}))}function Qr(i,e,t){return`SELECT COUNT() FROM ${bt(i)}`+ys(ws(e,{afterId:t}))}function go(i){let e=i.fields;return{name:i.name,label:i.label,labelPlural:i.labelPlural??"",keyPrefix:i.keyPrefix??null,custom:i.custom??!1,createable:i.createable,updateable:i.updateable,deletable:i.deletable,queryable:i.queryable,fields:e.map(t=>({name:t.name,label:t.label,type:t.type,length:t.length??0,nillable:t.nillable??!1,createable:t.createable,updateable:t.updateable,externalId:t.externalId??!1,referenceTo:t.referenceTo??[],relationshipName:t.relationshipName??null,picklistValues:t.picklistValues??[],defaultValue:t.defaultValue??null,calculated:t.calculated??!1,autoNumber:t.autoNumber??!1,unique:t.unique??!1,permissionable:t.permissionable??!0})),recordTypeInfos:i.recordTypeInfos??[],childRelationships:i.childRelationships??[]}}var Zo=new Set(["backup:execute","backup:list","backup:objects","backup:export","backup:delete","dataops:rollback","dataops:anonymize","dataops:anonymization-templates","dataops:anonymization-template:save","dataops:anonymization-template:delete","dataops:anonymize:coverage","dataops:anonymize:preview","dataops:automation","precheck:pii-scan"]),Jo=6e4,ei=10,ti=/^00D[0-9A-Za-z]{12}(?:[0-9A-Za-z]{3})?$/;function ni(i,e){return i.slice(0,15)===e.slice(0,15)}var Yr="ORG_REPLACED_SINCE_BACKUP",si="Backup was cancelled before it finished. Nothing was saved \u2014 run it again to take a complete snapshot.",Ot=class extends Error{constructor(){super(si),this.name="BackupCancelledError"}},cn=class extends Error{constructor(e){super(`The backup could not be written to disk: ${P(e)}`),this.name="BackupWriteError"}},Wt=class extends Error{constructor(t,n){super(t);this.retryable=n;this.name="BackupNotWholeError"}retryable},Cs="IsDeleted = false",ri="SystemModstamp",ho=5e4,oi=100,an=_s;function ii(i){return typeof i!="number"||!Number.isFinite(i)?ho:Math.min(an,Math.max(oi,Math.floor(i)))}var Dt=200,ai=1440*6e4,di=1440*6e4,Zr="backupRetention:since",Is="BACKUP_BUSY";function ci(i,e){return e===0?"success":i===0?"failure":"partial"}function Rs(i){return Un(i)}function Jr(i,e,t){i.length>=ei||i.push({objectApiName:e,message:t?.[0]?.message??"Unknown DML error"})}function Tn(i,e,t=!1){let n=(e?.rules??[]).map(r=>r.fieldPattern.split(".")[0]).filter((r,o,a)=>a.findIndex(d=>En(d,r))===o);if(i.objects)return i.objects.map(r=>n.find(o=>En(o,r))??(En(r,se)?se:r));if(!e)return[];let s=[...n];return t&&ln(i,e,se)&&s.push(se),s}function En(i,e){return i.toLowerCase()===e.toLowerCase()}var li=`${Lt} = true`;function ln(i,e,t){return i.objects===void 0&&t.toLowerCase()===se.toLowerCase()&&Ft(e,se).length===0&&cs(e.rules).length>0}function jn(i,e,t){return ln(i,e,t)?li:zn(i)}async function Ss(i,e){try{return(await i.describe(se)).fields.some(t=>t.name===Lt)}catch(t){return e(`[WARN] dataops: whether the org has person accounts was not read: ${P(t)}`),!1}}function Ft(i,e){let t=`${e.toLowerCase()}.`;return i.rules.filter(n=>n.fieldPattern.toLowerCase().startsWith(t)||n.fieldPattern==="*")}function dn(i,e){return e.toLowerCase()===se.toLowerCase()?cs(i.rules):[]}function Cn(i){let e=new Map;return{describe:t=>{let n=e.get(t)??i.describe(t);return e.set(t,n),n}}}async function vs(i,e){return new Xn(async n=>go(await i.describe(n))).deniedOf(e.map(({objectApiName:n,rules:s})=>({objectApiName:n,operation:"update",fieldNames:s.map(r=>r.fieldPattern.includes(".")?r.fieldPattern.split(".")[1]:r.fieldPattern).filter(r=>r!=="*")})))}function eo(i,e){return Ft(i,e).length>0||dn(i,e).length>0}function $s(i){return{objectApiName:i.objectApiName,recordCount:i.recordCount,truncated:i.truncated===!0,...i.orgCount!==void 0?{orgCount:i.orgCount}:{},...i.stoppedAt?{stoppedAt:i.stoppedAt}:{},...i.notKept&&i.notKept.length>0?{notKept:[...i.notKept]}:{},...i.where?{where:i.where}:{}}}function Ns(i,e){return i.flatMap(t=>{let n=e?.get(t.objectApiName);if(n!==void 0&&n<t.recordCount)return[`${t.objectApiName} ${n} of the ${t.recordCount} it listed (not found on disk)`];if(!t.truncated)return[];if(t.stoppedAt==="not_reached")return[`${t.objectApiName} none (the backup stopped before it)`];let s=t.orgCount!==void 0?` of ${t.orgCount}`:"",r=t.stoppedAt==="cap"?" (stopped at the cap)":t.stoppedAt==="failure"?" (the read failed)":"";return[`${t.objectApiName} ${t.recordCount}${s}${r}`]}).join(", ")}var rt=200,Os=95,un=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/,ui="NOTHING_TO_RESUME",to="TEMPLATE_NOT_FOUND";function Ts(i){return new Error(`Template "${i}" not found.`)}function pi(i){let e=i.Id;if(typeof e!="string"||!un.test(e))return[];let t=Object.keys(i).filter(n=>n!=="Id");return t.length>0?[{id:e,fields:t,digest:bs(i,t)}]:[]}var fi="COUNT_FAILED",on="SNAPSHOT_NOT_TAKEN",js=new Set(["QUERY_TIMEOUT","OPERATION_TOO_LARGE"]),mi=/^([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+):/;function Pn(i){if(typeof i=="object"&&i!==null){let{errorCode:e,code:t}=i;if(typeof e=="string"&&e!=="")return e;if(typeof t=="string"&&t!=="")return t}return mi.exec(P(i))?.[1]??"UNKNOWN"}var no=5;function so(i){return i==null?null:typeof i=="string"||typeof i=="number"||typeof i=="boolean"?i:JSON.stringify(i)}function bo(i){return i.done?0:Math.max(0,i.total-i.masked-i.nothingToMask-i.refused-i.unanswered-(i.deletedSince??0))}function Bn(i){return i.refused+i.unanswered+bo(i)+(i.late??0)}function _t(i){return i.reduce((e,t)=>({recordsProcessed:e.recordsProcessed+t.masked+t.nothingToMask,recordsFailed:e.recordsFailed+t.refused,recordsNotMasked:e.recordsNotMasked+Bn(t)}),{recordsProcessed:0,recordsFailed:0,recordsNotMasked:0})}function gi(i,e){let{recordsProcessed:t,recordsFailed:n,recordsNotMasked:s}=_t(i);return s===0?"success":t>0||e&&n===0?"partial":"failure"}function hi(i,e,t){if(!t||e==="success")return{outcome:e};let{recordsProcessed:n,recordsFailed:s}=_t(i);return n+s>0?{outcome:"cancelled"}:{outcome:"stopped",code:Gn}}function ro(i){return i.filter(e=>Bn(e)>0).map(e=>`${e.objectApiName} ${Bn(e)}`).join(", ")}function oo(i){return i.map(e=>({objectApiName:e.objectApiName,total:e.total,processed:e.masked+e.nothingToMask,failed:e.refused,notMasked:Bn(e)}))}function io(i){return i.filter(e=>e.total>0||e.masked+e.refused>0).map(e=>{let t=bo(e);return{...gn(e.objectApiName),updated:e.masked,failed:e.refused+e.unanswered,...e.unanswered>0?{mayHaveBeenWritten:e.unanswered}:{},...t>0?{notSent:t}:{}}})}async function ao(i,e,t,n,s,r){return Zs(i,`SELECT ${t} FROM ${e}${xn(r,s)} ORDER BY Id LIMIT ${n}`,n)}function xn(i,e){let t=i?.trim(),n=[...t?[`(${Gt(t)})`]:[],...e===void 0?[]:[`Id > '${e}'`]];return n.length===0?"":` WHERE ${n.join(" AND ")}`}function zn(i){let e=i.where?.trim();return e||void 0}function bi(i){let e=i?.trim();return e?`(${Gt(e)}) AND ${Cs}`:Cs}function ki(i){let e=new Map;for(let[t,n]of i){if(n.length===0)throw new Error(`No field of ${t} was named for the snapshot to read.`);e.set(t,n.map(s=>bt(s)).join(", "))}return e}function co(i,e,t){let n=e===void 0?"more records":`${e} records`;return new Wt(`${i} holds ${n}, past the ${t} a snapshot reads of one object: no snapshot was kept, as one holding part of the object would be taken for all of it.`,!1)}function ko(i,e){return`The org stopped answering the read of ${i} after ${e} record(s), before it said the read was done: no snapshot was kept.`}async function wi(i,e,t,n){let s={headers:{},maxFetch:1e4,autoFetch:!1,scanAll:t,responseTarget:"QueryResult"},r=await i.query(e,s),o=[...r.records];for(;!r.done;){if(!r.nextRecordsUrl)throw new Wt(ko(n,o.length),!0);r=await i.queryMore(r.nextRecordsUrl,s),o.push(...r.records)}return o}function yi(i,e,t){let n=i[i.length-1]?.Id;if(typeof n!="string"||!un.test(n)||n===e)throw new Error(`The org answered a page of ${t} that does not end past the page before it: masking stopped there rather than write the same rows again.`);return n}function Ai(i){let e=i?.[0];return e?.statusCode==="ENTITY_IS_DELETED"||e?.errorCode==="ENTITY_IS_DELETED"}function Mn(i){return i.slices.filter(e=>!e.late&&e.state!=="pending"&&e.lastId!==void 0).at(-1)?.lastId}function Ii(i){return i.slices.reduce((e,t)=>{let n=t.state==="masking"?Math.max(0,t.rows-t.masked-t.nothingToMask-t.refused-t.deletedSince-(t.unanswered??0)):0;return e+n+t.refused+(t.lateLeft??0)},0)}var lo=100,uo=3;function po(i){return`_refused_${i}`}var fo=class{constructor(e,t){this.deps=e;this.saveDialog=t??new On}deps;activeOrgOperations=new Set;writing=new Ar;dmlTracker=new $n;backupRecords;syncRuns;expiryListener;sweeping;liveTracker;backupsWriting=new Set;maskingKey=Qo(32).toString("hex");runKeys;freeBytes=async()=>{let e=this.backupRecords?.directory;if(e!==void 0)for(let t of[e,mo.dirname(e)])try{let n=await Yo(t);return Number(n.bavail)*Number(n.bsize)}catch{}};sliceRunsOn=new Map;saveDialog;get savedTemplates(){return new Nn(this.deps.configStore)}findTemplate(e){return tn.find(t=>t.id===e)??this.savedTemplates.load(e)}ruleConfig(e,t=this.maskingKey){let n={...e.config};return e.ruleType==="hash"&&(n.hashSalt=t),n}maskingRules(e,t,n=this.maskingKey){return t.map(s=>({objectApiName:e,fieldApiName:s.fieldPattern.includes(".")?s.fieldPattern.split(".")[1]:s.fieldPattern,method:s.ruleType,config:this.ruleConfig(s,n)}))}refuseUnknownTemplate(e,t,n){q(this.deps,e,"dataops:error",t,Ts(n),{code:to})}setLiveOperationTracker(e){this.liveTracker=e}setSyncRuns(e){this.syncRuns=e}setRunKeyStore(e){this.runKeys=e}setFreeBytes(e){this.freeBytes=e}get sliceSets(){return new Cr(this.deps.configStore)}busyMessage(e,t){let n=this.sliceRunsOn.get(e);if(n===void 0)return t;let s=this.onCommandLine?"the same line with --resume masks the rest, and --abandon gives the set up":"Resume masks the rest, and Abandon gives the set up";return`A masking run in slices (set ${n}) writes to org ${e} now, and holds its backups and restores until it ends: wait for it, or stop it; once stopped, ${s}.`}targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;muteLeases={};setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}setMuteOffered(e){this.muteOffered=e}muteOffered=!0;setOnCommandLine(e){this.onCommandLine=e}onCommandLine=!1;countGaveUp(e,t){if(!js.has(Pn(e)))return e;let n=this.onCommandLine?"give --slices, which reads the object a slice at a time by Id and plans on the org's own figure when no count comes, or narrow --where to an indexed field, such as a range of CreatedDate":`mask in slices, which reads the object a slice at a time by Id and plans on the org's own figure when no count comes, or narrow the run from the command line with sandforge dataops anonymize --object ${t} --where on an indexed field, such as a range of CreatedDate`;return new Error(`${P(e)} The org gave up counting the ${t} records the run would mask: ${n}. Nothing was masked.`)}duplicatesSettleMs=Rr;setDuplicatesSettle(e){this.duplicatesSettleMs=e}duplicatesWatchOf(e,t){return Sr({query:async n=>e.query(n),serverTime:async()=>(await e.soap.getServerTimestamp()).timestamp},t,{settleMs:this.duplicatesSettleMs})}ownReader(){return this.reader??=import("./chunk-GOOVPVWX.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(n=>We(n,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}orgNameOf(e){return Pt(this.deps.orgManager.getOrg(e),e)}readAct(e,t,n,s,r,o){let a=this.targetAutomation;return Or({act:n,target:this.orgNameOf(t),objects:s,org:Nr(e,d=>new vr(Jo).withTimeout("dataops automation",()=>a.read(t,d)),Un(this.deps.orgManager.getOrg(t))==="production"),accord:r,mayMute:this.muteOffered,muteLeases:this.muteLeases,...o?{voice:o}:{}})}async releaseMute(e,t){if(!e)return;let n=await e.release();for(let s of $r(n,this.orgNameOf(t)))this.deps.log(`[INFO] ${s}`);return n}async handleAutomation(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=je(ir,e,"dataops:error",this.deps);if(t)try{let n=await We(t.orgId,this.deps.orgRegistry,this.deps.orgManager),s=await this.readAct(n,t.orgId,t.act,t.objects,t,Jt(t)),r=ke(this.deps,e,"dataops:automation:response",{...s.answer});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} refusals=${s.answer.refusals.length}`)}catch(n){q(this.deps,"dataops:automation","dataops:error",e,n)}}setExpiryListener(e){this.expiryListener=e}setBackupRecordStore(e){this.backupRecords=e,this.sweeping=this.sweepBackupFiles()}swept(){return this.sweeping??Promise.resolve()}async sweepBackupFiles(e=Date.now()){await this.expireBackups(e);let t=this.backupRecords;if(t)try{let n=new Set(this.backupsWriting);for(let r of this.deps.configStore.getKeysByPrefix("backup:"))n.add(r.slice(7).split(":")[0]);let s=await t.sweep(n,ai,e);s.length>0&&this.deps.log(`[INFO] Removed ${s.length} backup file(s) whose backup never saved its metadata: `+s.join(", "))}catch(n){this.deps.log("[WARN] the files of backups that never saved their metadata were not removed: "+P(n))}}isWritingTo(e){return this.writing.has(e)}async handle(e){if(!Zo.has(e.type))return!1;switch(e.type){case"backup:execute":return await this.handleBackup(e),!0;case"backup:list":return this.handleBackupList(e),!0;case"backup:objects":return await this.handleBackupObjects(e),!0;case"backup:export":return await this.handleBackupExport(e),!0;case"backup:delete":return await this.handleBackupDelete(e),!0;case"dataops:rollback":return await this.writing.during(es(e,"orgId"),()=>this.handleRollback(e)),!0;case"dataops:anonymize":return await this.writing.during(es(e,"orgId"),()=>this.handleAnonymize(e)),!0;case"dataops:anonymization-templates":return this.handleAnonymizationTemplates(e),!0;case"dataops:anonymization-template:save":return this.handleTemplateSave(e),!0;case"dataops:anonymization-template:delete":return this.handleTemplateDelete(e),!0;case"dataops:anonymize:coverage":return await this.handleAnonymizeCoverage(e),!0;case"dataops:anonymize:preview":return await this.handleAnonymizePreview(e),!0;case"dataops:automation":return await this.handleAutomation(e),!0;case"precheck:pii-scan":return await this.handlePIIScan(e),!0;default:return!1}}async selectAllFields(e,t,n){let s=await e.describe(t),r=s.fields.filter(d=>d.type===gr).map(d=>d.name),o=r.length>0&&n&&!await n()?r:[];return{select:s.fields.filter(d=>!o.includes(d.name)).map(d=>d.name).join(", "),notKept:o}}async maskedFields(e,t,n,s=[]){let r=(await e.describe(t)).fields,o=new Map(r.map(u=>[u.name.toLowerCase(),u.name])),a=[],d=[];for(let u of n){let f=o.get(u.fieldApiName.toLowerCase());f!==void 0?a.push({...u,fieldApiName:f}):u.fieldApiName!=="*"&&!d.includes(u.fieldApiName)&&d.push(u.fieldApiName)}let c=Er({objectApiName:t,fields:r,kept:a,derived:s,detector:this.deps.infraServices?.piiDetector??new wr});if(c&&c.unseen.length>0){let u=await e.describe(Xt).then(f=>f.fields,()=>{});for(let f of xr(c.unseen,u))d.includes(f)||d.push(f)}let l=c?[...a,...c.rules]:a,p=l.map(u=>u.fieldApiName).filter((u,f,S)=>u!=="Id"&&S.indexOf(u)===f),g=c&&p.length>0&&!p.includes(Lt);return{rules:l,select:["Id",...p,...g?[Lt]:[]].join(", "),missing:d,rulesOf:c?u=>Br(t,u,l,c.personOnly):()=>l}}async countRows(e,t,n,s){let o=(await e.query(`SELECT COUNT() FROM ${t}${xn(s,n)}`)).totalSize;if(typeof o!="number"||!Number.isInteger(o)||o<0)throw new Error(`The org did not say how many records ${t} holds.`);return o}async organizationIdOf(e){try{let n=(await Et(e,"SELECT Id FROM Organization"))[0]?.Id;return typeof n=="string"&&ti.test(n)?n:void 0}catch(t){this.deps.log(`[WARN] dataops: the org did not say which org it is: ${P(t)}`);return}}async handleBackup(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=je(er,e,"dataops:error",this.deps);if(!t)return;let n=e.id,s=new Map;for(let[a,d]of Object.entries(t.wheres??{})){let c=t.objects.find(l=>En(l,a));c!==void 0&&d.trim()!==""&&s.set(xe(c),d.trim())}if(t.slices===!0){await this.backupInSlices(e,{orgId:t.orgId,objects:t.objects,wheres:s});return}let r=await this.takeBackup(n,{orgId:t.orgId,objects:t.objects,...s.size>0?{wheres:s}:{}},e.type);if("error"in r){q(this.deps,"backup:execute","dataops:error",e,r.error),this.endBackupNotTaken(n,r);return}let o=ke(this.deps,e,"dataops:backup:response",{operationId:n,status:"completed",objects:r.objects.map($s),totalRecords:r.totalRecords,...r.partial?{partial:!0}:{},timestamp:r.timestamp});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}async backupInSlices(e,t){let n=e.id,s={module:"dataops",operation:e.type},r=(g,u)=>{q(this.deps,"backup:execute","dataops:error",e,new Error(u),{...g?{code:g}:{}}),pe(this.deps,n,u,!1,{context:s,authored:!0})};if(!this.backupRecords){r(Re.needsStore,"A backup in slices writes each slice to the backup files, and this host keeps none.");return}let o=`backup:${t.orgId}`;if(this.activeOrgOperations.has(o)){r(void 0,this.busyMessage(t.orgId,`A backup or rollback operation is already running for org ${t.orgId}. Please wait for it to complete.`));return}this.activeOrgOperations.add(o);let a=new AbortController,d=()=>{},c,l,p=`Backup ${t.objects.length} object(s) in slices`;try{let g=await We(t.orgId,this.deps.orgRegistry,this.deps.orgManager);Yt(this.deps,n,"dataops",p),this.deps.infraServices?.backgroundRegistry?.register(n,"dataops",p,new Promise((A,B)=>{d=C=>{C===void 0?A():B(C instanceof Error?C:new Error(String(C)))}}),a),c=rn(this.liveTracker,n,"dataops",p,t.objects.length);let u=0,f=new Date().toISOString(),S=await this.organizationIdOf(g),k={setId:n,kind:"backup",orgId:t.orgId,...S!==void 0?{organizationId:S}:{},size:this.backupCap(),state:"open",startedAt:f,lastActivityAt:f,requestsSpent:0,objects:t.objects.map(A=>{let B=xe(A),C=t.wheres.get(B);return{objectApiName:B,...C?{where:C}:{},done:!1,slices:[]}})},E=this.sliceSets,j=()=>{k.lastActivityAt=new Date().toISOString(),k.requestsSpent=u,E.save(k)};j();let y,b=!1;e:for(let A of k.objects)for(s.objectName=A.objectApiName;;){if(a.signal.aborted){b=!0;break e}let B=A.slices.filter(Se=>!Se.late);if(B.length>=ht){y=`${A.objectApiName} holds more rows than ${ht} slices of ${k.size} do: the backup stopped there.`;break e}let C=as(k),ee=Mn(A),G={index:C,...ee!==void 0?{afterId:ee}:{},rows:0,snapshotId:is(k.setId,C),state:"pending",masked:0,refused:0,deletedSince:0,nothingToMask:0,sizeUsed:B.at(-1)?.sizeUsed??k.size};A.slices.push(G),j();let W=await this.snapshotSlice(g,t.orgId,k,A,G,{bounds:ee!==void 0?{afterId:ee}:{},stop:a.signal,onRequest:()=>{u++},origin:e.type,clock:!1});if("failed"in W){A.slices=A.slices.filter(Se=>Se!==G),j(),W.cancelled?b=!0:y=this.sliceNotTakenMessage(A.objectApiName,W);break e}if(W.lastId===void 0){await this.removeBackup(`backup:${G.snapshotId}`),A.slices=A.slices.filter(Se=>Se!==G),A.done=!0,j();break}G.rows=W.rows,G.lastId=W.lastId,G.sizeUsed=W.sizeUsed,G.takenAt=new Date().toISOString(),G.state="snapshotted",j();let X=`Backed up ${A.objectApiName} slice ${C} (${W.rows} records)`;Mt(this.deps,n,0,C,C,X),c.progress(0,C,C,X)}k.objects.every(A=>A.done)&&(k.state="done"),j();let I=k.objects.map(A=>({objectApiName:A.objectApiName,recordCount:A.slices.reduce((B,C)=>B+C.rows,0),truncated:!A.done,...A.done?{}:{stoppedAt:"failure"},...A.where?{where:A.where}:{}})),N=I.reduce((A,B)=>A+B.recordCount,0),D=k.state!=="done";b?(this.deps.infraServices?.backgroundRegistry?.abort(n),Qe(this.deps,n,{aborted:!0,totalRecords:N}),c.cancel()):(Qe(this.deps,n,{objects:I.map(A=>({objectApiName:A.objectApiName,recordCount:A.recordCount})),totalRecords:N,...D?{status:"partial"}:{}}),D?c.partial():c.complete()),y&&this.deps.log(`[WARN] backup ${n}: ${y}`);let R=ke(this.deps,e,"dataops:backup:response",{operationId:n,status:D?"partial":"completed",objects:I,totalRecords:N,...D?{partial:!0}:{},timestamp:k.lastActivityAt,slices:en(k,{requestsSpent:u})});this.deps.broker.postToWebview(R),this.deps.log(`[TX] ${R.type} id=${R.id} slices=${$t(k).length}`),(y||b)&&hn(this.deps,"warning","Backup",`${b?"The backup in slices was cancelled":y}: set ${k.setId} holds ${N} record(s) in ${$t(k).length} slice(s), listed as partial.`)}catch(g){l=g,q(this.deps,"backup:execute","dataops:error",e,g),pe(this.deps,n,P(g),!0,{context:s}),c?.fail(P(g))}finally{this.activeOrgOperations.delete(o),d(l)}}restoreOfSet(e,t){let n=t===void 0?e.operationId:t.origin==="slice"?t.setId:void 0;if(n===void 0)return e.slices?{refused:{code:"NOT_A_SLICE_SET",message:`Backup ${e.operationId} holds no slices: restore it whole, without naming a slice.`}}:{};let s=this.sliceSets.get(n);if(!s||s.orgId!==e.orgId)return{};if(s.kind==="masking"&&s.state==="open"){let u=this.sliceWays(this.onCommandLine?void 0:"page");return{refused:{code:Re.runOpen,message:`Set ${s.setId} is still open: its masking run stopped part way, and resumed it would mask again over what a restore puts back. Give it up first (${u.abandon}), then restore it; or resume it to its end (${u.resume}). Nothing was written.`}}}let r=e.slices??(t?.slice?[t.slice.index]:void 0),o=s.objects.flatMap(u=>u.slices.filter(f=>f.state!=="pending").map(f=>({objectApiName:u.objectApiName,slice:f})));o.sort((u,f)=>u.slice.index-f.slice.index);let a=(r??[]).filter(u=>!o.some(f=>f.slice.index===u));if(a.length>0)return{refused:{code:"SLICE_NOT_FOUND",message:`Set ${s.setId} holds no slice ${a.join(", ")}: its slices are ${o.map(u=>u.slice.index).join(", ")||"none"}. Nothing was written.`}};let d=r?o.filter(u=>r.includes(u.slice.index)):o,c=u=>r!==void 0||e.rewriteAll===!0||u.slice.restoredAt===void 0,l=d.filter(c).map(u=>({snapshotId:u.slice.snapshotId,objectApiName:u.objectApiName,recordCount:u.slice.rows,slice:u.slice})),p=d.filter(u=>!c(u)).map(u=>({index:u.slice.index,objectApiName:u.objectApiName,restored:0,failed:0,unchanged:0,skipped:!0}));if(l.length===0&&p.length>0){let u=p.map(S=>o.find(k=>k.slice.index===S.index)?.slice.restoredAt??"").sort().at(-1),f=this.onCommandLine?"--rewrite-all":"Write every row back";return{refused:{code:"NOTHING_TO_RESTORE",message:`Every slice of set ${s.setId} was restored already (the last on ${u}): nothing was written. ${f} restores them again.`}}}let g=s.objects.map(u=>({objectApiName:u.objectApiName,recordCount:l.filter(f=>f.objectApiName===u.objectApiName).reduce((f,S)=>f+S.recordCount,0)})).filter(u=>l.some(f=>f.objectApiName===u.objectApiName));return{set:s,meta:{orgId:s.orgId,...s.organizationId!==void 0?{organizationId:s.organizationId}:{},timestamp:s.startedAt,totalRecords:g.reduce((u,f)=>u+f.recordCount,0),objects:g},parts:l,skipped:p}}async backupForPipeline(e,t){let n=e.fields?ki(e.fields):void 0,s=await this.takeBackup(e.operationId,{orgId:e.orgId,objects:e.objects,...n?{fields:n}:{},...e.scanAll?{scanAll:new Set(e.scanAll)}:{},...e.origin?{origin:e.origin}:{},...e.failWhenTruncated===!0?{failWhenTruncated:!0}:{},...e.onConnection?{onConnection:e.onConnection}:{}},e.origin==="checkpoint"?"checkpoint:take":"pipeline:execute",t);if("error"in s){let r=P(s.error);throw this.endBackupNotTaken(e.operationId,s),s.cancelled?new wn(r):s.error instanceof Error?s.error:new Error(r)}return s}endBackupNotTaken(e,t){if(t.cancelled){Qe(this.deps,e,{aborted:!0});return}pe(this.deps,e,P(t.error),t.retryable,{context:t.context})}async takeBackup(e,t,n,s){let r={module:"dataops",operation:n},o=t.slice,a=`backup:${t.orgId}`;if(!o&&this.activeOrgOperations.has(a)){let y=`A backup or rollback operation is already running for org ${t.orgId}. Please wait for it to complete.`;return this.deps.log(`[WARN] ${y}`),{error:new Error(this.busyMessage(t.orgId,y)),retryable:!1,context:r}}o||this.activeOrgOperations.add(a);let d=()=>{},c,l=new AbortController,p=()=>l.abort();s?.aborted&&l.abort(),s?.addEventListener("abort",p,{once:!0});let g=this.backupCap(),u=this.backupWriter(e);this.backupsWriting.add(e);let f=[],S,k,E,j=(y,b,I,N)=>{o||(Mt(this.deps,e,y,b,I,N),E?.progress(y,b,I,N))};try{if(!o&&this.dmlTracker.isDuplicate(e))return this.deps.log(`[WARN] Duplicate backup operation detected: ${e}`),{error:new Error(`Duplicate operation: ${e}`),retryable:!1,context:r};o||this.dmlTracker.register(e,"backup","insert",t.objects.length);let y=await We(t.orgId,this.deps.orgRegistry,this.deps.orgManager);k=y,t.onConnection?.(y);let b=hr(async C=>(await y.query(C)).records),I=this.deps.orgManager.getOrg(t.orgId),N=In(I?.orgType==="Sandbox"||I?.orgType==="Scratch"),D=An(N).defaultQueryLimit,R=`Backup ${t.objects.length} object(s)`;o||(Yt(this.deps,e,"dataops",R),this.deps.infraServices?.backgroundRegistry?.register(e,"dataops",R,new Promise((C,ee)=>{d=G=>{G===void 0?C():ee(G instanceof Error?G:new Error(String(G)))}}),l),E=rn(this.liveTracker,e,"dataops",R,t.objects.length));for(let C of t.objects){if(l.signal.aborted)throw new Ot;let ee=xe(C);r.objectName=ee;let G=t.wheres?.get(ee),W={objectApiName:C,recordCount:0,truncated:!1,...G!==void 0?{where:G}:{}};S=W,await this.readIntoBackup(y,ee,W,u,{pageSize:D,cap:o?.size??g,select:t.fields?.get(ee),where:G,scanAll:t.scanAll?.has(ee)===!0,...t.origin==="checkpoint"?{stamp:ri}:{},whole:t.failWhenTruncated===!0||o!==void 0,viewsEncrypted:b,...o?{slice:{bounds:o.bounds,size:o.size,...o.skip?{skip:o.skip}:{}},onRequest:o.onRequest}:{}},l.signal,()=>{let X=Math.max(1,Math.min(W.orgCount??g,g));j(Math.round((f.length+W.recordCount/X)/t.objects.length*100),f.length,t.objects.length,`Reading ${C} (${W.recordCount} of ${X} records)`)}),S=void 0,f.push(W),W.stoppedAt==="cap"&&this.deps.log(`[WARN] backup of ${ee} stopped at the cap of ${g} record(s): the object holds ${W.orgCount??"more"}.`),j(Math.round(f.length/t.objects.length*100),f.length,t.objects.length,`Exported ${C} (${W.recordCount} records)`)}let A=o?void 0:await this.organizationIdOf(y);if(l.signal.aborted)throw new Ot;let B=this.saveBackupMeta({operationId:e,orgId:t.orgId,organizationId:A,cap:o?.size??g,...t.origin?{origin:t.origin}:{},...o?{origin:"slice",setId:o.setId,slice:{index:o.index,...o.bounds.afterId!==void 0?{afterId:o.bounds.afterId}:{},...f[0]?.lastId!==void 0?{lastId:f[0].lastId}:{},size:o.size}}:{}},f,u,!1);return o?{operationId:e,objects:f,totalRecords:B.totalRecords,partial:!1,timestamp:B.timestamp}:(this.pruneAfterBackup(t.orgId),Qe(this.deps,e,{objects:f.map(C=>({objectApiName:C.objectApiName,recordCount:C.recordCount})),totalRecords:B.totalRecords,...B.partial?{status:"partial"}:{}}),this.dmlTracker.markCompleted(e),B.partial?E?.partial():E?.complete(),{operationId:e,objects:f,totalRecords:B.totalRecords,partial:B.partial,timestamp:B.timestamp})}catch(y){o||this.dmlTracker.markFailed(e);let b=y instanceof Ot,I=b||y instanceof cn||t.failWhenTruncated===!0||o!==void 0?void 0:await this.keepFailedBackup({operationId:e,orgId:t.orgId,cap:g,...t.origin?{origin:t.origin}:{}},k,{taken:f,reading:S,planned:t.objects},u);I===void 0&&await u.discard().catch(R=>{this.deps.log(`[WARN] backup ${e}: what it wrote before it stopped was not removed: `+P(R))});let N=I===void 0?y:new Error(`${P(y)} \u2014 the backup keeps the ${I.totalRecords} record(s) read before it stopped, listed as partial: ${Ns(I.objects)}.`);c=N,b&&!o&&this.deps.infraServices?.backgroundRegistry?.abort(e),b?E?.cancel():E?.fail(P(N));let D=!(y instanceof Wt)||y.retryable;return{error:N,retryable:D,context:r,cancelled:b}}finally{s?.removeEventListener("abort",p),d(c),o||this.activeOrgOperations.delete(a),this.backupsWriting.delete(e)}}backupCap(){return ii(this.deps.services?.getSandforgeSetting?.("backup.maxRecordsPerObject",ho))}snapshotCapWay(e,t){let n=this.backupCap(),s=e.filter(d=>d.tally.total>n),r=s.length>0?s.map(d=>d.tally.objectApiName).join(", "):"the object",o=s.reduce((d,c)=>Math.max(d,Rn(c.tally.total,n)),1),a=n<an&&s.every(d=>d.tally.total<=an);return t==="step"?`A pipeline's step masks no slices: mask ${r} from the DataOps panel, in slices each backed up just before it is masked, or with sandforge dataops anonymize --slices.`:t===void 0&&this.onCommandLine?`Give --slices to mask ${r} in ${o} slices, each with its own snapshot (the same line with --dry-run shows the plan)`+(a?`, --max-records up to ${an} (this run held ${n})`:"")+", or narrow the run with --where.":`Tick "Mask in slices" in the confirmation: ${r} is then masked in ${o} slices, each backed up just before it is masked`+(a?`; or raise sandforge.backup.maxRecordsPerObject in Settings (this run held ${n}, 1,000,000 at most)`:"")+"."}backupWriter(e){let t=this.backupRecords;if(t){let s=new Set;return{begin:async r=>{s.add(r),await t.begin(e,r).catch(o=>{throw new cn(o)})},append:async(r,o)=>{await t.append(e,r,o).catch(a=>{throw new cn(a)})},keep:()=>{},discard:async()=>{for(let r of s)await t.delete(e,r)}}}let n=new Map;return{begin:async s=>{n.set(s,[])},append:async(s,r)=>{n.get(s)?.push(...r)},keep:()=>{for(let[s,r]of n)this.deps.configStore.set(`backup:${e}:${s}`,r,"backups")},discard:async()=>{n.clear()}}}async readIntoBackup(e,t,n,s,r,o,a){let d=r.scanAll===!0,c=()=>r.onRequest?.(),l={headers:{"Sforce-Query-Options":`batchSize=${r.pageSize}`},maxFetch:1e4,autoFetch:!1,scanAll:d,responseTarget:"QueryResult"},p=r.select;if(p===void 0){let y=await this.selectAllFields(e,t,r.viewsEncrypted);p=y.select,y.notKept.length>0&&(n.notKept=y.notKept)}let g=d?bi(r.where):r.where,u=r.slice,f=u?Vr(t,p,g,u.bounds,u.size):`SELECT ${p} FROM ${t}${xn(g,void 0)}`,S=r.stamp??Xs(f)?.stamp,k=Vs(f,S===void 0?void 0:["Id",S]),E=d||r.whole===!0?y=>(c(),wi(e,y,d,t)):y=>(c(),Et(e,y)),j=await e.query(k?.first??f,l);if(c(),tt(e.limitInfo,`dataops:backup query ${t}`),!u&&typeof j.totalSize=="number"&&Number.isInteger(j.totalSize)&&(n.orgCount=j.totalSize),!u&&r.whole===!0&&n.orgCount!==void 0&&n.orgCount>r.cap)throw co(t,n.orgCount,r.cap);for(await s.begin(n.objectApiName);;){let y=r.cap-n.recordCount,b=j.records.length>y,I=b?j.records.slice(0,y):j.records,N=I;k&&S!==void 0?N=await Ys(I,k,E,{stamp:S,...d?{idsWhere:Cs}:{}}):k&&await Qs(I,k,E);let D=j.done?void 0:j.nextRecordsUrl;if(r.whole===!0&&!j.done&&D===void 0)throw new Wt(ko(t,n.recordCount+N.length),!0);let R=b||D!==void 0&&n.recordCount+N.length>=r.cap;if(u){let A=N.at(-1)?.Id;typeof A=="string"&&(n.lastId=A);let B=u.skip?N.filter(C=>!u.skip?.(C)):N;if(await s.append(n.objectApiName,B),n.recordCount+=B.length,n.readCount=(n.readCount??0)+N.length,R||D===void 0)return;if(a(),o.aborted)throw new Ot;j=await e.queryMore(D,l),c(),tt(e.limitInfo,`dataops:backup query ${t}`);continue}if(R&&r.whole===!0)throw co(t,n.orgCount,r.cap);if(await s.append(n.objectApiName,N),n.recordCount+=N.length,R){n.truncated=!0,n.stoppedAt="cap";return}if(D===void 0)return;if(a(),o.aborted)throw new Ot;j=await e.queryMore(D,l),c(),tt(e.limitInfo,`dataops:backup query ${t}`)}}saveBackupMeta(e,t,n,s){let r={operationId:e.operationId,orgId:e.orgId,...e.organizationId!==void 0?{organizationId:e.organizationId}:{},...e.origin!==void 0?{origin:e.origin}:{},...e.setId!==void 0?{setId:e.setId}:{},...e.slice!==void 0?{slice:e.slice}:{},objects:t.map($s),partial:t.some(o=>o.truncated),...s?{status:"failed"}:{},cap:e.cap,timestamp:new Date().toISOString(),totalRecords:t.reduce((o,a)=>o+a.recordCount,0)};return this.deps.configStore.set(`backup:${e.operationId}`,r,"backups"),n.keep(),r}async keepFailedBackup(e,t,n,s){let{taken:r,reading:o}=n,a=o?[...r,{...o,truncated:!0,stoppedAt:"failure"}]:[...r],d=new Set(a.map(p=>p.objectApiName.toLowerCase())),c=n.planned.filter(p=>!d.has(p.toLowerCase())).map(p=>({objectApiName:p,recordCount:0,truncated:!0,stoppedAt:"not_reached"})),l=[...a,...c];if(!l.every(p=>p.recordCount===0))try{let p=t?await this.organizationIdOf(t):void 0,g=this.saveBackupMeta({...e,organizationId:p},l,s,!0);return this.pruneAfterBackup(e.orgId),{...g,objects:l}}catch(p){this.deps.log(`[WARN] backup ${e.operationId}: the rows read before it failed were not kept: `+P(p));try{this.deps.configStore.delete(`backup:${e.operationId}`)}catch{}return}}async expireBackups(e){let t=Ir(this.deps.services);if(t<=0)return;let n=e-t*di;try{let s=this.retentionSince(e);for(let r of this.backupMetaKeys()){let o=this.deps.configStore.get(r),a=Date.parse(o?.timestamp??"");if(!Number.isFinite(a)||a>=n||a<s||o?.origin==="checkpoint"||o?.origin==="slice"||o?.orgId!==void 0&&this.backupBusy(o.orgId))continue;await this.removeBackup(r);let d=o?.origin==="sync"?` \u2014 the values the Sync run ${o.runId??"(unknown)"} wrote over, which removing that run no longer puts back`:"";this.deps.log(`[INFO] Removed backup ${r}: taken more than ${t} day(s) ago${d}`),this.expiryListener?.({operationId:r.slice(7),days:t,...o?.timestamp!==void 0?{takenAt:o.timestamp}:{},...o?.origin==="sync"?{syncRunId:o.runId??""}:{}})}for(let r of this.sliceSets.list()){let o=Date.parse(r.lastActivityAt);!Number.isFinite(o)||o>=n||o<s||this.backupBusy(r.orgId)||(await this.removeSliceSet(r),this.deps.log(`[INFO] Removed set of slices ${r.setId}: last moved more than ${t} day(s) ago`+(r.state==="open"?", its run left open and now over":"")),this.expiryListener?.({operationId:r.setId,days:t,takenAt:r.startedAt}))}}catch(s){this.deps.log(`[WARN] the backups past their age were not removed: ${P(s)}`)}}async removeSliceSet(e){for(let t of e.objects)for(let n of t.slices)await this.removeBackup(`backup:${n.snapshotId}`),await this.backupRecords?.delete(n.snapshotId,po(t.objectApiName));this.sliceSets.delete(e.setId),e.kind==="masking"&&e.state==="open"&&e.templateId!==void 0&&new nt(this.deps.configStore).clear(e.orgId,e.templateId),await this.runKeys?.delete(e.setId).catch(t=>{this.deps.log(`[WARN] the key of set ${e.setId} was not removed: ${P(t)}`)})}retentionSince(e){let t=Date.parse(this.deps.configStore.get(Zr)??"");return Number.isFinite(t)?t:(this.deps.configStore.set(Zr,new Date(e).toISOString()),e)}backupMetaKeys(){return this.deps.configStore.getKeysByPrefix("backup:").filter(e=>!e.slice(7).includes(":"))}backupBusy(e){return this.activeOrgOperations.has(`backup:${e}`)}async removeBackup(e){let n=this.deps.configStore.get(e)?.objects??[];for(let r of n)this.deps.configStore.delete(`${e}:${r.objectApiName}`);this.deps.configStore.delete(e);let s=e.slice(7);for(let r of n)await this.backupRecords?.delete(s,r.objectApiName)}async handleBackupDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=je(rr,e,"dataops:error",this.deps);if(!t)return;if(this.backupBusy(t.orgId)){q(this.deps,"backup:delete","dataops:error",e,new Error(this.busyMessage(t.orgId,`A backup or rollback operation is already running for org ${t.orgId}. Delete its backups once it has ended.`)),{code:Is});return}let n=t.operationIds?new Set(t.operationIds):void 0;for(let o of n??[]){let a=this.deps.configStore.get(`backup:${o}`);if(!(a?.origin!=="slice"||a.orgId!==t.orgId)){q(this.deps,"backup:delete","dataops:error",e,new Error(`Backup ${o} is slice ${a.slice?.index??"?"} of set ${a.setId??"?"}: a slice is deleted with its set, which holds the way back of every slice. Delete set ${a.setId??"?"} to delete it. Nothing was deleted.`),{code:Re.deleteAlone});return}}let s=[];try{for(let o of this.backupMetaKeys()){let a=this.deps.configStore.get(o);if(a?.orgId!==t.orgId||a.origin==="slice")continue;let d=a.operationId??o.slice(7);n&&!n.has(d)||(await this.removeBackup(o),s.push(d))}for(let o of this.sliceSets.list(t.orgId))n&&!n.has(o.setId)||(await this.removeSliceSet(o),s.push(o.setId))}catch(o){q(this.deps,"backup:delete","dataops:error",e,o);return}this.deps.log(`[INFO] Deleted ${s.length} backup(s) of org ${t.orgId}`);let r=ke(this.deps,e,"backup:delete:result",{orgId:t.orgId,deleted:s});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} deleted=${s.length}`)}pruneAfterBackup(e){try{this.pruneBackups(e)}catch(t){this.deps.log(`[WARN] backup retention failed after the snapshot was written: ${P(t)}`)}this.sweepBackupFiles()}handleBackupList(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=je(tr,e,"dataops:error",this.deps);if(!t)return;let n=[];for(let o of this.deps.configStore.getKeysByPrefix("backup:")){if(o.slice(7).includes(":"))continue;let a=this.deps.configStore.get(o);!a||a.orgId!==t.orgId||a.origin!=="slice"&&n.push({operationId:a.operationId??o.slice(7),orgId:a.orgId,timestamp:a.timestamp??"",totalRecords:a.totalRecords??0,totalSize:0,status:a.status==="failed"?"failed":"completed",objectResults:(a.objects??[]).map($s),...a.partial?{partial:!0}:{},...a.origin==="sync"?{origin:"sync"}:{}})}n.sort((o,a)=>a.timestamp.localeCompare(o.timestamp));let s=this.sliceSets.list(t.orgId).map(Tr).sort((o,a)=>a.lastActivityAt.localeCompare(o.lastActivityAt)),r=ke(this.deps,e,"backup:list:result",{backups:n,...s.length>0?{sets:s}:{}});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id} count=${n.length}`)}async handleBackupExport(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=je(sr,e,"dataops:error",this.deps);if(!t)return;let n=`backup:${t.operationId}`,s=this.deps.configStore.get(n);if(!s||s.orgId!==t.orgId){q(this.deps,"backup:export","dataops:error",e,new Error(`Backup not found: ${t.operationId}`),{code:"BACKUP_NOT_FOUND"});return}let r=await this.saveDialog.saveStream(`sandforge-backup-${t.operationId}.json`,a=>this.writeBackupDocument(t,s,a),["json"]);if(r.status==="error"){q(this.deps,"backup:export","dataops:error",e,new Error(r.message));return}let o=ke(this.deps,e,"backup:export:result",r.status==="saved"?{operationId:t.operationId,status:"saved",path:r.path,objects:r.result}:{operationId:t.operationId,status:"cancelled"});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id} ${r.status}`)}async writeBackupDocument(e,t,n){let{operationId:s}=e,o=[["sandforgeBackupVersion",1],["operationId",s],["orgId",e.orgId],["timestamp",t.timestamp??""],["totalRecords",t.totalRecords??0]].map(([d,c])=>` "${d}": ${JSON.stringify(c)},
|
|
8
|
-
`);await n(`{
|
|
9
|
-
${o.join("")} "objects": {`);let a=[];for(let{objectApiName:d}of t.objects??[]){if(a.some(l=>l.objectApiName===d))continue;await n(`${a.length>0?",":""}
|
|
10
|
-
${JSON.stringify(d)}: [`);let c=0;for await(let l of await this.backupBatches(s,d))l.length!==0&&(await n(l.map((p,g)=>`${c+g>0?",":""}
|
|
11
|
-
${JSON.stringify(p)}`).join("")),c+=l.length);await n(c>0?`
|
|
12
|
-
]`:"]"),a.push({objectApiName:d,records:c})}return await n(`${a.length>0?`
|
|
13
|
-
`:""}}
|
|
14
|
-
}
|
|
15
|
-
`),a}async backupBatches(e,t){let n=await this.backupRecords?.batches(e,t,Dt);if(n)return n;let s=this.deps.configStore.get(`backup:${e}:${t}`),r=Array.isArray(s)?s:[];return{async*[Symbol.asyncIterator](){for(let o=0;o<r.length;o+=Dt)yield r.slice(o,o+Dt)}}}async firstBackupRecord(e,t,n){let s=await this.backupBatches(e,t),r=n.origin==="sync"?ms(s,Dt).batches:s;for await(let o of r)if(o[0]!==void 0)return o[0]}pruneBackups(e){let t=this.deps.services?.getSandforgeSetting?.("backup.maxCount",10)??10,n=[];for(let s of this.deps.configStore.getKeysByPrefix("backup:")){if(s.slice(7).includes(":"))continue;let o=this.deps.configStore.get(s);o?.orgId===e&&o.origin!=="sync"&&o.origin!=="checkpoint"&&o.origin!=="slice"&&n.push({key:s,timestamp:o.timestamp??""})}if(!(n.length<=t)){n.sort((s,r)=>s.timestamp.localeCompare(r.timestamp));for(let{key:s}of n.slice(0,n.length-t))this.removeBackup(s),this.deps.log(`[INFO] Pruned backup ${s} (retention: ${t} per org)`)}}async undeleteFromRecycleBin(e,t,n){let s=[];for await(let o of n){let a=o.map(c=>c.Id).filter(c=>typeof c=="string");if(a.length===0)continue;let d=a.map(c=>`'${Gs(c)}'`).join(", ");try{let c=await e.query(`SELECT Id FROM ${t} WHERE Id IN (${d}) AND IsDeleted = true`,{scanAll:!0});s.push(...c.records.map(l=>l.Id))}catch(c){return this.deps.log(`[WARN] Rollback on ${t}: could not look for deleted records \u2014 ${P(c)}`),{undeleted:0}}}let r=0;for(let o=0;o<s.length;o+=200){let a=await e.soap.undelete(s.slice(o,o+200));r+=a.filter(d=>d.success).length}return{undeleted:r}}refuseWithoutGuard(e,t,n,s){be(this.deps,{...s,outcome:"stopped",source:void 0,code:Qt.code}),e(new Error(Qt.message),{code:Qt.code}),pe(this.deps,t,Qt.message,!1,{context:n,authored:!0})}async handleRollback(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=je(or,e,"dataops:error",this.deps);if(!t)return;let n=t,s=e.id,r={module:"dataops",operation:e.type},o=`backup:${n.orgId}`;if(this.activeOrgOperations.has(o)){let k=this.busyMessage(n.orgId,`A backup or rollback operation is already running for org ${n.orgId}. Please wait for it to complete.`);this.deps.log(`[WARN] ${k}`),q(this.deps,"dataops:rollback","dataops:error",e,new Error(k)),pe(this.deps,s,k,!1,{context:r,authored:!0});return}this.activeOrgOperations.add(o);let a,d,c=[],l=!1,p=new AbortController,g=()=>{},u,f,S;try{if(this.dmlTracker.isDuplicate(s)){this.deps.log(`[WARN] Duplicate rollback operation detected: ${s}`),q(this.deps,"dataops:rollback","dataops:error",e,new Error(`Duplicate operation: ${s}`)),pe(this.deps,s,`Duplicate operation: ${s}`,!1,{context:r,authored:!0});return}this.dmlTracker.register(s,"rollback","upsert",0);let k=await We(n.orgId,this.deps.orgRegistry,this.deps.orgManager),E=new Xn(async $=>{let z=await k.describe($);return go(z)}),j=`backup:${n.operationId}`,y=this.deps.configStore.get(j),b=this.restoreOfSet(n,y);if("refused"in b){q(this.deps,"dataops:rollback","dataops:error",e,new Error(b.refused.message),{code:b.refused.code}),pe(this.deps,s,b.refused.message,!1,{context:r,authored:!0});return}d=b.set;let I=b.meta??y;if(!I)throw new Error(`No backup found for operation ${n.operationId}. Cannot rollback.`);let N=b.parts??I.objects.map($=>({snapshotId:n.operationId,objectApiName:$.objectApiName,recordCount:$.recordCount}));if(I.orgId!==n.orgId){let $=Pt(this.deps.orgManager.getOrg(I.orgId),I.orgId),z=Pt(this.deps.orgManager.getOrg(n.orgId),n.orgId);throw new Error(`Backup ${n.operationId} was taken from org ${I.orgId} and cannot be restored into org ${n.orgId}. A restore writes back by record Id, and an Id belongs to the org that holds it: to bring these records from ${$} into ${z}, copy them with Forge or Sync.`)}a={action:"backup_restore",module:"dataops",operationId:s,orgId:n.orgId,outcome:"failure",source:{origin:"backup",label:I.timestamp?.slice(0,16).replace("T"," ")??n.operationId}};let D=this.deps.infraServices?.productionGuard;if(!D){this.refuseWithoutGuard(($,z)=>q(this.deps,"dataops:rollback","dataops:error",e,$,z),s,r,a);return}let R=[],A=new Set;for(let $ of N){if(A.has($.objectApiName.toLowerCase()))continue;let z=await this.firstBackupRecord($.snapshotId,$.objectApiName,I);if(z===void 0)continue;A.add($.objectApiName.toLowerCase());let M=xe($.objectApiName);if(!(await E.checkCrudPermission(M,"upsert")).allowed){R.push({objectApiName:M,operation:"upsert",deniedFields:[]});continue}let{denied:Ke}=await E.partitionWritableFields(M,"upsert",Object.keys(z).filter(Ne=>Ne!=="attributes"));Ke.length>0&&R.push({objectApiName:M,operation:"upsert",deniedFields:Ke})}if(R.length>0){let $=bn(R);this.deps.log(`[WARN] CRUD/FLS check failed for rollback ${s}: ${$}`),be(this.deps,{...a,outcome:"stopped",source:void 0,code:xt}),q(this.deps,"dataops:rollback","dataops:error",e,new Error($),{code:xt}),pe(this.deps,s,$,!1,{context:r,authored:!0});return}let B=($,z,M,de=[])=>{be(this.deps,{...M,outcome:"stopped",source:void 0,code:$}),q(this.deps,"dataops:rollback","dataops:error",e,new Error(z),{code:$,...os({alsoRefused:de})}),pe(this.deps,s,z,!1,{context:r,authored:!0})},C=await this.readAct(k,n.orgId,"restore",I.objects.map($=>({objectApiName:$.objectApiName,records:$.recordCount})),n,Jt(n)),ee=yn(C.answer);if(ee){B(ee.code,ee.message,a,ee.alsoRefused);return}S=this.duplicatesWatchOf(k,ts(C.answer.automation,I.objects.filter($=>$.recordCount>0).map($=>$.objectApiName)));let G=this.deps.orgManager.getOrg(n.orgId),W={orgId:n.orgId,orgTier:Rs(G),operation:"upsert",objectName:I.objects.map($=>$.objectApiName).join(", ")||"RollbackData",recordCount:I.totalRecords??0,module:"dataops"},{check:X,decision:Se}=await Zn(D,W);if(a.guard=Se,(Se==="refused"||Se==="declined")&&be(this.deps,{...a,outcome:"stopped",source:void 0}),Se==="refused")throw Hn(X.blockedReason??X.impactSummary);if(Se==="declined"){let $="Operation cancelled by user (confirmation declined).";q(this.deps,"dataops:rollback","dataops:error",e,new Error($),{code:Kn.declined}),pe(this.deps,s,$,!1,{context:r,authored:!0});return}if(I.organizationId!==void 0){let $=await this.organizationIdOf(k);if($!==void 0&&!ni(I.organizationId,$)){let z=Pt(G,n.orgId),M=this.deps.infraServices?.confirmRestoreIntoReplacedOrg;if(!(M?await M({alias:z,backedUpFrom:I.organizationId,now:$}):!1)){be(this.deps,{...a,outcome:"stopped",source:void 0,code:Yr});let Ke=`Restore not run: ${z} answers as org ${$}, not as org ${I.organizationId}, which backup ${n.operationId} was taken from, `+(M?"and the restore into the org it is now was not confirmed.":"and nothing here can ask whether to restore into the org it is now.");q(this.deps,"dataops:rollback","dataops:error",e,new Error(Ke),{code:Yr}),pe(this.deps,s,Ke,!1,{context:r,authored:!0});return}}}let kt=await rs(C,s,n.acceptEmails===!0,Jt(n));if("refused"in kt){B(kt.refused.code,kt.refused.message,a);return}f=kt.held,Yt(this.deps,s,"dataops",`Rollback ${I.objects.length} object(s)`);let Ge=b.skipped??[];l=!0,this.deps.infraServices?.backgroundRegistry?.register(s,"dataops",`Rollback ${I.objects.length} object(s)`,new Promise(($,z)=>{g=M=>{M===void 0?$():z(M instanceof Error?M:new Error(String(M)))}}),p),u=rn(this.liveTracker,s,"dataops",`Rollback ${I.objects.length} object(s)`,I.objects.length);let we=!1,Ce=0,ve=0,Ze=0,ot=[],wt=new Map,Ut=I.origin==="sync"&&n.includeChanged!==!0,ze=Number.NEGATIVE_INFINITY,F=!1;if(Ut){let $=I.runId!==void 0?await this.syncRuns?.get(I.runId).catch(M=>{this.deps.log(`[WARN] Rollback: the Sync run of backup ${n.operationId} could not be read \u2014 ${P(M)}`)}):void 0,z=$?mr($):void 0;F=z===void 0,ze=await fr({serverTime:async()=>(await k.soap.getServerTimestamp()).timestamp},z)}let V=[];for(let $=0;$<N.length;$++){if(p.signal.aborted){we=!0;break}let z=N[$],M=xe(z.objectApiName);r.objectName=M;let de=await this.backupBatches(z.snapshotId,z.objectApiName),Ke=I.origin==="sync"?ms(de,Dt):void 0,Ne=Ke?.batches??de,Le;for await(let ce of Ne)if(Le=ce[0],Le!==void 0)break;if(Ut&&Le!==void 0){let ce=[];for await(let De of Ne)for(let Pe of De)typeof Pe.Id=="string"&&ce.push(Pe.Id);let et=await Wr({query:async(De,Pe)=>({records:(await k.query(De,Pe)).records})},M,ce,ze);et.size>0&&(V.push({objectApiName:M,count:et.size}),Ne=Ur(Ne,et))}if(Le===void 0){wt.set(z.objectApiName,wt.get(z.objectApiName)??0),this.deps.log(`[WARN] No backup records for ${z.objectApiName}, skipping.`);continue}let pn=Object.keys(Le).filter(ce=>ce!=="attributes"),{skipped:it}=await E.partitionWritableFields(M,"upsert",pn),at=new Set(it.filter(ce=>ce.toLowerCase()!=="id").map(ce=>ce.toLowerCase()));at.size>0&&this.deps.log(`[INFO] Rollback on ${M}: ${at.size} non-writable field(s) excluded from the payload \u2014 ${[...at].sort().join(", ")}`);let yt=await this.undeleteFromRecycleBin(k,M,Ne);yt.undeleted>0&&this.deps.log(`[INFO] Rollback on ${M}: ${yt.undeleted} record(s) brought back from the recycle bin`),r.batchSize=Dt;let dt=0,ct=0,Oe=0,At=0;for await(let ce of Ne){if(p.signal.aborted){we=!0;break}At+=ce.length;let et=ce.map(le=>{let He=M===se?mn(le,!1):void 0,Z={};for(let[qe,ut]of Object.entries(le))qe!=="attributes"&&(at.has(qe.toLowerCase())||He!==void 0&&fn(se,qe,He)||(Z[qe]=ut));return Z}),De=et;if(n.rewriteAll!==!0){let le=await _r({query:async He=>{let Z=await k.query(He);return{totalSize:Z.totalSize,records:Z.records}}},M,et);le.unread!==void 0&&this.deps.log(`[WARN] Rollback on ${M}: the org's values could not be read, so ${et.length} row(s) are written back without comparing \u2014 ${le.unread}`),De=le.write,Oe+=le.unchanged}if(De.length===0)continue;S.beforeWrite(M);let Pe;try{Pe=await k.sobject(M).upsert(De,"Id",{headers:Wn()})}catch(le){throw Jn(le)==="may-have-written"&&S.wrote(M,De.map(He=>He.Id)),le}let Ht=Array.isArray(Pe)?Pe:[Pe];S.wrote(M,Ht.flatMap((le,He)=>le.success?[De[He]?.Id]:[]));for(let le of Ht){if(le.success){dt++;continue}ct++,Jr(ot,M,le.errors)}}tt(k.limitInfo,`dataops:rollback upsert ${M}`),wt.set(z.objectApiName,(wt.get(z.objectApiName)??0)+(Ke&&!we?Ke.lines():At)),Ce+=dt,ve+=ct,Ze+=Oe;let Kt=c.find(ce=>ce.objectApiName===M);if(Kt?(Kt.updated+=dt,Kt.failed+=ct):c.push({...gn(M),updated:dt,failed:ct}),z.slice&&(Ge.push({index:z.slice.index,objectApiName:M,restored:dt,failed:ct,unchanged:Oe}),!we&&d&&(z.slice.restoredAt=new Date().toISOString(),z.slice.state="restored",d.lastActivityAt=z.slice.restoredAt,this.sliceSets.save(d))),we)break;let jt=`Restored ${M}${z.slice?` slice ${z.slice.index}`:""} (${dt}/${At}${Oe>0?`, ${Oe} unchanged`:""})`,lt=Math.round(($+1)/N.length*100);Mt(this.deps,s,lt,$+1,N.length,jt),u.progress(lt,$+1,N.length,jt)}let re=V.reduce(($,z)=>$+z.count,0),U=ci(Ce,ve),te=we&&ve===0||re>0&&U==="success"?"partial":U;a&&(l=!1,be(this.deps,{...a,...we?Ce+ve>0?{outcome:"cancelled"}:{outcome:"stopped",code:Gn}:{outcome:te},objects:c}));let Tt=await this.releaseMute(f,n.orgId);f=void 0;let Xe=await S.read();we?(this.deps.infraServices?.backgroundRegistry?.abort(s),Qe(this.deps,s,{aborted:!0,totalRestored:Ce,totalFailed:ve,totalUnchanged:Ze})):Qe(this.deps,s,{status:te,totalRestored:Ce,totalFailed:ve,totalUnchanged:Ze}),this.dmlTracker.markCompleted(s),we?u.cancel():te==="failure"?u.fail(`The org refused the ${ve} record(s)`):te==="partial"?u.partial():u.complete();let Be=Ns(I.objects,wt),Je=(we?`Rollback cancelled: ${Ce} records restored before the cancel; the rest still hold the values they had, and the same restore puts them back`:ve>0?`Rollback ${te}: ${Ce} restored, ${ve} rejected by the org`:re>0?`Rollback partial: ${Ce} records restored`:`Rollback completed: ${Ce} records restored`)+(Ze>0?`; ${Ze} already held the backup's values and were not written`:"")+(re>0?`; ${re} changed or deleted since the Sync run were left as they are `+(F?"(the run is no longer kept here, so every record reads as changed since it) ":"")+"unless the restore includes them":""),me=Zt(Xe,this.orgNameOf(n.orgId),"restore"),$e=Be===""?Je:`${Je}. The backup held only part of the org's records, and the rest were left as they are: ${Be}`,Ve=me?`${$e}. ${me}`:Be===""?$e:`${$e}.`,ae=ke(this.deps,e,"dataops:rollback:response",{operationId:n.operationId,status:te,message:Ve,totalRestored:Ce,totalFailed:ve,totalUnchanged:Ze,...n.rewriteAll===!0?{rewriteAll:!0}:{},...n.includeChanged===!0?{includeChanged:!0}:{},...re>0?{keptChanged:{total:re,objects:V,...F?{runNotKept:!0}:{}}}:{},errors:ot,...Be!==""?{partial:!0}:{},...we?{cancelled:!0}:{},...Tt?{mutedAutomation:Tt}:{},...Xe?{duplicates:Xe}:{},...d?{slices:Ge}:{}});this.deps.broker.postToWebview(ae),this.deps.log(`[TX] ${ae.type} id=${ae.id} status=${te}`),(ve>0||Be!==""||we||re>0||ss(Xe))&&hn(this.deps,te==="failure"?"error":"warning","Restore",`${Ve}${ot[0]?` \u2014 e.g. ${ot[0].message}`:""}`)}catch(k){this.dmlTracker.markFailed(s),await this.releaseMute(f,n.orgId),f=void 0;let E=await S?.read(),j=Zt(E,this.orgNameOf(n.orgId),"restore");q(this.deps,"dataops:rollback","dataops:error",e,j?new Error(`${P(k)} ${j}`):k,{code:qn(k),...E?{extraPayload:{duplicates:E}}:{}}),pe(this.deps,s,P(k),!0,{context:r}),u?.fail(P(k))}finally{await this.releaseMute(f,n.orgId),this.activeOrgOperations.delete(o),g(),l&&a&&be(this.deps,{...a,outcome:"failure",objects:c})}}async snapshotBeforeMasking(e,t,n,s,r){let o=new Map,a=new Map;try{for(let l of s){if(l.tally.total===0)continue;l.where!==void 0&&a.set(l.tally.objectApiName,l.where);let{select:p}=await this.maskedFields(e,l.tally.objectApiName,this.maskingRules(l.objectName,l.objectRules),this.maskingRules(l.objectName,l.personRules));p!=="Id"&&o.set(l.tally.objectApiName,p)}}catch(l){return{refused:`No snapshot was taken, so nothing was masked: ${P(l)}`,retryable:!0}}if(o.size===0)return{};let d=`${t}-snapshot`,c=await this.takeBackup(d,{orgId:n,objects:[...o.keys()],...a.size>0?{wheres:a}:{},fields:o},r.origin,r.stop);return"error"in c?(this.endBackupNotTaken(d,c),{refused:`No snapshot was taken, so nothing was masked: ${P(c.error)}`,retryable:c.retryable&&c.cancelled!==!0}):c.partial?{refused:`Snapshot ${d} holds only part of the records the run would mask, so nothing was masked: a restore could not put back the rest (${Ns(c.objects)}). `+this.snapshotCapWay(s),retryable:!1}:{taken:{operationId:d,totalRecords:c.totalRecords}}}async maskingNotCovered(e,t,n,s){if(s.length===0)return{code:Ue.masksNothing,message:`The template "${t.name}" has no rule for ${n.join(", ")}: the run would mask nothing. Choose an object its rules name, or another template. Nothing was masked.`,gaps:{fieldsNotFound:[],objectsNotCovered:[...n]}};let r=[],o=[];for(let d of s){if(d.tally.total===0)continue;let{objectApiName:c}=d.tally,{rules:l,missing:p}=await this.maskedFields(e,c,this.maskingRules(d.objectName,d.objectRules),this.maskingRules(d.objectName,d.personRules));r.push(...p.map(g=>({objectApiName:c,fieldApiName:g}))),l.length===0&&o.push(c)}let a={fieldsNotFound:r,objectsNotCovered:o};if(r.length>0){let d=r.map(c=>`${c.objectApiName}.${c.fieldApiName}`).join(", ");return{code:Ue.fieldsUnseen,message:`The template "${t.name}" masks ${d}, which the org does not show the user SandForge connects as: it has no such field, or field-level security hides it. `+(o.length>0?`No field of ${o.join(", ")} can be masked. `:"")+"A run masks every field its template names, or nothing: give that user read and edit access to the field, or take the field out of the template. Nothing was masked.",gaps:a}}if(o.length>0)return{code:Ue.masksNothing,message:`The template "${t.name}" masks no field of ${o.join(", ")} in this org: the run would write nothing over its records. Choose an object its rules name, or another template. Nothing was masked.`,gaps:a}}async anonymizeForPipeline(e,t){let n=this.deps.orgManager.getOrg(e.orgId);if(!n)throw st(Ue.orgUnknown,`The org the masking writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was masked.`);let s=Gr(Rs(n),e.answer,Pt(n,e.orgId));if(s)throw s;let r=ks(e,f=>this.findTemplate(f)!==void 0);if("refusal"in r)throw r.refusal;let o=crypto.randomUUID(),a,d,c,l={origin:"pipeline:execute",pipeline:e.pipeline,accord:e.accord??{},voice:"step",muted:f=>{c=f},refused:(f,S)=>{a??={err:f,...S},this.deps.log(`[ERR] dataops:anonymize ${o} for the pipeline "${e.pipeline.name}": `+P(f))},ended:f=>{d=f}};await this.writing.during(e.orgId,()=>yr(e.answer,()=>this.mask(r.asked,o,l,t)));let p=a,g=c;if(p){let f=P(p.err),S=p.err,k=p.code??(typeof S?.code=="string"?S.code:void 0),E=p.extraPayload?.snapshot,j={...k!==void 0?{code:k}:{},...E!==void 0?{snapshot:E}:{},...g?{mutedAutomation:g}:{}};throw Object.assign(k===Vt?new wn(f):new Error(f),j)}let u=d;if(u===void 0)throw new Error("The masking run ended without a result.");return{operationId:o,result:g?{...u,mutedAutomation:g}:u}}async previewMaskingForPipeline(e,t){let n=(b,I)=>st(b,I),s=()=>new wn("The simulation of the masking was stopped: nothing was masked.");if(!this.deps.orgManager.getOrg(e.orgId))throw n(Ue.orgUnknown,`The org the masking writes to is not connected to SandForge (${e.orgId}): connect it, or choose another. Nothing was masked.`);let r=ks(e,b=>this.findTemplate(b)!==void 0);if("refusal"in r)throw r.refusal;let o=r.asked,a=this.findTemplate(o.templateId);if(!a)throw Ts(o.templateId);let d=this.sliceSets.openFor(o.orgId,o.templateId);if(d)throw n(Re.runOpen,this.sliceRunOpenMessage(d,"step"));let c=await We(o.orgId,this.deps.orgRegistry,this.deps.orgManager),l=Cn(c),p=await this.plannedObjectsIn(l,o,a),g=[];for(let b of p){if(t?.aborted)throw s();let I=Ft(a,b),N=dn(a,b);if(I.length===0&&N.length===0)continue;let D=xe(b),R=jn(o,a,b),A;try{A=await this.countRows(c,D,void 0,R)}catch(B){throw this.countGaveUp(B,D)}g.push({objectName:b,...R!==void 0?{where:R}:{},objectRules:I,personRules:N,tally:{objectApiName:D,total:A,masked:0,nothingToMask:0,refused:0,unanswered:0,done:A===0},progress:{objectApiName:D,done:A===0,refused:[]}})}let u=await this.maskingNotCovered(l,a,p,g);if(u)throw n(u.code,u.message);let f=g.filter(b=>b.tally.total>0),S=await vs(l,f.map(b=>({objectApiName:b.tally.objectApiName,rules:[...b.objectRules,...b.personRules]})));if(S.length>0)throw n(xt,bn(S));let k=this.backupCap();if(g.some(b=>b.tally.total>k))throw n(on,`Nothing was masked: ${g.filter(b=>b.tally.total>k).map(b=>`${b.tally.objectApiName} holds ${b.tally.total} record(s)`).join(", ")}, more than the ${k} a snapshot holds of one object. `+this.snapshotCapWay(g,"step"));if(t?.aborted)throw s();let E=await this.readAct(c,o.orgId,"masking",g.map(b=>({objectApiName:b.tally.objectApiName,records:b.tally.total})),e.accord??{},"step"),j=yn(E.answer);if(j)throw n(j.code,j.message);let y=[];for(let b of g){let{rules:I}=await this.maskedFields(l,b.tally.objectApiName,this.maskingRules(b.objectName,b.objectRules),this.maskingRules(b.objectName,b.personRules));y.push({objectApiName:b.tally.objectApiName,records:b.tally.total,fields:[...new Set(I.map(N=>N.fieldApiName))].filter(N=>N!=="Id")})}return{objects:y,records:y.reduce((b,I)=>b+I.records,0)}}async handleAnonymize(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=je(kn,e,"dataops:error",this.deps);if(!t)return;let n=Jt(t);await this.mask(t,e.id,{...this.pageMaskingReplies(e),accord:{acceptAutomation:t.acceptAutomation===!0,acceptEmails:t.acceptEmails===!0,muteAutomation:t.muteAutomation===!0},...n?{voice:n}:{}})}pageMaskingReplies(e){return{origin:e.type,refused:(t,n)=>q(this.deps,"dataops:anonymize","dataops:error",e,t,n),ended:t=>{let n=ke(this.deps,e,"dataops:anonymize:response",t);this.deps.broker.postToWebview(n),this.deps.log(`[TX] ${n.type} id=${n.id} status=${t.status}`),(t.recordsNotMasked>0||ss(t.duplicates))&&hn(this.deps,t.status==="failure"?"error":"warning","Anonymize",`${t.message}${t.errors[0]?` \u2014 e.g. ${t.errors[0].message}`:""}`)}}}pageSizeFor(e){let t=this.deps.orgManager.getOrg(e);return An(In(t?.orgType==="Sandbox"||t?.orgType==="Scratch")).defaultQueryLimit}sliceWays(e){return e==="page"?{resume:"Resume",abandon:"Abandon",restore:()=>"Restore lists the set and puts its values back"}:e===void 0&&this.onCommandLine?{resume:"the same line with --resume",abandon:"--abandon",restore:t=>`the same command with --restore ${t} puts its values back`}:{resume:"Resume on the DataOps panel, or sandforge dataops anonymize --resume",abandon:"Abandon on the DataOps panel, or sandforge dataops anonymize --abandon",restore:()=>"the Backups tab of the DataOps panel lists the set and puts its values back"}}async approximateCount(e,t,n){if(js.has(Pn(n)))try{let s=await e.request(`/services/data/v${e.version}/limits/recordCount?sObjects=${t}`),{recordCountsOf:r}=await import("./chunk-ZQQXSCVI.mjs"),o=r(s)?.get(t);return o!==void 0&&this.deps.log(`[INFO] dataops:anonymize: the org gave up counting ${t}; its own figure, ${o}, plans the slices, approximate.`),o}catch(s){this.deps.log(`[WARN] dataops:anonymize: the org's figure of ${t} was not read: `+P(s));return}}async apiBudgetFor(e,t){let{apiBudgetCheckOf:n,readApiBudget:s}=await import("./chunk-XKWW3GKF.mjs"),r=await s(e).catch(a=>({unread:P(a)})),o=n(t,r);return o.verdict==="unread"?{verdict:"unread",unread:o.unread}:{verdict:o.verdict,remaining:o.remaining,max:o.max}}async sliceRunPlan(e,t,n,s){let r=[];for(let o of t){if(o.tally.total===0)continue;let{select:a}=await this.maskedFields(e,o.tally.objectApiName,this.maskingRules(o.objectName,o.objectRules),this.maskingRules(o.objectName,o.personRules));r.push({objectApiName:o.tally.objectApiName,rows:o.tally.total,fields:a.split(",").length})}return ls(r,n,s,"masking")}tooManySlicesMessage(e,t){let n=e.objects.filter(r=>e.tooMany.includes(r.objectApiName)).map(r=>`${r.objectApiName} (${r.slices} slices)`).join(", "),s=this.onCommandLine?`Give --max-records up to ${an}, so that a slice holds more, or narrow the run with --where.`:"Raise sandforge.backup.maxRecordsPerObject in Settings, up to 1,000,000, so that a slice holds more.";return`Nothing was masked: ${n} would take more than the ${ht} slices a set holds, at ${t} records a slice. ${s}`}diskShortMessage(e,t,n=!1){let s=this.backupRecords?.directory??"the backups folder",r=this.onCommandLine?"give --store a folder on another disk, delete the backups no longer needed (sandforge backup --list, then delete them), or keep backups fewer days (--max-age-days)":"delete the backups no longer needed in the Backups tab, or keep backups fewer days (sandforge.backup.maxAgeDays)";return`${n?"Nothing was masked":"The run stopped between two slices"}: the slices' snapshots take about ${us(e)}, and ${s} has ${us(t)} free. To make room, ${r}.`}sliceBudgetStop(e,t,n,s,r){if(t!==void 0&&n+s>t)return`Stopped between slices: the run sent ${n} request(s), and the next slice takes about ${s} more, past the ${t} of ${r==="page"?"the requests it was given":"--max-requests"}.`;let o=tt(e.limitInfo,"dataops:anonymize slices");if(o&&o.apiLimit>0&&(o.apiUsage+s)/o.apiLimit*100>=Os)return`Stopped between slices: the org used ${o.apiUsage} of its ${o.apiLimit} daily API requests, and the next slice takes about ${s} more, past the ${Os}% the run leaves the org's integrations below.`}sliceNotTakenMessage(e,t){if(t.code===Re.readTooHeavy){let n=this.onCommandLine?"narrow --where to an indexed field, such as a range of CreatedDate, or give a lower --max-records":"mask it from the command line with --where on an indexed field, such as a range of CreatedDate, or lower sandforge.backup.maxRecordsPerObject";return`The org would not read a slice of ${e} in time, even halved ${uo} times (${P(t.failed)}): the run stopped there, and nothing of that slice was masked. To go on, ${n}.`}return`The snapshot of the next slice of ${e} was not taken (${P(t.failed)}): the run stopped there, and nothing of that slice was masked.`}sliceRunOpenMessage(e,t){let n=$t(e),s=this.sliceWays(t);return`A masking run of this template in slices is still open on ${this.orgNameOf(e.orgId)} (set ${e.setId}, ${n.filter(Bt).length} of ${n.length} slice(s) masked, last moved ${e.lastActivityAt}): a new run would mask its rows again and write over where it stopped. Resume it (${s.resume}), or give it up (${s.abandon}), which masks nothing more and keeps its slices to restore. Nothing was masked.`}sliceKeyLostMessage(e,t){let n=this.sliceWays(t);return`The key set ${e.setId} was masked with is not kept where this run reads it: masked with another, the same address would get another digest and the same record another person. Give the set up (${n.abandon}); ${n.restore(e.setId)} if its values are wanted back, and a new run masks again. Nothing was masked.`}slicesSentence(e,t,n,s,r=[]){let o=this.sliceWays(n),a=$t(e),d=ds(e);return[...t?[t.message]:[],`Set ${e.setId}: ${a.filter(Bt).length} of ${a.length} slice(s) of up to ${e.size} records masked, each backed up just before it was masked; ${o.restore(e.setId)}.`,...d>0?[`${d} record(s) were created during the run in a range a slice had masked, or past its last slice: no snapshot holds them, and they were not masked.`]:[],...r.length>0?[`Whether records were created during the run in a range a slice had masked could not be read for ${r.join(", ")}: any such record was not masked.`]:[],...e.state==="open"&&s?[`${o.resume[0].toUpperCase()}${o.resume.slice(1)} masks the rest, each slice backed up first.`]:[]].join(" ")}async snapshotSlice(e,t,n,s,r,o){let a;try{o.clock!==!1&&(a=new Date((await e.soap.getServerTimestamp()).timestamp).toISOString(),o.onRequest())}catch(c){this.deps.log(`[WARN] dataops: the org's clock before slice ${r.index} was not read: `+P(c))}let d=r.sizeUsed;for(let c=0;;c++){let l=await this.takeBackup(r.snapshotId,{orgId:t,objects:[s.objectApiName],...s.where!==void 0?{wheres:new Map([[s.objectApiName,s.where]])}:{},...o.select!==void 0?{fields:new Map([[s.objectApiName,o.select]])}:{},slice:{setId:n.setId,index:r.index,bounds:o.bounds,size:d,...o.skip?{skip:o.skip}:{},onRequest:o.onRequest}},o.origin,o.stop);if(!("error"in l)){let g=l.objects[0];return{rows:g?.recordCount??0,read:g?.readCount??g?.recordCount??0,...g?.lastId!==void 0?{lastId:g.lastId}:{},sizeUsed:d,...a!==void 0?{readSince:a}:{}}}if(l.cancelled)return{failed:l.error,code:Vt,cancelled:!0};if(!js.has(Pn(l.error)))return{failed:l.error,code:on};if(c>=uo||d<=lo)return{failed:l.error,code:Re.readTooHeavy};d=Math.max(lo,Math.floor(d/2)),this.deps.log(`[INFO] dataops: the org would not read slice ${r.index} of ${s.objectApiName} in time; read again in ${d} records.`)}}async countLateRows(e,t,n){let s=[],r=async o=>{let a=await e.query(o);return n(),typeof a.totalSize=="number"?a.totalSize:0};for(let o of t.objects)try{let a=o.slices.filter(g=>!g.late&&g.lastId!==void 0),d=a.at(-1)?.lastId,c=await r(d!==void 0?Qr(o.objectApiName,o.where,d):`SELECT COUNT() FROM ${o.objectApiName}${xn(o.where,void 0)}`);c>0?(o.tailLeft=c,o.done=!1):delete o.tailLeft;let l=t.serverStartedAt;if(d===void 0||l===void 0||await r(As(o.objectApiName,o.where,l,{untilId:d}))===0)continue;for(let g of a){if(g.lastId===void 0)continue;let u=await r(As(o.objectApiName,o.where,g.readSince??l,{...g.afterId!==void 0?{afterId:g.afterId}:{},untilId:g.lastId}));u>0?g.lateLeft=u:delete g.lateLeft}}catch(a){this.deps.log(`[WARN] dataops: the ${o.objectApiName} records created during set ${t.setId} were not counted: ${P(a)}`),s.push(`${o.objectApiName} (${P(a)})`)}return s}async abandonSliceSet(e,t,n){if(!e){n.refused(new Error(`No masking run of this template in slices is open on ${this.orgNameOf(t.orgId)}: there is nothing to give up.`),{code:Re.nothingToAbandon});return}if(this.sliceRunsOn.get(t.orgId)===e.setId){n.refused(new Error(this.busyMessage(t.orgId,"")),{code:Is});return}e.state="abandoned",e.lastActivityAt=new Date().toISOString(),this.sliceSets.save(e),new nt(this.deps.configStore).clear(t.orgId,t.templateId),await this.runKeys?.delete(e.setId).catch(a=>{this.deps.log(`[WARN] dataops: the key of set ${e.setId} was not removed: ${P(a)}`)});let r=$t(e).filter(Bt).length,o=this.sliceWays(n.voice);this.deps.log(`[INFO] dataops: set ${e.setId} given up, ${r} slice(s) masked`),n.ended({templateId:t.templateId,status:"success",recordsProcessed:0,recordsFailed:0,recordsNotMasked:0,objects:[],message:`Set ${e.setId} given up: nothing more is masked. Its ${r} masked slice(s) stay masked, each with its snapshot; ${o.restore(e.setId)} until the retention removes them. The records no slice reached keep their values.`,errors:[],abandoned:!0,slices:en(e,{requestsSpent:0})})}async mask(e,t,n,s){let r,o={},a,d=async()=>(a??={released:await this.releaseMute(r,e.orgId)},a.released),c={...n,refused:(F,V)=>{if(!r){n.refused(F,V);return}o.answer??=re=>n.refused(F,re?{...V,extraPayload:{...V.extraPayload,mutedAutomation:re}}:V)},ended:F=>{if(!r){n.ended(F);return}o.answer??=V=>n.ended(V?{...F,mutedAutomation:V}:F)}},l={module:"dataops",operation:c.origin},p=this.findTemplate(e.templateId),g=Tn(e,p),u={action:"anonymize_execute",module:"dataops",operationId:t,orgId:e.orgId,outcome:"failure",source:{origin:"org",orgId:e.orgId}},f=[],S=[],k=zn(e),E=p?sn(p.rules,g,k):"",j=!1,y=!1,b=!1,I=!1,N,D,R,A=0,B=0,C,ee,G=!1,W=[],X=new AbortController,Se=()=>{},kt,Ge,we,Ce=async()=>ns(ee,await we?.read()),ve=this.deps.infraServices?.backgroundRegistry?.holdUntilStart(t);ve?.signal.addEventListener("abort",()=>X.abort(),{once:!0});let Ze=()=>X.abort();s?.aborted&&X.abort(),s?.addEventListener("abort",Ze,{once:!0});let ot=async()=>{be(this.deps,{...u,outcome:"stopped",source:void 0,code:Vt});let F="The masking run was cancelled before it wrote anything.";c.refused(new Error(F),{code:Vt,...D?{extraPayload:{snapshot:D}}:{}}),await d(),Qe(this.deps,t,{aborted:!0})},wt=(F,V,re)=>{kt=F;let U=P(F),te=_t(f),Tt=j&&te.recordsNotMasked>0,Xe=Zt(re,this.orgNameOf(e.orgId)),Be={...j?{...te,objects:oo(f)}:{},...D?{snapshot:D}:{},...re?{duplicates:re}:{},...R?{slices:en(R,{requestsSpent:A})}:{}},Je=Tt?`${U} \u2014 ${te.recordsProcessed} masked before it stopped; ${te.recordsNotMasked} still hold their original values (${ro(f)}).`:U;c.refused(Tt||Xe?new Error(Xe?`${Je} ${Xe}`:Je):F,{code:qn(F),extraPayload:Be}),pe(this.deps,t,U,V,{context:l,extraPayload:Be}),Ge?.fail(U)},Ut=()=>{I=!0;let F=new nt(this.deps.configStore),{recordsNotMasked:V}=_t(f),re=f.reduce((U,te)=>U+te.masked+te.nothingToMask+te.refused+te.unanswered,0);try{if(V===0&&R?.state!=="open"||R!==void 0&&R.state!=="open")return F.clear(e.orgId,e.templateId),!1;if(re===0&&R===void 0)return F.load(e.orgId,e.templateId,E)!==void 0;let U=S.map(te=>te.progress);return nn(U)>Nt?(this.deps.log(`[WARN] dataops:anonymize ${t}: the org refused ${nn(U)} record(s), more than a resume retries (${Nt}): only a full run masks them.`),F.clear(e.orgId,e.templateId),!1):(F.save({id:t,orgId:e.orgId,templateId:e.templateId,fingerprint:E,savedAt:new Date().toISOString(),objects:U,...N?{namesGiven:N.namesGiven()}:{},...R?{setId:R.setId}:{}}),!0)}catch(U){return this.deps.log(`[WARN] dataops:anonymize ${t}: where the run stopped was not kept: `+P(U)),!1}},ze=()=>{if(R){R.lastActivityAt=new Date().toISOString(),R.requestsSpent=B+A,this.sliceSets.save(R);try{new nt(this.deps.configStore).save({id:t,orgId:e.orgId,templateId:e.templateId,fingerprint:E,savedAt:new Date().toISOString(),objects:S.map(F=>F.progress),...N?{namesGiven:N.namesGiven()}:{},setId:R.setId})}catch(F){this.deps.log(`[WARN] dataops:anonymize ${t}: where the run is in set ${R.setId} was not kept: ${P(F)}`)}}};try{let F=this.deps.infraServices?.productionGuard;if(!F){this.refuseWithoutGuard((m,v)=>c.refused(m,v),t,l,u);return}if(!p){c.refused(Ts(e.templateId),{code:to});return}let V=ln(e,p,se)?Tn(e,p,!0):void 0,re=this.sliceSets,U=re.openFor(e.orgId,e.templateId);if(e.abandon===!0){await this.abandonSliceSet(U,e,c);return}let te=(m,v)=>sn(p.rules,m,k,v),Xe=(V?[g,V]:[g]).flatMap(m=>[te(m),...U?[te(m,U.size)]:[]]),Be=m=>c.refused(new Error(m??"There is nothing to resume: the run has finished since, another run of this template has stopped since, its rules have changed, or the slices it masked expired. Apply masks every record of its objects."),{code:ui}),Je=(m,v)=>{be(this.deps,{...u,outcome:"stopped",source:void 0,code:m}),c.refused(new Error(v),{code:m}),pe(this.deps,t,v,!1,{context:l,authored:!0})},me;if(e.resumeFrom!==void 0){let m=new nt(this.deps.configStore);if(me=Xe.map(v=>m.load(e.orgId,e.templateId,v)).find(v=>v?.id===e.resumeFrom),!me){Be();return}if(me.setId!==void 0&&me.setId!==U?.setId||me.setId===void 0&&e.slices===!0){Be(me.setId===void 0?"The run this one resumes was not in slices: it resumes as it ran, without slices, or Apply masks every record of its objects in slices. Nothing was masked.":void 0);return}}if(U&&me?.setId!==U.setId){Je(Re.runOpen,this.sliceRunOpenMessage(U,c.voice));return}let $e=me?.setId!==void 0?U?.size:e.slices===!0?this.backupCap():void 0;if(E=te(g,$e),$e!==void 0&&!this.backupRecords){Je(Re.needsStore,"A run in slices writes each slice to the backup files, and this host keeps none. Nothing was masked.");return}let Ve=this.maskingKey;if(me?.setId!==void 0&&U){if(Ve=await this.runKeys?.load(U.setId).catch(v=>{this.deps.log(`[WARN] dataops:anonymize: the key of set ${U.setId} was not read: `+P(v))})??this.maskingKey,U.keyCheck!==void 0&&fs(Ve)!==U.keyCheck){Je(Re.keyLost,this.sliceKeyLostMessage(U,c.voice));return}R=U,B=U.requestsSpent}let ae=await We(e.orgId,this.deps.orgRegistry,this.deps.orgManager),$=Cn(ae);if(V&&await Ss($,this.deps.log)&&(g=V,E=te(V,$e)),me&&me.fingerprint!==E){Be();return}let z,M=m=>{A++;let v=tt(ae.limitInfo,m);v&&v.usagePercent>=Os&&(z??=v)},de=()=>z,Ke=new Set;for(let m of g){let v=Ft(p,m),Q=dn(p,m);if(v.length===0&&Q.length===0)continue;let _=xe(m),L=jn(e,p,m);l.objectName=_;let T=me?.objects.find(Me=>Me.objectApiName===_),x={objectApiName:_,done:T?.done??!1,...T?.afterId!==void 0?{afterId:T.afterId}:{},refused:[...T?.refused??[]],...T?.unconfirmed?.length?{unconfirmed:[...T.unconfirmed]}:{},...T?.slice?{slice:{...T.slice}}:{}},ye=0,J=async Me=>{try{let Y=await this.countRows(ae,_,Me,L);return M(`dataops:anonymize count ${_}`),Y}catch(Y){let ge=$e!==void 0&&Me===void 0&&L===void 0?await this.approximateCount(ae,_,Y):void 0;if(ge!==void 0)return Ke.add(_),ge;throw be(this.deps,{...u,outcome:"failure",source:void 0,objects:[gn(_)],code:fi,details:{reason:Pn(Y)}}),this.countGaveUp(Y,_)}},Te=R?.objects.find(Me=>Me.objectApiName===_);Te?(ye=Ii(Te),Te.done||(ye+=await J(Mn(Te))),x.done=ye===0):x.done||(ye=await J(x.afterId),ye===0&&(x.done=!0));let St=ye+x.refused.length+(x.unconfirmed?.length??0),mt={objectApiName:_,total:St,masked:0,nothingToMask:0,refused:0,unanswered:0,done:St===0};f.push(mt),S.push({objectName:m,...L!==void 0?{where:L}:{},objectRules:v,personRules:Q,tally:mt,progress:x})}let Ne=f.reduce((m,v)=>m+v.total,0),Le=await this.maskingNotCovered($,p,g,S);if(Le){be(this.deps,{...u,outcome:"stopped",source:void 0,code:Le.code}),c.refused(new Error(Le.message),{code:Le.code,extraPayload:{...Le.gaps}}),pe(this.deps,t,Le.message,!1,{context:l,authored:!0});return}let pn=await vs($,S.filter(m=>m.tally.total>0).map(m=>({objectApiName:m.tally.objectApiName,rules:[...m.objectRules,...m.personRules]})));if(pn.length>0){let m=bn(pn);this.deps.log(`[WARN] CRUD/FLS check failed for anonymize ${t}: ${m}`),be(this.deps,{...u,outcome:"stopped",source:void 0,code:xt}),c.refused(new Error(m),{code:xt}),pe(this.deps,t,m,!1,{context:l,authored:!0});return}let it=(m,v,Q=[])=>{be(this.deps,{...u,outcome:"stopped",source:void 0,code:m}),c.refused(new Error(v),{code:m,...os({alsoRefused:Q})}),pe(this.deps,t,v,!1,{context:l,authored:!0})};if(e.snapshot===!0&&$e===void 0){let m=this.backupCap();if(S.some(v=>v.tally.total>m)){it(on,`Nothing was masked: ${S.filter(v=>v.tally.total>m).map(v=>`${v.tally.objectApiName} holds ${v.tally.total} record(s)`).join(", ")}, more than the ${m} a snapshot holds of one object. `+this.snapshotCapWay(S,c.voice));return}}if($e!==void 0){let m=await this.sliceRunPlan($,S,$e,this.pageSizeFor(e.orgId));if(m.tooMany.length>0){it(Re.tooMany,this.tooManySlicesMessage(m,$e));return}let v=await this.freeBytes();if(v!==void 0&&Sn(m.diskBytes)>v){it(Re.diskShort,this.diskShortMessage(Sn(m.diskBytes),v,!0));return}}let at=await this.readAct(ae,e.orgId,"masking",f.map(m=>({objectApiName:m.objectApiName,records:m.total})),c.accord,c.voice),yt=yn(at.answer);if(yt){it(yt.code,yt.message,yt.alsoRefused);return}let dt=ts(at.answer.automation,f.filter(m=>m.total>0).map(m=>m.objectApiName)),ct=()=>this.duplicatesWatchOf(ae,dt),Oe=ct();we=Oe;let At=this.deps.orgManager.getOrg(e.orgId),Kt={orgId:e.orgId,orgTier:Rs(At),operation:"update",objectName:g.join(", ")||"AnonymizeData",recordCount:Ne,module:"dataops"},{check:jt,decision:lt}=await Zn(F,Kt);if(u.guard=lt,(lt==="refused"||lt==="declined")&&be(this.deps,{...u,outcome:"stopped",source:void 0}),lt==="refused")throw Hn(jt.blockedReason??jt.impactSummary);if(lt==="declined"){let m="Operation cancelled by user (confirmation declined).";c.refused(new Error(m),{code:Kn.declined}),pe(this.deps,t,m,!1,{context:l,authored:!0});return}for(let m of jt.warnings)this.deps.log(`[WARN] dataops:anonymize ${t}: ${m}`);if(X.signal.aborted){await ot();return}let ce=await rs(at,t,c.accord.acceptEmails===!0,c.voice);if("refused"in ce){it(ce.refused.code,ce.refused.message);return}if(r=ce.held,j=!0,$e!==void 0){let m=`backup:${e.orgId}`;if(this.activeOrgOperations.has(m)){it(Is,this.busyMessage(e.orgId,`A backup or rollback operation is already running for org ${e.orgId}. Mask once it has ended.`));return}if(this.activeOrgOperations.add(m),G=!0,!R){let v=new Date().toISOString(),Q=await ae.soap.getServerTimestamp().then(L=>new Date(L.timestamp).toISOString()).catch(()=>v);A++;let _=await this.organizationIdOf(ae);A++,R={setId:t,kind:"masking",orgId:e.orgId,..._!==void 0?{organizationId:_}:{},templateId:e.templateId,fingerprint:E,size:$e,state:"open",startedAt:v,serverStartedAt:Q,lastActivityAt:v,requestsSpent:0,keyCheck:fs(Ve),objects:S.map(L=>({objectApiName:L.tally.objectApiName,...L.where!==void 0?{where:L.where}:{},done:L.tally.total===0,slices:[]}))},re.save(R),await this.runKeys?.save(R.setId,Ve).catch(L=>{this.deps.log(`[WARN] dataops:anonymize ${t}: the key of set ${t} was not kept, so only this window resumes it: ${P(L)}`)})}this.sliceRunsOn.set(e.orgId,R.setId)}let et=In(At?.orgType==="Sandbox"||At?.orgType==="Scratch"),De=An(et).defaultQueryLimit;if(e.snapshot===!0&&R===void 0){let m=await this.snapshotBeforeMasking($,t,e.orgId,S,{origin:c.origin,stop:X.signal});if("refused"in m&&X.signal.aborted){await ot();return}if("refused"in m){be(this.deps,{...u,outcome:"stopped",source:void 0,code:on}),c.refused(new Error(m.refused),{code:on}),await d(),pe(this.deps,t,m.refused,m.retryable,{context:l,authored:!0});return}if(D=m.taken,X.signal.aborted){await ot();return}}let Pe=c.pipeline?`Pipeline anonymization with ${p.name}`:`Anonymizing with ${p.name}`;Yt(this.deps,t,"dataops",Pe),y=!0,b=!0,this.deps.infraServices?.backgroundRegistry?.register(t,"dataops",Pe,new Promise((m,v)=>{Se=Q=>{Q===void 0?m():v(Q instanceof Error?Q:new Error(String(Q)))}}),X),Ge=rn(this.liveTracker,t,"dataops",Pe,Ne);let{AnonymizationEngine:Ht}=await import("./chunk-PZBZ7MNC.mjs"),le=new Ht(void 0,Ve);N=le,me&&!(me.namesGiven!==void 0&&le.continueFrom(me.namesGiven))&&this.deps.log(`[INFO] dataops:anonymize ${t}: the run it resumes kept no record of the names it made up, so this one may give again a name or an address that run gave.`);let He=[],Z=!1,qe=m=>m.masked+m.nothingToMask+m.refused+(m.deletedSince??0),ut,Ps=(m,v)=>{let Q=f.reduce((x,ye)=>x+qe(ye),0),_=Math.max(Ne,Q),L=Math.round(Q/_*100),T=`Anonymized ${m}${ut?` ${ut}`:""} (${qe(v)}/${Math.max(v.total,qe(v))})`;Mt(this.deps,t,L,Q,_,T),Ge?.progress(L,Q,_,T)},Ln=[],wo=async m=>{let v=R,Q=this.backupRecords,{safeObj:_,fields:L,tally:T,progress:x,writeBack:ye}=m,J=v?.objects.find(h=>h.objectApiName===_);if(!v||!Q||!J)throw new Error(`The set of slices holds no ${_}: nothing more was masked.`);let Te=po(_),St=L.split(",").length,mt=()=>({masked:T.masked,nothing:T.nothingToMask,refused:T.refused,gone:T.deletedSince??0}),Me=(h,w)=>{h.masked+=T.masked-w.masked,h.nothingToMask+=T.nothingToMask-w.nothing,h.deletedSince+=(T.deletedSince??0)-w.gone;let O=x.unconfirmed?.length??0;O>0?h.unanswered=O:delete h.unanswered},Y=async h=>{let w=[];for await(let O of await this.backupBatches(h.snapshotId,Te))for(let K of O)typeof K.Id=="string"&&w.push(K.Id);return w},ge=async(h,w)=>{w.length===0?await Q.delete(h.snapshotId,Te):(await Q.begin(h.snapshotId,Te),await Q.append(h.snapshotId,Te,w.map(O=>({Id:O})))),h.refused=w.length},Fe=async(h,w)=>{w.length!==0&&(await Q.append(h.snapshotId,Te,w.map(O=>({Id:O}))),h.refused+=w.length)},Ae=J.slices.find(h=>h.state==="masking")??J.slices.at(-1);if(Ae){Ae.masked+=T.masked,Ae.nothingToMask+=T.nothingToMask,Ae.deletedSince+=T.deletedSince??0,await Fe(Ae,x.refused),x.refused=[];let h=x.unconfirmed?.length??0;h>0?Ae.unanswered=h:delete Ae.unanswered}for(let h of J.slices){if(h.refused===0)continue;let w=await Y(h),O=[...w],K=[];for(let oe=0;oe<w.length;oe+=rt){if(X.signal.aborted)return Z=!0,"stopped";if(de())return"stopped";let ue=w.slice(oe,oe+rt),Ie=await Et(ae,`SELECT ${L} FROM ${_} WHERE Id IN (${ue.map(qt=>`'${qt}'`).join(", ")})`);M(`dataops:anonymize query ${_}`);let he=ue.length-Ie.length;h.deletedSince+=he,T.deletedSince=(T.deletedSince??0)+he;let _e=mt(),H=[],ne=!1;try{ne=await ye(Ie,(qt,Fn)=>H.push(...Fn),(qt,Fn)=>{x.unconfirmed=[...x.unconfirmed??[],...Fn]})}finally{Me(h,_e),O=O.slice(ue.length),K.push(...H),await ge(h,[...K,...ne?ue:[],...O]),ze()}if(ne)return"stopped"}}let Ee=async h=>{let w=new Set;for(let O of J.slices)if(!(O!==h&&O.lateOf!==h.index)&&O.state!=="pending")for await(let K of await this.backupBatches(O.snapshotId,_))for(let oe of K)typeof oe.Id=="string"&&w.add(oe.Id);return w},fe=async h=>{let w=x.slice?.index===h.index?x.afterId:void 0,O=w===void 0;for await(let K of await this.backupBatches(h.snapshotId,_)){let oe=K;if(!O){let H=oe.findIndex(ne=>ne.Id===w);if(H<0)continue;O=!0,oe=oe.slice(H+1)}if(oe.length===0)continue;if(X.signal.aborted)return Z=!0,!0;if(de())return!0;let ue=mt(),Ie=[],he=H=>{let ne=H[H.length-1]?.Id;typeof ne=="string"&&un.test(ne)&&(x.afterId=ne)},_e=!0;try{_e=await ye(oe,(H,ne)=>{Ie.push(...ne),he(H)},(H,ne)=>{x.unconfirmed=[...x.unconfirmed??[],...ne],he(H)}),_e||he(oe)}finally{Me(h,ue),await Fe(h,Ie)}if(_e)return!0}if(!O)throw new Error(`The snapshot of slice ${h.index} of ${_} no longer holds the row the run stopped at: it is not the file the slice was masked from, and nothing more of it was masked.`);return!1};for(;;){if(X.signal.aborted)return Z=!0,"stopped";if(de())return"stopped";let h=J.slices.find(w=>!Bt(w));if(!h){let w=J.slices.find(_e=>!_e.late&&(_e.lateLeft??0)>0);if(!w&&J.done)break;let O=J.slices.filter(_e=>!_e.late),K=O.at(-1)?.sizeUsed??v.size,oe=Math.max(1,Math.min(K,T.total-qe(T))),ue=Dr(oe,De,{masking:!0,duplicateRule:Oe.covers(_)}),Ie=this.sliceBudgetStop(ae,e.maxRequests,A,ue,c.voice);if(Ie)return C={budget:!0,message:Ie},"stopped";if(!w&&O.length>=ht)return C={code:Re.tooMany,message:`${_} holds more rows than ${ht} slices of ${K} do, as it grew during the run: the run stopped between two slices.`},"stopped";let he=as(v);h={index:he,...w?{late:!0,lateOf:w.index,...(w.lateAfterId??w.afterId)!==void 0?{afterId:w.lateAfterId??w.afterId}:{}}:Mn(J)!==void 0?{afterId:Mn(J)}:{},rows:0,snapshotId:is(v.setId,he),state:"pending",masked:0,refused:0,deletedSince:0,nothingToMask:0,sizeUsed:K},J.slices.push(h),ze()}if(h.state==="pending"){let w=h.late===!0?J.slices.find(ne=>ne.index===h?.lateOf):void 0,O=await this.freeBytes(),K=Sn(h.sizeUsed*(48+64*St));if(O!==void 0&&K>O)return J.slices=J.slices.filter(ne=>ne!==h),ze(),C={code:Re.diskShort,message:this.diskShortMessage(K,O)},"stopped";let oe=w?{...h.afterId!==void 0?{afterId:h.afterId}:{},...w.lastId!==void 0?{untilId:w.lastId}:{},createdSince:w.readSince??v.serverStartedAt??v.startedAt}:h.afterId!==void 0?{afterId:h.afterId}:{},ue=w?await Ee(w):void 0,Ie=Rn(Math.max(T.total,qe(T)),h.sizeUsed);ut=`slice ${h.index} of about ${Math.max(Ie,h.index)}`;let he=f.reduce((ne,qt)=>ne+qe(qt),0),_e=`Backing up ${_} ${ut}`;Mt(this.deps,t,Math.round(he/Math.max(Ne,he,1)*100),he,Math.max(Ne,he),_e);let H=await this.snapshotSlice(ae,e.orgId,v,J,h,{select:L,bounds:oe,...ue?{skip:ne=>ue.has(String(ne.Id))}:{},stop:X.signal,onRequest:()=>{A++},origin:c.origin});if("failed"in H)return J.slices=J.slices.filter(ne=>ne!==h),ze(),H.cancelled?(Z=!0,"stopped"):(C={code:H.code,message:this.sliceNotTakenMessage(_,H)},"stopped");if(H.lastId===void 0){await this.removeBackup(`backup:${h.snapshotId}`),J.slices=J.slices.filter(ne=>ne!==h),w?(delete w.lateLeft,delete w.lateAfterId,H.readSince&&(w.readSince=H.readSince)):J.done=!0,ze();continue}h.rows=H.rows,h.lastId=H.lastId,h.sizeUsed=H.sizeUsed,h.takenAt=new Date().toISOString(),H.readSince&&(h.readSince=H.readSince),w&&(H.read<H.sizeUsed?(delete w.lateLeft,delete w.lateAfterId,H.readSince&&(w.readSince=H.readSince)):w.lateAfterId=H.lastId),h.state="masking",x.slice={setId:v.setId,index:h.index},delete x.afterId,ze()}if(ut??=`slice ${h.index}`,await fe(h))return"stopped";Ln.push(h.index),ut=void 0,h.state="masked",delete h.unanswered,ee=ns(ee,await Oe.read()),Oe=ct(),we=Oe,le.forgetRecords(),delete x.slice,delete x.afterId,ze()}return T.done=!0,x.done=!0,"done"};for(let{objectName:m,where:v,objectRules:Q,personRules:_,tally:L,progress:T}of S){if(L.total===0)continue;if(X.signal.aborted){Z=!0;break}if(de())break;let x=L.objectApiName;l.objectName=x;let{select:ye,rulesOf:J}=await this.maskedFields($,x,this.maskingRules(m,Q,Ve),this.maskingRules(m,_,Ve));l.batchSize=rt;let Te=async(Y,ge,Fe)=>{let Ae=Y.map(J),Ee=Y.map((h,w)=>le.anonymize([h],Ae[w])[0]),fe=[];Y.forEach((h,w)=>{let O={Id:h.Id};for(let K of Ae[w])Yn(h[K.fieldApiName])&&(O[K.fieldApiName]=Ee[w][K.fieldApiName]);Object.keys(O).length>1?fe.push(O):L.nothingToMask++});for(let h=0;h<fe.length;h+=rt){if(X.signal.aborted)return Z=!0,!0;if(de())return!0;let w=fe.slice(h,h+rt),O;Oe.beforeWrite(x);try{O=await ae.sobject(m).update(w,{headers:Wn()})}catch(ue){throw Jn(ue)==="may-have-written"&&(L.unanswered+=w.length,Fe(w,w.flatMap(pi)),Oe.wrote(x,w.map(Ie=>Ie.Id))),ue}M(`dataops:anonymize update ${x}`);let K=[],oe=Array.isArray(O)?O:[O];Oe.wrote(x,oe.flatMap((ue,Ie)=>ue.success?[w[Ie]?.Id]:[])),oe.forEach((ue,Ie)=>{if(ue.success){L.masked++;return}if(R&&Ai(ue.errors)){L.deletedSince=(L.deletedSince??0)+1;return}L.refused++;let he=w[Ie]?.Id;typeof he=="string"&&un.test(he)&&K.push(he),Jr(He,x,ue.errors)}),ge(w,K),Ps(m,L)}return fe.length===0&&Ps(m,L),!1},St=T.unconfirmed??[];for(let Y=0;Y<St.length;Y+=rt){if(X.signal.aborted){Z=!0;break}if(de())break;let ge=St.slice(Y,Y+rt),Fe=ge.map(O=>`'${O.id}'`).join(", "),Ae=await Et(ae,`SELECT ${ye} FROM ${x} WHERE Id IN (${Fe})`);M(`dataops:anonymize query ${x}`);let Ee=new Map(Ae.map(O=>[String(O.Id),O])),fe=[];for(let O of ge){let K=Ee.get(O.id);K===void 0?L.total-=1:bs(K,O.fields)===O.digest?L.nothingToMask++:fe.push(O.id)}let h=new Set(ge.map(O=>O.id)),w=(T.unconfirmed??[]).filter(O=>!h.has(O.id));w.length>0?T.unconfirmed=w:delete T.unconfirmed,T.refused.push(...fe)}if(Z||de())break;let mt=[...T.refused];for(let Y=0;Y<mt.length;Y+=rt){if(X.signal.aborted){Z=!0;break}if(de())break;let ge=mt.slice(Y,Y+rt),Fe=await Et(ae,`SELECT ${ye} FROM ${x} WHERE Id IN (${ge.map(h=>`'${h}'`).join(", ")})`);M(`dataops:anonymize query ${x}`),L.total-=ge.length-Fe.length;let Ae=[];if(await Te(Fe,(h,w)=>Ae.push(...w),(h,w)=>{let O=new Set(w.map(K=>K.id));T.refused=T.refused.filter(K=>!O.has(K)),T.unconfirmed=[...T.unconfirmed??[],...w]}))break;let fe=new Set(ge);T.refused=[...T.refused.filter(h=>!fe.has(h)),...Ae]}if(Z||de())break;if(R){if(await wo({objectName:m,safeObj:x,fields:ye,tally:L,progress:T,writeBack:Te})!=="done")break;continue}if(T.done){L.done=!0;continue}let Me=T.afterId;for(;;){if(X.signal.aborted){Z=!0;break}if(de())break;let Y=await ao(ae,x,ye,De,Me,v);if(M(`dataops:anonymize query ${x}`),Y.records.length===0){L.done=!0,T.done=!0;break}let ge=Y.truncated?yi(Y.records,Me,x):void 0;if(X.signal.aborted){Z=!0;break}let Fe=Ee=>{let fe=Ee[Ee.length-1]?.Id;typeof fe=="string"&&un.test(fe)&&(T.afterId=fe)};if(await Te(Y.records,(Ee,fe)=>{T.refused.push(...fe),Fe(Ee)},(Ee,fe)=>{T.unconfirmed=[...T.unconfirmed??[],...fe],Fe(Ee)}))break;if(ge===void 0){L.done=!0,T.done=!0;break}Me=ge,T.afterId=ge}if(Z||de())break}if(R){!Z&&!de()&&!C&&(W=await this.countLateRows(ae,R,()=>{A++}));for(let m of f){let v=R.objects.find(_=>_.objectApiName===m.objectApiName),Q=m.done&&v?ds({objects:[v]}):0;Q>0&&(m.late=Q)}if(_t(f).recordsNotMasked===0&&R.objects.every(m=>m.done&&(m.tailLeft??0)===0&&m.slices.every(v=>Bt(v)&&v.refused===0&&(v.lateLeft??0)===0))&&(R.state="done"),$t(R).length===0&&R.state==="open"?(R.state="abandoned",this.sliceSets.delete(R.setId)):ze(),R.state!=="open"){let m=R.setId;await this.runKeys?.delete(m).catch(v=>{this.deps.log(`[WARN] dataops:anonymize ${t}: the key of set ${m} was not removed: ${P(v)}`)})}}let It=de(),pt=gi(f,Z),{recordsProcessed:Rt,recordsFailed:Ct,recordsNotMasked:ft}=_t(f),Ms=ro(f);y=!1,be(this.deps,{...u,...hi(f,pt,Z),objects:io(f),...R?{details:{setId:R.setId,sliceSize:R.size,...Ln.length>0?{slices:Ln.join(",")}:{}}}:{}});let Es=Ut();if(ft>0){let m=Z?"cancelled":It?`stopped at ${It.usagePercent}% of the org's API requests`:"refused by the org";this.deps.log(`[WARN] dataops:anonymize ${t} ${m}: ${ft} record(s) not masked \u2014 ${Ms}`)}await d();let Dn=await Ce();Z?(this.deps.infraServices?.backgroundRegistry?.abort(t),Qe(this.deps,t,{aborted:!0,totalProcessed:Rt,totalFailed:Ct,totalNotMasked:ft}),Ge?.cancel()):(Qe(this.deps,t,{status:pt,totalProcessed:Rt,totalFailed:Ct,totalNotMasked:ft}),pt==="failure"?Ge?.fail(`The org refused the ${Ct} record(s)`):pt==="partial"?Ge?.partial():Ge?.complete());let xs=`${ft} still hold their original values (${Ms})`,yo=Z?`Anonymization cancelled: ${Rt} masked before the cancel \u2014 ${xs}.`:It?`Anonymization stopped at ${It.usagePercent}% of the org's daily API requests (${It.apiUsage} of ${It.apiLimit}): ${Rt} masked \u2014 ${xs}. ${Es?"Resume it":"Run it again"} once the org has requests to spare.`:Ct===0?`Anonymization ${pt==="success"?"completed":pt}: ${Rt} records processed.`:`Anonymization ${pt}: ${Rt} masked, ${Ct} rejected by the org \u2014 those records still hold their original values.`,Ao=Es&&ft>0?" Resume masks only what this run left.":"",zs=Zt(Dn,this.orgNameOf(e.orgId)),Bs=R?this.slicesSentence(R,C,c.voice,ft>0,W):"",Io=yo+(Bs?` ${Bs}`:Ao)+(zs?` ${zs}`:"");c.ended({templateId:e.templateId,status:pt,recordsProcessed:Rt,recordsFailed:Ct,recordsNotMasked:ft,objects:oo(f),message:Io,errors:He,...Z?{cancelled:!0}:{},...It?{stoppedAtApiLimit:!0}:{},...D?{snapshot:D}:{},...r?{mutedAutomation:r.outcome}:{},...Dn?{duplicates:Dn}:{},...R?{slices:en(R,{requestsSpent:A,stoppedOnBudget:C?.budget===!0})}:{}})}catch(F){await d();let V=await Ce().catch(()=>{});wt(F,!0,V)}finally{let F=await d();if(F&&c.muted?.(F),y){let V=f.some(re=>re.masked>0);be(this.deps,{...u,outcome:V?"partial":"failure",objects:j?io(f):[]})}if(b&&!I){try{ze()}catch(V){this.deps.log(`[WARN] dataops:anonymize ${t}: its set of slices was not kept: `+P(V))}Ut()}G&&(this.activeOrgOperations.delete(`backup:${e.orgId}`),this.sliceRunsOn.delete(e.orgId)),Se(kt),ve?.release(),s?.removeEventListener("abort",Ze),o.answer?.(F)}}handleAnonymizationTemplates(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=this.listedTemplates(),n=ke(this.deps,e,"dataops:anonymization-templates:response",{templates:t});this.deps.broker.postToWebview(n),this.deps.log("[TX] dataops:anonymization-templates:response")}listedTemplates(){return[...tn,...this.savedTemplates.list()]}async handleBackupObjects(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=je(nr,e,"dataops:error",this.deps);if(!t)return;let n=t.templateId!==void 0?this.findTemplate(t.templateId):void 0;if(t.templateId!==void 0&&!n){this.refuseUnknownTemplate("backup:objects",e,t.templateId);return}try{let s,r=()=>s??=We(t.orgId,this.deps.orgRegistry,this.deps.orgManager).then(d=>Ss(d,this.deps.log)),o=[];for(let d of n?[n]:this.listedTemplates()){let c=ln({},d,se)&&await r();for(let l of Tn({},d,c))l!==""&&l!=="*"&&!o.includes(l)&&o.push(l)}let a=ke(this.deps,e,"backup:objects:response",{objects:o});this.deps.broker.postToWebview(a),this.deps.log(`[TX] ${a.type} id=${a.id} objects=${o.length}`)}catch(s){q(this.deps,"backup:objects","dataops:error",e,s)}}async plannedObjectsIn(e,t,n){let s=ln(t,n,se)&&await Ss(e,this.deps.log);return Tn(t,n,s)}async handleAnonymizeCoverage(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=je(ar,e,"dataops:error",this.deps);if(!t)return;let n=this.findTemplate(t.templateId);if(!n){this.refuseUnknownTemplate("dataops:anonymize:coverage",e,t.templateId);return}try{let s=this.latestBackup(t.orgId),r=await We(t.orgId,this.deps.orgRegistry,this.deps.orgManager),o=[],a=await this.plannedObjectsIn(r,t,n),d=[];for(let S of a){if(!eo(n,S))continue;let k=xe(S),E=jn(t,n,S),j=null,y;try{j=await this.countRows(r,k,void 0,E)}catch(N){this.deps.log(`[WARN] dataops:anonymize:coverage: ${k} not counted: ${P(N)}`),y=await this.approximateCount(r,k,N)}d.push({objectName:S,...j!==null?{rows:j}:y!==void 0?{rows:y}:{},...j===null&&y!==void 0?{approximate:!0}:{}});let b=s?.objects.find(N=>N.objectApiName.toLowerCase()===k.toLowerCase()),I=b?.where!==void 0&&b.where!==E;o.push({objectApiName:k,count:j,backedUp:I?0:b?.recordCount??0,truncated:!I&&b?.truncated===!0,...b?.stoppedAt&&!I?{stoppedAt:b.stoppedAt}:{},...I?{filtered:!0}:{}})}let c=this.sliceSets.openFor(t.orgId,t.templateId),l=c?.size??this.backupCap(),p;if(t.slices===!0||c!==void 0||d.some(S=>(S.rows??0)>this.backupCap())){let S=Cn(r),k=[];for(let y of d){if(y.rows===void 0)continue;let b=Ft(n,y.objectName),I=dn(n,y.objectName),N=await this.maskedFields(S,xe(y.objectName),this.maskingRules(y.objectName,b),this.maskingRules(y.objectName,I)).then(({select:D})=>D.split(",").length,()=>b.length+I.length+1);k.push({objectApiName:xe(y.objectName),rows:y.rows,fields:N,...y.approximate?{approximate:!0}:{}})}let E=ls(k,l,this.pageSizeFor(t.orgId),"masking");for(let y of o){let b=E.objects.find(I=>I.objectApiName===y.objectApiName);b&&(y.slicePlan=b)}let j=await this.freeBytes();p={requests:E.requests,parts:E.parts,bulkBatches:0,diskBytes:E.diskBytes,...j!==void 0?{diskFree:j}:{},seconds:E.seconds,apiBudget:await this.apiBudgetFor(r,E.requests)}}let g=new nt(this.deps.configStore),u=(c?g.load(t.orgId,t.templateId,sn(n.rules,a,zn(t),c.size)):void 0)??g.load(t.orgId,t.templateId,sn(n.rules,a,zn(t))),f=ke(this.deps,e,"dataops:anonymize:coverage:response",{templateId:t.templateId,...s?{backup:{operationId:s.operationId,timestamp:s.timestamp}}:{},objects:o,...u?{checkpoint:{id:u.id,savedAt:u.savedAt}}:{},...p?{plan:p}:{},...c?{sliceSet:jr(c)}:{}});this.deps.broker.postToWebview(f),this.deps.log(`[TX] ${f.type} id=${f.id} objects=${o.length}`)}catch(s){q(this.deps,"dataops:anonymize:coverage","dataops:error",e,s)}}async handleAnonymizePreview(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=je(dr,e,"dataops:error",this.deps);if(!t)return;let n=this.findTemplate(t.templateId);if(!n){this.refuseUnknownTemplate("dataops:anonymize:preview",e,t.templateId);return}try{let s=await We(t.orgId,this.deps.orgRegistry,this.deps.orgManager),{AnonymizationEngine:r}=await import("./chunk-PZBZ7MNC.mjs"),o=new r(void 0,this.maskingKey),a=[],d=[],c=Cn(s);for(let p of await this.plannedObjectsIn(s,t,n)){if(!eo(n,p))continue;let g=xe(p);try{let u=Ft(n,p),f=dn(n,p),{rules:S,select:k,missing:E,rulesOf:j}=await this.maskedFields(c,g,this.maskingRules(p,u),this.maskingRules(p,f)),y=await ao(s,g,k,no,void 0,jn(t,n,p));tt(s.limitInfo,`dataops:anonymize:preview ${g}`);let b=y.records.length>0;b&&d.push(...E.map(A=>({objectApiName:g,fieldApiName:A})));let[I]=b?await vs(c,[{objectApiName:g,rules:[...u,...f]}]):[],N=y.records.map(j),D=y.records.map((A,B)=>o.anonymize([A],N[B])[0]),R=S.map(A=>A.fieldApiName).filter((A,B,C)=>A!=="Id"&&C.indexOf(A)===B);a.push({objectApiName:g,fields:R,...b&&S.length===0?{notCovered:!0}:{},...I?{writeDenied:{deniedFields:[...I.deniedFields]}}:{},methods:Object.fromEntries(S.map(A=>[A.fieldApiName,A.method])),rows:y.records.slice(0,no).map((A,B)=>{let C={},ee={},G=new Set(N[B].map(W=>W.fieldApiName));for(let W of R)C[W]=so(A[W]),ee[W]=Yn(A[W])&&G.has(W)?so(D[B][W]):C[W];return{id:String(A.Id??""),before:C,after:ee}})})}catch(u){let f=P(u);this.deps.log(`[WARN] dataops:anonymize:preview: ${g} not read: ${f}`),a.push({objectApiName:g,fields:[],rows:[],error:f})}}let l=ke(this.deps,e,"dataops:anonymize:preview:response",{templateId:t.templateId,objects:a,fieldsNotFound:d});this.deps.broker.postToWebview(l),this.deps.log(`[TX] ${l.type} id=${l.id} objects=${a.length}`)}catch(s){q(this.deps,"dataops:anonymize:preview","dataops:error",e,s)}}latestBackup(e){let t;for(let n of this.deps.configStore.getKeysByPrefix("backup:")){let s=n.slice(7);if(s.includes(":"))continue;let r=this.deps.configStore.get(n);if(r?.orgId!==e||r.origin==="slice")continue;let o=r.timestamp??"";t&&t.timestamp.localeCompare(o)>=0||(t={operationId:s,timestamp:o,objects:r.objects??[]})}return t}handleTemplateSave(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=je(cr,e,"dataops:error",this.deps);if(t)try{let n=t.name.trim();if([...tn,...this.savedTemplates.list()].some(a=>a.name.trim().toLowerCase()===n.toLowerCase())){q(this.deps,"dataops:anonymization-template:save","dataops:error",e,new Error(`A template named "${n}" already exists. Pick another name.`),{code:"DUPLICATE_NAME"});return}let r={id:`tpl-saved-${crypto.randomUUID()}`,name:n,description:"",complianceFramework:"custom",rules:t.rules.map(a=>({...a,description:""})),saved:!0,createdAt:new Date().toISOString()};this.savedTemplates.save(r);let o=ke(this.deps,e,"dataops:anonymization-template:save:response",{template:r});this.deps.broker.postToWebview(o),this.deps.log(`[TX] ${o.type} id=${o.id}`)}catch(n){q(this.deps,"dataops:anonymization-template:save","dataops:error",e,n)}}handleTemplateDelete(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=je(lr,e,"dataops:error",this.deps);if(!t)return;let{templateId:n}=t;if(tn.some(s=>s.id===n)){q(this.deps,"dataops:anonymization-template:delete","dataops:error",e,new Error(`Template "${n}" ships with SandForge and cannot be deleted.`),{code:"BUILT_IN"});return}try{let s=this.savedTemplates.delete(n),r=ke(this.deps,e,"dataops:anonymization-template:delete:response",{templateId:n,deleted:s});this.deps.broker.postToWebview(r),this.deps.log(`[TX] ${r.type} id=${r.id}`)}catch(s){q(this.deps,"dataops:anonymization-template:delete","dataops:error",e,s)}}async handlePIIScan(e){this.deps.log(`[RX] ${e.type} id=${e.id}`);let t=je(ur,e,"dataops:error",this.deps);if(!t)return;let{orgId:n,objectNames:s}=t;try{if(!this.deps.infraServices?.piiDetector)throw new Error("PII Detector not available.");let r=await We(n,this.deps.orgRegistry,this.deps.orgManager),o=await Promise.all(s.map(async d=>{let c=xe(d),l=await r.describe(c);tt(r.limitInfo,`precheck:pii-scan describe ${c}`);let p=l.fields.map(u=>({apiName:u.name,label:u.label,type:u.type,length:u.length})),g=this.deps.infraServices.piiDetector.detectPII(d,p);return{objectName:d,piiFields:g.piiFields.map(u=>({fieldName:u.fieldApiName,piiType:u.classification,confidence:u.confidence}))}})),a=ke(this.deps,e,"precheck:pii-scan:response",{success:!0,results:o});this.deps.broker.postToWebview(a)}catch(r){this.deps.log(`[ERR] precheck:pii-scan: ${P(r)}`);let o=ke(this.deps,e,"precheck:pii-scan:response",{success:!1,error:P(r)});this.deps.broker.postToWebview(o)}}};export{tn as a,$n as b,An as c,In as d,Nn as e,cs as f,On as g,rn as h,ks as i,Sn as j,us as k,Pi as l,Mi as m,oi as n,an as o,fo as p};
|
package/lib/chunk-LC3NDW4N.mjs
DELETED
|
@@ -1,7 +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{nc as P,rc as v,uc as S}from"./chunk-KB4ZHM4Q.mjs";import{a as h,b as E}from"./chunk-VV3B6IC3.mjs";import{b as R}from"./chunk-CA5NAXSU.mjs";import{Rd as m,be as A,ee as c}from"./chunk-PMWAFDUB.mjs";import{b,f,k as w,l as p}from"./chunk-WZQEK4WT.mjs";var k="Messaging.reserveSingleEmailCapacity(1);",M="System.NoAccessException: The organization is not permitted to send email",x=`/tooling/executeAnonymous?anonymousBody=${encodeURIComponent(k)}`,I=`/query?q=${encodeURIComponent("SELECT PermissionsEmailSingle FROM UserPermissionAccess")}`,L=3e4,$=p({compiled:f(),success:f(),compileProblem:b().nullish(),exceptionMessage:b().nullish()}).loose(),O=p({records:w(p({PermissionsEmailSingle:f().optional()}).loose())}).loose(),V={reading:{unread:"SandForge runs no Apex in a production org"},requests:0};function U(e){return e%1e3===0?`${e/1e3} s`:`${e} ms`}function T(e,n){return e instanceof h?`the org did not answer within ${U(n)}`:`the org refused it: ${R(e)}`}function _(e){let n=$.safeParse(e);if(!n.success)return{unread:"its answer is not one anonymous Apex gives"};let{compiled:r,success:s,compileProblem:t,exceptionMessage:i}=n.data;if(!r)return{unread:`it did not compile${t?`: ${t}`:""}`};if(s)return{level:"all"};let a=i?.trim();return a===M?{refused:!0}:{unread:a?`the org answered: ${a}`:"it failed, and the org did not say why"}}async function Y(e,n={}){let r=n.timeoutMs??L,s=u=>new E(r).withTimeout("forge:deliverability",()=>e.request({method:"GET",url:u})),t;try{t=await s(x)}catch(u){return{reading:{unread:T(u,r)},requests:1}}let i=_(t);if(!("refused"in i))return{reading:i,requests:1};let a="so the org's refusal does not say how it is set",d;try{d=await s(I)}catch(u){return{reading:{unread:`whether the user the run writes as may send email could not be read (${T(u,r)}), ${a}`},requests:2}}let l=O.safeParse(d),o=l.success?l.data.records[0]?.PermissionsEmailSingle:void 0;return o===!0?{reading:{level:"withheld"},requests:2}:{reading:{unread:o===!1?`the user the run writes as may not send email (Send Email), ${a}`:`the org did not say whether the user the run writes as may send email, ${a}`},requests:2}}async function F(e){let n=m(e.running,{applyAssignmentRules:e.applyAssignmentRules,writes:e.writes}),r=P(e.running.automation.unread??[],{applyAssignmentRules:e.applyAssignmentRules===!0}),s=r!==void 0?{sendersUnread:r}:{};if(n.length===0&&r===void 0)return{senders:n};let t;try{t=await e.read()}catch(i){t={reading:{unread:R(i)},requests:1}}return{senders:n,...s,read:t}}function N(e,n={}){if(e.cannotAssign===!0)return[];let r=i=>`${i.objectApiName}\0${i.kind}\0${i.name}`,s=m(c(e,void 0,n.writes),n),t=new Set(m(c(e,A(e,n.writes),n.writes),n).map(r));return s.filter(i=>!t.has(r(i)))}function q(e,n){let r=new Set([...n.assigned,...n.held]);return{assign:e.assign.filter(s=>r.has(s.permissionSet))}}var z=["flows","processes","workflowRules"];async function Q(e){let{plan:n,writes:r,applyAssignmentRules:s,read:t,target:i,run:a}=e,d=typeof t.unread=="string"?void 0:t,l=s===!0?{applyAssignmentRules:s}:{},o=await F({running:d?c(d,n,r):{automation:{objects:[],unread:z.map(y=>({part:y,reason:String(t.unread)}))},firing:[]},...l,writes:r,read:e.readDeliverability}),u=e.mayMute===!0&&n===void 0&&d!==void 0&&o.senders.length>0?N(d,{...l,writes:r}):[],g=o.read?.reading;return{ofRun:o,gate:v({senders:o.senders,...o.sendersUnread!==void 0?{sendersUnread:o.sendersUnread}:{},...g!==void 0?{reading:g}:{},accepted:e.accepted,target:i,run:a,muteQuiets:u,keepsAddresses:e.keepsAddresses===!0}),afterLease:(y,D)=>{if(!(n===void 0||d===void 0))return S({planned:o.senders,held:m(c(d,q(n,y),r),{...l,writes:r}),...g!==void 0?{reading:g}:{},accepted:D,target:i,run:a})}}}export{L as a,V as b,Y as c,F as d,N as e,q as f,Q as g};
|
package/lib/chunk-OM5NORJG.mjs
DELETED
|
@@ -1,7 +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 xe}from"./chunk-Q7GIJBCD.mjs";import{a as Pe,b as Te,c as je,d as Oe,f as Me}from"./chunk-M6P5ZZLE.mjs";import{Ba as Ve,Ca as Ue,Ha as Be,Ja as B,Ka as Qe,Ma as We,ca as De,ma as Le,oa as qe,qa as Ie,ua as U}from"./chunk-KB4ZHM4Q.mjs";import{b as E}from"./chunk-CA5NAXSU.mjs";import{$d as Ge,O as Fe,Q as ve,R as Ne,S as _e,T as Ae,U as Ce,V as Se,W as Ee,ja as $e}from"./chunk-PMWAFDUB.mjs";import{e as X,l as ee}from"./chunk-WZQEK4WT.mjs";var v=class extends Error{};function ct(e){let r=[],n=0;for(;n<e.length;){let t=e.slice(n),s=/^\s+/.exec(t);if(s){n+=s[0].length;continue}if(t.startsWith("/*")){let d=e.indexOf("*/",n+2);if(d<0)throw new v("an unclosed comment");n=d+2;continue}let l=t[0];if(l==="'"||l==='"'){let d=1;for(;d<t.length&&t[d]!==l;)d+=t[d]==="\\"?2:1;if(d>=t.length)throw new v("an unclosed text");r.push(t.slice(0,d+1)),n+=d+1;continue}let f=/^(?:\d+(?:\.\d+)?|[A-Za-z_$][A-Za-z0-9_$.]*)/.exec(t);if(f){r.push(f[0]),n+=f[0].length;continue}let p=/^(?:&&|\|\||==|!=|<>|<=|>=|[=<>+\-*/^&!(),])/.exec(t);if(!p)throw new v(`an unexpected character: ${t[0]}`);r.push(p[0]),n+=p[0].length}return r}var Ke=[new Set(["||"]),new Set(["&&"]),new Set(["=","==","<>","!=","<",">","<=",">="]),new Set(["+","-","&"]),new Set(["*","/"]),new Set(["^"])];function dt(e){let r=ct(e),n=0,t=()=>r[n],s=u=>{if(r[n]!==u)throw new v(`${u} expected`);n++},l=u=>{if(u>=Ke.length)return f();let o=l(u+1);for(let a=t();a!==void 0&&Ke[u].has(a);a=t())n++,o={kind:"binary",op:a,left:o,right:l(u+1)};return o},f=()=>{if(t()==="!")return n++,{kind:"not",arg:f()};if(t()==="-"||t()==="+"){let u=r[n++],o=f();return u==="-"?{kind:"negative",arg:o}:o}return p()},p=()=>{let u=r[n++];if(u===void 0)throw new v("the formula ends early");if(u==="("){let a=l(0);return s(")"),a}if(u.startsWith("'")||u.startsWith('"'))return{kind:"literal",value:`text:${u.slice(1,-1)}`};if(/^\d/.test(u))return{kind:"literal",value:`number:${Number(u)}`};if(!/^[A-Za-z_$]/.test(u))throw new v(`${u} out of place`);if(t()==="("){n++;let a=[];if(t()!==")")for(a.push(l(0));t()===",";)n++,a.push(l(0));return s(")"),{kind:"call",name:u.toUpperCase(),args:a}}let o=u.toUpperCase();return o==="TRUE"||o==="FALSE"||o==="NULL"?{kind:"literal",value:o.toLowerCase()}:{kind:"reference",name:u.toLowerCase()}},d=l(0);if(n!==r.length)throw new v(`${r[n]} out of place`);return d}function $(e){switch(e.kind){case"call":return e.name==="PRIORVALUE"&&e.args.length===1?$(e.args[0]):{...e,args:e.args.map($)};case"binary":return{...e,left:$(e.left),right:$(e.right)};case"not":case"negative":return{...e,arg:$(e.arg)};default:return e}}function N(e){switch(e.kind){case"call":return`${e.name}(${e.args.map(N).join(",")})`;case"binary":{let r=e.op==="=="?"=":e.op==="!="?"<>":e.op,n=[N(e.left),N(e.right)];return(r==="="||r==="<>")&&n.sort(),`(${n[0]} ${r} ${n[1]})`}case"not":return`NOT(${N(e.arg)})`;case"negative":return`-(${N(e.arg)})`;case"literal":return e.value;case"reference":return e.name}}var ze=e=>e==="true"?"false":e==="false"?"true":"unknown";function O(e){return e.kind==="call"&&e.name==="AND"?e.args.flatMap(O):e.kind==="binary"&&e.op==="&&"?[...O(e.left),...O(e.right)]:[e]}function M(e){return e.kind==="call"&&e.name==="OR"?e.args.flatMap(M):e.kind==="binary"&&e.op==="||"?[...M(e.left),...M(e.right)]:[e]}function te(e){if(e.kind==="not"){let r=te(e.arg);return{condition:r.condition,holds:!r.holds}}if(e.kind==="call"&&e.name==="NOT"&&e.args.length===1){let r=te(e.args[0]);return{condition:r.condition,holds:!r.holds}}return e.kind==="binary"&&(e.op==="<>"||e.op==="!=")?{condition:N({...e,op:"="}),holds:!1}:{condition:N(e),holds:!0}}function ne(e){if(e.kind==="literal"){if(e.value==="true")return"true";if(e.value==="false")return"false"}}function R(e){let r=ne(e);if(r)return r;if(e.kind==="not")return ze(R(e.arg));if(e.kind==="call")switch(e.name){case"ISCHANGED":return"false";case"ISNEW":return"true";case"NOT":return e.args.length===1?ze(R(e.args[0])):"unknown";case"AND":return He(O(e));case"OR":return Ze(M(e));case"IF":{if(e.args.length!==3)return"unknown";let[n,t,s]=e.args,l=R(n);if(l==="true")return R(t);if(l==="false")return R(s);let f=R(t);return f===R(s)?f:"unknown"}default:return"unknown"}return e.kind==="binary"?e.op==="&&"?He(O(e)):e.op==="||"?Ze(M(e)):ft(e):"unknown"}function He(e){let r=e.map(R);if(r.includes("false"))return"false";let n=new Map;for(let t of e){let{condition:s,holds:l}=te(t),f=n.get(s);if(f!==void 0&&f!==l)return"false";n.set(s,l)}return r.every(t=>t==="true")?"true":"unknown"}function Ze(e){let r=e.map(R);return r.includes("true")?"true":r.every(n=>n==="false")?"false":"unknown"}function ft(e){let r=e.op==="="||e.op==="==",n=e.op==="<>"||e.op==="!=";if(N(e.left)===N(e.right))return n||e.op==="<"||e.op===">"?"false":"unknown";if(!r&&!n)return"unknown";let t=ne(e.left)??R(e.left),s=ne(e.right)??R(e.right);return t==="unknown"||s==="unknown"?"unknown":t===s===r?"true":"false"}function Ye(e){try{return R($(dt(e)))==="false"}catch(r){if(r instanceof v)return!1;throw r}}var nt=25,W=20,ie=W*De,G=4,Je=10,pt=2e3,gt=.8,Xe=["validationRules","validationRuleFormulas","duplicateRules","duplicateRuleActions","userPermissions","permissionSets","targetFields","sourceFields","apiBudget"];function mt(e){return typeof e!="object"||e===null?null:{optional:e.optionalFilter===!0}}function Bt(e){return{name:e.name,type:String(e.type),createable:e.createable===!0,nillable:e.nillable!==!1,defaultedOnCreate:e.defaultedOnCreate===!0,referenceTo:(e.referenceTo??[]).filter(r=>typeof r=="string"),picklistValues:(e.picklistValues??[]).filter(r=>r?.active!==!1&&typeof r?.value=="string").map(r=>r?.value),lookupFilter:mt(e.filteredLookupInfo)}}function oe(e){return`SELECT Id, ValidationName, NamespacePrefix, ErrorDisplayField, ErrorMessage, EntityDefinition.QualifiedApiName FROM ValidationRule WHERE Active = true AND EntityDefinition.QualifiedApiName IN (${e.map(n=>`'${n}'`).join(", ")})`}function ht(e){return`SELECT QualifiedApiName, Label FROM FieldDefinition WHERE EntityDefinition.QualifiedApiName = '${x.test(e)?e:""}'`}function q(e){return`SELECT Metadata FROM ValidationRule WHERE Id = '${e}'`}var yt="SELECT DeveloperName, MasterLabel, NamespacePrefix, SobjectType FROM DuplicateRule WHERE IsActive = true",ae=/^[A-Za-z0-9]{15}([A-Za-z0-9]{3})?$/,x=/^[A-Za-z][A-Za-z0-9_]{0,79}$/,wt=ee({DailyApiRequests:ee({Max:X(),Remaining:X()}).loose()}).loose(),y=e=>typeof e=="string"?e:"";function le(e){if(typeof e!="object"||e===null)return;let r=e.QualifiedApiName;return typeof r=="string"&&r!==""?r:void 0}function Q(e,r){return e?`${e}__${r}`:r}function L(e){return typeof e=="string"?[e]:Array.isArray(e)?e.filter(r=>typeof r=="string"):[]}function bt(e){return{...e,nodes:e.nodes.map(r=>r.leftOutByUser===!0?{...r,included:!0}:r)}}function se(e,r){let n=y(e).trim(),t=n.slice(n.lastIndexOf(".")+1);if(x.test(t))return r?r.find(s=>s.name.toLowerCase()===t.toLowerCase())?.name:t}function rt(e){let r=Ve({filterFormula:e}).filter(t=>t.bypass).map(t=>t.name),n=Ue(e).map(t=>t.value===void 0?t.reference:`${t.reference} = '${t.value}'`);return{bypasses:[...r.map(t=>`$Permission.${t}`),...n],permissions:r}}function Rt(e,r={}){let n=r.maxRecordsPerObject,t=e.nodes.filter(d=>d.included),s=$e(r)?"atMost":"exact",l=t.map(d=>d.recordCountUnknown===!0?(n===void 0?s="unknown":s==="exact"&&(s="atMost"),{...d,recordCount:n??0}):{...d,recordCount:n===void 0?d.recordCount:Math.min(d.recordCount,n)}),f=new xe().generate({...e,nodes:l}).totalApiCalls,p=l.reduce((d,u)=>d+Math.max(1,Math.ceil(u.recordCount/pt)),0);return{writes:f,reads:p,bound:s}}function P(e){let{idValue:r,...n}=e;return{id:Fe(e.kind,e.objectApiName,e.field,e.recordType,r??e.value),source:"metadata",rows:0,...n}}function ue(e){return e?{field:e}:{}}function Qt(e){return async r=>Ie(await e.request({method:"POST",url:"/tooling/composite",body:JSON.stringify(qe(`/services/data/v${e.version}`,r)),headers:{"Content-Type":"application/json"}}),r.length)}async function kt(e,r,n){let t=e.filter(({id:s})=>ae.test(s));t.length!==0&&await U(r,[{queries:t.map(({id:s,rule:l})=>({soql:q(s),retrieve:{sobject:"ValidationRule",id:s},take:f=>{let p=f[0]?.Metadata,d=typeof p=="object"&&p!==null?p.errorConditionFormula:void 0;typeof d=="string"&&Ye(d)&&(l.onChangeOnly=!0)},refused:()=>{}})),requests:W}],G,n)}async function Ft(e,r,n,t,s){let l=[...new Set(r)].filter(m=>x.test(m));if(l.length===0)return[];let f=new Map(l.map(m=>[m.toLowerCase(),m])),p=new Map(l.map((m,b)=>[m,b])),d=await e(oe(l)),u=new Map,o=async(m,b)=>{let k=se(b,void 0);if(!n)return k;let F=u.get(m);F||(F=n(m).catch(()=>[]),u.set(m,F));let C=y(b).trim().toLowerCase();if(!C)return;let _=k?.toLowerCase(),S=await F;return S.length===0?k:S.find(A=>A.name.toLowerCase()===_)?.name??S.find(A=>A.label?.trim().toLowerCase()===C)?.name},h=(await Promise.all(d.map(async m=>{let b=le(m.EntityDefinition),k=b===void 0?void 0:f.get(b.toLowerCase()),F=y(m.ValidationName);return!k||!F?[]:[{id:y(m.Id),rule:{objectApiName:k,name:Q(y(m.NamespacePrefix),F),message:y(m.ErrorMessage),...ue(await o(k,m.ErrorDisplayField))}}]}))).flat().sort((m,b)=>(p.get(m.rule.objectApiName)??0)-(p.get(b.rule.objectApiName)??0)||m.rule.name.localeCompare(b.rule.name));return t&&await kt(h,t,s),h.map(({rule:m})=>m)}async function Wt(e,r,n,t){let s=[...new Set(r)].filter(a=>x.test(a));if(s.length===0)return{rules:[],notRead:0,requests:0};let l=new Map(s.map(a=>[a.toLowerCase(),a])),f=await e(oe(s)),p=f.requests,d=f.records.flatMap(a=>{let h=le(a.EntityDefinition),m=h===void 0?void 0:l.get(h.toLowerCase()),b=y(a.ValidationName);return!m||!b?[]:[{id:y(a.Id),objectApiName:m,name:Q(y(a.NamespacePrefix),b),read:!1,permissions:[]}]}),u=d.filter(a=>ae.test(a.id)),o=(a,h)=>{let m=typeof h=="object"&&h!==null?h.errorConditionFormula:void 0;typeof m=="string"&&(a.read=!0,a.permissions=rt(m).permissions)};return n?p+=await U(n,[{queries:u.slice(0,ie).map(a=>({soql:q(a.id),retrieve:{sobject:"ValidationRule",id:a.id},take:h=>o(a,h[0]?.Metadata),refused:()=>{}})),requests:W}],G,t):await B(u.slice(0,nt).map(a=>async()=>{try{let h=await e(q(a.id));p+=h.requests,o(a,h.records[0]?.Metadata)}catch{p++}}),G),{rules:d.filter(a=>a.permissions.length>0).map(({objectApiName:a,name:h,permissions:m})=>({objectApiName:a,name:h,permissions:m})),notRead:d.filter(a=>!a.read).length,requests:p}}function Kt(e,r,n){let t=async s=>(await e(ht(s))).flatMap(l=>typeof l.QualifiedApiName=="string"?[{name:l.QualifiedApiName,...typeof l.Label=="string"?{label:l.Label}:{}}]:[]);return s=>Ft(e,s,t,r,n)}var et=class{deps;constructor(r){this.deps=r}async read(r,n,t,s={}){let l=new Set(s.excludedObjects??[]),f=Qe(bt(t),l),p=[];if(f.length===0)return{gaps:[],unread:[],requests:0};let d=0,u=(i,c,g)=>{p.push({part:i,reason:c,...g!==void 0?{objectApiName:g}:{}})},o=new Map(f.map(i=>[i.toLowerCase(),i])),a=i=>i===void 0?void 0:o.get(i.toLowerCase()),h=new Map(f.map((i,c)=>[i,c])),m=f.filter(i=>x.test(i)),b=[],k=[],F,C,_=new Map,S=new Map,A=new Set,I=(i,c,g)=>async()=>{try{let w=await c();d+=w.requests,g(w.records)}catch(w){d++,u(i,E(w))}},ce=(i,c,g,w)=>async()=>{try{let{fields:J,sent:lt,createable:ut}=await this.deps.describeFields(i,c);lt&&d++,w.set(c,J),w===_&&ut===!1&&A.add(c)}catch(J){d++,u(g,`${c}: ${E(J)}`,c)}};await B([...m.length>0?[I("validationRules",()=>this.deps.toolingQuery(n,oe(m)),i=>{b=i})]:[],I("duplicateRules",()=>this.deps.query(n,yt),i=>{k=i}),async()=>{try{d++,F=await this.deps.readLimits(n)}catch(i){C=E(i)}},...f.flatMap(i=>[ce(n,i,"targetFields",_),ce(r,i,"sourceFields",S)])],G);let T=b.flatMap(i=>{let c=a(le(i.EntityDefinition)),g=y(i.ValidationName);if(!c||!g)return[];let w=y(i.Id);return[{id:ae.test(w)?w:null,name:Q(y(i.NamespacePrefix),g),objectApiName:c,...ue(se(i.ErrorDisplayField,_.get(c))),message:y(i.ErrorMessage),formula:"notRead",bypasses:[],permissions:[]}]}).sort((i,c)=>(h.get(i.objectApiName)??0)-(h.get(c.objectApiName)??0)||i.name.localeCompare(c.name)),{toolingQueries:j,toolingRetrieves:de}=this.deps,K=T.filter(i=>i.id!==null).slice(0,j?ie:nt);for(let i of T)i.id===null&&(i.formula="unreadable");let z=k.flatMap(i=>{let c=a(y(i.SobjectType)),g=Q(y(i.NamespacePrefix),y(i.DeveloperName));return!c||!y(i.DeveloperName)?[]:[{objectApiName:c,developerName:g,label:y(i.MasterLabel)||g,fullName:`${y(i.SobjectType)}.${g}`}]}),fe=new Map,pe=[];for(let i=0;i<z.length;i+=Je)pe.push(z.slice(i,i+Je).map(c=>c.fullName));let V,H,ge=(i,c)=>{let g=typeof c=="object"&&c!==null?c.errorConditionFormula:void 0;if(typeof g!="string"){i.formula="unreadable";return}i.formula="read",Object.assign(i,rt(g));let w=se(c.errorDisplayField,_.get(i.objectApiName));w&&(i.field=w)},it=async()=>{if(!j||K.length===0)return;let i=await U(c=>j(n,c),[{queries:K.map(c=>({soql:q(c.id),retrieve:{sobject:"ValidationRule",id:c.id},take:g=>ge(c,g[0]?.Metadata),refused:g=>{c.formula="unreadable",V??=g}})),requests:W}],G,de&&(c=>de(n,c)));d+=i},me=new Map,Z={},he=[...A].filter(i=>x.test(i)),ot=async()=>{let[i,c]=await Promise.all([Oe((g,w)=>this.deps.toolingQuery(g,w),n,he),this.deps.createFacts?this.deps.createFacts(n).then(g=>({facts:g,requests:0})).catch(()=>({facts:{},requests:0})):je(this.deps,n)]);d+=i.requests+c.requests;for(let[g,w]of i.answered)me.set(g,w);Z=c.facts};await B([...he.length>0?[ot]:[],...j?[it]:[],...(j?[]:K).map(i=>async()=>{try{let c=await this.deps.toolingQuery(n,q(i.id));d+=c.requests,ge(i,c.records[0]?.Metadata)}catch(c){d++,i.formula="unreadable",V??=E(c)}}),...pe.map(i=>async()=>{try{d++;for(let c of await this.deps.readDuplicateRules(n,i)){if(typeof c!="object"||c===null)continue;let g=c,w=y(g.fullName);w&&fe.set(w.toLowerCase(),g)}}catch(c){H??=E(c)}})],G),V!==void 0&&u("validationRuleFormulas",V),H!==void 0&&u("duplicateRuleActions",H);let Y=new Set,ye=!1;T.some(i=>i.permissions.length>0)&&await I("userPermissions",()=>this.deps.query(n,Le),i=>{ye=!0;for(let c of i)Y.add(Be(y(c.NamespacePrefix),y(c.DeveloperName)))})();let we=[...new Set(T.flatMap(i=>i.permissions.filter(c=>!Y.has(c.toLowerCase()))))],at=we.length>0?await We(we,async i=>{let c=[];return await I("permissionSets",()=>this.deps.query(n,i),g=>{c=g})(),c},()=>p.some(i=>i.part==="permissionSets")):void 0,be=[...T.map(i=>At(i,ye?Y:void 0,at)),...z.map(i=>Ct(i,fe.get(i.fullName.toLowerCase()))),...f.flatMap(i=>{if(A.has(i))return[_t(i,Pe(i,Z,me.get(i.toLowerCase())),_.get(i)??[],Z)];let c=_.get(i),g=S.get(i);return c&&g?St(i,c,g,s):[]})],Re=wt.safeParse(F),ke=C===void 0&&Re.success?Re.data.DailyApiRequests:void 0;return ke||u("apiBudget",C??"the limits the org answered hold no DailyApiRequests"),be.push(Et(t,s,f[0],ke)),{gaps:Ae(be),unread:vt(p,h),requests:d}}};function vt(e,r){let n=t=>t===void 0?-1:r.get(t)??r.size;return[...e].sort((t,s)=>n(t.objectApiName)-n(s.objectApiName)||Xe.indexOf(t.part)-Xe.indexOf(s.part)||(t.reason<s.reason?-1:t.reason>s.reason?1:0)).map(({part:t,reason:s})=>({part:t,reason:s}))}var Nt={platform:"object_platform_only",setup:"object_setup_only",feature:"object_feature_off",parent:"object_through_parent",user:"object_not_createable"};function _t(e,r,n,t){let s=r==="parent"?Me(n,t):[];return P({kind:Nt[r],severity:Te(r)?"info":"blocking",objectApiName:e,...s.length>0?{detail:{editOn:s}}:{},decisions:["exclude_object"]})}function At(e,r,n){let t=r?e.permissions.filter(f=>r.has(f.toLowerCase())):[],s=t.length>0?[]:e.permissions.flatMap(f=>{let p=n?.find(d=>d.permission.toLowerCase()===f.toLowerCase());return p?[Ce(p)]:[]}),l=e.field?["leave_empty","ignore"]:["ignore"];return P({kind:"validation_rule",severity:t.length>0?"info":"warning",objectApiName:e.objectApiName,...ue(e.field),idValue:e.name,detail:{rule:e.name,message:e.message,formula:e.formula,...e.bypasses.length>0?{bypasses:e.bypasses}:{},...t.length>0?{heldBypasses:t}:{},...s.length>0?{assign:s}:{}},decisions:l,...e.field?{defaultDecision:"leave_empty"}:{}})}function Ct(e,r){let n=y(r?.actionOnInsert).toLowerCase(),t=n==="block"||n==="allow"?n:"unknown",s=L(r?.operationsOnInsert).map(f=>f.toLowerCase());return P({kind:"duplicate_rule",severity:t==="allow"?"info":"warning",objectApiName:e.objectApiName,idValue:e.developerName,detail:{rule:e.label,developerName:e.developerName,action:t,...t==="allow"?{alert:s.includes("alert")}:{},...t==="allow"?{report:s.includes("report")}:{}},decisions:t==="allow"?["ignore"]:["ignore","exclude_object"],...t==="allow"?{defaultDecision:"ignore"}:{}})}function St(e,r,n,t){let s=o=>o.toLowerCase(),l=new Set((t.fieldExclusions?.[e]??[]).map(s)),f=new Map(Object.entries(t.fieldMappings?.[e]??{}).map(([o,a])=>[s(o),s(a)])),p=new Set([...f].filter(([o])=>!l.has(o)).map(([,o])=>o)),d=new Map(n.map(o=>[s(o.name),o])),u=o=>{let a=s(o);if(p.has(a))return;let h=d.get(a);return h?l.has(a)||f.has(a)?"excluded":h.createable?void 0:"notCreateableInSource":"notInSource"};return r.flatMap(o=>{let a=u(o.name);if(o.createable&&!o.nillable&&!o.defaultedOnCreate&&a)return[P({kind:"required_field_missing",severity:"blocking",objectApiName:e,field:o.name,detail:{type:o.type,reason:a,...o.referenceTo.length>0?{referenceTo:o.referenceTo}:{},...o.picklistValues.length>0?{values:o.picklistValues}:{}},decisions:["set_default","exclude_object"]})];if(o.type==="reference"&&o.lookupFilter&&!a){let h=o.nillable;return[P({kind:"lookup_filter",severity:"warning",objectApiName:e,field:o.name,detail:{referenceTo:o.referenceTo,optional:h,filterOptional:o.lookupFilter.optional},decisions:h?["leave_empty","ignore"]:["ignore","exclude_object"],...h?{defaultDecision:"leave_empty"}:{}})]}return[]})}function Et(e,r,n,t){let s=e.nodes[0]?.objectApiName??n,l=Rt(e,r),f=l.writes+l.reads,p="warning";if(t&&l.bound!=="unknown"){let d=f>t.Remaining,u=t.Max-t.Remaining+f>gt*t.Max;p=d&&l.bound==="exact"?"blocking":d||u?"warning":"info"}return P({kind:"api_budget",severity:p,objectApiName:s,detail:{calls:f,writes:l.writes,reads:l.reads,estimate:l.bound,...t?{max:t.Max,remaining:t.Remaining}:{budgetRead:!1}},decisions:["ignore"]})}var $t={blocking:"BLOCKING",warning:"warning",info:"info"},Gt=new Set(["picklist_value_refused","dependent_value_invalid","picklist_value_absent","currency_inactive"]),xt=new Set(["record_type_unmapped","record_type_unavailable"]);function st(e,r,n=[e.id]){if(ve(r.ignoredGaps,e.id,n)!==void 0)return"left as it is";let t=e.objectApiName;if(r.excludedObjects?.includes(t))return`${t} left out of the run`;let s=new Set(e.decisions),{field:l,value:f}=e;if(s.has("skip_rows")&&Ne((r.skippedRows??[]).filter(o=>o.object===t),e.id,n))return"these rows held back";if(Gt.has(e.kind)&&l!==void 0&&f!==void 0&&(s.has("map_value")||s.has("leave_empty"))){let o=(r.picklistValueMappings??[]).filter(h=>h.object===t&&h.field===l&&h.from===f),a=_e(o,e,n);if(a?.to===null&&s.has("leave_empty"))return"the field left empty in these rows";if(a&&a.to!==null&&s.has("map_value"))return`written as "${a.to}"`}let p=xt.has(e.kind)?e.value??e.recordType:void 0;if(p!==void 0&&s.has("map_record_type")){let o=r.recordTypeMappings?.find(a=>a.object===t&&a.from===p);if(o)return o.to===null?"written with the object's default record type":`written as record type ${o.to}`}if(l===void 0)return;let d=o=>o.object===t&&o.field===l,u=s.has("set_default")?r.defaultValues?.find(d):void 0;if(u)return`default "${String(u.value)}"`;if(s.has("truncate")&&r.truncateFields?.some(d))return"cut to the field's length";if(s.has("leave_empty")&&r.fieldExclusions?.[t]?.includes(l))return"the field left out of the rows"}function zt(e,r){let n=e.gaps.map(t=>t.id);return{...e,gaps:e.gaps.map(t=>{let s=st(t,r,n);return s===void 0?t:{...t,answeredBy:s}})}}function tt(e,r,n,t){if(t)return`the mute lifts it (${t.permission}, in ${t.permissionSet}): ${re(e,!0)}`;let s=r?st(e,r,n):void 0;return s===void 0?`${$t[e.severity]}: ${re(e)}`:`answered by the run's decision: ${s} \u2014 ${re(e)}`}var Pt={validationRules:"the validation rules",validationRuleFormulas:"the formulas of some validation rules",duplicateRules:"the duplicate rules",duplicateRuleActions:"what the duplicate rules do on insert",userPermissions:"the custom permissions of the user the run writes as",permissionSets:"the permission sets that hold a bypass of a validation rule the user the run writes as does not",targetFields:"the fields of an object in the target",sourceFields:"the fields of an object in the source",apiBudget:"the daily API requests left"},Tt={notInSource:"the source has no such field",notCreateableInSource:"the source cannot give it",excluded:"the run leaves it out"},D=e=>typeof e=="number"?String(e):"?";function re(e,r=!1){let n=e.detail??{};switch(e.kind){case"required_field_missing":return`required field ${e.field??""} (${y(n.type)}): only the target requires it, and the run does not write it (${Tt[y(n.reason)]??y(n.reason)}): every row is refused unless it is given a value`;case"validation_rule":{let t=e.field?` on ${e.field}`:"",s=[...L(n.bypasses).map(f=>`not when ${f}`),...L(n.heldBypasses).length>0?[`kept quiet for this run: the user it writes as holds ${L(n.heldBypasses).join(", ")}`]:[],...n.formula==="notRead"?["formula not read"]:[],...n.formula==="unreadable"?["formula unreadable"]:[],...e.field&&!r?[`a row it refuses goes again without ${e.field}`]:[]],l=y(n.message)?`: "${y(n.message)}"`:"";return`validation rule "${y(n.rule)}"${t}${l}${s.length>0?` (${s.join("; ")})`:""}`}case"duplicate_rule":{let t=`duplicate rule "${y(n.rule)}"`;if(n.action==="block")return`${t}: blocks an insert it matches: a row it matches is refused, whatever allowSave says`;if(n.action==="allow"){let s=[n.alert===!0?"an alert":"",n.report===!0?"a report":""].filter(Boolean).join(" and ");return`${t}: allows an insert it matches${s?`, with ${s}`:""}: the run saves it (allowSave=true)`}return`${t}: what it does on insert was not read: a rule that blocks refuses a row it matches`}case"lookup_filter":return`lookup filter on ${e.field??""}: not checked before the run; `+(n.optional===!0?"a lookup it refuses is left empty":"the lookup is required, and a row it refuses is refused");case"object_not_createable":return"the user the run writes as may not create its records in the target: every row is skipped, after the objects written before it, unless the object is left out";case"object_platform_only":return"no user can create its records in the target, the platform writes them itself: the run skips every row of it";case"object_setup_only":return"no user can create its records in the target, not even one with Modify All Data, and no permission set gives Create on it: setup the org keeps as records, or the platform's own; the run skips every row of it";case"object_feature_off":return"even a user with Modify All Data may not create its records in the target, though a permission set can give Create on it: a feature or licence the target has not turned on for that user keeps it closed; turn it on, or every row is skipped, after the objects written before it, unless the object is left out";case"object_through_parent":{let t=L(n.editOn);return`no permission set gives Create on it: ${t.length>0?`the user the run writes as creates its records with Edit on ${t.join(" and ")}, which they hang from, or no user can`:"the records they hang from may open it to the user the run writes as, or no user can: read as a user with Modify All Data, the target would tell"}; every row is skipped, after the objects written before it, unless the object is left out`}case"api_budget":{let t=`about ${D(n.calls)} call(s) (${D(n.writes)} write(s) of 200 rows, ${D(n.reads)} read(s))`,s=n.estimate==="atMost"?`at most ${t}, counted on whole tables`:n.estimate==="unknown"?"an unknown number of calls: an object was never counted":t,l=n.budgetRead===!1?"the daily requests left could not be read":`${D(n.remaining)} of ${D(n.max)} daily requests left`;return`API budget: the run takes ${s}; ${l}`}default:return e.kind}}function jt(e,r,n){return Se(e).map(({permission:t,permissionSet:s,others:l})=>{if(!s)return` ${t}: no permission set of ${r} holds it: an admin creates one that includes it`;let f=l.length>0?`; also held by ${l.map(d=>d.name).join(", ")}`:"",p=n?`: ${Ge(s.name,r,n)}`:"";return` ${t}: held by permission set ${s.name}, the smallest${f}${p}`})}function Ht(e,r,n={}){let t=[`target gaps: what ${r} holds against the rows, read from its metadata`],s=e.gaps.map(u=>u.id),l=e.gaps.filter(u=>u.kind==="api_budget"),f=e.gaps.filter(u=>u.kind!=="api_budget"),p=[...new Set(f.map(u=>u.objectApiName))].sort((u,o)=>u.localeCompare(o));for(let u of p){t.push(` ${u}`);for(let o of f.filter(a=>a.objectApiName===u)){let a=Ee(o,n.lifted);t.push(` ${tt(o,n.decisions,s,a)}`),a||t.push(...jt(o,r,n.username))}}f.length===0&&t.push(e.unread.length>0?" nothing found in what could be read":" no validation rule, duplicate rule, field only the target requires or lookup filter");for(let u of l)t.push(` ${tt(u,n.decisions,s)}`);let d=f.filter(u=>u.detail?.formula==="notRead").length;d>0&&t.push(` ${d} validation rule formula(s) not read: the read takes ${n.formulasBound??ie} at most`);for(let{part:u,reason:o}of e.unread)t.push(` ${Pt[u]??u} could not be read: ${o}`);return t.push(` read in ${e.requests} request(s) to ${r}`),t}export{nt as a,W as b,ie as c,Bt as d,oe as e,ht as f,q as g,yt as h,rt as i,Rt as j,Qt as k,Ft as l,Wt as m,Kt as n,et as o,st as p,zt as q,Ht as r};
|
package/lib/chunk-OVNMB6Q2.mjs
DELETED
|
@@ -1,7 +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,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r}from"./chunk-HIDW7FNV.mjs";import"./chunk-BOGNK4LV.mjs";import"./chunk-LC3NDW4N.mjs";import"./chunk-KB4ZHM4Q.mjs";import"./chunk-23SEDORH.mjs";import"./chunk-W6PN6TJG.mjs";import"./chunk-3Q353S2R.mjs";import"./chunk-VV3B6IC3.mjs";import"./chunk-RHNTHGNU.mjs";import"./chunk-INIT2UKJ.mjs";import"./chunk-Q7TLC3I2.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-D4GF4FAB.mjs";import"./chunk-CVHNXJH3.mjs";import"./chunk-TQ2TQHTT.mjs";import"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import"./chunk-EADHKH3A.mjs";import"./chunk-M6K34KGF.mjs";import"./chunk-TNT27RBG.mjs";import"./chunk-TZE3Y7IQ.mjs";import"./chunk-CA5NAXSU.mjs";import"./chunk-PC247GKX.mjs";import"./chunk-S42RBRH2.mjs";import"./chunk-UNDIBZWG.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-PMWAFDUB.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";export{p as actDeliverability,o as actEmailsGate,n as actSendersOf,q as afterLeaseEmailsRefusal,l as checkpointEmails,j as checkpointEmailsUncounted,c as draftedByDiff,d as draftedByPlan,a as emailsOfLimit,m as emailsRefusal,k as emailsUncountedWords,r as pageEmailsRefusal,e as statusBackByDiff,f as statusBackByPlan,b as updatedByDiff,g as writtenByDiff,h as writtenByPlan,i as writtenByUndo};
|