sandforge 1.85.0 → 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-THYQOG24.mjs → chunk-22L43JMK.mjs} +1 -1
- package/lib/{chunk-U4S27YRP.mjs → chunk-2LSGWTWX.mjs} +1 -1
- package/lib/{chunk-MRN72UEO.mjs → chunk-2YJJTQNC.mjs} +1 -1
- package/lib/chunk-34SMB5PA.mjs +10 -0
- package/lib/chunk-35B73566.mjs +7 -0
- package/lib/{chunk-YZKE6D3K.mjs → chunk-35IJ4WEU.mjs} +1 -1
- package/lib/chunk-3EHPAFKV.mjs +7 -0
- package/lib/{chunk-3OKDWZ32.mjs → chunk-3HAVVEXF.mjs} +1 -1
- package/lib/{chunk-32ZB5ICW.mjs → chunk-3I6FXFCN.mjs} +1 -1
- package/lib/{chunk-JFVY66BS.mjs → chunk-3KJCSYXY.mjs} +1 -1
- package/lib/{chunk-ULEYGOZU.mjs → chunk-3L6DVNCR.mjs} +1 -1
- package/lib/chunk-3LRFPGYZ.mjs +7 -0
- package/lib/{chunk-GHUA6OQQ.mjs → chunk-3MVWGL5A.mjs} +1 -1
- package/lib/{chunk-SF52ZSIV.mjs → chunk-4CSBZZAL.mjs} +1 -1
- package/lib/{chunk-FBYFCKPG.mjs → chunk-4NSXPONF.mjs} +1 -1
- package/lib/{chunk-A3QNSALB.mjs → chunk-4VLP6RHC.mjs} +1 -1
- package/lib/{chunk-TWYNQ2OO.mjs → chunk-4XROG5CT.mjs} +1 -1
- package/lib/chunk-54V4FVEY.mjs +7 -0
- package/lib/chunk-55OJJT2Q.mjs +7 -0
- package/lib/{chunk-JRI6A24G.mjs → chunk-5EHHQ5UX.mjs} +1 -1
- package/lib/{chunk-VPGX5Z5D.mjs → chunk-5JMQXHJ2.mjs} +1 -1
- package/lib/{chunk-CI2O7WBH.mjs → chunk-65AMXOQU.mjs} +1 -1
- package/lib/{chunk-5T3LFDJ5.mjs → chunk-6HHSAPIM.mjs} +1 -1
- package/lib/chunk-6KVBCFVS.mjs +7 -0
- package/lib/chunk-6NG7C2U3.mjs +476 -0
- package/lib/{chunk-F2424IKX.mjs → chunk-6ROL3KBM.mjs} +1 -1
- package/lib/{chunk-7ZYCRIHE.mjs → chunk-72AWCN7U.mjs} +1 -1
- package/lib/{chunk-MQLTEXB7.mjs → chunk-7KHA5UIQ.mjs} +1 -1
- package/lib/chunk-7O6EFNQS.mjs +10 -0
- package/lib/{chunk-73SLYGWD.mjs → chunk-A2CH2QGX.mjs} +1 -1
- package/lib/chunk-A2TXLAC3.mjs +276 -0
- package/lib/chunk-ALWVNR34.mjs +7 -0
- package/lib/{chunk-JBOGAUGH.mjs → chunk-ATBQIE2V.mjs} +1 -1
- package/lib/{chunk-C2MHMI7U.mjs → chunk-ATQML7ZK.mjs} +1 -1
- package/lib/chunk-AVY742BJ.mjs +7 -0
- package/lib/{chunk-VLAU5QQT.mjs → chunk-AXTB2HJS.mjs} +1 -1
- package/lib/chunk-BBZUGKBZ.mjs +10 -0
- package/lib/chunk-BIDXK7KA.mjs +7 -0
- package/lib/{chunk-KYLHS74X.mjs → chunk-BLMJ4WVI.mjs} +1 -1
- package/lib/{chunk-A7YP27GQ.mjs → chunk-BNHJCJJM.mjs} +1 -1
- package/lib/{chunk-ZDMSTL2L.mjs → chunk-BNPQEQXC.mjs} +1 -1
- package/lib/chunk-C5AUNG6T.mjs +37 -0
- package/lib/{chunk-LY6EPMIP.mjs → chunk-C5EQ7GFC.mjs} +1 -1
- package/lib/{chunk-LOO42EW5.mjs → chunk-C7CKDZMC.mjs} +62 -62
- package/lib/{chunk-ZP3WJGS3.mjs → chunk-CB4U22NR.mjs} +1 -1
- package/lib/chunk-CJAWKLAL.mjs +7 -0
- package/lib/chunk-CL75DEMQ.mjs +9 -0
- package/lib/{chunk-7L6FE5PP.mjs → chunk-CLUNF4FK.mjs} +1 -1
- package/lib/chunk-CSMGP53U.mjs +7 -0
- package/lib/{chunk-S6BMJSLD.mjs → chunk-CT324C7I.mjs} +1 -1
- package/lib/{chunk-YXOPKGDX.mjs → chunk-CZXDJXQP.mjs} +1 -1
- package/lib/{chunk-PGG4ULEW.mjs → chunk-D2X6U3MS.mjs} +1 -1
- package/lib/{chunk-FG4Y4ZVL.mjs → chunk-DAUX63UB.mjs} +1 -1
- package/lib/chunk-DB7JNALQ.mjs +10 -0
- package/lib/chunk-DDNCJVZ2.mjs +17 -0
- package/lib/{chunk-YGE4AUXG.mjs → chunk-DLSU66MY.mjs} +1 -1
- package/lib/{chunk-DCJBP3LE.mjs → chunk-DO6PSHQZ.mjs} +1 -1
- package/lib/{chunk-ROTDZKOE.mjs → chunk-DUBECLZV.mjs} +1 -1
- package/lib/{chunk-SES5HPBZ.mjs → chunk-DYHF6DNT.mjs} +1 -1
- package/lib/chunk-E5FSPXYH.mjs +930 -0
- package/lib/{chunk-QAXKUEJT.mjs → chunk-EGL3I3IX.mjs} +1 -1
- package/lib/chunk-EIYMQPMG.mjs +7 -0
- package/lib/{chunk-AX3YF7SC.mjs → chunk-EUIALBMX.mjs} +1 -1
- package/lib/{chunk-57QRXYAZ.mjs → chunk-FI3R5ZOQ.mjs} +1 -1
- package/lib/{chunk-FCZDWGQI.mjs → chunk-FM4QCTO7.mjs} +1 -1
- package/lib/{chunk-74HZ274R.mjs → chunk-FRSIEASH.mjs} +1 -1
- package/lib/{chunk-G6IYOZEH.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-NZJXEULY.mjs → chunk-GFB2DNCB.mjs} +1 -1
- package/lib/chunk-GFGMGFSH.mjs +7 -0
- package/lib/{chunk-EFHDE7W4.mjs → chunk-GIFQXB2Q.mjs} +1 -1
- package/lib/{chunk-P6A22FMQ.mjs → chunk-GP5J3DGS.mjs} +1 -1
- package/lib/chunk-GQZEX7LH.mjs +231 -0
- package/lib/{chunk-BRN42U26.mjs → chunk-GYDTM62J.mjs} +1 -1
- package/lib/{chunk-GNCEHAJY.mjs → chunk-GYFIXUJG.mjs} +1 -1
- package/lib/chunk-GZW2GNFK.mjs +7 -0
- package/lib/chunk-H6BHWAX7.mjs +8 -0
- package/lib/{chunk-GUYEXPJ4.mjs → chunk-HDDJ3CVN.mjs} +1 -1
- package/lib/{chunk-3GATEVHC.mjs → chunk-HDWB4ZOG.mjs} +1 -1
- package/lib/chunk-HGVPBJR6.mjs +7 -0
- package/lib/{chunk-55VBV2WK.mjs → chunk-HLROVOR6.mjs} +1 -1
- package/lib/{chunk-HV3TDLFR.mjs → chunk-HUOR4M2L.mjs} +1 -1
- package/lib/chunk-HZCS6EED.mjs +8 -0
- package/lib/{chunk-WZX6VCIT.mjs → chunk-HZUI56KZ.mjs} +1 -1
- package/lib/chunk-IAB5H7WN.mjs +7 -0
- package/lib/{chunk-RY7WUJXH.mjs → chunk-IQ5UKRHU.mjs} +1 -1
- package/lib/{chunk-OUWR5M5G.mjs → chunk-IRQ4WANV.mjs} +1 -1
- package/lib/{chunk-F44EHXLI.mjs → chunk-IT3DGX37.mjs} +1 -1
- package/lib/chunk-J347SPU6.mjs +49 -0
- package/lib/{chunk-IZ2M2RGO.mjs → chunk-JANBNTR5.mjs} +1 -1
- package/lib/chunk-JFXQZPRY.mjs +9 -0
- package/lib/{chunk-VKA5OZBJ.mjs → chunk-JRLYWVF4.mjs} +1 -1
- package/lib/{chunk-FM5ESRH6.mjs → chunk-JSNMUTY6.mjs} +1 -1
- package/lib/chunk-JTNJKSAA.mjs +7 -0
- package/lib/{chunk-4D6OHSX3.mjs → chunk-JV2LAKWQ.mjs} +1 -1
- package/lib/{chunk-BY42YL4D.mjs → chunk-JV7K2ZHK.mjs} +1 -1
- package/lib/{chunk-A6IJUOLB.mjs → chunk-K4TQ7YHX.mjs} +1 -1
- package/lib/chunk-K5PUMHZU.mjs +7 -0
- package/lib/chunk-KH4KLCYG.mjs +7 -0
- package/lib/{chunk-FZF6FB65.mjs → chunk-KQVLZVOP.mjs} +1 -1
- package/lib/chunk-KWUS7UAV.mjs +19 -0
- package/lib/{chunk-2UUSF32M.mjs → chunk-L6G73FXM.mjs} +1 -1
- package/lib/{chunk-LUNGNCM3.mjs → chunk-LG466Q5H.mjs} +1 -1
- package/lib/{chunk-YTBM3TSW.mjs → chunk-LHNAR6FC.mjs} +1 -1
- package/lib/chunk-LT4GHEI2.mjs +7 -0
- package/lib/{chunk-P3OYE2FS.mjs → chunk-MR262Y3B.mjs} +1 -1
- package/lib/{chunk-TSTCHIBU.mjs → chunk-NCCHOV2N.mjs} +1 -1
- package/lib/chunk-NICRSGLS.mjs +7 -0
- package/lib/chunk-NV5QA2HY.mjs +7 -0
- package/lib/{chunk-6HAKOS6W.mjs → chunk-O3GIN5TU.mjs} +1 -1
- package/lib/chunk-O6FHK6NQ.mjs +13 -0
- package/lib/{chunk-OXIIKAUZ.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-K2WOT75I.mjs → chunk-OO2WY3UB.mjs} +1 -1
- package/lib/{chunk-3EOIAC2M.mjs → chunk-OT2NHL2V.mjs} +1 -1
- package/lib/{chunk-BK5SRDAD.mjs → chunk-P2M5ZXWU.mjs} +1 -1
- package/lib/{chunk-DCZYWMSA.mjs → chunk-P4YOHLZ4.mjs} +1 -1
- package/lib/chunk-PBHDPTT6.mjs +343 -0
- package/lib/chunk-PE7CHD2W.mjs +7 -0
- package/lib/{chunk-LU7M5URW.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-LNAZHI3J.mjs → chunk-QGVL5EW3.mjs} +1 -1
- package/lib/chunk-QHE2RUWX.mjs +7 -0
- package/lib/{chunk-4RNP65FV.mjs → chunk-RCW5BZNW.mjs} +1 -1
- package/lib/{chunk-OTKXTBTX.mjs → chunk-RJ6HHG7J.mjs} +1 -1
- package/lib/{chunk-IVDBVWKK.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-2UUS4IGB.mjs → chunk-RZOINFNL.mjs} +1 -1
- package/lib/chunk-SOOTWGMQ.mjs +7 -0
- package/lib/chunk-STQ2JMIZ.mjs +7 -0
- package/lib/{chunk-RC25QQVF.mjs → chunk-SUIPDW5O.mjs} +1 -1
- package/lib/{chunk-Z354SAEF.mjs → chunk-SZOJ7BEJ.mjs} +1 -1
- package/lib/{chunk-45375WT5.mjs → chunk-T542Z54E.mjs} +1 -1
- package/lib/chunk-TAN2CIRI.mjs +21 -0
- package/lib/{chunk-BGJBYDRW.mjs → chunk-TCNBINOG.mjs} +1 -1
- package/lib/chunk-TFDF3DBN.mjs +7 -0
- package/lib/{chunk-B5A4JHNN.mjs → chunk-TICZXC53.mjs} +1 -1
- package/lib/chunk-TLX45X5U.mjs +7 -0
- package/lib/{chunk-W6SLQZKQ.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-4N425UJC.mjs → chunk-UCUFLFNK.mjs} +1 -1
- package/lib/chunk-UK3QLBHW.mjs +7 -0
- package/lib/{chunk-SKGAERV4.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-LSEM2BZH.mjs → chunk-VFKG2G37.mjs} +1 -1
- package/lib/chunk-VJNEW5MQ.mjs +7 -0
- package/lib/{chunk-EYFP3NA6.mjs → chunk-VKREON6Q.mjs} +1 -1
- package/lib/{chunk-TIVI2KGB.mjs → chunk-VNNDYPBL.mjs} +1 -1
- package/lib/{chunk-J3FJ3BWE.mjs → chunk-VRBETPHY.mjs} +1 -1
- package/lib/{chunk-UX4AOSMU.mjs → chunk-VT6P3X6R.mjs} +1 -1
- package/lib/{chunk-CUOWQMGW.mjs → chunk-VUTQY76O.mjs} +1 -1
- package/lib/chunk-WF5S4FW5.mjs +7 -0
- package/lib/{chunk-JHJDDQDE.mjs → chunk-WJGK6VGU.mjs} +1 -1
- package/lib/{chunk-IZREPWYQ.mjs → chunk-WJHMB3SL.mjs} +1 -1
- package/lib/{chunk-XZRON54U.mjs → chunk-WQCXOZEJ.mjs} +1 -1
- package/lib/{chunk-N2MXYD67.mjs → chunk-WVVFR4E3.mjs} +1 -1
- package/lib/{chunk-GG5I52UT.mjs → chunk-XBYXT74L.mjs} +1 -1
- package/lib/chunk-XJE3LJHP.mjs +7 -0
- package/lib/{chunk-3QCUSZIZ.mjs → chunk-XV4CVZYD.mjs} +1 -1
- package/lib/chunk-Y37ED7AS.mjs +7 -0
- package/lib/{chunk-MN3XBJPE.mjs → chunk-YGBNZYT4.mjs} +1 -1
- package/lib/{chunk-SBDF4AE5.mjs → chunk-YGTOX7IL.mjs} +1 -1
- package/lib/{chunk-SQM32AOQ.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-SU24AE3H.mjs → chunk-YZKZC62O.mjs} +1 -1
- package/lib/{chunk-LJNRN7MY.mjs → chunk-YZQN7BRB.mjs} +1 -1
- package/lib/{chunk-NMF55UBQ.mjs → chunk-Z5IUK2QO.mjs} +1 -1
- package/lib/{chunk-6ZWY36LK.mjs → chunk-ZEGSMW5A.mjs} +1 -1
- package/lib/{chunk-YV7JYHJP.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 +29 -16
- 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-26EGXYZ4.mjs +0 -21
- package/lib/chunk-2JRVBXJL.mjs +0 -7
- package/lib/chunk-2METQHGG.mjs +0 -7
- package/lib/chunk-3XU7CEJQ.mjs +0 -7
- package/lib/chunk-4BQPAVMP.mjs +0 -14
- package/lib/chunk-4KMKOE77.mjs +0 -156
- package/lib/chunk-4RPA7Z52.mjs +0 -7
- package/lib/chunk-5C7LQXYS.mjs +0 -7
- package/lib/chunk-5EESNYE3.mjs +0 -8
- package/lib/chunk-6ZW6BLV5.mjs +0 -7
- package/lib/chunk-AAOMUI7S.mjs +0 -15
- package/lib/chunk-AIUAEBHR.mjs +0 -7
- package/lib/chunk-BD724WOH.mjs +0 -7
- package/lib/chunk-CRPLDXJU.mjs +0 -48
- package/lib/chunk-CSSOLHE3.mjs +0 -7
- package/lib/chunk-D63HEQ3B.mjs +0 -7
- package/lib/chunk-DN7YBILC.mjs +0 -21
- package/lib/chunk-DNE7JI3A.mjs +0 -11
- package/lib/chunk-EFHM2U4D.mjs +0 -7
- package/lib/chunk-EINEGS6E.mjs +0 -7
- package/lib/chunk-EM5EFMHA.mjs +0 -272
- package/lib/chunk-FH5UR35W.mjs +0 -7
- package/lib/chunk-FN7TOBJR.mjs +0 -7
- package/lib/chunk-HGJFATSI.mjs +0 -10
- package/lib/chunk-HOEE3PE5.mjs +0 -7
- package/lib/chunk-HV63UGL5.mjs +0 -7
- package/lib/chunk-JKFCGYJE.mjs +0 -7
- package/lib/chunk-KATBU46O.mjs +0 -7
- package/lib/chunk-LD34JNCC.mjs +0 -7
- package/lib/chunk-LPN4WYTP.mjs +0 -478
- package/lib/chunk-MAOUFJ47.mjs +0 -7
- package/lib/chunk-MB2DG66I.mjs +0 -13
- package/lib/chunk-NCASRA7L.mjs +0 -9
- package/lib/chunk-NEKNAILD.mjs +0 -7
- package/lib/chunk-NN2IO4WE.mjs +0 -7
- package/lib/chunk-O3ZQSWDN.mjs +0 -10
- package/lib/chunk-OFQOKSEW.mjs +0 -7
- package/lib/chunk-PP7PJXRJ.mjs +0 -341
- package/lib/chunk-PT2E2HFD.mjs +0 -7
- package/lib/chunk-PZBZ7MNC.mjs +0 -7
- package/lib/chunk-QBYK5XIT.mjs +0 -8
- package/lib/chunk-RFD6NPWJ.mjs +0 -8
- package/lib/chunk-RIIJJRGF.mjs +0 -7
- package/lib/chunk-RKTFFCNS.mjs +0 -7
- package/lib/chunk-RM5G4IP6.mjs +0 -19
- package/lib/chunk-RTPNK7OB.mjs +0 -7
- package/lib/chunk-RZXEO5IE.mjs +0 -7
- package/lib/chunk-SAHGDSZQ.mjs +0 -37
- package/lib/chunk-SRPWW4A2.mjs +0 -10
- package/lib/chunk-SVNSAHG3.mjs +0 -7
- package/lib/chunk-T63U4OZJ.mjs +0 -7
- package/lib/chunk-TE2W76II.mjs +0 -10
- package/lib/chunk-TEIBWMJM.mjs +0 -7
- package/lib/chunk-TFGJDZFE.mjs +0 -7
- package/lib/chunk-TG52WNGV.mjs +0 -10
- package/lib/chunk-TQONVFI3.mjs +0 -7
- package/lib/chunk-TW3N6W5Z.mjs +0 -7
- package/lib/chunk-UZMLPKW6.mjs +0 -7
- package/lib/chunk-WB2RIVO3.mjs +0 -7
- package/lib/chunk-WQO7RXEB.mjs +0 -926
- package/lib/chunk-X3MBY2RX.mjs +0 -7
- package/lib/chunk-XMJRXXUN.mjs +0 -7
- package/lib/chunk-YNMU5I7P.mjs +0 -7
- package/lib/chunk-YSQJKIO6.mjs +0 -7
- package/lib/chunk-YVVPJRZC.mjs +0 -7
- package/lib/chunk-ZLQHBI6V.mjs +0 -9
- package/lib/chunk-ZRUDYB7O.mjs +0 -7
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
+
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
+
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
+
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
+
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
+
import{a as Bn,b as Md,c as Wn,d as zr}from"./chunk-AXTB2HJS.mjs";import{a as Dn,b as Od,c as xn,d as Sd,f as Td,g as _n,i as jd,j as Fd}from"./chunk-NCCHOV2N.mjs";import{a as Cr,b as Ad,c as Uo,d as it,e as $n,f as dr,g as Ko,h as Pd}from"./chunk-2LSGWTWX.mjs";import{j as Ed,k as Ld,n as Nd,o as Cd,p as zd}from"./chunk-LHNAR6FC.mjs";import{l as La}from"./chunk-XBYXT74L.mjs";import{c as vd,d as pe}from"./chunk-UV74P4H2.mjs";import{k as Id}from"./chunk-UM2B4GR7.mjs";import{i as Na}from"./chunk-2YJJTQNC.mjs";import{e as Ea,f as zo}from"./chunk-4VLP6RHC.mjs";import{K as Rd,R as Go,S as kd,i as pd,p as Mn,q as gd,r as hd,s as md,t as yd,z as wd}from"./chunk-WF5S4FW5.mjs";import{l as bd}from"./chunk-FYG47CNA.mjs";import{a as la,b as jn}from"./chunk-XCA5AONB.mjs";import{$a as $i,Ac as st,Rc as Tn,Sc as Eo,_a as xi,a as ji,ab as _i,b as Ot,bb as Bi,cb as jo,db as Wi,eb as qi,fb as Gi,g as Oo,gb as Ui,h as Fi,hb as Ki,j as Ae,k as Ei,l as Pr,m as Li,n as bt,o as te,s as So}from"./chunk-CJAWKLAL.mjs";import{a as On}from"./chunk-CE6ZDGBB.mjs";import{a as ma,b as ya}from"./chunk-BOGNK4LV.mjs";import{Ma as dd,Qa as cd,R as ad,Xa as ld,Za as qo,a as oi,ab as ud,b as si,bb as fd,i as ed,j as td,o as Bo,za as Wo}from"./chunk-C5AUNG6T.mjs";import{e as ta,f as Fo,g as ra,h as na,i as oa,p as da,q as ca}from"./chunk-7O6EFNQS.mjs";import{A as Ji,B as Xi,I as Zi,M as Bt,N as Qi,O as Pn,P as ea}from"./chunk-3LRFPGYZ.mjs";import{a as zn,b as od,d as sd,e as id}from"./chunk-GB6W4Q56.mjs";import{a as rd,b as _o,c as Nr,d as Cn,i as nd}from"./chunk-AVY742BJ.mjs";import{g as Ta,j as ja,l as Fa}from"./chunk-HZCS6EED.mjs";import{f as Pa,i as Co,j as Ln}from"./chunk-35B73566.mjs";import{f as In,g as vn}from"./chunk-TYUYPFDJ.mjs";import{a as sa,c as ia,d as aa,r as No}from"./chunk-DLSU66MY.mjs";import{H as Lo,L as ba,i as wa,k as En}from"./chunk-4CSBZZAL.mjs";import{r as Se}from"./chunk-OT2NHL2V.mjs";import{b as ua,c as fa,g as pa}from"./chunk-ZVU7MD2S.mjs";import{Ic as Ja,Jc as Xa,Kc as Za,Pb as _a,Uc as Qa,bb as Mo,dc as Ba,j as jr,jc as Wa,k as Fn,kb as Do,l as ga,lc as qa,mb as xo,mc as Ga,nb as Ca,q as ha,qc as Ua,rb as za,rc as Ka,s as Fr,sb as $o,tb as Ma,uc as Va,vb as Lr,vc as Ha,wb as Da,wc as Ya,xb as xa,zb as $a}from"./chunk-OLCS7JCT.mjs";import{f as Si,g as Ai,j as Pi,k as Ze,l as Ti}from"./chunk-TQ6HEJ73.mjs";import{q as Nn}from"./chunk-6HHSAPIM.mjs";import{a as vi,b as vo,f as Oi}from"./chunk-K5PUMHZU.mjs";import{a as ut,b as St}from"./chunk-VV3B6IC3.mjs";import{a as xt}from"./chunk-4TLYUZD5.mjs";import{b as Ra,d as ka,f as Er,g as Ia,h as va,i as Oa,j as Sa,p as Aa}from"./chunk-EUIALBMX.mjs";import{i as Ni}from"./chunk-INIT2UKJ.mjs";import{h as Hi}from"./chunk-ATBQIE2V.mjs";import{b as Yi,d as Tr}from"./chunk-UCUFLFNK.mjs";import{b as Sn}from"./chunk-HFSBDM7B.mjs";import{b as zi,c as lt,e as Ao,g as Mi,h as Po,i as Di,j as To}from"./chunk-OHEOJISY.mjs";import{a as Ci}from"./chunk-EADHKH3A.mjs";import{h as ar}from"./chunk-DAUX63UB.mjs";import{$ as yi,E as fi,F as $t,G as wt,I as ko,L as pi,M as gi,N as hi,Y as Io,Z as mi,a as Sr,b as Xe,c as rr,d as wn,da as _t,ea as wi,f as nr,fa as bi,g as ii,ga as Ri,ha as ki,ia as Ii,ja as sr,k as ai,ka as ir,l as Ro,m as di,n as ci,o as li,p as ui,q as Ke,r as Ue,s as bn,t as Ar,u as Rn,v as or,z as kn}from"./chunk-SZOJ7BEJ.mjs";import{a as Be,h as ye}from"./chunk-TZE3Y7IQ.mjs";import{b as ee}from"./chunk-CA5NAXSU.mjs";import{a as Vi}from"./chunk-22L43JMK.mjs";import{b as An}from"./chunk-UNDIBZWG.mjs";import{Fc as Xs,Gc as er,Jc as ln,Lc as qe,Mc as un,Nc as yt,Oc as Mt,Pc as fn,Sc as Ge,Tc as Je,Uc as pn,Vc as _e,Wc as tr,Xc as Zs,Zc as Qs,_c as gn,ce as ri,ed as ei,je as ni,kd as ti,le as Or,qd as hn,rd as mn,s as Js,te as Dt,ue as yn}from"./chunk-J347SPU6.mjs";import{b as $e,e as Ks,f as cn,k as mt,l as ot,s as Vs,u as Hs,v as Ys,z as bo}from"./chunk-WZQEK4WT.mjs";import{createHash as Dd}from"node:crypto";import*as Gn from"node:fs/promises";import*as Dr from"node:path";import*as Rt from"node:fs/promises";import*as At from"node:path";var Mr="platform-records.json",Vo=class extends Error{constructor(e){let t=e.checks.filter(r=>!r.passed).map(r=>`${r.name} (${r.violations.length} violation(s))`).join(", ");super(`Refusing to write the frozen dataset: non-reidentification control FAILED [${t}]. A FAIL means nothing is written or versioned.`),this.name="ControlNotPassedError"}},qn=class{guard;constructor(e){this.guard=e??new pe}async write(e,t,r,n){if(!n.passed)throw new Vo(n);let s=this.guard.assertOutsideRepo(e),i=this.guard.assertOutsideRepo(At.join(s,"data"));await Rt.mkdir(i,{recursive:!0});for(let l of await Rt.readdir(i))l.endsWith(".json")&&await Rt.rm(this.guard.assertOutsideRepo(At.join(i,l)));let d=[],a=async(l,u)=>{let f=this.guard.assertOutsideRepo(l);await Rt.writeFile(f,`${JSON.stringify(u)}
|
|
8
|
+
`,"utf8"),d.push(f)},c=this.guard.assertOutsideRepo(At.join(s,"manifest.json"));await Rt.writeFile(c,Wn(r),"utf8"),d.push(c);for(let l of t.objects)await a(At.join(i,`${l.objectApiName}.json`),{objectApiName:l.objectApiName,records:l.records});return await a(At.join(s,"record-types.json"),t.recordTypes),await a(At.join(s,"personcontact-sidecar.json"),t.personContactSidecar),await a(At.join(s,Mr),{...t.standardPricebook?{standardPricebook:t.standardPricebook}:{}}),{dir:s,files:d}}};var Ho="manifest.json",Sl=["record-types.json","personcontact-sidecar.json",Mr],Yo="data",Al="sha256:";async function np(o){let e=await Jo(Dr.join(o,Ho));if(e===void 0)throw new Error(`No frozen dataset at ${o}: it holds no ${Ho}.`);let t=[{name:Ho,content:Tl(e)}];for(let n of Sl){let s=await Jo(Dr.join(o,n));s!==void 0&&t.push({name:n,content:s})}for(let n of await Pl(Dr.join(o,Yo))){let s=await Jo(Dr.join(o,Yo,n));s!==void 0&&t.push({name:`${Yo}/${n}`,content:s})}let r=Dd("sha256");for(let{name:n,content:s}of t.sort((i,d)=>xd(i.name,d.name)))r.update(`${n}\0${Dd("sha256").update(s).digest("hex")}
|
|
9
|
+
`);return`${Al}${r.digest("hex")}`}async function Pl(o){let e;try{e=await Gn.readdir(o)}catch(t){if(t.code==="ENOENT")return[];throw t}return e.filter(t=>t.endsWith(".json"))}async function Jo(o){try{return await Gn.readFile(o)}catch(e){if(e.code==="ENOENT")return;throw e}}function Tl(o){let e;try{e=JSON.parse(o.toString("utf8"))}catch{return o}if(Zo(e)&&Zo(e.controls)){let t={...e.controls};delete t.dryRunLoad,e={...e,controls:t}}return Buffer.from(Xo(e),"utf8")}function Xo(o){return Array.isArray(o)?`[${o.map(Xo).join(",")}]`:Zo(o)?`{${Object.keys(o).sort(xd).map(t=>`${JSON.stringify(t)}:${Xo(o[t])}`).join(",")}}`:JSON.stringify(o)??"null"}function Zo(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function xd(o,e){return o===e?0:o<e?-1:1}var Ve=class extends Error{constructor(t,r,n={}){super(r);this.code=t;this.params=n;this.name="LoadGuardError"}code;params};function cr(o){return o.objects.reduce((e,t)=>e+t.records.length,0)}function xr(o){return o.orgName??o.orgId}async function $d(o){if(Qo(o),o.protectedOrgIds?.includes(o.orgId))throw new Ve("protected-environment",`Refusing frozen-dataset load on protected environment ${xr(o)}: it is listed in the protectedOrgIds configuration. Remediation: pick an unprotected sandbox, or review the protected-environment configuration if this org was retired.`,{orgId:o.orgId});if(o.manifest&&o.manifest.source.orgId===o.orgId)throw new Ve("source-is-target",`Refusing frozen-dataset load on ${xr(o)}: this org is the dataset SOURCE (manifest source.orgId). Loading would mix pseudonymized records with their origin. Remediation: target a fresh dev sandbox instead.`,{orgId:o.orgId});if(!await o.mockDetector.areCalloutsMocked(o.orgId))throw new Ve("unmocked-callouts",`Refusing frozen-dataset load on ${xr(o)}: unmocked callouts detected. Records under load would trigger real external calls. Remediation: deploy the mock configuration to the TARGET org (e.g. the custom metadata flag read by CustomMetadataCalloutMockDetector), then retry \u2014 never edit data on the source org.`,{orgId:o.orgId});if(cr(o.dataset)===0)throw new Ve("empty-dataset","Refusing frozen-dataset load: the dataset contains zero records. Remediation: re-run the selection/extraction with a coverage matrix that matches the source data, then freeze a new dataset version.")}function Qo(o){if(!(o.orgTier==="staging"&&o.stagingReplay===!0)){if(o.orgTier==="staging")throw new Ve("non-sandbox",`Refusing frozen-dataset load on ${xr(o)}: it is a sandbox marked Staging, which holds real data, and a load never goes into one. Remediation: pick another sandbox, or, if this one holds no real data, untick Staging in its Edit dialog on the Organizations page.`,{orgId:o.orgId,tier:o.orgTier});if(o.orgTier!=="development"&&o.orgTier!=="scratch")throw new Ve("non-sandbox",`Refusing frozen-dataset load on ${o.orgTier} org ${xr(o)}: loads go into sandboxes and Developer Edition orgs only. Remediation: target a Developer/Scratch sandbox or a Developer Edition org \u2014 deploy the required configuration THERE; never run DML against a shared or source org.`,{orgId:o.orgId,tier:o.orgTier})}}var $r=class{constructor(e,t){this.orgAccess=e;this.config=t}orgAccess;config;async areCalloutsMocked(e){let t=`SELECT Id FROM ${ye(this.config.metadataTypeApiName)} WHERE ${ye(this.config.isMockedFieldApiName)} = true LIMIT 1`;try{return(await this.orgAccess.query(e,t)).length>0}catch{return!1}}};var Un=class{constructor(e){this.orgAccess=e}orgAccess;uiApiCache=new Map;async alignObject(e){let t=new Map(e.describe.fields.map(d=>[d.name,d])),r=new Map,n=[],s=[],i=[];for(let d of e.records){let a={},c=e.accountKindOf?.(d.referenceId);for(let[l,u]of Object.entries(d.fields)){if(c!==void 0&&hn(Ke,l,c))continue;let f=t.get(l);if(!f){this.countRemoval(r,l,"not-in-target");continue}if(!f.createable){this.countRemoval(r,l,"not-createable");continue}if(e.leaveOutEncrypted===!0&&f.type===sa){u!=null&&u!==""&&this.countRemoval(r,l,"may-hold-masks");continue}let p=u;typeof p=="string"&&p!==""&&f.restrictedPicklist===!0&&(f.type==="picklist"||f.type==="multipicklist")&&(p=await this.alignPicklistValue(e,f.name,f.type,d,p,n,s)),a[l]=p}i.push(a)}return{objectApiName:e.objectApiName,alignedRecords:i,removals:[...r.entries()].map(([d,a])=>({objectApiName:e.objectApiName,field:d,reason:a.reason,affectedRecords:a.count})),adjustments:n,missingRequired:this.detectMissingRequired(e,i),uiApiWarnings:s}}detectMissingRequired(e,t){let r=t.filter((a,c)=>!e.linked?.has(e.records[c].referenceId));if(r.length===0)return[];let n=[],s=e.accountKindOf,i=s?e.records.filter(a=>!e.linked?.has(a.referenceId)).map(a=>s(a.referenceId)):[];for(let a of e.describe.fields){let c=s?mn(Ke,a.name):void 0;if(!a.createable||a.nillable&&c===void 0||a.defaultedOnCreate)continue;let l=r.filter((f,p)=>c===void 0||or(c,i[p]));if(l.length===0)continue;if(!l.some(f=>{let p=f[a.name];return p!=null&&p!==""})){let f=a.unique?"unique":a.nameField?"name":void 0,p=(a.referenceTo?.length??0)>0,g=(a.picklistValues??[]).filter(h=>h.active).map(h=>h.value);n.push({objectApiName:e.objectApiName,field:a.name,isLookup:p,referenceTo:a.referenceTo??[],...f?{distinct:f}:{},...c?{accountKind:c}:{},...!p&&a.type?{fieldType:a.type}:{},...!p&&g.length>0?{activeValues:g}:{}})}}let d=gn(e.objectApiName,a=>e.describe.fields.some(c=>c.name===a&&c.createable),a=>r.some(c=>c[a]!==void 0&&c[a]!==null&&c[a]!==""));if(d!==void 0&&!n.some(a=>a.field===d)){let a=e.describe.fields.find(c=>c.name===d)?.type;n.push({objectApiName:e.objectApiName,field:d,isLookup:!1,referenceTo:[],...a?{fieldType:a}:{}})}return n}async alignPicklistValue(e,t,r,n,s,i,d){let a=r==="multipicklist",c=a?s.split(";"):[s],l=e.describe.fields.find(y=>y.name===t),u=new Set((l?.picklistValues??[]).filter(y=>y.active).map(y=>y.value)),f=c.filter(y=>!u.has(y));if(f.length>0){let y=e.ruleFor(e.objectApiName,t);return i.push({objectApiName:e.objectApiName,field:t,referenceId:n.referenceId,value:s,rule:y,scope:"global"}),this.applyRule(y,c,f,a)}let p=e.resolvedRecordTypes.get(n.referenceId);if(!p)return s;let g=await this.uiApiValues(e,p,t,d);if(g===null)return s;let h=c.filter(y=>!g.includes(y));if(h.length===0)return s;let m=e.ruleFor(e.objectApiName,t);return i.push({objectApiName:e.objectApiName,field:t,referenceId:n.referenceId,value:s,rule:m,scope:"record-type"}),this.applyRule(m,c,h,a)}async uiApiValues(e,t,r,n){let s=`${e.orgId}|${e.objectApiName}|${t}|${r}`,i=this.uiApiCache.get(s);if(i!==void 0)return i;try{let d=await this.orgAccess.picklistValues(e.orgId,e.objectApiName,t,r);return this.uiApiCache.set(s,d),d}catch(d){return this.uiApiCache.set(s,null),n.push(`UI API picklist-values read failed for ${e.objectApiName}.${r} (recordType ${t}): ${d instanceof Error?d.message:String(d)}. Record-type assignment gap check skipped for this field.`),null}}applyRule(e,t,r,n){return e.action==="replace"?e.value:n?t.filter(s=>!r.includes(s)).join(";"):""}countRemoval(e,t,r){let n=e.get(t);n?n.count++:e.set(t,{reason:r,count:1})}};function jl(o){return o.slice(0,15)}var Kn=class{met=new Map;updated(e,t){let r=t.filter(n=>n.lockResends!==void 0);r.length>0&&this.of(e,"update").updates.push(...r)}placeholderInserted(e,t){t.lockResends!==void 0&&this.of(e,"placeholder").updates.push(t)}deleted(e,t,r){let n=this.met.get(_d(e,"delete"))?.deletes;r.forEach((s,i)=>{let d=t[i];if(d===void 0)return;let a=jl(d);s.lockResends===void 0&&!n?.has(a)||this.of(e,"delete").deletes.set(a,{id:d,outcome:s})})}list(e){return[...this.met.values()].map(({objectApiName:t,write:r,updates:n,deletes:s})=>{let i=r==="delete"?[...s.values()].map(({id:c,outcome:l})=>({outcome:l,taken:e(t,c)})):n.map(c=>({outcome:c,taken:c.success})),d=0,a=0;for(let{outcome:c,taken:l}of i)l?d++:Tr(c.errors,c.errorDetails)&&a++;return{objectApiName:t,write:r,rows:i.length,written:d,stillLocked:a}})}of(e,t){let r=_d(e,t),n=this.met.get(r);return n||(n={objectApiName:e,write:t,updates:[],deletes:new Map},this.met.set(r,n)),n}};function Bd(o){return[...o.perObject.flatMap(({objectApiName:e,sentAgainForALock:t})=>t&&t.rows>0?[{objectApiName:e,write:"insert",...t}]:[]),...o.sentAgainForALock??[]]}function _d(o,e){return`${e}:${o}`}var _r="Opportunity",Br="SyncedQuoteId",Fl="OpportunityLineItem",es="QuoteLineItem";function ts(o,e){let t=(d,a)=>{let c=new Map;for(let{referenceId:l,fields:u}of o.get(d)??[]){let f=u[a];typeof f!="string"||f===""||!e(l)||c.set(f,(c.get(f)??0)+1)}return c},r=t(Fl,"OpportunityId"),n=t(es,"QuoteId"),s=new Set((o.get("Quote")??[]).map(d=>d.referenceId)),i=[];for(let{referenceId:d,fields:a}of o.get(_r)??[]){let c=a[Br];if(typeof c!="string"||!s.has(c)||!e(d)||!e(c))continue;let l=r.get(d)??0,u=n.get(c)??0;l>u&&i.push({opportunity:d,quote:c,products:l,lines:u})}return i}function Wd(o,e,t=!1){if(o.length===0)return;let r=o.length===1,n=o.reduce((l,u)=>l+u.products,0),s=o.reduce((l,u)=>l+u.lines,0),i=r?"its":"their",d=r?"the quote's":"the quotes'",a=s===0?`none of ${d} lines`:`${s} of ${d} lines`,c=e&&s===0?", which excludedObjects leaves out":"";return{objectApiName:_r,count:o.length,note:`${o.length} ${t?"would be ":""}left unsynced with ${i} quote: the load ${t?"would write":"wrote"} ${n} of ${i} products and ${a}${c} \u2014 synced, the platform replaces an opportunity's products with its quote's lines; ${Br} left empty, the products kept`}}var et=class extends Error{constructor(t,r,n){super(t);this.gaps=r;this.recordTypesUntold=n;this.name="LoadConfigError"}gaps;recordTypesUntold;refusedBeside},qr=class extends Error{constructor(e){super(e),this.name="LoadRecordsExceededError"}},lr=class extends Error{constructor(t){let r=t.reduce((n,s)=>n+s.count,0);super(`This reload finds in the target ${r} record(s) that its purge would delete along with what the loads before it created \u2014 ${t.map(n=>`${n.objectApiName} (${n.count}, under ${n.under.join(", ")})`).join("; ")}: the target deletes them with the record they hang from, which the reload does not find again, and the load would then write against records no longer there. Nothing was written. Give the records they hang from identity keys too, so that the reload finds them again, or take the load back first with a removal, then load the dataset again.`);this.found=t;this.name="ReloadTakesAlongError"}found};function El(o){return o.perObject.reduce((e,t)=>e+t.toInsert,0)}function Ll(o,e){if(!(e===void 0||o<=e))return`This load would insert ${o} record(s), more than the ${e} it may: nothing was written. The dataset or the target changed since that count was taken: preview the load again, and load with the count it gives.`}var Qe=class extends Error{constructor(t,r=!0){super(r?`The load was cancelled ${rc(t,void 0)}`:"The load was cancelled before it created or purged a record: the mapping is left as it was.");this.written=t;this.name="FrozenLoadCancelledError"}written},qt=class extends Error{constructor(t,r,n){super(Nl(t,r,n),{cause:t});this.written=r;this.name="FrozenLoadFailedError",this.mappingKept=n===void 0}written;mappingKept};function Nl(o,e,t){return`${ee(o)}
|
|
10
|
+
The load failed ${rc(e,t)}`}function rc(o,e){let t=new Map,r=(a,c)=>{c!==0&&t.set(a,(t.get(a)??0)+c)};for(let a of o.placeholders)r(a.placeholderObjectApiName,1);for(let a of o.perObject)r(a.objectApiName,a.inserted);let n=[...t.values()].reduce((a,c)=>a+c,0),s=[...Object.values(o.purge.deleted),...Object.values(o.purge.deactivated)].reduce((a,c)=>a+c,0),i=[...n>0?[`created ${n} record(s) (`+[...t].map(([a,c])=>`${a}: ${c}`).join(", ")+")"]:[],...s>0?[`purged ${s} record(s) that earlier loads created`]:[]].join(" and "),d;return e!==void 0?d=n>0?`The mapping could not be written, and nothing names what it created \u2014 no removal or reload will find it: ${e}`:`The mapping could not be written: ${e}`:d=n>0?"What it created is kept in the mapping: a removal takes it back, and a reload purges it or finds it again.":"What the earlier loads created and it did not purge is still named in the mapping, for a removal or the next reload.",i===""?`before it had written the whole dataset. ${d}`:`after it had ${i}. ${d}`}function nc(o,e){let t=[];for(let[r,n]of o.givenRules){let s=[],i={};for(let{referenceId:a,fields:c}of o.alignedByObject.get(r)??[]){if(!gt(c.RecordTypeId)||!e(a))continue;s.push(a);let l=o.withoutRecordType.get(a)??"notRead";i[l]=(i[l]??0)+1}if(s.length===0)continue;let{predicted:d}=n;t.push({given:{objectApiName:r,rows:s.length,why:i,...d?{predicted:d}:{}},rule:n,keys:s})}return t}function oc(o){return{namespacePrefix:o.namespacePrefix,developerName:o.developerName}}function Cl(o){if(!o)return"the user's default record type applies";if(o.kind==="master")return"the target leaves it on Master for that user";let{developerName:e}=o.info;return o.basis==="userDefault"?`the target gives it ${e}, the user's default record type`:`the target gives it ${e}, the only other record type open to the user`}function qd(o){return(e,t)=>!o.failures.some(r=>r.objectApiName===e&&ce(r.recordId)===ce(t))}async function zl(o,e){if(!e.mappingKept())try{await e.keepMapping()}catch(t){return new qt(o,e.written,ee(t))}return new qt(o,e.written)}function sc(o,e,t){let r=t.map(n=>lt(n.namespacePrefix,n.developerName));return new et(`The dataset's ${o} records name record type "${e}" by its label, which ${r.join(" and ")} share in the source: which one each record had cannot be told, the dataset having been extracted before SandForge kept each record's record type by its name. Extract the dataset again. Nothing was written.`,void 0,{reason:"label",objectApiName:o,name:e,recordTypes:r})}function Ml(o){for(let{objectApiName:e,records:t}of o.objects){let r=o.recordTypes[e]??[];if(!(r.length<2))for(let n of t){let s=n.fields.RecordTypeId;if(typeof s!="string"||s==="")continue;if(n.recordTypeDeveloperName!==void 0){let d=Po(n.recordTypeDeveloperName,r,oc);if(d&&"found"in d)continue}let i=r.filter(d=>d.name===s);if(i.length>1)return sc(e,s,i)}}}var ic="Opportunity",Hn="placeholder:",ns=class{byObject=new Map;auditDated=new Set;add(e,t,r=!1){let n=this.byObject.get(e)??[];n.push(t),this.byObject.set(e,n),r&&this.auditDated.add(e)}sentAuditDates(e){return this.auditDated.has(e)}list(e=[]){let t=new Map,r=(n,s)=>{t.set(n,[...t.get(n)??[],...s])};for(let{objectApiName:n,referenceIds:s}of e)r(n,s);for(let[n,s]of this.byObject)r(n,s);return[...t].map(([n,s])=>({objectApiName:n,referenceIds:s}))}};function Dl(o){if(o.startsWith(Hn))return o.split(":")[1]??"Unknown";let e=o.lastIndexOf("-");return e>0?o.slice(0,e):"Unknown"}function xl(o){return typeof o=="number"?String(o):typeof o=="boolean"?o?"TRUE":"FALSE":`'${Be(String(o))}'`}var Pt=200;function ce(o){return o.slice(0,15)}var $l=["CreatedDate","LastModifiedDate"],_l=[["CreatedDate","LastModifiedDate","SystemModstamp"],["SystemModstamp"]];function Wt(o){return typeof o=="string"?Date.parse(o):Number.NaN}function Gd(o){return o.success||o.errors.some(e=>e.includes("ENTITY_IS_DELETED"))}function Ud(o){if(o.tried===0)return"";let e=o.tried-o.went,t=[o.went>0?`${o.went} went`:"",e>0?`${e} refused again`:""].filter(Boolean);return` \u2014 ${o.tried} refused at first, sent again once the rest had gone: ${t.join(", ")}`}function Kd(o,e,t){let r=`Status set to ${e.draft} for the purge, and left there: ${e.status} could not be given back \u2014 ${t}`,n=o.failures.find(s=>s.objectApiName===e.objectApiName&&ce(s.recordId)===ce(e.id));n?n.errors=[...n.errors,r]:o.failures.push({objectApiName:e.objectApiName,recordId:e.id,errors:[r]})}function rs(o,e){let t=(o.notInserted??0)+(e.notInserted??0),r=[o.writtenWithoutFields,e.writtenWithoutFields].reduce((s,i)=>i?Co(s,i):s,void 0),n=[o.sentAgainForALock,e.sentAgainForALock].reduce((s,i)=>i?{rows:(s?.rows??0)+i.rows,written:(s?.written??0)+i.written,stillLocked:(s?.stillLocked??0)+i.stillLocked}:s,void 0);return{objectApiName:e.objectApiName,fromFiles:o.fromFiles+e.fromFiles,inserted:o.inserted+e.inserted,reused:o.reused+e.reused,skippedDuplicates:[...o.skippedDuplicates,...e.skippedDuplicates],failed:[...o.failed,...e.failed],...r?{writtenWithoutFields:r}:{},...t>0?{notInserted:t}:{},...n?{sentAgainForALock:n}:{}}}function Bl(o){if(o.size===0)return;let e=0,t=0;for(let r of o.values())r.success?e++:Tr(r.errors,r.errorDetails)&&t++;return{rows:o.size,written:e,stillLocked:t}}function Vd(o){let e=o.filter(r=>r.replacedWith===void 0).map(r=>r.field),t=o.filter(r=>r.replacedWith!==void 0).map(r=>`${r.field} set to "${r.replacedWith}"`);return[...e.length>0?[`without ${e.join(", ")}`]:[],...t.length>0?[`with ${t.join(", ")}`]:[]].join(" and ")}function Yn(o,e="inserted"){return o>0?`, ${o} not ${e}: the load was cancelled first`:""}function os(o,e="inserted"){return o>0?`, ${o} not ${e}: the load failed`:""}function Wl(o,e){return o>0?"error":e>0?"stopped":"done"}function pt(o,e,t,r){return{phase:o,status:"error",progress:e,message:`${t} \u2014 ${ee(r)}`}}var Hd={phase:"guards",status:"started",progress:0,message:"Running the safety checks"};function Vn(o,e){let{phase:t,progress:r,did:n,refused:s,notDone:i,done:d,notes:a=""}=o;return e?{phase:t,status:"error",progress:r,message:`${n}${os(i,d)}${a} \u2014 ${ee(e.cause)}`}:{phase:t,status:Wl(s,i),progress:r,message:`${n}${Yn(i,d)}${a}`}}var Wr={accountNotInDataset:"its person account is not in the dataset",accountNotLoaded:"person account was not loaded (see perObject failures/skips)",noPersonAccounts:"the target org has no person accounts: it holds the account as a business account, which takes the contact as one of its own",businessAccount:"the target holds the account as a business account, which takes the contact as one of its own"};function ql(o){return o.accountReferenceId===""?"Not written: a person account's contact goes in with its account, which the dataset does not hold":"Not written: a person account's contact goes in with its account, which the load did not write"}function ac(o,e){let t=new Map;for(let{accountReferenceId:r,contactReferenceId:n}of o.personContactSidecar??[])e.get(n)===Ue&&t.set(n,r);for(let r of o.objects.find(n=>n.objectApiName===Ue)?.records??[]){if(t.has(r.referenceId)||!Ar(r.fields))continue;let n=r.fields.AccountId;t.set(r.referenceId,typeof n=="string"&&e.get(n)===Ke?n:"")}return t}function Gl(o){let e=new Set;for(let{accountReferenceId:t}of o.personContactSidecar??[])t!==""&&e.add(t);for(let t of o.objects.find(r=>r.objectApiName===Ke)?.records??[]){let r=t.fields.LastName;(Ar(t.fields)||r!=null)&&e.add(t.referenceId)}return e}function Jn(o,e,t){let r=o.accountKind;return r===void 0?[...e]:e.filter(n=>or(r,t(n.referenceId)))}var Gr=class{constructor(e){this.deps=e;this.config=e.config??{},this.sasGuard=e.sasGuard??new pe}deps;config;sasGuard;journal;lockResent;async gateLoad(e){try{await this.passEntryGuards(e)}catch(s){throw e.onProgress?.(Hd),e.onProgress?.(pt("guards",2,"Safety checks not passed",s)),s}let t=e.dataset;if(e.pilot)try{t=this.filterPilotScope(e.dataset,e.pilot.rootReferenceId)}catch(s){throw e.onProgress?.({phase:"pilot",status:"started",progress:3,message:"Selecting the root folder"}),e.onProgress?.(pt("pilot",4,"Root folder not selected",s)),s}let r=Ml(t);if(r)throw e.onProgress?.({phase:"align",status:"started",progress:12,message:"Resolving record types"}),e.onProgress?.(pt("align",20,"Schema not aligned",r)),r;let n=e.reload===!0&&!e.pilot;return this.consultGuard(e,{orgId:e.orgId,orgTier:e.orgTier,operation:n?"delete":"insert",objectName:e.dataset.objects.filter(s=>s.records.length>0).map(s=>s.objectApiName).join(", "),recordCount:{atMost:cr(e.dataset)},module:"frozendataset"})}passEntryGuards(e){return $d({orgId:e.orgId,...e.orgName!==void 0?{orgName:e.orgName}:{},orgTier:e.orgTier,...e.stagingReplay?{stagingReplay:!0}:{},dataset:e.dataset,manifest:e.manifest,mockDetector:this.deps.mockDetector,protectedOrgIds:this.config.protectedOrgIds})}async load(e){let t={};try{return await this.loadKeeping(e,t)}finally{await this.journal?.close().catch(()=>{}),this.journal=void 0,this.lockResent=void 0}}async loadKeeping(e,t){try{return await this.loadInto(e,t)}catch(r){t.endOpenLine?.(r);let n=t.load;throw r instanceof Qe||!n?.wroteSome()?r:await zl(r,n)}}async planLoad(e){let t=e.now??(()=>new Date),r=d=>e.onProgress?.(d),n=await this.prepare(e,r,{}),s=e.reload&&!e.pilot?await this.planPurge(e.orgId,n.previousLoads,n.mapping):void 0;if(s){let d=await this.foundUnderThePurge(e.orgId,s.residuals,n.mapping,n.refIndex);if(d.length>0)throw new lr(d)}let i=Jd(n,s,{orgId:e.orgId,mode:{pilot:e.pilot!==void 0,reload:e.reload===!0},plannedAt:t().toISOString(),undeletableObjects:this.config.undeletableObjects??{},requiredFieldDefaults:this.config.requiredFieldDefaults??{},excludedObjects:this.config.excludedObjects??[]});return this.withValidationRules(i)}async withValidationRules(e){let t=this.deps.readValidationRules,r=e.perObject.filter(a=>a.toInsert>0).map(a=>a.objectApiName),n=[...new Set([...r,...e.placeholders.map(a=>a.placeholderObjectApiName)])];if(!t||n.length===0)return e;let s=new Map,i=new Map;try{for(let{objectApiName:a,onChangeOnly:c,...l}of await t(n))c?i.set(a,[...i.get(a)??[],l.name]):s.set(a,[...s.get(a)??[],l])}catch(a){return{...e,validationRulesUnread:ee(a)}}let d=new Set(r);return{...e,perObject:e.perObject.map(a=>{if(a.toInsert===0)return a;let c=s.get(a.objectApiName)??[],l=i.get(a.objectApiName)??[];return{...a,...c.length>0?{validationRules:c}:{},...l.length>0?{validationRulesOnChange:l}:{}}}),placeholders:e.placeholders.map(a=>{let c=d.has(a.placeholderObjectApiName)?[]:s.get(a.placeholderObjectApiName)??[];return c.length>0?{...a,validationRules:c}:a})}}async prepare(e,t,r){let{orgId:n}=e;t(Hd);try{await this.passEntryGuards(e)}catch($){throw t(pt("guards",2,"Safety checks not passed",$)),$}t({phase:"guards",status:"done",progress:2,message:"Safety checks passed"}),t({phase:"mapping",status:"started",progress:2,message:"Reading the mapping of earlier loads"});let s=await this.deps.mappingStore.previousLoads().catch($=>{throw t(pt("mapping",3,"Mapping not read",$)),$});t({phase:"mapping",status:"done",progress:3,message:`Mapping read: ${s.length} earlier load(s)`});let i=e.dataset;if(e.pilot){t({phase:"pilot",status:"started",progress:3,message:"Selecting the root folder"});try{i=this.filterPilotScope(e.dataset,e.pilot.rootReferenceId)}catch(U){throw t(pt("pilot",4,"Root folder not selected",U)),U}let $=i.objects.reduce((U,oe)=>U+oe.records.length,0);t({phase:"pilot",status:"done",progress:4,message:`Root folder selected: ${$} record(s)`})}let d=as(i),a=Hl(e.dataset),c=ac(i,d),l=tu(i,d,c),u=oi(l),f=u.flat(),p=new nr,g=new nr(eu),h={...i,objects:i.objects.map($=>({...$,records:$.records.filter(U=>!p.leaveOut($.objectApiName,U.referenceId,ai($.objectApiName,U.fields,typeof U.fields.RelationId=="string"?d.get(U.fields.RelationId):void 0))&&!g.leaveOut($.objectApiName,U.referenceId,U.fields))}))},m=new Map,y=new Set,R=new Set;if(e.reload||e.linkByKeys){t({phase:"reload",status:"started",progress:5,message:"Reusing reference data"}),r.endOpenLine=$=>t(pt("reload",10,"Reference data not reused",$)),await this.reuseByIdentityKeys(e,h,m,y);for(let $ of y)R.add($);t({phase:"reload",status:"done",progress:10,message:`Reference data: ${y.size} reused`}),r.endOpenLine=void 0}if(h.standardPricebook||Qd(h).length>0){t({phase:"catalog",status:"started",progress:10,message:"Looking up the catalog the target already holds"});let $;try{$=await this.lookUpTheCatalog(n,h,m,y)}catch(U){throw t(pt("catalog",11,"Catalog not looked up",U)),U}t({phase:"catalog",status:"done",progress:11,message:`Catalog looked up: ${$.join("; ")}`})}t({phase:"align",status:"started",progress:12,message:"Resolving record types"}),r.endOpenLine=$=>t(pt("align",20,"Schema not aligned",$));let j=[],T=new Map,P=new Map,_=new Map;for(let $ of h.objects){let U=[];for(let oe of $.records)U.push(await this.resolveRecordType(e,i,$.objectApiName,oe,P,j,_));T.set($.objectApiName,U)}let q=new Un(this.deps.orgAccess),C={objectResults:[],excludedObjects:[],removals:[],adjustments:[],recordTypeIssues:j},I=new Map,w=new Map,O=new Map,F=new Map,v=new Map,A,L=Gl(i),x=$=>L.has($)?A===!1?"personAsBusiness":"person":"business",B=new Map,D=new Map,G=e.writeEncrypted!==!0&&e.manifest?.coverage?.encryptedNotKept===void 0;for(let $ of h.objects){let U=$.objectApiName;if($.records.length===0)continue;let oe=$.records.filter(S=>!y.has(S.referenceId)),se=(S,Y,J)=>{C.excludedObjects.push({objectApiName:U,reason:S,...J}),v.set(U,{objectApiName:U,fromFiles:i.objects.find(re=>re.objectApiName===U)?.records.length??$.records.length,inserted:0,reused:$.records.length-oe.length,skippedDuplicates:[],failed:oe.map(re=>({objectApiName:U,referenceId:re.referenceId,errors:[Y]}))}),oe.length!==0&&t({phase:"align",objectName:U,status:"error",progress:12,message:`Skipped ${U} \u2014 ${S}`})},me;try{me=await this.deps.orgAccess.describe(n,U)}catch(S){let Y=S instanceof Error?S.message:String(S),J=`Not present in target org: ${Y}. Deploy it to the target, or give the loading user Read on it, then load again; or leave it out of the configuration (excludedObjects) and extract again`;se(J,J,{cause:"notInTarget",detail:Y});continue}if(U===Ke&&(A=me.fields.some(S=>S.name===bn)),me.createable===!1&&oe.length>0){se(`Not createable in target org: ${oe.length} record${oe.length===1?"":"s"} of the dataset not loaded. Give the loading user Create on it in a permission set, where the platform lets a user create it; otherwise leave it out of the configuration (excludedObjects) and extract again`,"Not createable in target org: the running user may not insert it",{cause:"notCreateable",records:oe.length});continue}O.set(U,new Set(me.fields.filter(S=>S.updateable===!1).map(S=>S.name)));let de=me.fields.filter(S=>S.lookupFilter!==void 0&&S.createable&&(S.referenceTo?.length??0)>0).map(S=>({field:S.name,referenceTo:[...S.referenceTo??[]]}));de.length>0&&F.set(U,de);let Fe=Sn(me.recordTypeInfos);if(Fe.some(S=>!S.master)){let S=od(zn(Fe));D.set(U,{types:Fe,...S?{predicted:S}:{}})}let k=Xl(U,me,this.config);k.length>0&&B.set(U,k),w.set(U,new Set(me.fields.filter(S=>S.createable&&!S.nillable&&!S.defaultedOnCreate&&(S.referenceTo?.length??0)>0).map(S=>S.name)));let E=await q.alignObject({orgId:n,objectApiName:U,records:T.get(U)??[],describe:me,resolvedRecordTypes:P,ruleFor:(S,Y)=>this.picklistRuleFor(S,Y),linked:y,...U===Ke?{accountKindOf:x}:{},...G?{leaveOutEncrypted:G}:{}});C.objectResults.push(E),C.removals.push(...E.removals),C.adjustments.push(...E.adjustments),I.set(U,E.alignedRecords.map((S,Y)=>({referenceId:(T.get(U)??[])[Y].referenceId,fields:S})))}let X=await this.linkWhatThePlatformKeeps(n,C.objectResults,I,a,m,y,x),K=e.reload||e.linkByKeys?await this.reuseByKeysAsWritten(n,h,C.objectResults,I,a,m,y,x):{linked:[],said:[],leftEmpty:[]};for(let $ of[...X.linked,...K.linked])R.add($);let H=[...X.said,...K.said];t({phase:"align",status:"done",progress:20,message:`Schema aligned${H.length>0?` \u2014 ${H.join("; ")}`:""}`}),r.endOpenLine=void 0;let N=new nr(Zl(B));Jl(I,w,[p,g,N]);for(let $ of C.objectResults){let U=(I.get($.objectApiName)??[]).filter(oe=>!y.has(oe.referenceId));$.missingRequired=$.missingRequired.filter(oe=>Jn(oe,U,x).some(se=>gt(se.fields[oe.field])))}t({phase:"placeholders",status:"started",progress:22,message:"Checking required fields"});let Z=await this.planRequiredFields(e,C.objectResults).catch($=>{throw t(pt("placeholders",22,"Required fields not covered",$)),$});return t({phase:"placeholders",status:"done",progress:22,message:"Required fields checked"}),{previousLoads:s,working:i,refIndex:d,personContacts:c,groups:u,groupOrder:f,leftToThePlatform:p,untypedFeedItems:g,heldForExclusions:N,loading:h,mapping:m,reused:y,reusedByKeys:R,ranks:a,recordTypeIssues:j,alignment:C,alignedByObject:I,requiredLookups:w,fixedAtInsert:O,filteredLookups:F,lostObjects:v,targetHasPersonAccounts:A,accountKindOf:x,plans:Z,givenRules:D,withoutRecordType:_,keysLeftEmpty:[...X.leftEmpty,...K.leftEmpty]}}async loadInto(e,t){let r=e.now??(()=>new Date),n=r(),s=b=>e.onProgress?.(b),{orgId:i}=e;this.journal=this.deps.mappingStore.journal?.(n);let d=new Kn;this.lockResent=d;let a=await this.prepare(e,s,t),{previousLoads:c,working:l,refIndex:u,personContacts:f,groups:p,groupOrder:g,leftToThePlatform:h,untypedFeedItems:m,heldForExclusions:y,mapping:R,reused:j,ranks:T,recordTypeIssues:P,alignment:_,alignedByObject:q,requiredLookups:C,fixedAtInsert:I,lostObjects:w,targetHasPersonAccounts:O,accountKindOf:F,plans:v}=a,A=Ll(El(Jd(a,void 0,{orgId:i,mode:{pilot:e.pilot!==void 0,reload:e.reload===!0},plannedAt:n.toISOString(),undeletableObjects:this.config.undeletableObjects??{},requiredFieldDefaults:this.config.requiredFieldDefaults??{},excludedObjects:this.config.excludedObjects??[]})),e.maxRecords);if(A)throw new qr(A);let L=await this.runUserIdOf(i);L&&this.journal?.writtenAs(L);let x={deleted:{},deactivated:{},failures:[]},B=[],D=[],G=new ns,X=new Map,K=[],H=new Set,N,Z=new Map,$=!1,U=async()=>{let b=await this.readWrittenBetween(i,G,R),W=N?.linked??new Map,z=e.pilot?void 0:e.purgeSweep?.stillToSweep?.();await this.deps.mappingStore.persist(R,{created:G.list(K),startedAt:n,...b?{writtenBetween:b}:{},earlier:{settled:[...H],...z&&z.length>0?{stillToSweep:[...z]}:{}},...W.size>0?{personContacts:Object.fromEntries(W)}:{},...Z.size>0?{withTheirRecord:Object.fromEntries(Z)}:{},...L?{runUserId:L}:{}}),$=!0},oe=()=>G.list().length>0||Object.keys(x.deleted).length>0||Object.keys(x.deactivated).length>0,se=async()=>{if(!e.signal?.aborted)return;let b=oe();throw b&&await U(),new Qe(me(),b)},me=()=>{let b=d.list(qd(x));return{perObject:D,placeholders:B,purge:x,...b.length>0?{sentAgainForALock:b}:{}}};t.load={keepMapping:U,mappingKept:()=>$,wroteSome:oe,get written(){return me()}};let de=[];if(e.reload){let b="",W={residuals:0},z={tried:0,went:0},ae=be=>{let Te=Ne=>Object.values(Ne).reduce((Re,ue)=>Re+ue,0);return Vn({phase:"reload",progress:24,did:`Purge: ${Te(x.deleted)} deleted, ${Te(x.deactivated)} deactivated, ${x.failures.length} failed`,refused:x.failures.length,notDone:W.residuals,done:"purged",notes:`${Ud(z)}${b}`},be)};if(!e.pilot){s({phase:"reload",status:"started",progress:23,message:"Purging what earlier loads created"});let be=await this.planPurge(i,c,R),Te=await this.foundUnderThePurge(i,be.residuals,R,u);if(Te.length>0){let ue=new lr(Te);throw s(ae({cause:ue})),ue}K=be.carried;for(let ue of K.flatMap(ne=>ne.referenceIds)){let ne=R.get(ue);ne&&H.add(ce(ne))}let Ne=Object.values(be.leftUnrecorded).reduce((ue,ne)=>ue+ne,0);Ne>0&&(x.leftUnrecorded=be.leftUnrecorded,b=` \u2014 ${Ne} record(s) left in place of a load recorded before loads kept what they created: it may have linked them`);let Re=Object.entries(be.keptByThePlatform);Re.length>0&&(x.keptByThePlatform=be.keptByThePlatform,b+=" \u2014 kept, the platform does not delete them: "+Re.map(([ue,ne])=>`${ue} (${ne})`).join(", "));try{e.purgeSweep&&(await se(),await e.purgeSweep.first()),await this.purgeResiduals(e,be,[...g].reverse(),x,se,H,W,z),e.purgeSweep&&!e.signal?.aborted&&await e.purgeSweep.afterPurge()}catch(ue){throw s(ae(ue instanceof Qe?void 0:{cause:ue})),ue}for(let ue of c)if(!ue.created)for(let ne of ue.mapping.values())H.add(ce(ne));s(W.residuals>0||x.failures.length>0?ae():{phase:"reload",status:"done",progress:24,message:`Reload pass done${Ud(z)}${b}`})}}let Fe=b=>(q.get(b)??[]).filter(W=>!j.has(W.referenceId)),k=v.filter(b=>b.kind==="placeholder").length,E=b=>Vn({phase:"placeholders",progress:25,did:`Placeholders: ${B.length} created`,refused:0,notDone:k-B.length,done:"created"},b);k>0&&(await se(),s({phase:"placeholders",status:"started",progress:24,message:"Creating placeholders"}));try{for(let b of v)b.kind==="placeholder"?(await se(),await this.createPlaceholder(e,b,Fe(b.missing.objectApiName),R,B,G)):this.applyScalarDefault(b.missing,Jn(b.missing,Fe(b.missing.objectApiName),F),de,T)}catch(b){throw s(E(b instanceof Qe?void 0:{cause:b})),b}k>0&&s(E());let S=p.flatMap(b=>b.length>1?si(b,ru(q,C,u,f)):b),Y=[],J=[],re=this.config.duplicateErrorPatterns??Ad,Ie=new Set(S.includes(rr)?(q.get(rr)??[]).map(b=>b.referenceId):[]),Q=[],Ee=null,M=0,we=!1,We=b=>b===Xe&&Q.length>0?`, ${Q.length} on a case waiting for ${Q.length===1?"its task":"their tasks"}`:"",He=new Set,V=async()=>{if(N)return N;let b=await this.linkPersonContacts(i,f,R,j,O,P);for(let W of b.linked.keys())j.add(W);return He=new Set(b.unlinked.map(W=>W.contactReferenceId).filter(W=>!j.has(W))),N=b,b},ie=b=>{if(b.objectApiName!==Ue||!N)return b;let W=N.unlinked.filter(z=>He.has(z.contactReferenceId));return W.length===0?b:{...b,failed:[...b.failed,...W.map(z=>({objectApiName:Ue,referenceId:z.contactReferenceId,errors:[ql(z)]}))]}},Le=()=>{if(N)for(let[b,W]of N.own)R.has(b)||(N.own.delete(b),N.unlinked.push({accountReferenceId:W.accountReferenceId,contactReferenceId:b,cause:"target-not-loaded",detail:`contact ${b} was not loaded (skipped, failed or excluded)`}))},he=()=>{let b=N?.linked.size??0,W=N?.own.size??0,z=He.size;return[...b>0?[`${b} linked to the contact the platform wrote with ${b===1?"its":"their"} person account`]:[],...W>0?[`${W} sent as ${W===1?"a contact of its own":"contacts of their own"}: the target holds ${W===1?"its":"their"} account as a business account`]:[],...z>0?[`${z} not written: a person account's contact goes in with its account`]:[]]},jt=(b,W)=>[...b===Ue?he():[],...W?[W]:[],...h.counts(b).map(({why:z,count:ae})=>ii(ae,z)),...m.counts(b).map(({why:z,count:ae})=>Zd(ae,z)),...y.counts(b).map(({why:z,count:ae})=>gc(ae,z))].map(z=>`, ${z}`).join(""),rt=(b,W,z,ae,be)=>{let Te=D.findIndex(Zt=>Zt.objectApiName===b),Ne=Te>=0?D[Te]:void 0,Re=z.filter(Zt=>j.has(Zt.referenceId)).length,ue=Ne?.inserted??0,ne=Ne?.skippedDuplicates??[],De=Ne?.failed??[],ct=Ne?.writtenWithoutFields,Oe=Ne?.sentAgainForALock,Xt=z.length-Re-ue-ne.length-De.length,ht=ie({objectApiName:b,fromFiles:W,inserted:ue,reused:Re,skippedDuplicates:ne,failed:De,...ct?{writtenWithoutFields:ct}:{},...Xt>0?{notInserted:Xt}:{},...Oe?{sentAgainForALock:Oe}:{}});Ne?D[Te]=ht:D.push(ht),s({phase:"insert",objectName:b,status:"error",progress:25+Math.round(55*M/Math.max(S.length,1)),message:`${b}: ${ue} inserted, ${ht.reused} reused, ${ne.length} duplicates skipped, ${ht.failed.length} failed${We(b)}${os(Xt)}${Ln(ct)}${jt(b,ae)} \u2014 ${ee(be)}`})},Ye,ge=(b,W,z)=>{if(b.waiting>0){let Re=D.find(ue=>ue.objectApiName===Xe);Re&&(Re.notInserted=(Re.notInserted??0)+b.waiting)}let ae=W==="cancel"&&b.waiting>0,be="";ae?be=Yn(b.waiting):b.waiting>0&&(be=os(b.waiting));let Te=b.status;z?Te="error":ae&&b.status!=="error"&&(Te="stopped");let Ne=z?` \u2014 ${ee(z.cause)}`:"";s({phase:"insert",objectName:Xe,status:Te,progress:25+Math.round(55*M/Math.max(S.length,1)),message:`${b.message}${be}${b.notes}${Ne}`})},ve=async()=>{let b=Ee;b&&e.signal?.aborted&&(Ee=null,ge(b,"cancel")),await se()};t.endOpenLine=b=>{let W=Ye;Ye=void 0,W&&!(b instanceof Qe)&&W(b);let z=Ee;Ee=null,z&&ge(z,b instanceof Qe?"cancel":"failure")};let Ft=async()=>{we=!0;let b=Q.splice(0,Q.length),W=Ee;if(Ee=null,b.length===0)return;let z=25+Math.round(55*M/Math.max(S.length,1)),ae;try{await se()}catch(ne){throw W&&ge(W,ne instanceof Qe?"cancel":"failure"),ne}let be=ne=>`${ne.inserted} inserted, ${ne.reused} reused, ${ne.skippedDuplicates.length} duplicates skipped, ${ne.failed.length} failed${Yn(ne.notInserted??0)}${Ln(ne.writtenWithoutFields)}`,Te=ne=>{let De=D.findIndex(ct=>ct.objectApiName===Xe);De>=0?D[De]=rs(D[De],ne):D.push(ne)},Ne={};try{ae=await this.insertObject(e,Xe,0,b,u,R,j,Y,re,G,X,Yd(D),ne=>{Ne.result=ne})}catch(ne){let De=Ne.result;if(De&&Te(De),W&&De){let ct=De.inserted+De.skippedDuplicates.length+De.failed.length;ge({...W,waiting:Math.max(W.waiting-ct,0),message:`${W.message}; after their task: ${be(De)}`},"failure",{cause:ne})}else W&&ge(W,"failure",{cause:ne});throw ne}Te(ae);let Re=be(ae),ue="done";ae.failed.length>0||W?.status==="error"?ue="error":(ae.notInserted??0)>0&&(ue="stopped"),s({phase:"insert",objectName:Xe,status:ue,progress:z,message:W?`${W.message}; after their task: ${Re}${W.notes}`:`${Xe} after their task: ${Re}`})};for(let b of S){await ve();let W=q.get(b);if(!W){let fe=w.get(b);if(fe&&b===Ue&&f.size>0){try{await V()}catch(xe){throw s({phase:"insert",objectName:b,status:"error",progress:25+Math.round(55*M/Math.max(S.length,1)),message:`${b}: person accounts' contacts not linked \u2014 ${ee(xe)}`}),xe}Le();let Ce=N?.linked??new Map,ze=fe.failed.filter(xe=>!Ce.has(xe.referenceId));D.push({...fe,reused:fe.reused+fe.failed.length-ze.length,failed:ze})}else fe&&D.push(fe);continue}M++,s({phase:"insert",objectName:b,status:"started",progress:25+Math.round(55*M/Math.max(S.length,1)),message:`Inserting ${b}`});let z,ae=l.objects.find(fe=>fe.objectApiName===b)?.records.length??W.length,be=W;if(Ye=fe=>rt(b,ae,be,z,fe),b===Ue&&f.size>0){let fe=await V();be=W.filter(Ce=>!He.has(Ce.referenceId));for(let Ce of be){let ze=fe.own.get(Ce.referenceId),xe=Ce.fields.AccountId;ze&&(xe==null||xe==="")&&(Ce.fields.AccountId=ze.accountReferenceId)}}b===Sr&&await this.matchDirectRelations(i,l,W,R,j,Z),b===rr&&await this.matchTasksWrittenWithEmails(i,l,W,R,j,Z),Io[b]!==void 0&&(z=await this.matchActivityRelations(e,b,W,R,j,I.get(b)??new Set));let Te=0;if(b===$t){let fe=await this.matchContactRolesWrittenWithOpportunities(e,{working:l,aligned:W,refIndex:u,mapping:R,reused:j,withTheirRecord:Z,pendingFk:Y,fixedAtInsert:I.get(b)??new Set});Te=fe.linked,z=fe.note}let Ne=_t[b],Re=Ne?await this.startAsDrafts(i,b,Ne,be,J):be;if(b===Xe&&!we&&Ie.size>0){let fe=Ce=>li(Ce,ze=>u.get(ze))&&Ie.has(String(Ce.ActivityId));Q.push(...Re.filter(Ce=>fe(Ce.fields))),Re=Re.filter(Ce=>!fe(Ce.fields))}let ue=Re.filter(fe=>!j.has(fe.referenceId)).length,ne=e.signal?.aborted===!0&&ue>0,De=(fe,Ce,ze=xe=>D.push(xe))=>this.insertObject(e,b,Ce,fe,u,R,j,Y,re,G,X,Yd(D),ze),ct=l.standardPricebook,Oe;if(ne)Oe={objectApiName:b,fromFiles:ae,inserted:0,reused:Re.length-ue,skippedDuplicates:[],failed:[],notInserted:ue};else if(fn(b)&&ct){let fe=await De(Re.filter(ze=>ze.fields[yt]===ct),0),Ce=Re.filter(ze=>ze.fields[yt]!==ct);if(e.signal?.aborted){let ze=Ce.filter(Ol=>j.has(Ol.referenceId)).length,xe={...fe,fromFiles:ae,reused:fe.reused+ze},Qt=Re.length-xe.inserted-xe.reused-xe.skippedDuplicates.length-xe.failed.length;Oe={...xe,...Qt>0?{notInserted:Qt}:{}}}else{let ze={},xe=await De(Ce,ae,Qt=>{ze.result=Qt}).catch(Qt=>{throw D.push(ze.result?rs(fe,ze.result):{...fe,fromFiles:ae}),Qt});Oe=rs(fe,xe)}}else Oe=await De(Re,ae);Ye=void 0,b===Ue&&Le(),Oe=ie(Oe),Te>0&&(Oe={...Oe,writtenByThePlatform:Te});let Xt=b===Xe?Q.filter(fe=>!j.has(fe.referenceId)).length:0;(Oe.notInserted??0)>0&&(Oe.notInserted=(Oe.notInserted??0)+Xt);let ht=Oe.notInserted??0;D.push(Oe);let Zt=jt(b,z),qs=We(b),yo=Oe.failed.length>0,Gs=yo?"error":"done";!yo&&ht>0&&(Gs="stopped");let Us=25+Math.round(55*M/Math.max(S.length,1)),wo=`${b}: ${Oe.inserted} inserted, ${Oe.reused} reused, ${Oe.skippedDuplicates.length} duplicates skipped, ${Oe.failed.length} failed${qs}${Yn(ht)}${Ln(Oe.writtenWithoutFields)}`;qs&&ht===0?(Ee={status:yo?"error":"done",message:wo,notes:Zt,waiting:Xt},s({phase:"insert",objectName:b,status:"started",progress:Us,message:wo})):s({phase:"insert",objectName:b,status:Gs,progress:Us,message:`${wo}${Zt}`}),b===rr&&await Ft(),ht>0&&await ve()}await Ft(),await se(),s({phase:"pass2",status:"started",progress:82,message:"Patching cycle FKs"});let dt={report:{resolved:0,unresolved:[]},unanswered:0},kt=ts(q,b=>R.has(b)),dn=new Set(kt.map(b=>b.opportunity)),mo=Y.filter(b=>b.objectApiName!==_r||b.field!==Br||!dn.has(b.referenceId)),wr=kt.length>0?`, ${kt.length} synced quote${kt.length===1?"":"s"} left unset`:"",br=b=>Vn({phase:"pass2",progress:88,did:`Pass 2: ${dt.report.resolved} resolved, ${dt.report.unresolved.length} unresolved${wr}`,refused:dt.report.unresolved.length,notDone:dt.unanswered,done:"resolved"},b);try{await this.patchCycleFks(e,mo,R,dt)}catch(b){throw s(br({cause:b})),b}s(br());let Et=dt.report;await se();let Me={report:{restored:0,refused:[]},unanswered:0},Yt=b=>Vn({phase:"pass2",progress:89,did:`Statuses: ${Me.report.restored} applied, ${Me.report.refused.length} refused`,refused:Me.report.refused.length,notDone:Me.unanswered,done:"applied"},b);try{await this.applyDeferredStatuses(e,J,R,Me)}catch(b){throw s(Yt({cause:b})),b}let Lt=Me.report;Lt.restored+Lt.refused.length+Me.unanswered>0&&s(Yt()),await se();let It=await V(),nt={restored:It.linked.size,sent:[...It.own.values()],unresolved:It.unlinked};f.size>0&&s({phase:"personcontact",status:It.unlinked.length>0?"error":"done",progress:94,message:`Person contacts: ${It.linked.size} linked to the contact the platform wrote with their account, ${It.own.size} sent as contacts of their own, ${It.unlinked.length} not linked`}),await se(),await e.lease?.giveBack().catch(()=>{}),s({phase:"persist",status:"started",progress:96,message:"Persisting mapping and contract"}),await U();let Nt=h.counts(),Rr=m.counts(),vt=y.counts(),kr=this.writeContract(e,l,D,B,{now:r,startedAt:n},new Set(w.keys()),[...Nt.map(({objectApiName:b,count:W})=>({objectApiName:b,count:W,reason:"left-to-the-platform"})),...Rr.map(({objectApiName:b,count:W})=>({objectApiName:b,count:W,reason:"untyped-feed-item"})),...vt.map(({objectApiName:b,count:W})=>({objectApiName:b,count:W,reason:"excluded-parent"}))],He.size,X,Et.unresolved.filter(b=>b.cause==="target-not-loaded"));s({phase:"persist",status:"done",progress:98,message:"Sas artifacts written"});let Ir=D.some(b=>b.failed.length>0)||Et.unresolved.length>0||nt.unresolved.length>0||Lt.refused.length>0||x.failures.length>0,Jt=new Set(G.list().flatMap(({referenceIds:b})=>b)),Ct=await this.readBackRecordTypes(i,nc(a,b=>Jt.has(b)),R),vr=d.list(qd(x)),zt={status:Ir?"completed-with-errors":"completed",orgId:i,mode:{pilot:e.pilot!==void 0,reload:e.reload===!0},startedAt:n.toISOString(),durationMs:r().getTime()-n.getTime(),alignment:_,placeholders:B,requiredDefaults:de,perObject:D,...vr.length>0?{sentAgainForALock:vr}:{},pass2:Et,personContact:nt,statuses:Lt,purge:x,...Nt.length>0?{leftToThePlatform:Bn(Nt)}:{},...Rr.length>0?{untypedFeedItems:Rr.map(({objectApiName:b,why:W,count:z})=>({objectApiName:b,count:z,note:Zd(z,W)}))}:{},...vt.length>0?{heldForExcludedParents:hc(vt)}:{},...pc(kt,this.config),...cc(a.keysLeftEmpty),...Ct.length>0?{recordTypesGiven:Ct}:{},...L?{runUserId:L}:{},mappingPath:this.deps.mappingStore.filePath,contractPath:kr};return s({phase:"done",status:zt.status==="completed"?"done":"error",progress:100,message:`Load ${zt.status}`}),zt}async checkGuard(e,t,r,n){await this.consultGuard(e,{orgId:e.orgId,orgTier:e.orgTier,operation:t,objectName:r,recordCount:n,module:"frozendataset"})}async consultGuard(e,t){let{check:r,decision:n}=await Tn(this.deps.guard,t);if(e.onGuardDecision?.(n),n==="refused"||n==="declined")throw new Ve("guard-refused",`Production guard refused ${t.operation} on ${t.objectName}: ${r.blockedReason??"confirmation declined"}`,{decision:n,...n==="refused"&&r.blockedReason!==void 0?{reason:r.blockedReason}:{}});return n}filterPilotScope(e,t){return ds(e,this.config.rootObjectApiName,t)}async reuseByIdentityKeys(e,t,r,n){for(let[s,i]of Object.entries(this.config.identityKeys??{})){let d=t.objects.find(a=>a.objectApiName===s)?.records??[];for(let[a,c]of await this.findByKeys(e.orgId,s,i,d))r.set(a,c),n.add(a)}}async findByKeys(e,t,r,n){let s=new Map,i=n.filter(l=>r.every(u=>!gt(l.fields[u])));if(i.length===0)return s;let d=["Id",...r].map(ye).join(", "),a=new Map,c=100;for(let l=0;l<i.length;l+=c){let u=i.slice(l,l+c).map(p=>`(${r.map(g=>`${ye(g)} = ${xl(p.fields[g])}`).join(" AND ")})`).join(" OR "),f=`SELECT ${d} FROM ${ye(t)} WHERE ${u}`;for(let p of await this.deps.orgAccess.query(e,f))typeof p.Id=="string"&&a.set(ec(r.map(g=>p[g])),p.Id)}for(let l of i){let u=a.get(ec(r.map(f=>l.fields[f])));u&&s.set(l.referenceId,u)}return s}async linkWhatThePlatformKeeps(e,t,r,n,s,i,d){let a={linked:[],said:[],leftEmpty:[]};for(let[c,l]of Object.entries(Cr)){let u=this.config.identityKeys?.[c]??l,f=(r.get(c)??[]).filter(g=>!i.has(g.referenceId));if(f.length===0)continue;let p=await this.linkByKeysAsWritten(e,{objectApiName:c,keyFields:u,records:f,missingRequired:t.find(g=>g.objectApiName===c)?.missingRequired??[],ranks:n,accountKindOf:d},s,i,a);p>0&&a.said.push(`${c}: ${p} found by ${u.join(", ")}, which the platform does not delete`)}return a}async reuseByKeysAsWritten(e,t,r,n,s,i,d,a){let c={linked:[],said:[],leftEmpty:[]};for(let[l,u]of Object.entries(this.config.identityKeys??{})){if(Object.prototype.hasOwnProperty.call(Cr,l))continue;let f=new Set((t.objects.find(h=>h.objectApiName===l)?.records??[]).filter(h=>u.some(m=>gt(h.fields[m]))).map(h=>h.referenceId)),p=(n.get(l)??[]).filter(h=>f.has(h.referenceId)&&!d.has(h.referenceId));if(p.length===0)continue;let g=await this.linkByKeysAsWritten(e,{objectApiName:l,keyFields:u,records:p,missingRequired:r.find(h=>h.objectApiName===l)?.missingRequired??[],ranks:s,accountKindOf:a},i,d,c);g>0&&c.said.push(`${l}: ${g} found by ${u.join(", ")}, as the load writes `+(g===1?"it":"them"))}return c}async linkByKeysAsWritten(e,t,r,n,s){let{objectApiName:i,keyFields:d}=t,a=Vl(t,this.config.requiredFieldDefaults??{}),c=a.flatMap(u=>{let f=d.filter(p=>gt(u.fields[p]));return f.length>0?[f]:[]});if(c.length>0){let u=d.filter(f=>c.some(p=>p.includes(f)));s.leftEmpty.push({objectApiName:i,fields:u,count:c.length}),s.said.push(`${i}: ${c.length} not looked up, ${u.join(", ")} left empty`)}let l=await this.findByKeys(e,i,d,a);for(let[u,f]of l)r.set(u,f),n.add(u),s.linked.push(u);return l.size}async lookUpTheCatalog(e,t,r,n){let s=[],i=t.standardPricebook;if(i){let[c]=await this.deps.orgAccess.query(e,Mt);typeof c?.Id=="string"?(r.set(i,c.Id),n.add(i),s.push("standard price book linked")):s.push("standard price book not found")}let d=await this.matchByNaturalKey(e,t,r,n),a=await this.matchSellingModelOptions(e,t,r,n);Qd(t).includes(_e)&&d.push({objectApiName:_e,linked:a});for(let{objectApiName:c,linked:l,notAsked:u}of d)u===void 0&&s.push(`${c}: ${l} linked`);for(let{objectApiName:c,notAsked:l}of d)l!==void 0&&s.push(`${c} not looked up \u2014 ${l}`);return s}async matchByNaturalKey(e,t,r,n){let s=[];for(let[i,d]of Object.entries(wn)){let a=t.objects.find(f=>f.objectApiName===i)?.records??[];if(a.length===0)continue;let c=a.filter(f=>!r.has(f.referenceId)&&d.every(p=>f.fields[p]!==void 0&&f.fields[p]!=="")),l=[];if(c.length>0)try{l=await Ii(f=>this.deps.orgAccess.query(e,f),i,d,c.map(f=>f.fields))}catch(f){s.push({objectApiName:i,linked:0,notAsked:ee(f)});continue}let u=0;c.forEach((f,p)=>{let g=l[p];g!==void 0&&(r.set(f.referenceId,g),n.add(f.referenceId),u++)}),s.push({objectApiName:i,linked:u})}return s}async matchSellingModelOptions(e,t,r,n){let s=[];for(let d of t.objects.find(a=>a.objectApiName===_e)?.records??[]){if(r.has(d.referenceId))continue;let a=d.fields[Ge],c=d.fields[Je],l=typeof a=="string"?r.get(a):void 0,u=typeof c=="string"?r.get(c):void 0;l===void 0||u===void 0||s.push({referenceId:d.referenceId,pair:{[Ge]:l,[Je]:u}})}if(s.length===0)return 0;let i=await ki(d=>this.deps.orgAccess.query(e,d),s.map(d=>d.pair));for(let[d,a]of i)r.set(s[d].referenceId,a),n.add(s[d].referenceId);return i.size}async planPurge(e,t,r){let n={residuals:new Map,datedBy:new Map,carried:[],leftUnrecorded:{},keptByThePlatform:{}},s=new Map;for(let[g,h]of r)s.has(ce(h))||s.set(ce(h),g);let i=new Set,d=(g,h)=>{n.residuals.set(g,[...n.residuals.get(g)??[],h])},a=(g,h)=>{let m=n.carried.at(-1);m?.objectApiName===g?m.referenceIds.push(h):n.carried.push({objectApiName:g,referenceIds:[h]})},c=g=>{n.leftUnrecorded[g]=(n.leftUnrecorded[g]??0)+1},l=[],u=t.some(g=>g.created&&!g.writtenBetween)?await this.targetClockAheadMs():Number.NaN,f=t.map(g=>{let h=new Set;if(!g.created)return h;let m=new Set(g.created.flatMap(y=>y.referenceIds));for(let[y,R]of g.mapping)m.has(y)||h.add(ce(R));return h}),p=new Set(f.flatMap(g=>[...g]));if(t.forEach((g,h)=>{if(!g.created){for(let[R,j]of g.mapping){let T=ce(j);if(s.has(T)||i.has(T))continue;i.add(T);let P=Dl(R);this.mayHaveLinked(P,R)||p.has(T)?c(P):P==="Pricebook2"&&!R.startsWith(Hn)?l.push(j):d(P,j)}return}let m=g.writtenBetween?Wt(g.writtenBetween.last):Wt(g.endedAt)+u+Zi,y=new Map(Object.entries(g.removalStamps??{}).map(([R,j])=>[ce(R),Wt(j)]));for(let{objectApiName:R,referenceIds:j}of g.created)for(let T of j){let P=g.mapping.get(T);if(P===void 0)continue;let _=ce(P);if(f[h].has(_)||i.has(_))continue;i.add(_);let q=s.get(_);if(q!==void 0){a(R,q);continue}if(this.keptByThePlatform(R)){n.keptByThePlatform[R]=(n.keptByThePlatform[R]??0)+1;continue}d(R,P);let C=[m,y.get(_)??Number.NaN].filter(Number.isFinite);C.length>0&&n.datedBy.set(_,Math.max(...C))}}),l.length>0){let g;try{let[h]=await this.deps.orgAccess.query(e,Mt);g=typeof h?.Id=="string"?ce(h.Id):""}catch{g=void 0}for(let h of l)g===void 0||ce(h)===g?c("Pricebook2"):d("Pricebook2",h)}return n}async targetClockAheadMs(){let e=this.deps.serverTime;if(!e)return Number.NaN;let t=Date.now();try{return Wt(await e())-(t+Date.now())/2}catch{return Number.NaN}}async foundUnderThePurge(e,t,r,n){let s=new Set([...t.values()].flat().map(ce)),i=new Map;for(let[c,l]of r){let u=n.get(c);u===void 0||s.has(ce(l))||i.set(u,[...i.get(u)??[],l])}if(s.size===0||i.size===0)return[];let d=new Map,a=(c,l,u)=>{let f=d.get(c)??{keys:new Set,under:new Set};f.keys.add(ce(l)),f.under.add(u),d.set(c,f)};for(let c of t.keys()){let l;try{l=(await this.deps.orgAccess.describe(e,c)).cascadeChildren??[]}catch{continue}for(let{childSObject:u,field:f}of l){let p=i.get(u);if(!p)continue;let g;try{g=await this.readRecords(e,u,[f],p)}catch{for(let h of p)a(u,h,c);continue}for(let h of g){let m=h[f];typeof h.Id!="string"||typeof m!="string"||s.has(ce(m))&&a(u,h.Id,c)}}}return[...d].map(([c,{keys:l,under:u}])=>({objectApiName:c,count:l.size,under:[...u]}))}mayHaveLinked(e,t){return t.startsWith(Hn)?!1:e==="Unknown"||e===_e||Object.prototype.hasOwnProperty.call(wn,e)||Object.prototype.hasOwnProperty.call(Cr,e)||Object.prototype.hasOwnProperty.call(this.config.identityKeys??{},e)}keptByThePlatform(e){return Object.prototype.hasOwnProperty.call(Cr,e)&&this.config.undeletableObjects?.[e]===void 0}async purgeResiduals(e,t,r,n,s,i,d,a){let c=t.residuals,l=[],u=[...c.values()].reduce((T,P)=>T+P.length,0),f=0,p=()=>{d.residuals=u-f},g=async()=>{let T=l.splice(0);T.length>0&&await this.giveStatusesBack(e,T,n)},h=async()=>{e.signal?.aborted&&await g(),await s()},m=r.filter(T=>c.has(T)),y=[...c.keys()].filter(T=>!r.includes(T)).sort(),R=[...m,...y],j=new Set;try{j=await this.residualsInSight(e.orgId,c),await this.draftResiduals(e,t,l,h);for(let T of R){let P=c.get(T)??[],_=this.config.undeletableObjects?.[T];if(_!==void 0){await h(),await this.checkGuard(e,"update",T,P.length);let q=await this.updateRecords(e.orgId,T,P.map(C=>({Id:C,[_]:!1})));q.forEach((C,I)=>{C.success?(n.deactivated[T]=(n.deactivated[T]??0)+1,i.add(ce(P[I]))):n.failures.push({objectApiName:T,recordId:P[I],errors:C.errors})}),f+=q.length}else{let q=fn(T)?await this.customPricesFirst(e.orgId,P):T===Sr?[await this.withoutDirectRelations(e.orgId,P)]:[P];f+=P.length-q.reduce((C,I)=>C+I.length,0);for(let C of q){if(C.length===0)continue;await h(),await this.checkGuard(e,"delete",T,C.length);let I=await this.deleteRecords(e.orgId,T,C);I.forEach((w,O)=>{Gd(w)?(n.deleted[T]=(n.deleted[T]??0)+1,i.add(ce(C[O]))):n.failures.push({objectApiName:T,recordId:C[O],errors:w.errors})}),f+=I.length}}}await this.purgeAgain(e,R,n,i,h,a)}catch(T){throw await g(),p(),T}e.signal?.aborted||await this.settleTakenAlong(e.orgId,n,i,j),await g(),p()}async residualsInSight(e,t){let r=new Set;for(let[n,s]of t)try{for(let i of await this.readRecords(e,n,[],s))typeof i.Id=="string"&&r.add(ce(i.Id))}catch{}return r}async purgeAgain(e,t,r,n,s,i){for(let d of t){if(this.config.undeletableObjects?.[d]!==void 0)continue;let a=r.failures.filter(l=>l.objectApiName===d).map(l=>l.recordId);if(a.length===0)continue;let c=fn(d)?await this.customPricesFirst(e.orgId,a).catch(()=>[a]):[a];for(let l of c){if(l.length===0)continue;await s(),await this.checkGuard(e,"delete",d,l.length),(await this.deleteRecords(e.orgId,d,l)).forEach((f,p)=>{let g=r.failures.findIndex(h=>h.objectApiName===d&&h.recordId===l[p]);g<0||(i.tried++,Gd(f)?(r.failures.splice(g,1),r.deleted[d]=(r.deleted[d]??0)+1,n.add(ce(l[p])),i.went++):r.failures[g]={objectApiName:d,recordId:l[p],errors:f.errors})})}}}async settleTakenAlong(e,t,r,n){for(let s of new Set(t.failures.map(i=>i.objectApiName))){let i=t.failures.filter(h=>h.objectApiName===s).map(h=>h.recordId),d=h=>this.readRecords(e,s,[],h),{gone:a,unchecked:c,failure:l}=await Ji(i,d,h=>n.has(ce(h))),u=l?`Not checked: not read back once the purge was through, to tell whether a parent deleted after it took it along \u2014 ${l}`:"Not checked: the purge could not read it before its delete, nor after \u2014 gone, or out of the session's sight",f=new Set(c.map(ce));for(let h of t.failures)h.objectApiName!==s||!f.has(ce(h.recordId))||h.errors.includes(u)||(h.errors=[...h.errors,u]);let p=new Set(a.map(ce));if(p.size===0)continue;let g=t.failures.filter(h=>h.objectApiName!==s||!p.has(ce(h.recordId)));t.failures.splice(0,t.failures.length,...g),t.deleted[s]=(t.deleted[s]??0)+p.size;for(let h of p)r.add(h)}}async draftResiduals(e,t,r,n){for(let[s,i]of Object.entries(_t)){if(wi.has(s))continue;let d=t.residuals.get(s);if(!d||d.length===0)continue;let a=await this.statusCategories(e.orgId,i),c=a?.draft;if(!a||!c)continue;let l;try{l=await this.readRecords(e.orgId,s,["Status","LastModifiedDate"],d)}catch{continue}let u=l.flatMap(f=>{let p=a.categoryOf.get(String(f.Status));if(typeof f.Id!="string"||p===void 0||p==="Draft")return[];let g=t.datedBy.get(ce(f.Id))??Number.NaN;return[{objectApiName:s,id:f.Id,draft:c,status:String(f.Status),unchanged:Wt(f.LastModifiedDate)<=g}]});u.length!==0&&(await n(),await this.checkGuard(e,"update",s,u.length),r.push(...u),await this.updateRecords(e.orgId,s,u.map(({id:f})=>({Id:f,Status:c}))))}}async giveStatusesBack(e,t,r){let n=this.deps.restoringWriter??this.deps.writer,s=await this.runningUser(e.orgId),i={};for(let d of new Set(t.map(a=>a.objectApiName))){let a=t.filter(p=>p.objectApiName===d),c=new Map(a.map(p=>[ce(p.id),p])),l;try{l=await this.readRecords(e.orgId,d,["Status"],a.map(p=>p.id))}catch(p){for(let g of a)Kd(r,g,`its status was not read back: ${ee(p)}`);continue}let u=l.flatMap(p=>{let g=typeof p.Id=="string"?c.get(ce(p.Id)):void 0;return g&&p.Status===g.draft?[g]:[]});for(let p=0;p<u.length;p+=Pt){let g=u.slice(p,p+Pt),h;try{await this.checkGuard(e,"update",d,g.length),h=await this.updateRecords(e.orgId,d,g.map(({id:m,status:y})=>({Id:m,Status:y})),n)}catch(m){let y=ee(m);h=g.map(()=>({success:!1,errors:[y]}))}g.forEach((m,y)=>{let R=h[y];R?.success||Kd(r,m,R?.errors.join("; ")||"the org gave no reason")})}let f=u.filter(p=>p.unchanged);if(!(f.length===0||s===void 0))try{let p=await this.readRecords(e.orgId,d,["LastModifiedDate","LastModifiedById"],f.map(g=>g.id));for(let g of p)typeof g.Id=="string"&&typeof g.LastModifiedDate=="string"&&typeof g.LastModifiedById=="string"&&ce(g.LastModifiedById)===s&&(i[g.Id]=g.LastModifiedDate)}catch{}}if(Object.keys(i).length!==0)try{await this.deps.mappingStore.recordStamps(i)}catch{}}async updateRecords(e,t,r,n=this.deps.writer){let s=await n.update(e,t,r);return this.lockResent?.updated(t,s),s}async deleteRecords(e,t,r){let n=await this.deps.writer.delete(e,t,r);return this.lockResent?.deleted(t,r,n),n}async runningUser(e){let t=await this.runUserIdOf(e);return t?ce(t):void 0}async runUserIdOf(e){let t=this.deps.orgAccess.userId;if(t)try{return await t.call(this.deps.orgAccess,e)||void 0}catch{return}}async readBackRecordTypes(e,t,r){let n=[];for(let{given:s,rule:i,keys:d}of t){let a=d.flatMap(c=>r.get(c)??[]);try{let c=await this.deps.orgAccess.query(e,sd(s.objectApiName,a));n.push({...s,readBack:id(c,i.types)})}catch(c){let l=ee(c);n.push({...s,readBack:{read:0,types:[],unread:l}})}}return n}async readRecords(e,t,r,n){let s=["Id",...r].map(ye).join(", "),i=[];for(let d=0;d<n.length;d+=Pt){let a=n.slice(d,d+Pt).map(c=>`'${Be(c)}'`).join(", ");i.push(...await this.deps.orgAccess.query(e,`SELECT ${s} FROM ${ye(t)} WHERE Id IN (${a})`))}return i}async resolveRecordType(e,t,r,n,s,i,d){let a={...n.fields};r===Ke&&delete a[bn];let c=a.RecordTypeId;if(typeof c!="string"||c==="")return"RecordTypeId"in a&&d.set(n.referenceId,"masterInSource"),delete a.RecordTypeId,{referenceId:n.referenceId,fields:a};let l=t.recordTypes[r]??[],u=n.recordTypeDeveloperName===void 0?void 0:Po(n.recordTypeDeveloperName,l,oc),f=u&&"found"in u?[u.found]:l.filter(m=>m.name===c),p=f[0];if(!p)return delete a.RecordTypeId,d.set(n.referenceId,"dropped"),i.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:c,detail:"RecordType name absent from the dataset recordTypes map \u2014 RecordTypeId dropped"}),{referenceId:n.referenceId,fields:a};if(f.length>1)throw sc(r,c,f);let g=lt(p.namespacePrefix,p.developerName),h=await this.deps.recordTypeResolver.resolveByDeveloperName(e.orgId,r,p.developerName,...p.namespacePrefix!==void 0?[p.namespacePrefix]:[]);if(h!==null&&typeof h=="object"&&"ambiguous"in h)throw new et(`The dataset names ${r} record type ${p.developerName} without its namespace \u2014 it was extracted before SandForge read one \u2014 and ${To(r,p.developerName,"the target org",h.carriers)}. Extract the dataset again: a dataset extracted now names each record type with its namespace. Nothing was written.`,void 0,{reason:"namespace",objectApiName:r,name:p.developerName,recordTypes:h.carriers.map(m=>lt(m.namespacePrefix,m.developerName))});if(h!==null&&typeof h=="object"){let m=await this.deps.recordTypeResolver.givenRecordType?.(e.orgId,r).catch(()=>{});return delete a.RecordTypeId,d.set(n.referenceId,"dropped"),i.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:c,detail:`RecordType ${g} is in the target org but not available to the running user \u2014 RecordTypeId dropped, ${Cl(m)}. Assign it to the user's profile or a permission set to keep it.`}),{referenceId:n.referenceId,fields:a}}return h?(a.RecordTypeId=h,s.set(n.referenceId,h),{referenceId:n.referenceId,fields:a}):(delete a.RecordTypeId,d.set(n.referenceId,"dropped"),i.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:c,detail:`RecordType ${g} not found in target org \u2014 RecordTypeId dropped`}),{referenceId:n.referenceId,fields:a})}async planRequiredFields(e,t){let r=[],n=[];for(let s of t)for(let i of s.missingRequired){let d=`${i.objectApiName}.${i.field}`;if(!i.isLookup){if(this.config.requiredFieldDefaults?.[d]===void 0){let u=i.accountKind?` of a ${i.accountKind} account`:"";n.push(`requiredFieldDefaults["${d}"]: ${Yl(i)} for this required field${u}`)}else r.push({kind:"default",missing:i});continue}let a=this.config.requiredLookupPlaceholders?.[d];if(!a){n.push(`requiredLookupPlaceholders["${d}"]: a placeholder (name + recordTypeDeveloperName) for this required lookup to ${i.referenceTo.join(" or ")||"its parent"}`);continue}let c=a.targetObjectApiName??i.referenceTo[0];if(!c){n.push(`requiredLookupPlaceholders["${d}"].targetObjectApiName: the target describe names no object this lookup points at`);continue}let l;if(a.recordTypeDeveloperName){let u=await this.deps.recordTypeResolver.resolveByDeveloperName(e.orgId,c,a.recordTypeDeveloperName);if(u!==null&&typeof u=="object"&&"ambiguous"in u){let f=u.carriers.find(p=>p.namespacePrefix);n.push(`requiredLookupPlaceholders["${d}"]: `+To(c,a.recordTypeDeveloperName,"the target org",u.carriers)+(f?" \u2014 a package's is named with its namespace: "+lt(f.namespacePrefix,f.developerName):""));continue}if(u!==null&&typeof u=="object"){n.push(`requiredLookupPlaceholders["${d}"]: record type ${a.recordTypeDeveloperName} on ${c} is not available to the running user`);continue}if(l=u??void 0,!l){n.push(`requiredLookupPlaceholders["${d}"]: record type ${a.recordTypeDeveloperName} is not on ${c} in the target org \u2014 deploy it before loading`);continue}}r.push({kind:"placeholder",missing:i,key:d,name:a.name,targetObject:c,recordTypeId:l})}if(n.length>0)throw new et(`The dataset leaves ${n.length} required field(s) empty that the configuration does not cover. Nothing was written. Declare them all, then load again \u2014 records are never silently excluded:
|
|
11
|
+
- ${n.join(`
|
|
12
|
+
- `)}`,n);return r}async createPlaceholder(e,t,r,n,s,i){let{missing:d,key:a,targetObject:c}=t,l={Name:t.name};t.recordTypeId&&(l.RecordTypeId=t.recordTypeId),await this.checkGuard(e,"insert",c,1);let[u]=await this.deps.writer.insert(e.orgId,c,[l]);if(u===void 0&&e.signal?.aborted)return;if(u!==void 0&&this.lockResent?.placeholderInserted(c,u),!u?.success||!u.id){let g=u!==void 0&&Tr(u.errors,u.errorDetails)?"Load again once what holds the record lets go of it.":"Fix the target org configuration and retry.";throw new et(`Placeholder insert failed for required lookup ${a} on ${c}: ${u?.errors.join("; ")||"no id returned"}. ${g}`)}let f=`${Hn}${c}:${a}`;n.set(f,u.id),i.add(c,f),this.journal?.created(c,[[f,u.id]]);let p=0;for(let g of r){let h=g.fields[d.field];(h==null||h==="")&&(g.fields[d.field]=u.id,p++)}s.push({objectApiName:d.objectApiName,field:d.field,placeholderObjectApiName:c,placeholderName:t.name,placeholderId:u.id,affectedRecords:p})}applyScalarDefault(e,t,r,n){let s=`${e.objectApiName}.${e.field}`,i=this.config.requiredFieldDefaults?.[s],d=ss(i,e.distinct),a=0;for(let c of t)gt(c.fields[e.field])&&(c.fields[e.field]=is(i,d,{referenceId:c.referenceId,rank:n.get(c.referenceId)??0}),a++);r.push({objectApiName:e.objectApiName,field:e.field,value:i,affectedRecords:a,...d?{perRecord:d}:{}})}async insertObject(e,t,r,n,s,i,d,a,c,l,u,f,p){let g={objectApiName:t,fromFiles:r,inserted:0,reused:0,skippedDuplicates:[],failed:[]},h=n.filter(w=>!d.has(w.referenceId));g.reused=n.length-h.length;let m=[];for(let w of h){let O=Ul(t,w.fields,s,f);O?g.failed.push({objectApiName:t,referenceId:w.referenceId,errors:[O]}):m.push(w)}if(m.length===0)return g;let y=m.map(w=>{let O={},F=[];for(let[A,L]of Object.entries(w.fields))if(!(L===""||L===null||L===void 0))if(typeof L=="string"&&s.has(L)){let x=i.get(L);x&&!(t===_r&&A===Br)?O[A]=x:F.push({objectApiName:t,referenceId:w.referenceId,field:A,targetReferenceId:L})}else O[A]=L;let v=di(t,O);for(let A of v)delete O[A];a.push(...F.filter(A=>!v.includes(A.field)));for(let A of Qs(t,O))delete O[A];return O}),R=(w,O,F)=>{i.set(w,O),l.add(t,w,$l.some(v=>v in F)),g.inserted++};await this.checkGuard(e,"insert",t,y.length);let j=await this.deps.writer.insert(e.orgId,t,y,(w,O)=>this.journalBatch(t,m,w,O)),T=[],P=new Map;j.forEach((w,O)=>{let F=m[O].referenceId;if(w.lockResends!==void 0&&P.set(F,w),w.success&&w.id){R(F,w.id,y[O]);return}if(tc(w.errors,c)){g.skippedDuplicates.push({objectApiName:t,referenceId:F,errors:w.errors});return}let v=this.sentAgain(t,y[O],w);v?T.push({...v,referenceId:F,errors:w.errors}):g.failed.push({objectApiName:t,referenceId:F,errors:w.errors})});let _=m.length-j.length;_>0&&e.signal?.aborted&&(g.notInserted=_);let q=()=>{let w=Bl(P);w&&(g.sentAgainForALock=w)};if(q(),T.length===0)return g;let C=(w,O)=>{for(let F of w)g.failed.push({objectApiName:t,referenceId:F.referenceId,errors:[...F.errors,`Not written again ${Vd(F.fields)}: ${O}`]})};if(e.signal?.aborted)return C(T,"the load was cancelled first"),g;let I;try{await this.checkGuard(e,"insert",t,T.length),I=await this.deps.writer.insert(e.orgId,t,T.map(w=>w.payload),(w,O)=>this.journalBatch(t,T,w,O))}catch(w){throw C(T,ee(w)),p?.(g),w}return T.forEach((w,O)=>{let F=I[O];if(!F){C([w],e.signal?.aborted?"the load was cancelled first":"no answer came for it");return}if((F.lockResends!==void 0||P.has(w.referenceId))&&P.set(w.referenceId,F),F.success&&F.id){R(w.referenceId,F.id,w.payload),g.writtenWithoutFields=Co(g.writtenWithoutFields,{rows:1,fields:w.fields.map(A=>({...A,rows:1}))});for(let{field:A,replacedWith:L}of w.fields){if(L!==void 0)continue;let x=u.get(t)??new Map;x.set(A,[...x.get(A)??[],w.referenceId]),u.set(t,x)}return}let v=[...F.errors,`Sent again ${Vd(w.fields)} after the first refusal: ${w.errors.join("; ")}`];tc(F.errors,c)?g.skippedDuplicates.push({objectApiName:t,referenceId:w.referenceId,errors:v}):g.failed.push({objectApiName:t,referenceId:w.referenceId,errors:v})}),q(),g}journalBatch(e,t,r,n){let s=this.journal;s&&s.created(e,n.flatMap((i,d)=>{let a=t[r+d];return i.success&&i.id&&a?[[a.referenceId,i.id]]:[]}))}sentAgain(e,t,r){let n=Pa(r.errorDetails,t,void 0);if(!n)return;let s={...t},i=n.map(d=>{let a=d.refusedBy==="restricted-picklist"?this.picklistRuleFor(e,d.field):void 0;return a?.action==="replace"&&a.value!==""&&a.value!==t[d.field]?(s[d.field]=a.value,{...d,replacedWith:a.value}):(delete s[d.field],{...d})});return{payload:s,fields:i}}async matchDirectRelations(e,t,r,n,s,i){let d=new Map;for(let l of t.objects.find(u=>u.objectApiName==="Contact")?.records??[])d.set(l.referenceId,l.fields.AccountId);let a=r.filter(l=>{let u=l.fields.ContactId;return typeof u=="string"&&l.fields.AccountId!==void 0&&d.get(u)===l.fields.AccountId&&n.has(u)&&typeof l.fields.AccountId=="string"&&n.has(l.fields.AccountId)});if(a.length===0)return;let c=await bi(l=>this.deps.orgAccess.query(e,l),a.map(l=>({AccountId:n.get(l.fields.AccountId),ContactId:n.get(l.fields.ContactId)})));for(let[l,u]of a.entries()){let f=c.get(l);typeof f=="string"&&(n.set(u.referenceId,f),s.add(u.referenceId),i.set(u.referenceId,u.fields.ContactId))}}async matchTasksWrittenWithEmails(e,t,r,n,s,i){let d=new Set(r.map(l=>l.referenceId)),a=new Map;for(let l of t.objects.find(u=>u.objectApiName===Xe)?.records??[]){let u=l.fields.ActivityId;if(typeof u!="string"||!d.has(u)||s.has(l.referenceId))continue;let f=n.get(l.referenceId);f&&a.set(u,{id:f,key:l.referenceId})}if(a.size===0)return;let c=await ui(l=>this.deps.orgAccess.query(e,l),[...new Set([...a.values()].map(l=>l.id))]);for(let[l,u]of a){let f=c.get(u.id);f!==void 0&&(n.set(l,f),s.add(l),i.set(l,u.key))}}async matchContactRolesWrittenWithOpportunities(e,t){let{aligned:r,refIndex:n,mapping:s,reused:i}=t,d=I=>typeof I=="string"?s.get(I):void 0,a=new Map;for(let I of t.working.objects.find(w=>w.objectApiName===ic)?.records??[]){let w=s.get(I.referenceId),O=d(I.fields[wt]);w&&O&&!i.has(I.referenceId)&&a.set(w,O)}if(a.size===0)return{linked:0};let c=r.map(I=>({OpportunityId:d(I.fields.OpportunityId),[wt]:d(I.fields[wt]),IsPrimary:I.fields.IsPrimary})),l=ko(c,I=>a.get(I)).filter(I=>!i.has(r[I].referenceId));if(l.length===0)return{linked:0};let u=I=>{let w={},O=[];for(let[F,v]of Object.entries(I.fields))if(!(F==="OpportunityId"||F===wt)&&!t.fixedAtInsert.has(F)&&!(v===""||v===null||v===void 0))if(typeof v=="string"&&n.has(v)){let A=s.get(v);A?w[F]=A:O.push({objectApiName:$t,referenceId:I.referenceId,field:F,targetReferenceId:v})}else w[F]=v;return{fields:w,owed:O}},f=new Map(l.map(I=>[I,{opportunity:String(c[I].OpportunityId),contact:String(c[I][wt])}])),p=[...new Set(l.flatMap(I=>Object.keys(u(r[I]).fields)))],g=await pi(I=>this.deps.orgAccess.query(e.orgId,I),[...new Set([...f.values()].map(({opportunity:I})=>I))],p),{found:h,alike:m}=gi(f,g),y=m.length>0?hi(m.length):void 0;if(h.size===0)return y?{linked:0,note:y}:{linked:0};let R=I=>y?`${I}; ${y}`:I,j=[];for(let[I,w]of h){let O=r[I],F=String(w.Id);s.set(O.referenceId,F),i.add(O.referenceId),t.withTheirRecord.set(O.referenceId,String(O.fields.OpportunityId));let{fields:v,owed:A}=u(O);t.pendingFk.push(...A);let L=Object.entries(v).filter(([x,B])=>String(w[x]??"")!==String(B));L.length>0&&j.push({Id:F,...Object.fromEntries(L)})}let T=h.size,P=`${T} written by the platform with ${fi($t)}`;if(j.length===0)return{linked:T,note:R(P)};let _=(I,w)=>`${P}, ${I} of them left as it wrote ${I===1?"it":"them"}, without the fields of the source's role: ${w}`;if(e.signal?.aborted)return{linked:T,note:R(_(j.length,"the load was cancelled before the update"))};await this.checkGuard(e,"update",$t,j.length);let q=await this.updateRecords(e.orgId,$t,j),C=j.flatMap((I,w)=>{let O=q[w];return O?.success?[]:[O?O.errors.join("; ")||"refused":"no answer came for it"]});return C.length===0?{linked:T,note:R(P)}:{linked:T,note:R(_(C.length,C[0]))}}async matchActivityRelations(e,t,r,n,s,i){let{orgId:d}=e,a=Io[t],c=u=>typeof u=="string"?n.get(u):void 0,l=await mi(u=>this.deps.orgAccess.query(d,u),t,r.map(u=>({[a]:c(u.fields[a]),RelationId:c(u.fields.RelationId)})));for(let[u,f]of l)n.set(r[u].referenceId,f),s.add(r[u].referenceId);return yi(t,[...l].map(([u,f])=>[r[u].fields,f]),u=>!i.has(u),async u=>(await this.checkGuard(e,"update",t,u.length),this.updateRecords(d,t,u)),()=>e.signal?.aborted===!0)}async startAsDrafts(e,t,r,n,s){let i=await this.statusCategories(e,r);return i?.draft?n.map(d=>{let a=ir(d.fields.Status,i);return a?(s.push({objectApiName:t,referenceId:d.referenceId,status:String(d.fields.Status)}),{referenceId:d.referenceId,fields:{...d.fields,Status:a}}):d}):n}async withoutDirectRelations(e,t){let r=new Set;for(let n=0;n<t.length;n+=Pt){let s=t.slice(n,n+Pt).map(d=>`'${Be(d)}'`).join(", "),i=await this.deps.orgAccess.query(e,`SELECT Id FROM ${Sr} WHERE Id IN (${s}) AND IsDirect = true`);for(let d of i)r.add(String(d.Id))}return t.filter(n=>!r.has(n))}async customPricesFirst(e,t){let r=await Ri(n=>this.deps.orgAccess.query(e,n),t);return[t.filter(n=>!r.has(n)),t.filter(n=>r.has(n))]}async readWrittenBetween(e,t,r){let n=Number.POSITIVE_INFINITY,s=Number.NEGATIVE_INFINITY;for(let{objectApiName:i,referenceIds:d}of t.list()){let a=[...new Set(d.flatMap(l=>{let u=r.get(l);return u?[u]:[]}))],c=t.sentAuditDates(i);for(let l=0;l<a.length;l+=Pt){let u=await this.writtenDatesOf(e,i,a.slice(l,l+Pt));if(!u)return;for(let f of u){let p=Wt(f.SystemModstamp),g=y=>{let R=c?Number.NaN:Wt(f[y]);return Number.isFinite(R)?R:p},h=g("CreatedDate"),m=g("LastModifiedDate");Number.isFinite(h)&&(n=Math.min(n,h)),Number.isFinite(m)&&(s=Math.max(s,m))}}}if(!(!Number.isFinite(n)||!Number.isFinite(s)))return{first:new Date(n).toISOString(),last:new Date(Math.max(n,s)).toISOString()}}async writtenDatesOf(e,t,r){let n=r.map(s=>`'${Be(s)}'`).join(", ");for(let s of _l)try{return await this.deps.orgAccess.query(e,`SELECT Id, ${s.join(", ")} FROM ${ye(t)} WHERE Id IN (${n})`)}catch{}}async statusCategories(e,t){return sr(r=>this.deps.orgAccess.query(e,r),t)}async applyDeferredStatuses(e,t,r,n){let{refused:s}=n.report,i=new Map;for(let d of t){let a=r.get(d.referenceId);a&&i.set(d.objectApiName,[...i.get(d.objectApiName)??[],{...d,id:a}])}n.unanswered=[...i.values()].reduce((d,a)=>d+a.length,0);for(let[d,a]of i){if(e.signal?.aborted)continue;let c=a.map(u=>({Id:u.id,Status:u.status}));await this.checkGuard(e,"update",d,c.length);let l=await this.updateRecords(e.orgId,d,c);l.forEach((u,f)=>{u.success?n.report.restored++:s.push({objectApiName:d,referenceId:a[f].referenceId,status:a[f].status,detail:u.errors.join("; ")})}),n.unanswered-=l.length}}async patchCycleFks(e,t,r,n){let{unresolved:s}=n.report,i=new Map,d=new Map;for(let c of t){let l=r.get(c.referenceId),u=r.get(c.targetReferenceId);if(!l||!u){s.push({objectApiName:c.objectApiName,referenceId:c.referenceId,field:c.field,cause:l?"target-not-loaded":"record-not-loaded",detail:l?`referenced record ${c.targetReferenceId} was not loaded (skipped, failed or excluded)`:"child record was not loaded (see perObject failures/skips)"});continue}d.set(l,c.referenceId);let f=i.get(c.objectApiName)??new Map,p=f.get(l)??{Id:l};p[c.field]=u,f.set(l,p),i.set(c.objectApiName,f)}let a=c=>c.reduce((l,u)=>l+Object.keys(u).length-1,0);n.unanswered=[...i.values()].reduce((c,l)=>c+a([...l.values()]),0);for(let[c,l]of i){let u=[...l.values()];if(e.signal?.aborted)continue;await this.checkGuard(e,"update",c,u.length);let f=await this.updateRecords(e.orgId,c,u);f.forEach((p,g)=>{p.success?n.report.resolved+=Object.keys(u[g]).length-1:s.push({objectApiName:c,referenceId:d.get(String(u[g].Id))??String(u[g].Id),field:Object.keys(u[g]).filter(h=>h!=="Id").join(","),cause:"update-refused",detail:p.errors.join("; ")})}),n.unanswered-=a(u.slice(0,f.length))}}async linkPersonContacts(e,t,r,n,s,i){let d={linked:new Map,own:new Map,unlinked:[]},a=new Map,c=[...t].map(([f,p])=>({accountReferenceId:p,contactReferenceId:f}));for(let f of c){let p=f.accountReferenceId===""?void 0:r.get(f.accountReferenceId);p!==void 0&&a.set(p,[...a.get(p)??[],f])}let l=a.size===0||s===!1?new Map:await kn(f=>this.deps.orgAccess.query(e,f),[...a.keys()]),u=new Map;for(let[f,p]of a){let g=l.get(f);if(g!==void 0)for(let h of p)u.set(h.contactReferenceId,g)}for(let f of c){let p=u.get(f.contactReferenceId);if(p!==void 0){r.set(f.contactReferenceId,p),d.linked.set(f.contactReferenceId,f.accountReferenceId);continue}if(f.accountReferenceId===""||!r.has(f.accountReferenceId)){d.unlinked.push({...f,cause:"record-not-loaded",detail:f.accountReferenceId===""?Wr.accountNotInDataset:Wr.accountNotLoaded});continue}if(n.has(f.contactReferenceId))continue;let g=i.find(m=>m.objectApiName===Ke&&m.referenceId===f.accountReferenceId),h=Wr.noPersonAccounts;s!==!1&&(h=g?`${Wr.businessAccount}: ${g.detail}`:`${Wr.businessAccount}: its record type there is no person account's`),d.own.set(f.contactReferenceId,{...f,detail:h})}return d}writeContract(e,t,r,n,s,i,d,a=0,c=new Map,l=[]){let u=new Map;for(let{objectApiName:h,referenceId:m,field:y}of l){let R=u.get(h)??{};R[y]=[...R[y]??[],m],u.set(h,R)}let f=new Map;for(let{objectApiName:h,count:m,reason:y}of d){let R=f.get(h)??{};R[y]=(R[y]??0)+m,f.set(h,R)}let p=[...r];for(let[h,m]of f)p.some(y=>y.objectApiName===h)||p.push({objectApiName:h,fromFiles:t.objects.find(y=>y.objectApiName===h)?.records.length??Object.values(m).reduce((y,R)=>y+R,0),inserted:0,reused:0,skippedDuplicates:[],failed:[]});let g={};for(let h of p){let m={};h.skippedDuplicates.length>0&&(m["duplicate-skipped"]=h.skippedDuplicates.length);let y=h.objectApiName===Ue?a:0,R=h.failed.filter(C=>Kl(C.errors)).length;if(R>0&&(m["parent-refused"]=R),h.failed.length-R>y){let C=i.has(h.objectApiName)?"object-not-loaded":"dml-failed";m[C]=h.failed.length-R-y}y>0&&(m["person-contact-not-sent"]=y);let j=0;for(let[C,I]of Object.entries(f.get(h.objectApiName)??{}))m[C]=I,j+=I;let T=h.skippedDuplicates.length+h.failed.length+j,P=n.filter(C=>C.placeholderObjectApiName===h.objectApiName).length,_=c.get(h.objectApiName),q=u.get(h.objectApiName);g[h.objectApiName]={fromFiles:h.fromFiles,exclusionReasons:m,excluded:T,added:P,expected:h.inserted+h.reused+P,..._&&_.size>0?{writtenWithout:Object.fromEntries(_)}:{},...q?{parentNotLoaded:q}:{}}}return Od(this.sasGuard,e.sasDir,{version:1,orgId:e.contractOrgId??e.orgId,datasetVersion:t.datasetVersion,writtenAt:s.now().toISOString(),loadStartedAt:s.startedAt.toISOString(),objects:g})}picklistRuleFor(e,t){return this.config.picklistRules?.[`${e}.${t}`]??this.config.defaultPicklistRule??{action:"clear"}}contractPath(e,t){return Dn(this.sasGuard,e,t)}};function Yd(o){let e=new Map;for(let t of o)for(let r of t.failed)e.set(r.referenceId,t.objectApiName);return e}function Ul(o,e,t,r){if(r.size===0)return;let n=new Set(o===Xe&&!Ro(e,s=>t.get(s))?["ActivityId"]:[]);for(let[s,i]of Object.entries(e)){if(typeof i!="string"||n.has(s)||!t.has(i))continue;let d=r.get(i);if(d!==void 0)return`PARENT_REFUSED: the ${d} record its ${s} names was refused in this load, and written without it this record would stand without its ${d}.`}}function Kl(o){return o.length===1&&o[0].startsWith("PARENT_REFUSED:")}function gt(o){return o==null||o===""}var dc=/\{(n|referenceId)\}/g;function ss(o,e){if(typeof o=="string")return o.match(dc)?"token":e}function is(o,e,t){return typeof o!="string"||e===void 0?o:e==="token"?o.replace(dc,(r,n)=>n==="n"?String(t.rank):t.referenceId):`${o} ${t.rank}`}function Vl(o,e){let{objectApiName:t,keyFields:r,ranks:n,accountKindOf:s}=o,i=o.missingRequired.filter(d=>!d.isLookup&&r.includes(d.field));return o.records.map(d=>{let a={...d.fields};for(let c of i){let l=e[`${t}.${c.field}`];l===void 0||!gt(a[c.field])||Jn(c,[d],s).length!==0&&(a[c.field]=is(l,ss(l,c.distinct),{referenceId:d.referenceId,rank:n.get(d.referenceId)??0}))}return{referenceId:d.referenceId,fields:a}})}function cc(o,e=!1){return o.length===0?{}:{keysLeftEmpty:o.map(({objectApiName:t,fields:r,count:n})=>{let s=n===1?"its":"their",i=r.join(", "),d="the dataset holds no value, and no default fills it";return{objectApiName:t,fields:[...r],count:n,note:e?`${n} not looked up by ${s} identity keys: ${i} stays empty in what the load would write \u2014 ${d} \u2014 so ${n===1?"it":"they"} would be inserted, never matched`:`${n} not looked up by ${s} identity keys: ${i} stayed empty in what the load wrote \u2014 ${d} \u2014 so ${n===1?"it was":"they were"} sent to be inserted, never matched`}})}}function Hl(o){let e=new Map;for(let t of o.objects)t.records.forEach((r,n)=>e.set(r.referenceId,n+1));return e}function lc(o){let e=as(o),t=new Map(o.objects.map(n=>[n.objectApiName,n.records])),r=new Set;return new Set([...uc(t,r),...fc(t,r,ac(o,e),n=>e.get(n))])}function uc(o,e){let t=(o.get($t)??[]).filter(a=>!e.has(a.referenceId));if(t.length===0)return new Set;let r=new Map,n=a=>{if(typeof a!="string"||a==="")return;let c=r.get(a);return c===void 0&&(c=String(r.size+1).padStart(15,"0"),r.set(a,c)),c},s=new Set((o.get(Ue)??[]).map(a=>a.referenceId)),i=new Map;for(let a of o.get(ic)??[]){if(e.has(a.referenceId))continue;let c=a.fields[wt];typeof c!="string"||!s.has(c)||i.set(n(a.referenceId),n(c))}if(i.size===0)return new Set;let d=t.map(a=>({OpportunityId:n(a.fields.OpportunityId),[wt]:n(a.fields[wt]),IsPrimary:a.fields.IsPrimary}));return new Set(ko(d,a=>i.get(a)).map(a=>t[a].referenceId))}function fc(o,e,t,r){let n=l=>(o.get(l)??[]).filter(u=>!e.has(u.referenceId)),s=new Set,i=new Map;for(let l of n(Ue))t.has(l.referenceId)||i.set(l.referenceId,l.fields.AccountId);let d=new Set((o.get("Account")??[]).map(l=>l.referenceId));for(let l of n(Sr)){let{AccountId:u,ContactId:f}=l.fields;typeof u!="string"||typeof f!="string"||i.get(f)===u&&d.has(u)&&s.add(l.referenceId)}let a=new Set([...o.values()].flatMap(l=>l.map(u=>u.referenceId))),c=new Set(n(rr).map(l=>l.referenceId));for(let l of n(Xe)){let u=l.fields.ActivityId,f=l.fields.RelatedToId;typeof u!="string"||!c.has(u)||typeof f!="string"||!a.has(f)||Ro(l.fields,r)||s.add(u)}return s}function Jd(o,e,t){let{working:r,loading:n,alignedByObject:s,reused:i,reusedByKeys:d,alignment:a,ranks:c}=o,l=o.targetHasPersonAccounts===!1?new Set:o.personContacts,u=I=>(s.get(I)??[]).filter(w=>!i.has(w.referenceId)),f=[...new Set([...o.groupOrder,...r.objects.map(I=>I.objectApiName),...e?[...e.residuals.keys()].sort():[]])],p=0,g=uc(s,i),h=fc(s,i,l,I=>o.refIndex.get(I)),m=[];for(let I of f){let w=r.objects.find(K=>K.objectApiName===I)?.records.length??0,O=e?.residuals.get(I)?.length??0;if(w===0&&O===0)continue;let F=s.get(I),A=(F??n.objects.find(K=>K.objectApiName===I)?.records??[]).filter(K=>i.has(K.referenceId)),L=A.filter(K=>d.has(K.referenceId)).length,x=F?u(I):[],B=x.filter(K=>l.has(K.referenceId)).length;p+=B;let D=x.filter(K=>g.has(K.referenceId)||h.has(K.referenceId)).length,G=(o.filteredLookups.get(I)??[]).flatMap(({field:K,referenceTo:H})=>{let N=x.filter(Z=>!gt(Z.fields[K])).length;return N>0?[{field:K,referenceTo:H,records:N}]:[]}),X=t.undeletableObjects[I]!==void 0;m.push({objectApiName:I,fromFiles:w,toInsert:x.length-B-D,reusedByKeys:L,reusedFromCatalog:A.length-L,...D>0?{writtenByThePlatform:D}:{},fieldsDropped:a.removals.filter(K=>K.objectApiName===I).length,picklistsRewritten:a.adjustments.filter(K=>K.objectApiName===I).length,notSent:w-(F?F.length:A.length),toPurge:X?0:O,toDeactivate:X?O:0,...G.length>0?{lookupFilters:G}:{}})}let y=(I,w)=>u(I).filter(O=>gt(O.fields[w])),R=(I,w)=>y(I,w).length,j=I=>{let w=Jn(I,y(I.objectApiName,I.field),o.accountKindOf),O=t.requiredFieldDefaults[`${I.objectApiName}.${I.field}`],F=ss(O,I.distinct),v=w[0];return{objectApiName:I.objectApiName,field:I.field,affectedRecords:w.length,...F?{perRecord:F}:{},...F&&v?{example:String(is(O,F,{referenceId:v.referenceId,rank:c.get(v.referenceId)??0}))}:{}}},T=e?.leftUnrecorded??{},P=e?.keptByThePlatform??{},_=o.heldForExclusions.counts(),q=nc(o,I=>!i.has(I)&&!l.has(I)).map(({given:I})=>I),C=new Set([...s.values()].flatMap(I=>I.map(w=>w.referenceId)));return{orgId:t.orgId,mode:t.mode,plannedAt:t.plannedAt,perObject:m,excludedObjects:a.excludedObjects,removals:a.removals,placeholders:o.plans.flatMap(I=>I.kind==="placeholder"?[{objectApiName:I.missing.objectApiName,field:I.missing.field,placeholderObjectApiName:I.targetObject,placeholderName:I.name,affectedRecords:R(I.missing.objectApiName,I.missing.field)}]:[]),requiredDefaults:o.plans.flatMap(I=>I.kind==="default"?[j(I.missing)]:[]),recordTypeIssues:o.recordTypeIssues.length,personContacts:p,earlierLoads:o.previousLoads.length,...Object.keys(T).length>0?{leftUnrecorded:T}:{},...Object.keys(P).length>0?{keptByThePlatform:P}:{},..._.length>0?{heldForExcludedParents:hc(_)}:{},...pc(ts(s,I=>C.has(I)),t,!0),...cc(o.keysLeftEmpty,!0),...q.length>0?{recordTypesGiven:q}:{}}}var Xd=5;function Yl(o){switch(o.fieldType){case"date":return'a date, as "2026-12-31",';case"datetime":return'a date and time, as "2026-12-31T09:00:00Z",';case"time":return'a time, as "09:00:00.000Z",';case"double":case"currency":case"percent":return"a number";case"int":case"long":return"a whole number";case"boolean":return"true or false";case"picklist":case"multipicklist":{let e=o.activeValues??[];return e.length===0?"one of its values":`one of its active values (${e.slice(0,Xd).join(", ")}${e.length>Xd?", \u2026":""})`}case"email":return"an email address";case"string":case"textarea":case"phone":case"url":case"encryptedstring":case"combobox":return"a string";default:return"a value"}}function pc(o,e,t=!1){let r=Wd(o,(e.excludedObjects??[]).includes(es),t);return r?{quotesLeftUnsynced:[r]}:{}}function Jl(o,e,t){for(let r=!0;r;){r=!1;for(let[n,s]of o){let i=[...e.get(n)??[]],d=s.filter(a=>!t.some(c=>c.leaveOut(n,a.referenceId,a.fields,i)));d.length!==s.length&&(o.set(n,d),r=!0)}}}function Xl(o,e,t){let r=new Set(t.excludedObjects??[]);if(r.size===0)return[];let n=[];for(let s of e.fields){let i=s.referenceTo??[];i.length===0||!i.every(d=>r.has(d))||!s.createable||s.defaultedOnCreate||er(o,s.name,s.nillable)&&(t.requiredLookupPlaceholders?.[`${o}.${s.name}`]||n.push({field:s.name,excludedObject:i[0]}))}return n}function Zl(o){return(e,t)=>{for(let{field:r,excludedObject:n}of o.get(e)??[])if(gt(t[r]))return{field:r,value:"",noun:n}}}function gc(o,e){return e.through?`${o} left out: ${e.through} names a record left out for the ${e.rows.noun} excludedObjects leaves out`:`${o} left out: ${e.rows.field??"a lookup"} names ${/^[AEIOU]/i.test(e.rows.noun)?"an":"a"} ${e.rows.noun} record, which excludedObjects leaves out \u2014 declare a placeholder in requiredLookupPlaceholders to load them`}function hc(o){return o.map(({objectApiName:e,why:t,count:r})=>({objectApiName:e,count:r,note:gc(r,t)}))}var Ql={field:"Type",value:"",noun:"feed item whose type the dataset does not carry"};function eu(o,e){if(o!=="FeedItem")return;let t=e.Type;return typeof t=="string"&&t!==""?void 0:Ql}function Zd(o,e){let t="extract the dataset again, with rules that keep FeedItem.Type";return e.through?`${o} left out: ${e.through} names a feed item whose type the dataset does not carry \u2014 ${t}`:`${o} feed item${o===1?"":"s"} left out: the dataset does not carry ${o===1?"its":"their"} type, and a tracked change cannot be told from a post \u2014 ${t}`}function as(o){let e=new Map;for(let t of o.objects)for(let r of t.records)e.set(r.referenceId,t.objectApiName);return e}function tu(o,e,t=new Map){let r=new Map;for(let n of o.objects){let s=r.get(n.objectApiName)??new Set;for(let i of n.records)for(let[d,a]of Object.entries(i.fields))if(!(n.objectApiName===Ke&&d===bn)&&typeof a=="string"){let c=e.get(a);c&&c!==n.objectApiName&&s.add(c)}r.set(n.objectApiName,s)}t.size>0&&r.has(Ke)&&r.get(Ue)?.add(Ke);for(let{sourceObject:n,targetObject:s}of Aa(new Set(r.keys()),[]))r.get(s)?.add(n);for(let{sourceObject:n,targetObject:s}of ci(new Set(r.keys())))r.get(n)?.delete(s),r.get(s)?.add(n);return r}function ru(o,e,t,r=new Map){let n=new Map;for(let[s,i]of o){let d=e.get(s),a=new Set;if(d)for(let c of i)for(let l of d){let u=c.fields[l],f=typeof u=="string"?t.get(u):void 0;f&&f!==s&&a.add(f)}n.set(s,a)}return r.size>0&&n.set(Ue,new Set([...n.get(Ue)??[],Ke])),n}function nu(o,e){let t=h=>o.objects.find(m=>m.objectApiName===h)?.records??[],r=(h,m)=>m.map(y=>String(h[y]??"")).join("|"),n=[Ge,Je,tr],s=[Ge,Je],i=(h,m)=>typeof h[m]=="string"&&h[m]!=="",d=t(qe),a=d.filter(h=>e.has(h.referenceId)&&i(h.fields,Ge)),c=o.standardPricebook,l=h=>c!==void 0&&h.fields[yt]===c,u=new Set(a.filter(h=>!l(h)).map(h=>r(h.fields,n))),f=d.filter(h=>l(h)&&u.has(r(h.fields,n))),p=new Set([...a,...f].filter(h=>i(h.fields,Je)).map(h=>r(h.fields,s))),g=t(_e).filter(h=>p.has(r(h.fields,s)));return[...f,...g].map(h=>h.referenceId)}function Qd(o){return[...Object.keys(wn),_e].filter(e=>o.objects.some(t=>t.objectApiName===e&&t.records.length>0))}function ou(o,e){for(let t of o.objects){let r=t.records.find(n=>n.referenceId===e);if(r)return r}}function ec(o){return JSON.stringify(o.map(e=>e===void 0?null:e))}function tc(o,e){return o.some(t=>e.some(r=>t.toLowerCase().includes(r.toLowerCase())))}function ds(o,e,t){if(!e)throw new et("Pilot mode requires config.rootObjectApiName (the business-folder root object).");let r=o.objects.find(l=>l.objectApiName===e)?.records??[],n=t??r[0]?.referenceId;if(!n||!r.some(l=>l.referenceId===n))throw new et(`Pilot root ${t??"<first>"} not found in ${e} records (${r.length} in dataset). Provide pilot.rootReferenceId of an existing root record.`);let s=as(o),i=new Set([n]),d=!0;for(;d;){d=!1;for(let l of o.objects)for(let u of l.records)i.has(u.referenceId)||Object.values(u.fields).some(f=>typeof f=="string"&&i.has(f))&&(i.add(u.referenceId),d=!0)}let a=l=>{for(;l.length>0;){let u=l.pop(),f=ou(o,u);if(f)for(let p of Object.values(f.fields))typeof p=="string"&&s.has(p)&&!i.has(p)&&(i.add(p),l.push(p))}};a([...i]);let c=nu(o,i).filter(l=>!i.has(l));for(let l of c)i.add(l);return a(c),{...o,objects:o.objects.map(l=>({...l,records:l.records.filter(u=>i.has(u.referenceId))})).filter(l=>l.records.length>0)}}import{randomBytes as su}from"node:crypto";import{readFile as iu}from"node:fs/promises";var cs="frozen.salt";function au(){return su(32).toString("base64url")}function mc(o){let e=o[rd];return e?{salt:e,source:"environment"}:void 0}function $p(o,e=process.env){let t=async()=>{let r=mc(e);if(r)return r;let n=await o.getSecret(cs);return n?{salt:n,source:"secretStorage"}:void 0};return{read:t,forExtraction:async()=>{let r=await t();if(r)return r;let n=au();if(await o.storeSecret(cs,n),await o.getSecret(cs)!==n)throw new Nr;return{salt:n,source:"secretStorage",created:!0}}}}function yc(o=process.env,e){let t=async()=>{let r=mc(o);if(r)return r;if(e===void 0)return;let n=(await iu(e,"utf8")).trim();return n?{salt:n,source:"file"}:void 0};return{read:t,forExtraction:async()=>{let r=await t();if(!r)throw new Nr;return r}}}import{createHash as du}from"node:crypto";import{appendFileSync as cu,mkdirSync as lu,readFileSync as uu}from"node:fs";import*as Ur from"node:path";var fu=15*6e4;function Xn(o){return`sha256:${du("sha256").update(Ur.resolve(o)).digest("hex").slice(0,16)}`}function wc(o,e){if(!o?.writtenBetween)return;let t=Date.parse(o.endedAt),r=Date.parse(e);if(!Number.isFinite(t)||!Number.isFinite(r)||t<r)return;let n=Date.parse(o.writtenBetween.first),s=Date.parse(o.writtenBetween.last);if(!(!Number.isFinite(n)||!Number.isFinite(s)))return new Date(Math.max(n,s)).toISOString()}function pu(o,e){return e.some(t=>{let r=Date.parse(t.endedAt),n=Date.parse(t.startedAt??t.endedAt);return Number.isFinite(r)&&o>=(Number.isFinite(n)?n:r)-6e4&&o<=r+fu})}function bc(o,e){let t=[];for(let r of o){let n=Date.parse(r.endedAt);if(!Number.isFinite(n)||(r.sas!==void 0?r.sas===e.sasMark:pu(n,e.own)))continue;let s=Date.parse(r.lastWriteAt??""),i=Number.isFinite(s)?s:n,d=Date.parse(r.startedAt??r.endedAt);t.push({ids:[],idsUntold:!0,from:Number.isFinite(d)?Math.min(d,i):i,to:i})}return t}var Rc="frozen-loads.ndjson";function Gp(o,e){lu(o,{recursive:!0,mode:vi});let t=Ur.join(o,Rc);Oi(t,vo),cu(t,`${JSON.stringify(e)}
|
|
13
|
+
`,{encoding:"utf8",mode:vo})}function gu(o,e){return o.slice(0,15)===e.slice(0,15)}function Up(o,e){let t;try{t=uu(Ur.join(o,Rc),"utf8")}catch{return[]}let r=[];for(let n of t.split(`
|
|
14
|
+
`)){if(n.trim()==="")continue;let s;try{s=JSON.parse(n)}catch{continue}let{organizationId:i,sas:d,startedAt:a,endedAt:c,lastWriteAt:l}=s??{};typeof i!="string"||typeof c!="string"||gu(i,e)&&r.push({endedAt:c,...typeof d=="string"?{sas:d}:{},...typeof a=="string"?{startedAt:a}:{},...typeof l=="string"?{lastWriteAt:l}:{}})}return r}function kc(o){return o.filter(e=>(e.action==="frozen_load"||e.action==="checkpoint_replay")&&e.outcome!=="stopped").map(e=>{let t=e.details?.sas,r=e.details?.startedAt,n=e.details?.lastWriteAt;return{endedAt:e.timestamp,...typeof t=="string"?{sas:t}:{},...typeof r=="string"?{startedAt:r}:{},...typeof n=="string"?{lastWriteAt:n}:{}}})}var hu="FROZEN_EMAILS_EXCEEDED";function Xp(o,e){return[...Ka(o.counted,e),...o.uncounted!==void 0?[` emails: not counted, ${o.uncounted} could not be read`]:[],...o.deliverability?[` ${Ya(o.deliverability.reading)}`]:[]]}function mu(o){return typeof o.unread=="string"}async function Ic(o){let{read:e,plan:t,writes:r,target:n}=o,s=await pa({read:e,...t?{plan:t}:{},writes:r,readDeliverability:o.readDeliverability,accepted:o.accepted,target:n,run:"load",keepsAddresses:!0,mayMute:o.mayMute}),i=[],d;if(mu(e))d=`the target's automation: ${e.unread}`;else{let u=Dt(e,t,r).automation,f={objects:o.inserts.map(g=>({...g,storageBytes:0}))};d=Ga(u,qa(f));let p=ri(u);if(p.length>0){let g=await o.readLimits().catch(h=>({unread:ee(h)}));i=Wa(f,p,g)}}let a=Ua(i,n),c=a?{code:hu,message:`${a} Nothing was written.`}:s.gate.stop,{deliverability:l}=s.gate;return{run:s,info:{counted:i.map(u=>({...u,objects:[...u.objects]})),...d!==void 0?{uncounted:d}:{},verdict:s.gate.verdict,...l?{deliverability:l}:{},accepted:o.accepted,...c?{refused:{code:c.code,message:c.message}}:{}},...c?{stop:c}:{}}}var yu="AUTOMATION_NOT_ACCEPTED";function wu(o){let e=new Set(o);return(t,r)=>e.has(t)&&(r==="insert"||r==="update")}function bu(o){return typeof o.unread=="string"}function Ru({kind:o,name:e}){return o==="flow"?`flow "${e}"`:o==="process"?`process "${e}"`:o==="workflowRule"?`workflow rule "${e}"`:`Apex trigger ${e}`}var vc={flows:"the flows",triggers:"the Apex triggers",processes:"the Process Builder processes",workflowRules:"the workflow rules",automation:"what runs"};function Oc(o){return`${o.objectApiName}: ${Ru(o)} (${o.writes.join(", ")})`}function ku(o,e,t){let r=[];o.firing.length>0&&r.push(`${e} runs automation as this load inserts its records and updates them: ${o.firing.map(Oc).join("; ")}.`);for(let{part:n,reason:s}of o.unread??[]){let i=vc[n];r.push(`${i[0].toUpperCase()}${i.slice(1)} of ${e} could not be read (${s}), so what fires as the load writes is not known.`)}return r.push(...t),r.push(`Nothing was written. Add --accept-automation to load all the same, or turn that automation off in ${e} first.`),r.join(" ")}function ls(o){let{read:e,target:t}=o,r=wu(o.written),n=[],s=[],i=[];if(bu(e))s=[{part:"automation",reason:e.unread}];else{let c=Dt(e,o.plan,r),l=new Map;for(let p of c.firing){if(p.write!=="insert"&&p.write!=="update")continue;let g=`${p.objectApiName}\0${p.kind}\0${p.name}`,h=l.get(g);h?h.writes.includes(p.write)||h.writes.push(p.write):l.set(g,{objectApiName:p.objectApiName,kind:p.kind,name:p.name,writes:[p.write]})}n=[...l.values()].map(p=>({...p,writes:["insert","update"].filter(g=>p.writes.includes(g))})),s=Za(e);let u=Xa(c.automation,Ja(c.automation,[...o.written])),f=[...new Set(u.flatMap(p=>p.permissionSet??[]))];i=[...Qa(u,t,"the load"),...o.mayMute&&f.length>0?[e.cannotAssign===!0?`--mute-automation would be refused: ${ga}.`:`With --mute-automation, the load assigns ${f.join(", ")} to the user it writes as for the load alone, under a lease, and what ${f.length===1?"it keeps":"they keep"} quiet does not fire.`]:[]]}if(n.length===0&&s.length===0)return{};let d={firing:n,...s.length>0?{unread:s}:{},accepted:o.accepted};if(o.accepted)return{info:d};let a={code:yu,message:ku(d,t,i)};return{info:{...d,refused:a},stop:a}}function rg(o,e){return[`target automation: what ${e} runs as the load inserts its records and updates them`,...o.firing.map(t=>` ${Oc(t)}`),...(o.unread??[]).map(({part:t,reason:r})=>` ${vc[t]} could not be read: ${r}`),...o.accepted?[" accepted (--accept-automation): the load writes all the same"]:[]]}import{existsSync as Pf}from"node:fs";import*as Pe from"node:fs/promises";import*as kl from"node:os";import*as je from"node:path";var ur=class extends Error{constructor(t,r=[]){super(r.length>0?`${t}:
|
|
15
|
+
- ${r.join(`
|
|
16
|
+
- `)}`:t);this.violations=r;this.name="RulesFileError"}violations},Iu=/^\d+\.\d+\.\d+$/,Sc=/^[A-Za-z][A-Za-z0-9_]*\.[A-Za-z][A-Za-z0-9_]*$/,vu=new Set(_o);function us(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function Zn(o){let e=[];if(!us(o))throw new ur("Rules file must be a JSON object");let t=o.rulesVersion;(typeof t!="string"||!Iu.test(t))&&e.push('rulesVersion is required and must be semver (e.g. "1.0.0")');let r=o.rules;if(!us(r))throw e.push('rules is required and must be an object keyed by "Object.Field"'),new ur("Invalid rules file",e);let n={};for(let[s,i]of Object.entries(r)){if(!Sc.test(s)){e.push(`"${s}": key must match "ObjectApiName.FieldApiName"`);continue}if(!us(i)){e.push(`"${s}": rule must be an object with a "generator" property`);continue}let d=i.generator;if(typeof d!="string"||!vu.has(d)){e.push(`"${s}": unknown generator ${JSON.stringify(d)} (supported: ${_o.join(", ")})`);continue}let a=i.approved===!0;if(d==="keep"&&!a){e.push(`"${s}": generator "keep" requires "approved": true (explicit human review)`);continue}let c={generator:d};i.approved!==void 0&&(c.approved=a),typeof i.comment=="string"&&(c.comment=i.comment),n[s]=c}if(e.length>0)throw new ur("Invalid rules file",e);return{rulesVersion:t,rules:n}}function Ac(o){let e=Object.keys(o.rules).sort(),t={};for(let r of e)t[r]=o.rules[r];return`${JSON.stringify({rulesVersion:o.rulesVersion,rules:t},null,2)}
|
|
17
|
+
`}var fs={rulesVersion:"1.0.0",rules:{}};function Pc(o){if(o===null)return{found:!1};try{let e=Zn(JSON.parse(o));return{found:!0,rulesVersion:e.rulesVersion,ruleCount:Object.keys(e.rules).length}}catch(e){return{found:!0,invalid:e instanceof Error?e.message:String(e)}}}var Ou=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Su=new Set(["FeedItem.Type","Pricebook2.IsActive","PricebookEntry.IsActive","Product2.IsActive",...Ou.flatMap(o=>[`BusinessHours.${o}StartTime`,`BusinessHours.${o}EndTime`]),"BusinessHours.TimeZoneSidKey","OperatingHours.TimeZone","TimeSlot.DayOfWeek","TimeSlot.StartTime","TimeSlot.EndTime","TimeSlot.Type"]),Au=new Set(["TimeZoneSidKey","LocaleSidKey","LanguageLocaleKey","CurrencyIsoCode","EmailEncodingKey"]);function ft(o,e,t){let r=`${e}.${t}`,n=o.rules[r]?.generator;return n||(o.personalBySchema?.has(r)===!0?"clear":Su.has(r)||Au.has(t)||o.keptBySchema?.has(r)===!0?"keep":"clear")}function Tc(o,e,t){let r=new Set(o.keptBySchema??[]),n=new Set(o.personalBySchema??[]);for(let[s,i]of e){let d=new Set(t.detectPII(s,i.map(a=>({apiName:a.name,label:a.label??a.name,type:a.type}))).piiFields.map(a=>a.fieldApiName));for(let a of i){let c=`${s}.${a.name}`;d.has(a.name)?n.add(c):a.type==="picklist"&&(a.restrictedPicklist===!0||a.nillable===!1)&&a.compoundFieldName===void 0&&r.add(c)}}return{...o,keptBySchema:r,personalBySchema:n}}function jc(o,e){let t=new Set;for(let r of o.objects)for(let n of r.records)for(let s of Object.keys(n.fields)){let i=`${r.objectApiName}.${s}`;e.rules[i]===void 0&&ft(e,r.objectApiName,s)==="keep"&&t.add(i)}return[...t].sort()}function Fc(o,e,t){let r=[];for(let n of o.objects){let s=t.get(n.objectApiName)??[];for(let l of s){let u=mn(n.objectApiName,l.name);if(l.name==="Id"||l.createable===!1||l.nillable!==!1&&u===void 0||l.defaultedOnCreate===!0||l.type==="reference"||(l.referenceTo?.length??0)>0||ft(e,n.objectApiName,l.name)!=="clear")continue;n.records.some(p=>{if(u!==void 0&&!or(u,Rn(p.fields,!1)))return!1;let g=p.fields[l.name];return g!=null&&g!==""})&&r.push(`${n.objectApiName}.${l.name}`)}let i=n.objectApiName,d=gn(i,l=>s.some(u=>u.name===l&&u.createable!==!1),l=>ft(e,i,l)!=="clear"),a=`${i}.${d}`;d!==void 0&&n.records.some(l=>{let u=l.fields[d];return u!=null&&u!==""})&&!r.includes(a)&&r.push(a)}return r.sort()}var Pu="Cleared on review of the extraction result: kept in clear text without a rule before.";function Ec(o,e){let t=Zn(o),r=e.filter(c=>!Sc.test(c));if(r.length>0)throw new ur('Fields to clear must be named "ObjectApiName.FieldApiName"',r.map(c=>JSON.stringify(c)));let n=o,s={...n.rules},i=[],d=[];for(let c of[...new Set(e)].sort()){if(t.rules[c]!==void 0){d.push(c);continue}s[c]={generator:"clear",comment:Pu},i.push(c)}let a=i.length>0?Tu(t.rulesVersion):t.rulesVersion;return{payload:{...n,rulesVersion:a,rules:s},rulesVersion:a,cleared:i,alreadyRuled:d}}function Tu(o){let[e,t]=o.split(".").map(Number);return`${e}.${t+1}.0`}import*as Lc from"node:fs/promises";import*as Nc from"node:path";var ps=/\{\{([A-Z][A-Z0-9_]*)\}\}/g,Cc=/^[A-Z][A-Z0-9_]*$/,Tt=class extends Error{constructor(e){super(e),this.name="QueryTemplateError"}};function Kr(o,e){for(let i of Object.keys(e))if(!Cc.test(i))throw new Tt(`Invalid token name ${JSON.stringify(i)}`);let t=new Set;for(let i of o.matchAll(ps))t.add(i[1]);let r=[...t].filter(i=>!(i in e));if(r.length>0)throw new Tt(`Query template references token(s) without a value: ${r.join(", ")}. Token values (ID lists, date bounds) must be provided from the sas at execution time.`);let n=o.replace(ps,(i,d)=>e[d]),s=n.match(ps);if(s)throw new Tt(`Unresolved placeholder(s) after render: ${s.join(", ")}`);return n}async function zc(o,e,t){let n=(t??new pe).assertOutsideRepo(Nc.join(o,e)),s=JSON.parse(await Lc.readFile(n,"utf8"));if(typeof s!="object"||s===null||Array.isArray(s))throw new Tt(`Token file ${n} must contain a JSON object`);let i={};for(let[d,a]of Object.entries(s)){if(!Cc.test(d))throw new Tt(`Invalid token name ${JSON.stringify(d)} in ${n}`);if(typeof a!="string")throw new Tt(`Token ${d} in ${n} must be a string`);i[d]=a}return i}var Vr=class extends Error{constructor(){super("Selection stopped"),this.name="SelectionStopped"}};function ju(o,e){return e?e.aborted?(o.catch(()=>{}),Promise.reject(new Vr)):new Promise((t,r)=>{let n=()=>r(new Vr);e.addEventListener("abort",n,{once:!0}),o.then(s=>{e.removeEventListener("abort",n),t(s)},s=>{e.removeEventListener("abort",n),r(s)})}):o}var Fu=2500,Eu=3,Lu=5;function Nu(o,e){return Object.entries(o).filter(([t,r])=>t!==e&&r>0).sort(([t,r],[n,s])=>s-r||t.localeCompare(n)).slice(0,Lu).map(([t,r])=>({objectApiName:t,count:r}))}var Gt=class extends Error{constructor(t,r,n,s){let i=Nu(t,s),d=i.map(c=>`${c.objectApiName} ${c.count}`),a=i.length>0?`The heaviest: ${d.join(", ")}. Leave out those the dataset does not need with excludedObjects (${JSON.stringify(i.map(c=>c.objectApiName))}), narrow the coverage axes/edge cases, or raise budgetMaxRecords explicitly. `:"Narrow the coverage axes/edge cases or raise budgetMaxRecords explicitly. ";super(`Volumetry budget exceeded: ${r} records measured for a budget of ${n}. ${a}Per-object counts: ${JSON.stringify(t)}`);this.measured=t;this.total=r;this.budgetMax=n;this.name="VolumetryBudgetExceededError",this.heaviest=d}measured;total;budgetMax;heaviest},gs=class extends Error{constructor(e){super(e),this.name="CoverageSelectionError"}},Qn=class{deps;constructor(e){this.deps=e}async select(e,t={}){let r=e.budgetMaxRecords??Fu,n=e.candidatesPerCombination??Eu,s=ye(e.rootObject),{signal:i}=t,d=p=>t.onProgress?.(p),a=[],c=[],l=[],u={during:"axes",pending:[]},f=()=>{let p={};for(let h of l)for(let[m,y]of Object.entries(h))p[m]=(p[m]??0)+y;let g=Object.values(p).reduce((h,m)=>h+m,0);if(g>r)throw new Gt(p,g,r,s);return{roots:a,uncovered:c,volumetry:{measured:p,total:g,budgetMax:r,summed:!0},selectedAt:(this.deps.now?.()??new Date).toISOString(),stopped:{reason:i?.reason==="timeout"?"timeout":"cancelled",during:u.during,...u.combinationKey!==void 0?{combinationKey:u.combinationKey}:{},...u.candidate!==void 0?{candidate:u.candidate,candidates:n}:{},notProbed:u.pending}}};try{return await this.run(e,{rootObject:s,budgetMax:r,candidateLimit:n,signal:i,tell:d},{roots:a,uncovered:c,ownMeasures:l,at:u})}catch(p){if(p instanceof Vr)return f();throw p}}async run(e,t,r){let{rootObject:n,budgetMax:s,candidateLimit:i,signal:d,tell:a}=t,{roots:c,uncovered:l,ownMeasures:u,at:f}=r,p=P=>ju(P,d),g=new Map,h=new Map;for(let P of e.axes)a({phase:"axis",axis:P.name}),g.set(P.name,await p(this.enumerateAxisValues(P,e.tokens))),h.set(P.name,await p(this.deps.fieldType?.(n,P.filterField).catch(()=>{})??Promise.resolve(void 0)));let m=e.axes.length===0?[[]]:Mu(e.axes.map(P=>({axis:P.name,values:g.get(P.name)??[]}))),y=P=>P.length===0?"all":P.map(_=>`${_.axis}=${_.value??"NULL"}`).join("|");f.pending=[...m.map(y),...e.edgeCases.map(P=>`edge:${P.name}`)];let R=async(P,_)=>(f.during="combination",f.combinationKey=P,f.candidate=void 0,f.pending=f.pending.filter(q=>q!==P),this.pickHealthyRoot(n,_,i,e.tokens,{step:p,onCandidate:q=>{f.candidate=q,a({phase:"candidate",combinationKey:P,candidate:q,candidates:i})}}));for(let[P,_]of m.entries()){let q=y(_);a({phase:"combination",combinationKey:q,index:P+1,of:m.length});let C=_.map(O=>{let F=ye(e.axes.find(v=>v.name===O.axis)?.filterField??"");return O.value===null?`${F} = NULL`:`${F} = ${zu(O.value,h.get(O.axis))}`}).join(" AND "),I=await R(q,C),w={};for(let O of _)w[O.axis]=O.value;I.id?(c.push({rootRecordId:I.id,combinationKey:q,axisValues:w}),I.measured&&u.push(I.measured)):l.push({combinationKey:q,reason:Mc(I,i)})}for(let[P,_]of e.edgeCases.entries()){let q=`edge:${_.name}`;a({phase:"combination",combinationKey:q,index:P+1,of:e.edgeCases.length});let C=await R(q,`(${_.whereFragment})`);C.id?(c.push({rootRecordId:C.id,combinationKey:q,axisValues:{},edgeCase:_.name}),C.measured&&u.push(C.measured)):l.push({combinationKey:`edge:${_.name}`,reason:C.probed===0?"no record matches the edge-case marker":Mc(C,i)})}f.during="measure",f.combinationKey=void 0,f.candidate=void 0,c.length>0&&a({phase:"measure",roots:c.length});let j=c.length===0?{}:await p(this.deps.measureVolumetry(c.map(P=>P.rootRecordId))),T=Object.values(j).reduce((P,_)=>P+_,0);if(T>s)throw new Gt(j,T,s,n);return{roots:c,uncovered:l,volumetry:{measured:j,total:T,budgetMax:s},selectedAt:(this.deps.now?.()??new Date).toISOString()}}async enumerateAxisValues(e,t){let r=Kr(e.valuesSoql,t??{}),n=await this.deps.query(r),s=[];for(let i of n){if(!("axisValue"in i))throw new gs(`Axis "${e.name}" query must alias its grouped value as axisValue (e.g. SELECT ${e.filterField} axisValue, COUNT(Id) cnt ... GROUP BY ${e.filterField})`);let d=i.axisValue;d==null?s.push(null):typeof d=="string"?s.push(d):s.push(String(d))}return[...new Set(s)].sort((i,d)=>(i??"").localeCompare(d??""))}async pickHealthyRoot(e,t,r,n,s){let i=t===""?`SELECT Id FROM ${e} ORDER BY Id ASC LIMIT ${Math.max(1,Math.floor(r))}`:`SELECT Id FROM ${e} WHERE ${t} ORDER BY Id ASC LIMIT ${Math.max(1,Math.floor(r))}`,d=await s.step(this.deps.query(Kr(i,n??{}))),a=0,c;for(let l of d){let u=l.Id;if(typeof u!="string"||u==="")continue;a++,s.onCandidate(a);let f=await s.step(this.deps.checkHealth.check(u));if(f.healthy)return{id:u,probed:a,...f.measured?{measured:f.measured}:{}};c=f.reason}return{id:null,probed:a,lastReason:c}}};function Mc(o,e){if(o.probed===0)return"no candidate record";let t=`no healthy candidate among the ${o.probed} probed (limit ${e})`;return o.lastReason?`${t} \u2014 last: ${o.lastReason}`:t}var Cu=new Set(["int","long","double","currency","percent"]);function zu(o,e){let t=`'${Be(o)}'`;switch(e){case"boolean":return/^(true|false)$/i.test(o)?o.toLowerCase():t;case"date":return/^\d{4}-\d{2}-\d{2}$/.test(o)?o:t;case"datetime":return/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?(Z|[+-]\d{2}:?\d{2})$/.test(o)?o:t;default:return e!==void 0&&Cu.has(e)&&/^-?\d+(\.\d+)?$/.test(o)?o:t}}function Mu(o){let e=[[]];for(let{axis:t,values:r}of o){let n=[];for(let s of e)for(let i of r)n.push([...s,{axis:t,value:i}]);e=n}return e}var eo=class{constructor(e,t){this.measure=e;this.expectedObjects=t}measure;expectedObjects;async check(e){let t;try{t=await this.measure([e])}catch(r){return{healthy:!1,reason:`extraction failed: ${r instanceof Error?r.message:String(r)}`}}for(let r of this.expectedObjects)if((t[r]??0)===0)return{healthy:!1,reason:`no ${r} record in this dossier`};return{healthy:!0,measured:t}}};import*as fr from"node:fs/promises";import*as hs from"node:path";var Hr="selection.json";async function Dc(o,e,t){let r=t??new pe,n=r.assertOutsideRepo(o);await fr.mkdir(n,{recursive:!0});let s=r.assertOutsideRepo(hs.join(n,Hr));return await fr.writeFile(s,`${JSON.stringify({fileVersion:1,selection:e},null,2)}
|
|
18
|
+
`,"utf8"),s}async function ms(o,e){let r=(e??new pe).assertOutsideRepo(hs.join(o,Hr)),n=JSON.parse(await fr.readFile(r,"utf8"));if(typeof n!="object"||n===null||n.fileVersion!==1||typeof n.selection!="object")throw new Error(`Invalid selection file at ${r} (expected fileVersion 1)`);return n.selection}import*as pr from"node:fs/promises";import*as ys from"node:path";var xc="discovery.json",xu=1440*6e4,$u=ot({name:$e(),fields:mt(ot({name:$e(),type:$e(),referenceTo:mt($e())}).loose()),childRelationships:mt(ot({childSObject:$e(),field:$e(),relationshipName:$e()}).loose())}).loose(),_u=ot({fileVersion:Ys(1),sourceOrgId:$e().min(1),rootObject:$e().min(1),maxNodes:Ks().int().positive(),step:Hs(["select","extract"]),discoveredAt:bo.datetime(),schemaStamp:bo.datetime().optional(),graph:ot({nodes:mt(ot({objectApiName:$e(),included:cn()}).loose()),edges:mt(ot({sourceObject:$e(),targetObject:$e()}).loose())}).loose(),describes:Vs($e(),$u),objects:mt(ot({name:$e(),keyPrefix:$e().nullable()}))});async function $c(o,e,t=new pe){let r=t.assertOutsideRepo(o);await pr.mkdir(r,{recursive:!0});let n=t.assertOutsideRepo(ys.join(r,xc));return await pr.writeFile(n,`${JSON.stringify(e)}
|
|
19
|
+
`,"utf8"),n}async function _c(o,e=new pe){let t=e.assertOutsideRepo(ys.join(o,xc)),r;try{r=await pr.readFile(t,"utf8")}catch{return{none:"no graph kept in the sas"}}let n;try{n=JSON.parse(r)}catch{return{none:"the graph kept in the sas could not be read"}}let s=_u.safeParse(n);return s.success?{kept:s.data}:{none:"the graph kept in the sas could not be read"}}function Bc(o,e,t=new Date){if(o.sourceOrgId!==e.sourceOrgId)return"the graph kept is of another org";if(o.rootObject!==e.rootObject)return`the graph kept is of ${o.rootObject}, not ${e.rootObject}`;if(o.maxNodes!==e.maxNodes)return`the graph kept was discovered at a cap of ${o.maxNodes}, not ${e.maxNodes}`;let r=t.getTime()-Date.parse(o.discoveredAt);if(!(r>=0&&r<=xu))return`the graph kept was discovered on ${o.discoveredAt}, more than a day ago`;if(!o.schemaStamp)return"the org did not give its clock when the graph kept was discovered"}function Wc(o){let e=Date.parse(o);if(!Number.isNaN(e))return new Date(Math.floor(e/1e3)*1e3-1e3).toISOString()}import*as ro from"node:fs/promises";import*as qc from"node:path";var Bu="SELECT Id, SobjectType, DeveloperName, NamespacePrefix, Name FROM RecordType ORDER BY SobjectType, DeveloperName",Wu="rt-map.json",qu=10;function Gu(o,e){return Er.has(o)?e:e.map(t=>t.type==="reference"&&t.referenceTo.some(r=>Er.has(r))?{...t,nillable:!0}:t)}function Ut(o){if(!("attributes"in o))return o;let e={...o};return delete e.attributes,e}var ws=class{constructor(e){this.keyPrefixes=e}keyPrefixes;prefixes=new Map;known=new Set;fromOrg;learnFrom(e){for(let[t,r]of e){let n=r.keys().next();n.done||this.note(t,n.value.slice(0,3))}}async objectsOf(e,t){return t.length<2?t:(!this.known.has(e.slice(0,3))&&this.keyPrefixes&&(this.fromOrg??=this.keyPrefixes().then(r=>{for(let[n,s]of r)this.prefixes.has(n)||this.note(n,s)},()=>{}),await this.fromOrg),Sa(e,t,this.prefixes))}note(e,t){this.prefixes.set(e,t),this.known.add(t)}};function Yr(o,e){return e.filter(t=>t.type==="reference"&&er(o,t.name,t.nillable)).map(t=>t.name)}function Uu(o,e,t){return{objectApiName:o,recordCount:0,fieldCount:e.length,status:"idle",progress:0,included:!0,piiFields:[],anonymizeFields:[],level:t,successCount:0,failureCount:0,errors:[],createableFieldCount:0,estimatedSizeMB:0,estimatedApiCalls:0,batchStrategy:"auto"}}var Ku=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/,to=class extends Error{constructor(e){super(e),this.name="FrozenExtractionError"}},Jr=class{deps;soqlBuilder=new Ra;constructor(e){this.deps=e}query(e){return Ni(e,t=>this.deps.query(t))}async extract(e){if(!Ku.test(e.asOf))throw new to(`asOf must be a strict ISO instant (e.g. 2026-08-03T09:44:52Z), got ${JSON.stringify(e.asOf)}`);if(e.rootRecordIds.length===0)throw new to("No root record IDs provided \u2014 empty selection refused");let t=e.guard??new pe,r=t.assertOutsideRepo(e.sasDir),n=`CreatedDate <= ${e.asOf}`,s=new Bo;s.add(e.rootObject,e.rootRecordIds),s.addReached(e.rootObject,e.rootRecordIds);let i=new Map,d=new nr,a=new Set,c={},l=new ws(this.deps.keyPrefixes),u=new Map,f=async w=>{let O=u.get(w);if(O)return O;let F=await this.deps.describeFields(w);return u.set(w,F),F},p=async w=>{let O=await f(w);O.some(v=>v.name==="CreatedDate")||a.add(w);let F=O.filter(v=>v.type==="base64").map(v=>v.name);return F.length>0&&(c[w]=F),O},g=new Set(e.excludedObjects??[]),h=await this.withWhatStatusesNeed(Oa(e.graph,g),f,g),m=h.graph,y=[...m.nodes].filter(w=>w.included).sort((w,O)=>w.level-O.level),R=new Set(y.map(w=>w.objectApiName));for(let w of y){let O=await p(w.objectApiName),F=this.selectFields(w.objectApiName,O,e.excludedFields),v=O.some(K=>K.name==="CreatedDate"),A=this.soqlBuilder.build({node:w,fields:Gu(w.objectApiName,O),selectFields:F,edges:m.edges,cache:s,rootObjectApiName:`__frozen_root_${e.rootObject}__`,rootRecordId:e.rootRecordIds[0],extraWhere:v?n:void 0,everyEdge:!Er.has(w.objectApiName),readObjects:R,catalog:Er,fromAboveOnly:!0});if(!A.scoped)continue;let L=[],x=[];for(let[K,H]of A.statements.entries()){let N=await this.query(H);if(L.push(...N),!(K<A.byIdCount))for(let Z of N)typeof Z.Id=="string"&&x.push(Z.Id)}let B=d.keep(w.objectApiName,await this.keepWhatStatusesNeed(h.added.get(w.objectApiName),L,i),Yr(w.objectApiName,O)),D=i.get(w.objectApiName);D||(D=new Map,i.set(w.objectApiName,D));let G=[];for(let K of B){let H=K.Id;typeof H!="string"||H===""||(G.push(H),D.has(H)||D.set(H,Ut(K)))}s.addRead(w.objectApiName,G);let X=new Set(G);s.addReached(w.objectApiName,x.filter(K=>X.has(K))),l.learnFrom(i);for(let K of O)if(K.type==="reference")for(let H of B){let N=H[K.name];if(!(typeof N!="string"||N===""))for(let Z of await l.objectsOf(N,K.referenceTo))s.add(Z,[N])}w.objectApiName===e.rootObject&&await this.readWhatTheRootsName({rootObject:e.rootObject,fields:O,selectFields:F,bucket:D,cache:s,owners:l,recordsByObject:i,leftToThePlatform:d,extraWhere:v?n:void 0})}await this.readWhatNamedStatusesNeed({nodes:y,edges:m.edges,cache:s,recordsByObject:i,describe:p,asOfWhere:n,excludedFields:e.excludedFields,leftToThePlatform:d}),await this.completeRequiredParents({...e,graph:m},i,p,n,l,d,g),await Vu(i,p,d);let j=await this.addStandardPrices(e,i,n);await this.addSellingModelOptions({...e,graph:m},i,p,n,g);let T=(i.get(pn)?.size??0)>0,P=await this.exclusionCosts(i,p,g,T),_=await this.leaveOutWhatReadsMasked(i,f),q=[...i.entries()].sort(([w],[O])=>w.localeCompare(O)).map(([w,O])=>{let F=[...O.values()].sort((A,L)=>String(A.Id).localeCompare(String(L.Id)));w===qe&&(F=Zs(F,{sellingModel:T}));let v=F.map((A,L)=>({referenceId:`${w}-${String(L+1).padStart(6,"0")}`,sourceId:String(A.Id),fields:A}));return{objectApiName:w,records:v}}),C=await this.pullRecordTypes(e);await ro.mkdir(r,{recursive:!0});let I=t.assertOutsideRepo(qc.join(r,Wu));return await ro.writeFile(I,`${JSON.stringify(C,null,2)}
|
|
20
|
+
`,"utf8"),{objects:q,asOf:e.asOf,recordTypeMap:C,unboundedObjects:[...a],fileFields:c,...j?{standardPricebookSourceId:j}:{},leftToThePlatform:d.counts(),...P.length>0?{exclusionCosts:P}:{},..._.length>0?{encryptedNotKept:_}:{}}}async leaveOutWhatReadsMasked(e,t){let r=aa(ia(s=>this.deps.query(s)),async s=>({fields:await t(s)})),n=[];for(let[s,i]of e)if(i.size!==0)for(let d of await r(s)){let a=!1;for(let c of i.values())d in c&&(a||=c[d]!==null&&c[d]!==void 0,delete c[d]);a&&n.push(`${s}.${d}`)}return n.sort()}async withWhatStatusesNeed(e,t,r){let n=new Set(e.nodes.map(a=>a.objectApiName)),s=new Map,i=[],d=[];for(let a of e.nodes){let c=ln[a.objectApiName];if(!a.included||!c||n.has(c.object)||s.has(c.object)||r.has(c.object))continue;let l;try{l=await t(c.object)}catch{continue}let u=l.find(f=>f.name===c.lookup&&f.type==="reference"&&f.referenceTo.includes(a.objectApiName));u&&(s.set(c.object,{parent:a.objectApiName,lookup:u.name}),i.push(Uu(c.object,l,a.level+1)),d.push({sourceObject:a.objectApiName,targetObject:c.object,relationshipName:u.name,type:"lookup",required:er(c.object,u.name,u.nillable)}))}return s.size===0?{graph:e,added:s}:{graph:{...e,nodes:[...e.nodes,...i],edges:[...e.edges,...d]},added:s}}async readWhatTheRootsName(e){let{rootObject:t,bucket:r,cache:n}=e,s=new Set([...n.get(t)??[]].filter(a=>!r.has(a)));if(s.size===0)return;let i=[];for(let a of this.soqlBuilder.buildById({objectApiName:t,selectFields:e.selectFields,ids:s,extraWhere:e.extraWhere}))i.push(...await this.query(a));let d=e.leftToThePlatform.keep(t,i,Yr(t,e.fields));for(let a of d)typeof a.Id=="string"&&!r.has(a.Id)&&r.set(a.Id,Ut(a));e.owners.learnFrom(e.recordsByObject);for(let a of e.fields)if(a.type==="reference")for(let c of d){let l=c[a.name];if(!(typeof l!="string"||l===""))for(let u of await e.owners.objectsOf(l,a.referenceTo))n.add(u,[l])}}async keepWhatStatusesNeed(e,t,r){if(!e)return t;let n=_t[e.parent],s=n?await sr(d=>this.query(d),n):void 0,i=new Set;for(let[d,a]of r.get(e.parent)??[])s&&ir(a.Status,s)&&i.add(d);return t.filter(d=>{let a=d[e.lookup];return typeof a=="string"&&i.has(a)})}async readWhatNamedStatusesNeed(e){for(let[t,r]of Object.entries(ln)){let n=e.nodes.find(m=>m.objectApiName===r.object),s=e.recordsByObject.get(t),i=_t[t];if(!n||!s||s.size===0||!i)continue;let d=e.cache.reachedOf(t),a=[...s].filter(([m])=>!d?.has(m));if(a.length===0)continue;let c=await sr(m=>this.query(m),i);if(!c)continue;let l=a.filter(([,m])=>ir(m.Status,c)).map(([m])=>m);if(l.length===0)continue;let u=await e.describe(r.object),f=new Bo;f.addRead(t,l);let p=this.soqlBuilder.build({node:n,fields:u,selectFields:this.selectFields(r.object,u,e.excludedFields),edges:e.edges,cache:f,rootObjectApiName:`__frozen_root_${t}__`,rootRecordId:l[0],extraWhere:u.some(m=>m.name==="CreatedDate")?e.asOfWhere:void 0,under:new Set([t])});if(!p.scoped)continue;let g=e.recordsByObject.get(r.object);g||(g=new Map,e.recordsByObject.set(r.object,g));let h=Yr(r.object,u);for(let m of p.statements){let y=e.leftToThePlatform.keep(r.object,await this.query(m),h);for(let R of y)typeof R.Id=="string"&&!g.has(R.Id)&&g.set(R.Id,Ut(R))}}}async completeRequiredParents(e,t,r,n,s,i,d){let a=new Set(e.graph.nodes.filter(f=>f.included).map(f=>f.objectApiName)),c=va(e.graph,d),l=f=>a.has(f)||c.has(f),u=new Map;for(let f=0;f<qu;f++){s.learnFrom(t);let p=new Map;for(let[g,h]of t){let m=(await r(g)).filter(y=>y.type==="reference"&&Ia(g,y));for(let y of h.values())for(let R of m){let j=y[R.name];if(typeof j!="string"||j===""||i.has(j)||!R.referenceTo.some(l))continue;let T=(await s.objectsOf(j,R.referenceTo)).filter(l);for(let P of T)t.get(P)?.has(j)||u.get(P)?.has(j)||p.set(P,(p.get(P)??new Set).add(j))}}if(p.size===0)return;for(let[g,h]of p){u.set(g,new Set([...u.get(g)??[],...h]));let m=await r(g),y=t.get(g);y||(y=new Map,t.set(g,y));let R=this.soqlBuilder.buildById({objectApiName:g,selectFields:this.selectFields(g,m,e.excludedFields),ids:h,extraWhere:m.some(T=>T.name==="CreatedDate")?n:void 0}),j=Yr(g,m);for(let T of R)for(let P of i.keep(g,await this.query(T),j))typeof P.Id=="string"&&!y.has(P.Id)&&y.set(P.Id,Ut(P))}}}async addStandardPrices(e,t,r){let n=t.get(qe);if(!n||n.size===0)return;let[s]=await this.query(Mt),i=typeof s?.Id=="string"?s.Id:void 0;if(!i)return;let d=g=>[Ge,Je,tr].map(h=>String(g[h]??"")).join("|"),a=new Set,c=new Set;for(let g of n.values()){if(g[yt]===i)continue;let h=g[Ge];typeof h=="string"&&h!==""&&(a.add(h),c.add(d(g)))}if(a.size===0)return;let l=async(g,h)=>{let m=await this.deps.describeFields(g),y=this.selectFields(g,m,e.excludedFields).map(j=>ye(j)).join(", "),R=m.some(j=>j.name==="CreatedDate")?` AND ${r}`:"";return this.query(`SELECT ${y} FROM ${g} WHERE ${h}${R}`)},u=t.get(un);if(u||(u=new Map,t.set(un,u)),!u.has(i))for(let g of await l(un,`Id = '${Be(i)}'`))u.set(i,Ut(g));let f=await this.deps.describeFields(qe),p=this.soqlBuilder.buildJoining({objectApiName:qe,selectFields:this.selectFields(qe,f,e.excludedFields),split:{field:Ge,ids:a},whole:{field:yt,ids:new Set([i])},extraWhere:f.some(g=>g.name==="CreatedDate")?r:void 0});for(let g of p)for(let h of await this.query(g))typeof h.Id!="string"||n.has(h.Id)||c.has(d(h))&&n.set(h.Id,Ut(h));return i}async addSellingModelOptions(e,t,r,n,s){if(s.has(_e)||e.graph.nodes.some(m=>m.objectApiName===_e&&!m.included))return;let i=t.get(qe),d=t.get(ka),a=t.get(pn);if(!i||!d||!a)return;let c=m=>`${String(m[Ge]??"")}|${String(m[Je]??"")}`,l=new Set,u=new Set,f=new Set;for(let m of i.values()){let y=m[Ge],R=m[Je];typeof y!="string"||!d.has(y)||typeof R!="string"||!a.has(R)||(l.add(y),u.add(R),f.add(c(m)))}if(f.size===0)return;let p=await r(_e),g=this.soqlBuilder.buildJoining({objectApiName:_e,selectFields:this.selectFields(_e,p,e.excludedFields),split:{field:Ge,ids:l},whole:{field:Je,ids:u},extraWhere:p.some(m=>m.name==="CreatedDate")?n:void 0}),h=t.get(_e);h||(h=new Map,t.set(_e,h));for(let m of g)for(let y of await this.query(m))typeof y.Id!="string"||h.has(y.Id)||f.has(c(y))&&h.set(y.Id,Ut(y))}async exclusionCosts(e,t,r,n){if(r.size===0)return[];let s=[],i=a=>`record${a===1?"":"s"}`,d=new Map;for(let[a,c]of e){if(c.size===0)continue;let l=(await t(a)).filter(g=>g.type==="reference"&&g.referenceTo.length===1&&g.referenceTo[0]!==a&&r.has(g.referenceTo[0])&&er(a,g.name,g.nillable)),u=a===qe&&n&&r.has(_e);if(l.length===0&&!u)continue;let f=new Map,p=new Map;for(let[g,h]of c){let m;for(let j of l){let T=h[j.name],P=j.referenceTo[0];if(!(typeof T!="string"||T==="")&&!e.get(P)?.has(T)){m={field:j.name,excluded:P};break}}let y=h[Je];if(!m&&u&&typeof y=="string"&&e.get(pn)?.has(y)&&(m={field:Je,excluded:_e}),!m)continue;f.set(g,m.excluded);let R=p.get(m.excluded)??{field:m.field,count:0};R.count++,p.set(m.excluded,R)}f.size>0&&d.set(a,f);for(let[g,{field:h,count:m}]of p)s.push({objectApiName:a,excludedObject:g,count:m,note:g===_e?`${m} ${a} ${i(m)} sold under a selling model cannot be loaded without the option that sells the product under it, and excludedObjects leaves ${g} out`:`${m} ${a} ${i(m)} cannot be loaded without the ${g} named by ${h}, which excludedObjects leaves out`})}for(let[a,c]of Object.entries(ln)){let l=e.get(a),u=_t[a];if(!l||l.size===0||!u)continue;let f=await sr(y=>this.query(y),u);if(!f)continue;let p=new Set,g=new Map,h=d.get(c.object);for(let[y,R]of e.get(c.object)??[]){let j=R[c.lookup];if(typeof j!="string")continue;let T=h?.get(y);T?g.has(j)||g.set(j,T):p.add(j)}let m=new Map;for(let[y,R]of l){if(!ir(R.Status,f))continue;let j=r.has(c.object)?c.object:p.has(y)?void 0:g.get(y);j&&m.set(j,(m.get(j)??0)+1)}for(let[y,R]of m){let j=R===1;s.push({objectApiName:a,excludedObject:y,count:R,note:`${R} ${a} ${i(R)} past Draft will be loaded as ${j?"a draft":"drafts"} and stay so: `+(y===c.object?`the platform gives ${a} this status only with ${c.object} records under it, and excludedObjects leaves ${c.object} out`:`none of ${j?"its":"their"} ${c.object} records can be loaded without ${y}, which excludedObjects leaves out`)})}}return s}selectFields(e,t,r){let n=new Set(r?.[e]??[]),s=t.map(i=>i.name).filter(i=>!n.has(i));return s.includes("Id")||s.unshift("Id"),s}async pullRecordTypes(e){let t=e.recordTypesSoqlTemplate??Bu,r=Kr(t,e.tokens??{}),n=await this.query(r),s=[];for(let i of n)typeof i.Id=="string"&&typeof i.SobjectType=="string"&&typeof i.DeveloperName=="string"&&typeof i.Name=="string"&&s.push({id:i.Id,sobjectType:i.SobjectType,developerName:i.DeveloperName,..."NamespacePrefix"in i?{namespacePrefix:typeof i.NamespacePrefix=="string"&&i.NamespacePrefix!==""?i.NamespacePrefix:null}:{},name:i.Name});return s}};async function Vu(o,e,t){for(let r=!0;r;){r=!1;for(let[n,s]of o){let i=[...s.values()],d=Yr(n,await e(n)),a=t.keep(n,i,d);if(a.length===i.length)continue;r=!0;let c=new Set(a.map(l=>l.Id));for(let l of s.keys())c.has(l)||s.delete(l)}}}var no=class{anonymize(e){let{rules:t,pseudonymizer:r}=e,n=Object.entries(e.extracted.fileFields??{}).filter(([u,f])=>f.some(p=>ft(t,u,p)!=="keep")).map(([u])=>u).filter(u=>e.extracted.objects.some(f=>f.objectApiName===u&&f.records.length>0)).sort(),s={...e.extracted,objects:e.extracted.objects.filter(u=>!n.includes(u.objectApiName))},i=new Map;for(let u of s.objects)for(let f of u.records)i.set(f.sourceId,f.referenceId);let d=new Map(s.recordTypeMap.map(u=>[u.id,u])),a={};for(let u of s.objects)a[u.objectApiName]=s.recordTypeMap.filter(f=>f.sobjectType===u.objectApiName).map(f=>({name:f.name,developerName:f.developerName,...f.namespacePrefix!==void 0?{namespacePrefix:f.namespacePrefix}:{}}));let c=[];for(let u of s.objects){let f=u.records.map(p=>{let g=this.anonymizeRecordFields(u.objectApiName,p.fields,i,d,t,r),h=p.fields.RecordTypeId,m=typeof h=="string"?d.get(h):void 0;return{referenceId:p.referenceId,fields:g,...m?{recordTypeDeveloperName:lt(m.namespacePrefix,m.developerName)}:{}}});c.push({objectApiName:u.objectApiName,records:f})}let l=s.standardPricebookSourceId?i.get(s.standardPricebookSourceId):void 0;return{datasetVersion:e.datasetVersion,objects:c,recordTypes:a,personContactSidecar:Hu(s,i),...l?{standardPricebook:l}:{},...n.length>0?{filesLeftOut:n}:{}}}anonymizeRecordFields(e,t,r,n,s,i){let d={};for(let[a,c]of Object.entries(t)){if(a==="Id")continue;if(c==null){d[a]=c;continue}if(a==="RecordTypeId"&&typeof c=="string"){let u=n.get(c);d[a]=u?u.name:"";continue}if(typeof c=="string"){let u=r.get(c);if(u!==void 0){d[a]=u;continue}}let l=ft(s,e,a);d[a]=i.pseudonymize(l,c)}for(let[a,c]of Object.entries(d))typeof c=="string"&&An(c)&&(d[a]="");return d}};function Hu(o,e){let t=[],r=o.objects.find(n=>n.objectApiName==="Account");if(!r)return t;for(let n of r.records){let s=n.fields.PersonContactId;if(typeof s!="string"||s==="")continue;let i=e.get(s);i!==void 0&&t.push({accountReferenceId:n.referenceId,contactReferenceId:i})}return t}var Yu=/^[A-Z]{2}-\d{3}-[A-Z]{2}$/,Ju=/^\+3363998\d{4}$/,Xu=/^[a-z0-9-]+@example\.invalid$/,Zu=/^\d{2}0+$/,Qu=3,oo=class{run(e,t,r,n={}){let s=new Set,i=new Map;for(let u of t.objects)for(let f of u.records)s.add(f.referenceId),i.set(f.referenceId,{objectApiName:u.objectApiName,record:f});let d={substitution:[],"clear-empty":[],formats:[],"no-residual-id":[]},a=new Map(e.recordTypeMap.map(u=>[u.id,[u.name,u.developerName]])),c=new Set(t.filesLeftOut??[]);for(let u of e.objects)if(!c.has(u.objectApiName))for(let f of u.records){let p=i.get(f.referenceId);if(!p){d.substitution.push({check:"substitution",objectApiName:u.objectApiName,referenceId:f.referenceId,detail:"record missing from the frozen dataset"});continue}let g=f.fields.RecordTypeId;this.checkSubstitution(u.objectApiName,f,p.record,r,d.substitution,new Set(typeof g=="string"?a.get(g)??[]:[]))}for(let u of t.objects)for(let f of u.records)this.checkClearEmpty(u.objectApiName,f,r,s,d["clear-empty"]),this.checkNoResidualId(u.objectApiName,f,s,d["no-residual-id"]);this.checkFormats(e,t,r,i,d.formats);let l=["substitution","clear-empty","formats","no-residual-id"].map(u=>({name:u,passed:d[u].length===0,violations:d[u]}));return{passed:l.every(u=>u.passed),checks:l,author:n.author??"frozen-dataset-engine",checkedAt:(n.now?.()??new Date).toISOString()}}checkSubstitution(e,t,r,n,s,i){for(let[d,a]of Object.entries(t.fields)){if(d==="Id"||a===null||a===void 0||a===""||ft(n,e,d)==="keep")continue;let l=r.fields[d];if(ef(l,a)){s.push({check:"substitution",objectApiName:e,referenceId:t.referenceId,field:d,detail:"original value still present in its own field"});continue}if(typeof a=="string"&&a.length>=Qu)for(let[u,f]of Object.entries(r.fields))u===d||typeof f!="string"||f!==a||ft(n,e,u)==="keep"||u==="RecordTypeId"&&i.has(f)||s.push({check:"substitution",objectApiName:e,referenceId:t.referenceId,field:u,detail:`transversal leak: original value of "${d}" found in "${u}"`})}}checkClearEmpty(e,t,r,n,s){for(let[i,d]of Object.entries(t.fields))i!=="RecordTypeId"&&(typeof d=="string"&&n.has(d)||ft(r,e,i)==="clear"&&d!==""&&d!==null&&d!==void 0&&s.push({check:"clear-empty",objectApiName:e,referenceId:t.referenceId,field:i,detail:`residual value under "clear" generator: ${JSON.stringify(d)}`}))}checkFormats(e,t,r,n,s){let i={registrationSIV:d=>Yu.test(d),phoneE164:d=>Ju.test(d),email:d=>Xu.test(d),postalCodeGeneralize:(d,a)=>Zu.test(d)&&d.length===a.trim().length};for(let d of e.objects)for(let a of d.records){let c=n.get(a.referenceId);if(c)for(let[l,u]of Object.entries(a.fields)){if(typeof u!="string"||u==="")continue;let f=ft(r,d.objectApiName,l),p=i[f];if(!p)continue;let g=c.record.fields[l];typeof g!="string"||g===""||p(g,u)||s.push({check:"formats",objectApiName:d.objectApiName,referenceId:a.referenceId,field:l,detail:`format not conserved for ${f}: ${JSON.stringify(g)}`})}}}checkNoResidualId(e,t,r,n){for(let[s,i]of Object.entries(t.fields))typeof i=="string"&&An(i)&&n.push({check:"no-residual-id",objectApiName:e,referenceId:t.referenceId,field:s,detail:"checksum-valid Salesforce ID survived the sweep"})}};function ef(o,e){return o===e?!0:o==null||e===null||e===void 0?!1:String(o)===String(e)}var Xr=class{constructor(e){this.orgAccess=e}orgAccess;cache=new Map;describes=new Map;async resolveByDeveloperName(e,t,r,n){let s=n===void 0?Mi(r):{namespacePrefix:n,developerName:r},i=`${e}|${t}|${String(s.namespacePrefix)}|${s.developerName}`,d=this.cache.get(i);if(d!==void 0)return d;let a=`SELECT Id, DeveloperName, NamespacePrefix FROM RecordType WHERE SobjectType = '${Be(t)}' AND DeveloperName = '${Be(s.developerName)}'`,c=zi(await this.orgAccess.query(e,a)),l=Di(s,c,Ao),u;if("ambiguous"in l)u={ambiguous:!0,carriers:l.ambiguous.map(Ao)};else if("found"in l){let f=l.found.id;u=await this.isUnavailable(e,t,f)?{unavailable:!0,id:f}:f}else u=null;return this.cache.set(i,u),u}async isUnavailable(e,t,r){let n=this.describeOf(e,t);return n?(await n).recordTypeInfos?.find(i=>i.recordTypeId===r)?.available===!1:!1}async givenRecordType(e,t){let r=this.describeOf(e,t);if(r)return zn(Sn((await r).recordTypeInfos))}describeOf(e,t){let r=this.orgAccess.describe;if(!r)return;let n=`${e}|${t}`,s=this.describes.get(n);return s||(s=r(e,t),this.describes.set(n,s)),s}};import*as ao from"node:fs";var tf=2e3,rf=3,nf=10,of=o=>new Promise(e=>setTimeout(e,o)),so=class{constructor(e){this.deps=e;this.sasGuard=e.sasGuard??new pe}deps;sasGuard;personAccounts=new Map;async verify(e){let t=e.now??(()=>new Date),r=e.sleep??of,n=g=>e.onProgress?.(g),s=e.measurementIntervalMs??tf,i=e.maxAttempts??rf,d=xn(this.sasGuard,e.contractPath);n({phase:"verify",status:"started",progress:0,message:"Measuring org state"});let a=null,c=null,l=null,u=0;for(let g=1;g<=i;g++){u=g,l=await this.measure(e,d);let h=bs(l);if(a!==null&&h===a){c=l;break}a=h,g<i&&await r(s)}let f=this.buildChecks(e,d,c??l,c!==null),p={status:uf(f,d,c),checks:f,attempts:u,measuredAt:t().toISOString(),objects:ff(d,c??l)};return e.manifestPath&&(this.consignVerdict(e.manifestPath,p,e.author),p.manifestPath=this.sasGuard.assertOutsideRepo(e.manifestPath)),n({phase:"verify",status:p.status==="passed"?"done":"error",progress:100,message:`Post-load verification: ${p.status} (${u} measurement(s))`}),p}async measure(e,t){return{counts:await this.measureCounts(e,t),orphans:await this.measureOrphans(e,t),personContact:await this.measurePersonContacts(e),presence:await this.measurePresence(e,t)}}async measureCounts(e,t){let r=e.mapping?Uc(e.mapping):void 0,n={};for(let s of Object.keys(t.objects).sort()){let i=`SELECT COUNT() FROM ${ye(s)}`;if(!r){n[s]=await this.deps.orgAccess.count(e.orgId,i);continue}let d=0;for(let a of Kc(r.get(s)??[]))d+=await this.deps.orgAccess.count(e.orgId,`${i} WHERE ${a}`);n[s]=d}return n}async measureOrphans(e,t){let r={},n=e.orphanSampleSize??nf,s=e.mapping?Uc(e.mapping):void 0;for(let[i,d]of Object.entries(e.mandatoryLookups??{}))for(let a of d){let c=new Set([...Gc(t,i,a),...Rs(t.objects[i]?.parentNotLoaded,a)].flatMap(f=>{let p=e.mapping?.get(f);return p===void 0?[]:[p]})),l=s?Kc((s.get(i)??[]).filter(f=>!c.has(f))):[""],u=[];for(let f of l){let p=`SELECT Id FROM ${ye(i)} WHERE ${ye(a)} = null${f?` AND ${f}`:""} ORDER BY Id LIMIT ${n}`,g=await this.deps.orgAccess.query(e.orgId,p);u.push(...g.map(h=>String(h.Id)))}r[`${i}.${a}`]=u.sort().slice(0,n)}return r}async measurePersonContacts(e){let t=e.dataset?.personContactSidecar??[];if(t.length===0||!e.mapping)return{checked:0,unrestored:[]};let r=t.filter(a=>e.mapping?.has(a.accountReferenceId));if(r.length===0||!await this.describesPersonAccounts(e.orgId))return{checked:0,unrestored:[]};let n=r.map(a=>e.mapping?.get(a.accountReferenceId)),s=await kn(a=>this.deps.orgAccess.query(e.orgId,a),n),i=[],d=0;for(let a of r){let c=e.mapping.get(a.accountReferenceId),l=s.get(c);l!==void 0&&(d++,e.mapping.get(a.contactReferenceId)!==l&&i.push(a.accountReferenceId))}return{checked:d,unrestored:i.sort()}}describesPersonAccounts(e){let t=this.personAccounts.get(e);if(!t){let r=this.deps.orgAccess.describe;t=r?r.call(this.deps.orgAccess,e,"Account").then(n=>n.fields.some(s=>s.name==="PersonContactId")).catch(()=>!0):Promise.resolve(!0),this.personAccounts.set(e,t)}return t}async measurePresence(e,t){let r={};if(!e.dataset)return r;for(let[n,s]of Object.entries(e.presenceKeys??{})){let i=new Set(Gc(t,n,s)),d=(e.dataset.objects.find(l=>l.objectApiName===n)?.records??[]).filter(l=>!i.has(l.referenceId)),a=[...new Set(d.map(l=>l.fields[s]).filter(l=>typeof l=="string"&&l!==""))].sort();if(a.length===0){r[n]=[];continue}let c=new Set;for(let l=0;l<a.length;l+=io){let u=a.slice(l,l+io).map(p=>`'${Be(p)}'`).join(", "),f=await this.deps.orgAccess.query(e.orgId,`SELECT ${ye(s)} k FROM ${ye(n)} WHERE ${ye(s)} IN (${u})`);for(let p of f)c.add(String(p.k))}r[n]=a.filter(l=>!c.has(l))}return r}buildChecks(e,t,r,n){let s=[];if(s.push({name:"stability",passed:n,detail:n?"Two identical consecutive measurements \u2014 org reads are stable":"No two identical measurements within the attempt budget \u2014 org reads are transiently inconsistent"}),!r)return s;let i=Object.entries(t.objects).filter(([f,p])=>r.counts[f]!==p.expected).map(([f,p])=>`${f}: expected ${p.expected}, got ${r.counts[f]??0}`);s.push({name:"counts",passed:i.length===0,detail:i.length===0?"All object counts match the counting contract":`Count mismatches \u2014 ${i.join("; ")}`});let d=Vc(t),a=sf(t,r);s.push({name:"load",passed:d.records===0&&a.length===0,detail:df(d,a)});let c=Object.entries(r.orphans).filter(([,f])=>f.length>0),l=lf(t),u=[...c.length>0?[`Orphans \u2014 ${c.map(([f,p])=>`${f} (${p.length}: ${p.join(", ")})`).join("; ")}`]:[],...l.length>0?["Lookups the load left empty because the record they name was not loaded \u2014 "+l.map(({link:f,count:p})=>`${f} (${p})`).join("; ")]:[]];if(s.push({name:"orphans",passed:u.length===0,detail:u.length===0?"No orphans on the mandatory lookups of the graph":u.join("; ")}),(e.dataset?.personContactSidecar?.length??0)>0&&e.mapping&&s.push({name:"personcontact",passed:r.personContact.unrestored.length===0,detail:r.personContact.unrestored.length===0?`All ${r.personContact.checked} person account(s) hold the contact the load linked`:`Person accounts without the contact the load linked \u2014 accounts: ${r.personContact.unrestored.join(", ")}`}),e.dataset&&Object.keys(e.presenceKeys??{}).length>0){let f=Object.entries(r.presence).filter(([,p])=>p.length>0);s.push({name:"presence",passed:f.length===0,detail:f.length===0?"All referential keys present in the org":`Missing keys \u2014 ${f.map(([p,g])=>`${p}: ${g.join(", ")}`).join("; ")}`})}return s}consignVerdict(e,t,r){let n=this.sasGuard.assertOutsideRepo(e),s=zr(JSON.parse(ao.readFileSync(n,"utf8")));s.controls.dryRunLoad={status:t.status==="passed"?"passed":"failed",at:t.measuredAt,detail:`post-load check by ${r??"unknown"}: verdict=${t.status}; `+t.checks.map(i=>`${i.name}=${i.passed?"OK":"KO"}`).join(", ")},ao.writeFileSync(n,Wn(s),"utf8")}};function bs(o){return Array.isArray(o)?`[${o.map(bs).join(",")}]`:typeof o=="object"&&o!==null?`{${Object.entries(o).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${bs(r)}`).join(",")}}`:JSON.stringify(o)}function Gc(o,e,t){return Rs(o.objects[e]?.writtenWithout,t)}function Rs(o,e){let t=o?.[e];return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}var Zr={refused:["dml-failed","person-contact-not-sent"],heldBack:["parent-refused"],notLoadable:["object-not-loaded"]};function Vc(o){let e={whole:[],part:[],refused:0,heldBack:0,notLoadable:[],records:0};for(let[t,r]of Object.entries(o.objects).sort(([n],[s])=>n.localeCompare(s))){let n=c=>c.reduce((l,u)=>l+(r.exclusionReasons[u]??0),0),s=n(Zr.notLoadable);s>0&&e.notLoadable.push({objectApiName:t,records:s});let i=n(Zr.refused),d=n(Zr.heldBack),a=i+d;a!==0&&(e.refused+=i,e.heldBack+=d,e.records+=a,r.expected===0?e.whole.push({objectApiName:t,notLoaded:a}):e.part.push({objectApiName:t,notLoaded:a,of:a+r.expected}))}return e}function sf(o,e){return Object.entries(o.objects).sort(([t],[r])=>t.localeCompare(r)).flatMap(([t,r])=>{let n=e.counts[t]??0;return n<r.expected?[{objectApiName:t,gone:r.expected-n,of:r.expected}]:[]})}function af(o){return o.length===0?"":`${o.reduce((t,r)=>t+r.gone,0)} record(s) it wrote or linked are no longer in the target \u2014 `+o.map(t=>`${t.objectApiName} (${t.gone} of ${t.of})`).join(", ")}function df(o,e=[]){let t=cf(o),r=af(e);if(o.records===0)return r===""?`Every record the load had to write went in${t}`:`The load wrote every record it had to, and ${r}${t}`;let n=[...o.whole.length>0?["Objects the load wrote none of \u2014 "+o.whole.map(i=>`${i.objectApiName} (${i.notLoaded} not loaded)`).join(", ")]:[],...o.part.length>0?["Objects it wrote part of \u2014 "+o.part.map(i=>`${i.objectApiName} (${i.notLoaded} of ${i.of} not loaded)`).join(", ")]:[]],s=[...o.refused>0?[`${o.refused} refused by the target org`]:[],...o.heldBack>0?[`${o.heldBack} held back for a parent the target org refused`]:[]];return`${o.records} record(s) not loaded: ${s.join(", ")}. ${n.join("; ")}${r===""?"":`; ${r}`}${t}`}function cf(o){return o.notLoadable.length===0?"":`; ${o.notLoadable.reduce((t,r)=>t+r.records,0)} record(s) not loadable, as the simulation said \u2014 `+o.notLoadable.map(t=>`${t.objectApiName} (${t.records})`).join(", ")}function lf(o){let e=[];for(let[t,r]of Object.entries(o.objects).sort(([n],[s])=>n.localeCompare(s)))for(let n of Object.keys(r.parentNotLoaded??{}).sort()){let s=Rs(r.parentNotLoaded,n).length;s>0&&e.push({link:`${t}.${n}`,count:s})}return e}function uf(o,e,t){if(t===null)return"unstable";let r=o.filter(i=>!i.passed);if(r.length===0)return"passed";let n=Object.values(t.orphans).some(i=>i.length>0);return r.every(i=>i.name==="load"||i.name==="orphans")&&!n&&Vc(e).whole.length===0?"partial":"failed"}function ff(o,e){let t=r=>r.slice(0,r.indexOf("."));return Object.entries(o.objects).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>{let s=[...Zr.refused,...Zr.heldBack].reduce((u,f)=>u+(n.exclusionReasons[f]??0),0),i=e?.counts[r]??0,d=Object.entries(e?.orphans??{}).filter(([u])=>t(u)===r).reduce((u,[,f])=>u+f.length,0),a=e?.presence[r]?.length??0,c=r==="Account"?e?.personContact.unrestored.length??0:0,l=e!==null&&i===n.expected&&s===0&&d===0&&a===0&&c===0;return{objectApiName:r,status:l?"passed":"failed",expected:n.expected,found:i,notLoaded:s,orphans:d,missingKeys:a,...c>0?{personContactsUnlinked:c}:{}}})}var io=200;function Uc(o){let e=new Map;for(let[t,r]of o){let n=t.startsWith("placeholder:")?t.split(":")[1]:t.slice(0,t.lastIndexOf("-"));if(!n)continue;let s=e.get(n)??[];s.push(r),e.set(n,s)}return e}function Kc(o){let e=[];for(let t=0;t<o.length;t+=io){let r=o.slice(t,t+io).map(n=>`'${Be(n)}'`);e.push(`Id IN (${r.join(", ")})`)}return e}var Is=200;function vs(o,e=Is){return{insert:(t,r,n,s)=>ks(o.insert(r,n,e,s?pf(s):void 0)),update:(t,r,n)=>ks(o.update(r,n,e)),delete:(t,r,n)=>ks(o.delete(r,n,e))}}function pf(o){let e=0,t=0;return{sending:(r,n,s)=>{t=s},answered:(r,n,s,i)=>{i?s.forEach((d,a)=>{let c=i[a];c!==void 0&&o(c,[d])}):(o(e,s),e+=t),t=0}}}async function ks(o){try{return await o}catch(e){if(e instanceof bd)return e.written;throw e}}var gf=200;function Hc(o){let e={threshold:o.threshold,perCall:Is,...o.duplicateRules?{duplicateRules:o.duplicateRules}:{}},t=o.inserts.filter(({rows:n})=>n>0),r=t.reduce((n,{rows:s})=>n+Math.ceil(s/gf),0);return Go(t,e)+Go((o.purged??[]).filter(({rows:n})=>n>0),e)+kd(t.length,o.automationRead??0)+r}function le(o){return o.slice(0,15)}var Xc=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function ke(o){return Vi(o)??o}function Yc(o,e){return`${o}-${ke(e)}`}var Os="005",Ss="00G",Zc="00D",As="00e",Qc="OwnerId",Fs="RecordTypeId",Ps="SetupOwnerId",en="CurrencyIsoCode",lo="Pricebook2",Kt=200,Ts=new Set([...Ea,zo]),hf=["Title","Name"];async function*js(o,e){let t=await No.read(o.folder,o.checkpoint.snapshotId,e);for await(let r of t.records())typeof r.Id=="string"&&(yield r)}async function mf(o,e){let t=await No.read(o.folder,o.checkpoint.snapshotId,e),r=[];for(let n=0;n<t.size;n++)r.push(t.idAt(n));return r}function uo(o,e){return o!==void 0&&!o.unread.some(t=>t.part===e)}async function yf(o){let e=Ld(o.checkpoint,o.choices),t=new Map;for(let p of o.checkpoint.objects)for(let g of await mf(o,p.objectApiName))t.set(le(g),p.objectApiName);let r=new Set,n=new Set,s=new Set,i=new Set,d=new Map,a=new Set,c=[],l=new Set;for(let p of e.replayed)for await(let g of js(o,p.objectApiName)){l.add(le(g.Id));for(let[h,m]of Object.entries(g)){if(Ts.has(h)||typeof m!="string"||(h===en&&m!==""&&a.add(m),!Xc.test(m)))continue;let y=le(m);if(h===Fs)s.add(y);else if(y.startsWith(Os))r.add(y);else if(y.startsWith(Ss)&&h===Qc)n.add(y);else if(y.startsWith(As)&&h===Ps)i.add(y);else if(!t.has(y)&&!y.startsWith(Zc)){let R=`${p.objectApiName}.${h}`,j=d.get(R)??new Set;j.add(y),d.set(R,j)}}if(p.objectApiName===qe){let h=g[yt],m=g[Ge];if(typeof h=="string"&&typeof m=="string"){let y=g[tr];c.push({book:le(h),product:le(m),currency:typeof y=="string"?y:""})}}}let u=[];if((o.checkpoint.files?.links??0)>0)for await(let p of La(o.folder))l.has(le(p.LinkedEntityId))&&u.push({ContentDocumentId:p.ContentDocumentId,LinkedEntityId:p.LinkedEntityId,ShareType:p.ShareType,Visibility:p.Visibility});let f=[];for(let p of e.leftOut)if(p.reason==="fileContentNotKept")for await(let g of js(o,p.objectApiName)){let h=hf.map(m=>g[m]).find(m=>typeof m=="string"&&m!=="");f.push({objectApiName:p.objectApiName,id:ke(g.Id),...h!==void 0?{name:h}:{}})}return{objects:e,heldBy:t,users:r,queues:n,recordTypes:s,profiles:i,notHeld:d,currencies:a,standardPricebook:wf(o,c,t),fileLinks:u,filesLeft:f}}function wf(o,e,t){let r=o.checkpoint.objects.some(a=>a.objectApiName===lo||a.objectApiName===qe);if(uo(o.annex,"standardPricebook")&&o.annex.standardPricebookId)return{id:ke(o.annex.standardPricebookId),how:"annex"};let n=e.filter(a=>t.has(a.product));if(n.length===0||!r)return{how:"none"};let s=new Set(n.map(a=>`${a.product}|${a.currency}`)),i=new Map;for(let a of n){let c=i.get(a.book)??new Set;c.add(`${a.product}|${a.currency}`),i.set(a.book,c)}let d=[...i].filter(([,a])=>a.size===s.size).map(([a])=>a);return d.length===1?{id:ke(d[0]),how:"deduced"}:{how:"ambiguous"}}function Qr(o,e){let t=[];for(let r=0;r<o.length;r+=e)t.push(o.slice(r,r+e));return t}function co(o){return o.map(e=>`'${Be(e)}'`).join(", ")}function el(o){let e=o.lastIndexOf("@"),t=o.lastIndexOf("."),r=o.slice(e+1);return e>=0&&t>e&&r.split(".").length>2?o.slice(0,t):o}function bf(o){if(o===void 0)return;let e=el(o);return e===o?void 0:o.slice(e.length)}async function Rf(o){let{access:e,orgId:t,survey:r,source:n}=o,s=0,i=async v=>(s++,e.query(t,v)),d=new Map,a=new Map,c=async v=>{s++;try{d.set(v,await e.describe(t,v))}catch(A){a.set(v,ee(A))}};for(let v of r.objects.replayed)await c(v.objectApiName);r.fileLinks.length>0&&await c(ar);let l=new Map,u=v=>typeof v.Id=="string"&&typeof v.Username=="string"?{id:ke(v.Id),username:v.Username,isActive:v.IsActive===!0,userType:typeof v.UserType=="string"?v.UserType:""}:void 0,f=[...new Set([...r.users,...Object.values(n.choices.ownerMap??{}).map(le)])].sort();for(let v of Qr(f,Kt))for(let A of await i(`SELECT Id, Username, IsActive, UserType FROM User WHERE Id IN (${co(v)})`)){let L=u(A);L&&l.set(le(L.id),L)}let p=new Map;if(uo(n.annex,"users")){let v=o.tier==="sandbox"?bf(o.username):void 0,A=new Map;for(let B of n.annex.users){let D=le(B.id),G=l.get(D);if(G?.isActive===!0&&G.userType==="Standard")continue;let X=n.checkpoint.org.tier==="sandbox"?el(B.username):B.username,K=[B.username,X,...v!==void 0?[`${X}${v}`]:[]];A.set(D,[...new Set(K.map(H=>H.toLowerCase()))])}let L=[...new Set([...A.values()].flat())].sort(),x=new Map;for(let B of Qr(L,Kt)){let D=B.map(G=>`'${Be(G)}'`).join(", ");for(let G of await i(`SELECT Id, Username, IsActive, UserType FROM User WHERE Username IN (${D})`)){let X=u(G);X&&x.set(X.username.toLowerCase(),X)}}for(let[B,D]of A){let G=D.map(X=>x.get(X)).find(X=>X!==void 0);G&&p.set(B,G)}}let g=[],h=[...d.keys()].filter(v=>d.get(v)?.fields.some(A=>A.name===Fs));if(h.length>0){let v=tl(d),A=await i(`SELECT Id, SobjectType, DeveloperName, NamespacePrefix, Name, IsActive${v?", IsPersonType":""} FROM RecordType WHERE SobjectType IN (${h.map(L=>`'${ye(L)}'`).join(", ")})`);for(let L of A)typeof L.Id!="string"||typeof L.SobjectType!="string"||typeof L.DeveloperName!="string"||g.push({id:ke(L.Id),sobjectType:L.SobjectType,developerName:L.DeveloperName,...typeof L.NamespacePrefix=="string"&&L.NamespacePrefix!==""?{namespacePrefix:L.NamespacePrefix}:{},name:typeof L.Name=="string"?L.Name:L.DeveloperName,isActive:L.IsActive!==!1,...typeof L.IsPersonType=="boolean"?{isPersonType:L.IsPersonType}:{}})}let m=[];if(r.queues.size>0){let v=new Map;for(let A of await i("SELECT QueueId, SobjectType FROM QueueSobject"))typeof A.QueueId!="string"||typeof A.SobjectType!="string"||v.set(le(A.QueueId),[...v.get(le(A.QueueId))??[],A.SobjectType]);for(let A of await i("SELECT Id, DeveloperName FROM Group WHERE Type = 'Queue'"))typeof A.Id!="string"||typeof A.DeveloperName!="string"||m.push({id:ke(A.Id),developerName:A.DeveloperName,sobjectTypes:v.get(le(A.Id))??[]})}let y;if([...d.values()].some(v=>v.fields.some(A=>A.name===en))&&r.currencies.size>0){y=new Set;for(let v of await i("SELECT IsoCode, IsActive FROM CurrencyType"))typeof v.IsoCode=="string"&&v.IsActive===!0&&y.add(v.IsoCode)}let j;if(r.standardPricebook.id!==void 0){let[v]=await i(Mt);typeof v?.Id=="string"&&(j=ke(v.Id))}let T=new Set,P=new Map;for(let[v,A]of r.heldBy){let L=P.get(A);L?L.push(v):P.set(A,[v])}let _=async(v,A)=>{let L=0;for(let x of Qr(A,Kt))for(let B of await i(`SELECT Id FROM ${ye(v)} WHERE Id IN (${co(x)})`))typeof B.Id=="string"&&(T.add(le(B.Id)),L++);return L},q=new Set(r.objects.replayed.map(v=>v.objectApiName));for(let[v,A]of P){if(a.has(v)||Ed(v))continue;let L=[...A].sort(),x=L.slice(0,Kt);try{await _(v,x)>0&&await _(v,L.slice(Kt))}catch(B){if(q.has(v))throw B}}let C=new Map;for(let[v,A]of r.notHeld){let[L,x]=v.split("."),B=d.get(L)?.fields.find(X=>X.name===x),D=B?.type==="reference"?B.referenceTo??[]:[];if(D.length!==1)continue;let G=C.get(D[0])??new Set;for(let X of A)G.add(X);C.set(D[0],G)}for(let[v,A]of C)try{await _(v,[...A].sort())}catch{}let I=new Map;for(let v of r.objects.replayed){if(v.customSetting===void 0||a.has(v.objectApiName))continue;let A={names:new Set,owners:new Set};for(let L of await i(`SELECT Id, Name, SetupOwnerId FROM ${ye(v.objectApiName)}`))typeof L.Name=="string"&&A.names.add(L.Name),typeof L.SetupOwnerId=="string"&&A.owners.add(le(L.SetupOwnerId));I.set(v.objectApiName,A)}let w=new Set;for(let v of Qr([...r.profiles].sort(),Kt))for(let A of await i(`SELECT Id FROM Profile WHERE Id IN (${co(v)})`))typeof A.Id=="string"&&w.add(le(A.Id));let O=new Set,F=[...new Set(r.fileLinks.map(v=>le(v.ContentDocumentId)))];if(!a.has(ar))for(let v of Qr(F.sort(),Kt))for(let A of await i(`SELECT Id FROM ContentDocument WHERE Id IN (${co(v)})`))typeof A.Id=="string"&&O.add(le(A.Id));return{organizationId:ke(o.organizationId),runningUserId:ke(o.runningUserId),describes:d,missing:a,usersById:l,usersByUsername:p,recordTypes:g,queues:m,...y!==void 0?{currencies:y}:{},...j!==void 0?{standardPricebookId:j}:{},sameIds:T,customSettings:I,profiles:w,files:O,requests:s}}function tl(o){return o.get("Account")?.fields.some(e=>e.name===zo)===!0}function kf(o,e,t){let r=[...new Set(Object.values(o.ownerMap??{}).map(le))].sort(),n=r.filter(i=>{let d=e.usersById.get(i);return d===void 0||d.userType!=="Standard"});if(n.length>0)return{code:"OWNER_MAP_UNKNOWN",users:n.map(ke),message:`The owners chosen give records to users ${t} does not hold as standard users: ${n.map(ke).join(", ")}. Choose users of ${t}. Nothing was written.`};let s=r.filter(i=>e.usersById.get(i)?.isActive!==!0);if(s.length>0)return{code:"OWNER_MAP_INACTIVE",users:s.map(ke),message:`The owners chosen give records to users ${t} holds inactive: ${s.map(ke).join(", ")}. It refuses a record owned by an inactive user: choose an active user, or reactivate them there. Nothing was written.`}}var Vt=class{constructor(e){this.id=e}id;counts=new Map;add(e,t=1){let r=this.id(e),n=this.counts.get(r);n?n.n+=t:this.counts.set(r,{key:e,n:t})}entries(){return[...this.counts.values()]}};function If(o,e){return e.createable&&e.nillable===!1&&e.defaultedOnCreate!==!0||Xs(o,e.name)}function vf(o){let e=o.length;return typeof e=="number"&&e>0?e:void 0}var Of=new Set(["id","reference","boolean","double","int","long","percent","currency","date","datetime","time","picklist","multipicklist"]);async function Sf(o){let{survey:e,target:t,choices:r,annex:n}=o,s=kf(r,t,o.targetName);if(s)return{refusal:s};let i=new Vt(k=>`${k.object}|${k.reason}`);for(let k of e.objects.leftOut)i.add({object:k.objectApiName,reason:k.reason},k.records);let d=e.objects.replayed.filter(k=>t.missing.has(k.objectApiName)?(i.add({object:k.objectApiName,reason:"notInTarget"},k.records),!1):t.describes.get(k.objectApiName)?.createable===!1?(i.add({object:k.objectApiName,reason:"notCreateable"},k.records),!1):!0),a=new Set(d.map(k=>k.objectApiName)),c=new Vt(k=>`${k.field}|${k.reason}`),l={kept:0,toRunningUser:0,reasons:{notInTarget:0,inactive:0,queueMissing:0}},u=new Vt(k=>`${k.object}|${k.recordType}|${k.outcome}`),f=new Vt(k=>k),p=new Map,g=!1,h={inserted:0,alreadyThere:0},m=new Map,y=new Map,R=tl(t.describes),j=new Set,T=e.standardPricebook,P=T.id!==void 0?le(T.id):void 0,_=new Map(Object.entries(r.ownerMap??{}).map(([k,E])=>[le(k),ke(E)])),q=k=>{let E=t.usersById.get(k);if(E?.userType==="Standard"&&E.isActive)return{id:E.id};let S=t.usersByUsername.get(k);return S?.userType==="Standard"&&S.isActive?{id:S.id}:{why:E!==void 0||S!==void 0?"inactive":"notInTarget"}},C=(k,E)=>{let S=re=>re.sobjectTypes.includes(k),Y=t.queues.find(re=>le(re.id)===E&&S(re));if(Y)return Y.id;let J=uo(n,"queues")?n.queues.find(re=>le(re.id)===E):void 0;if(J!==void 0)return t.queues.find(re=>re.developerName===J.developerName&&S(re))?.id},I=(k,E,S)=>{let Y=le(E),J=uo(n,"recordTypes")?n.recordTypes.find(V=>le(V.id)===Y):void 0,re=t.recordTypes.filter(V=>V.sobjectType===k&&V.isActive),Ie,Q="default";if(J!==void 0&&(Ie=re.find(V=>V.developerName===J.developerName&&(V.namespacePrefix??null)===(J.namespacePrefix??null)),Ie&&(Q="byName")),Ie===void 0&&(Ie=re.find(V=>le(V.id)===Y),Ie&&(Q="byId")),Ie===void 0&&S){let V=re.filter(ie=>ie.isPersonType===!0);if(V.length!==1)return{refused:`the checkpoint does not say which of the person account record types of ${o.targetName} its person accounts had: take it again with SandForge 1.81 or later, or leave Account out`};Ie=V[0]}let Ee={recordType:J!==void 0?lt(J.namespacePrefix,J.developerName):ke(E),outcome:Q};if(Ie===void 0)return{given:Ee};let M=Ie,we=t.describes.get(k)?.recordTypeInfos?.find(V=>le(V.recordTypeId)===le(M.id));if(we!==void 0&&!we.available)return{refused:`${lt(M.namespacePrefix,M.developerName)} is not assigned to the user who replays in ${o.targetName}: assign it to them, or leave ${k} out`};let We={name:M.name,developerName:M.developerName,namespacePrefix:M.namespacePrefix??null},He=y.get(k)??new Map;return He.set(M.id,We),y.set(k,He),{ref:We,given:Ee}},w=[];for(let k of d){let E=k.objectApiName,S=t.describes.get(E);if(S===void 0)continue;let Y=new Map(S.fields.map(Q=>[Q.name,Q])),J=k.fields.filter(Q=>!Ts.has(Q)&&!Y.has(Q)&&!(Q===en&&t.currencies===void 0));J.length>0&&p.set(E,new Set(J));let re=k.customSetting,Ie=t.customSettings.get(E);for await(let Q of js(o,E)){let Ee=le(Q.Id);if(t.sameIds.has(Ee)){m.set(Yc(E,Q.Id),ke(Q.Id));continue}let M={objectApiName:E,key:Ee,referenceId:Yc(E,Q.Id),fields:{},pointsAt:new Map,sourceId:ke(Q.Id),emptied:[]},we=(V,ie)=>{M.refused??={reason:V,...ie!==void 0?{path:ie}:{}}},We=(E==="Account"||E==="Contact")&&Ar(Q);We&&!R&&we("personAccountsUnsupported",`turn person accounts on in ${o.targetName}, or leave ${E} out`),We&&E==="Contact"&&j.add(Ee);let He=E==="Account"?Rn(Q,!1):void 0;for(let[V,ie]of Object.entries(Q)){if(Ts.has(V)||He!==void 0&&hn(E,V,He))continue;let Le=Y.get(V);if(Le===void 0){V===en&&typeof ie=="string"&&ie!==""&&(g||=t.currencies===void 0);continue}if(ie==null||ie==="")continue;if(V===en&&typeof ie=="string"){t.currencies!==void 0&&!t.currencies.has(ie)&&(we("inactiveCurrency",`activate ${ie} in ${o.targetName}, or leave ${E} out`),f.add(ie)),M.fields[V]=ie;continue}if(V===Fs&&typeof ie=="string"){let ge=I(E,ie,We);ge.given!==void 0&&(M.recordType=ge.given),ge.refused!==void 0?we("recordTypeUnavailable",ge.refused):ge.ref!==void 0&&(M.fields[V]=ge.ref.name,M.recordTypeDeveloperName=lt(ge.ref.namespacePrefix,ge.ref.developerName));continue}if(Le.type!=="reference"||typeof ie!="string"||!Xc.test(ie)){M.fields[V]=ie;continue}let he=le(ie),jt=If(E,Le),rt=(ge,ve)=>{jt?we("requiredLookupMissing",ve):M.emptied.push({field:`${E}.${V}`,reason:ge})};if(he.startsWith(Zc)){M.fields[V]=t.organizationId;continue}if(V===Ps){(he.startsWith(As)?t.profiles.has(he):t.usersById.has(he))?M.fields[V]=ke(ie):we("requiredLookupMissing",`the ${he.startsWith(As)?"profile":"user"} its row is of is not in ${o.targetName}`);continue}if(V===Qc&&(he.startsWith(Os)||he.startsWith(Ss))){let ge=_.get(he);if(ge!==void 0)M.owner="kept",M.fields[V]=ge;else if(r.owners==="me")M.owner="toRunningUser";else if(he.startsWith(Ss)){let ve=C(E,he);M.owner=ve!==void 0?"kept":"queueMissing",ve!==void 0&&(M.fields[V]=ve)}else{let ve=q(he);M.owner=ve.id!==void 0?"kept":ve.why??"notInTarget",ve.id!==void 0&&(M.fields[V]=ve.id)}continue}if(he.startsWith(Os)){let ge=q(he);ge.id!==void 0?M.fields[V]=ge.id:jt?M.fields[V]=t.runningUserId:M.emptied.push({field:`${E}.${V}`,reason:"userNotInTarget"});continue}if(P!==void 0&&he===P){t.sameIds.has(he)?M.fields[V]=ke(ie):a.has(lo)&&e.heldBy.has(he)?M.pointsAt.set(V,he):t.standardPricebookId!==void 0?M.fields[V]=t.standardPricebookId:rt("objectNotHeld",`${o.targetName} has no standard price book`);continue}let Ye=e.heldBy.get(he);Ye!==void 0&&t.sameIds.has(he)?M.fields[V]=ke(ie):Ye!==void 0&&a.has(Ye)?M.pointsAt.set(V,he):Ye!==void 0?rt("objectNotReplayed",`replay ${Ye} too`):t.sameIds.has(he)?M.fields[V]=ke(ie):rt("objectNotHeld",`the checkpoint holds no record it points at, and ${o.targetName} holds none under its Id`)}if(E===qe&&T.how==="ambiguous"&&we("requiredLookupMissing",`the checkpoint does not say which of its price books is the standard one, which every other price needs first: take it again with SandForge 1.81 or later, or leave ${qe} out`),re!==void 0&&Ie!==void 0){let V=M.fields[Ps];if(re==="list"?typeof Q.Name=="string"&&Ie.names.has(Q.Name):typeof V=="string"&&Ie.owners.has(le(V))){h.alreadyThere++;continue}}w.push(M)}}let O=new Map(w.map(k=>[k.key,k])),F=new Map;for(let k of w)for(let E of k.pointsAt.values()){let S=F.get(E);S?S.push(k):F.set(E,[k])}let v=w.filter(k=>k.refused!==void 0);for(let k=0;k<v.length;k++){let E=v[k];for(let S of F.get(E.key)??[])S.refused===void 0&&(S.refused={reason:"parentRefused",path:`its ${E.objectApiName} is refused: lift that first`},v.push(S))}let A=new Vt(k=>`${k.object}|${k.reason}`),L=new Map,x=[];for(let k of w){if(k.refused!==void 0){A.add({object:k.objectApiName,...k.refused});continue}for(let S of k.emptied)c.add(S);k.recordType!==void 0&&u.add({object:k.objectApiName,...k.recordType}),k.owner==="kept"?l.kept++:k.owner!==void 0&&(l.toRunningUser++,k.owner!=="toRunningUser"&&l.reasons[k.owner]++);for(let[S,Y]of k.pointsAt){let J=O.get(Y);J!==void 0&&J.refused===void 0?k.fields[S]=J.referenceId:c.add({field:`${k.objectApiName}.${S}`,reason:"objectNotReplayed"})}j.has(k.key)&&typeof k.fields.AccountId=="string"&&x.push({accountReferenceId:k.fields.AccountId,contactReferenceId:k.referenceId});let E=L.get(k.objectApiName)??[];E.push({referenceId:k.referenceId,fields:k.fields,...k.recordTypeDeveloperName!==void 0?{recordTypeDeveloperName:k.recordTypeDeveloperName}:{}}),L.set(k.objectApiName,E)}for(let k of d)k.customSetting!==void 0&&(h.inserted+=L.get(k.objectApiName)?.length??0);let B=t.describes.get(ar);if(B!==void 0&&B.createable!==!1){let k=[];for(let E of e.fileLinks){let S=O.get(le(E.LinkedEntityId));S===void 0||S.refused!==void 0||t.files.has(le(E.ContentDocumentId))&&k.push({referenceId:`${ar}-${ke(E.ContentDocumentId)}_${S.sourceId}`,fields:{ContentDocumentId:ke(E.ContentDocumentId),LinkedEntityId:S.referenceId,ShareType:E.ShareType,Visibility:E.Visibility}})}k.length>0&&L.set(ar,k)}let D=new nd(o.salt),G=r.mask?new ad(void 0,o.salt):void 0,X=r.mask?new vn:void 0,K=[],H=[];for(let[k,E]of L){let S=t.describes.get(k);if(S===void 0)continue;let Y=new Set(E.flatMap(M=>Object.keys(M.fields))),J=S.fields.filter(M=>Y.has(M.name)).map(M=>{let we=vf(M);return{name:M.name,queryable:!0,createable:M.createable,isReference:M.type==="reference",type:M.type,...we!==void 0?{length:we}:{}}});if(r.contactPoints==="neutralized"){let M=D.forObject(k,J);if(M)for(let we of E)M(we.fields)}if(G===void 0||X===void 0)continue;let re=J.filter(M=>!Of.has((M.type??"").toLowerCase())),Ie=new Set(In(X,re.map(M=>({name:M.name,type:M.type??"string"})))),Q=re.filter(M=>Ie.has(M.name)).map(M=>({name:M.name,type:M.type??"string",...M.length!==void 0?{length:M.length}:{}}));for(let M of Q)K.push(`${k}.${M.name}`);for(let M of re)!Ie.has(M.name)&&(M.type??"").toLowerCase()==="textarea"&&H.push(`${k}.${M.name}`);if(Q.length===0)continue;let Ee=G.anonymize({objectApiName:k,records:E.map(M=>M.fields),sourceIds:E.map(M=>M.referenceId),fields:Q,methods:{}});E.forEach((M,we)=>{M.fields=Ee[we]??M.fields})}let N={};for(let[k,E]of y)N[k]=[...E.values()];let Z=[...L].map(([k,E])=>({objectApiName:k,records:E})),$=P!==void 0?O.get(P):void 0,U=$!==void 0&&$.refused===void 0&&$.objectApiName===lo?$.referenceId:void 0,oe={datasetVersion:"1.0.0",objects:Z,recordTypes:N,personContactSidecar:x,...U!==void 0?{standardPricebook:U}:{}},se=Z.reduce((k,E)=>k+E.records.length,0),me=e.objects.replayed.some(k=>k.objectApiName===lo||k.objectApiName===qe),de=A.entries(),Fe={records:{toCreate:se-(U!==void 0?1:0),linkedById:m.size,linkedByKey:0,refusedBeforeWrite:de.reduce((k,E)=>k+E.n,0)},owners:l,recordTypes:u.entries().map(({key:k,n:E})=>({...k,records:E})).sort((k,E)=>Jc(`${k.object}.${k.recordType}`,`${E.object}.${E.recordType}`)),notReplayed:i.entries().map(({key:k,n:E})=>({...k,records:E})),lookupsEmptied:c.entries().map(({key:k,n:E})=>({...k,records:E})).sort((k,E)=>Jc(k.field,E.field)),refused:de.map(({key:k,n:E})=>({object:k.object,records:E,reason:k.reason,...k.path!==void 0?{path:k.path}:{}})),fieldsNotInTarget:[...p].map(([k,E])=>({object:k,fields:[...E].sort()})),...e.objects.replayed.some(k=>k.customSetting!==void 0)?{customSettings:h}:{},currencies:{refused:f.entries().map(({key:k,n:E})=>({code:k,records:E})),...g?{singleCurrencyTarget:!0}:{}},...me?{standardPricebook:T.how}:{},masked:{fields:K.sort(),...r.mask?{unmaskedFreeText:H.sort()}:{}},contactPoints:r.contactPoints,degraded:Af(n),auditDates:"new"};return{conversion:{dataset:oe,summary:Fe,identityKeys:Object.fromEntries(r.link.map(k=>[k.objectApiName,[...k.fields]])),linkedById:m,filesLeft:e.filesLeft}}}function Af(o){return o===void 0?["recordTypes","users","queues","standardPricebook"]:[...new Set(o.unread.map(e=>e.part))]}function Jc(o,e){return o<e?-1:o>e?1:0}async function rl(o){let e={folder:o.folder,checkpoint:o.checkpoint,annex:o.annex,choices:o.choices},t=await yf(e),r=await Rf({...o,source:e,survey:t});return{...await Sf({...e,survey:t,target:r,targetName:o.targetName,...o.salt!==void 0?{salt:o.salt}:{}}),target:r,survey:t}}var Tf={insert:async()=>{throw new Error("A preview writes nothing.")},update:async()=>{throw new Error("A preview writes nothing.")},delete:async()=>{throw new Error("A preview writes nothing.")}},jf=new Set(["frozen:config:get","frozen:config:save","frozen:select","frozen:extract","frozen:load","frozen:load:preview","frozen:verify","frozen:remove","frozen:remove:sweep","frozen:remove:automation","frozen:remove:preview","frozen:status","frozen:rules:clear","frozen:rules:create"]),fo="REPLACE_LEAVES_RECORDS",hr=class extends Error{constructor(t){super(t.message);this.stop=t;this.name="RemovalStopped"}stop;get code(){return this.stop.code}},mr=class extends Error{constructor(t,r,n,s){super(r);this.code=t;this.emails=n;this.orgId=s;this.name="LoadEmailsStop"}code;emails;orgId},on=class extends Error{constructor(t,r,n,s){super(r);this.code=t;this.automation=n;this.orgId=s;this.name="LoadAutomationStop"}code;automation;orgId},sn=class extends Error{constructor(t,r,n){super(t);this.apiRequests=r;this.orgId=n;this.name="LoadBudgetStop"}apiRequests;orgId;code=$o},Il="FROZEN_STORAGE_EXCEEDED",an=class extends Error{constructor(t,r,n){super(t);this.storage=r;this.orgId=n;this.name="LoadStorageStop"}storage;orgId;code=Il};function tn(o){let e=o<10?100:10;return String(o<=0?0:Math.ceil(o*e-1e-9)/e)}function nl(o){let e;return{request:t=>(e===void 0&&(e=Promise.resolve().then(()=>o.request(t)),e.catch(()=>{})),e)}}function ol(o){if("unread"in o.storage)return;let e=Math.max(0,o.automationBytes??0),t=Bs(o.dataset,o.sent)+e,r=(o.purged??[]).filter(p=>p.deletes).reduce((p,g)=>p+Mo(g.objectApiName,{rows:g.rows}),0),n=1024*1024,{remainingMB:s,maxMB:i,uncountedWrites:d}=o.storage,a=Math.max(0,s-(d?.mb??0));if(t<=a*n+r)return;let c={estimateMB:t/n,...e>0?{automationMB:e/n}:{},remainingMB:s,maxMB:i,...r>0?{freedMB:r/n}:{},...d?{uncountedWrites:d}:{},...o.pilot===!0?{pilot:!0}:{}},l=_a(d?{uncountedWrites:d}:{},o.target),u=c.freedMB!==void 0?`, and the reload's purge frees about ${tn(c.freedMB)} MB first`:"",f=c.automationMB!==void 0?`, about ${tn(c.automationMB)} MB of it for what the target's automation creates under them`:"";return o.replay===!0?{storage:c,message:`The replay was refused before it wrote anything: the checkpoint's records take about ${tn(c.estimateMB)} MB of data storage${f}, and ${o.target} has ${s} MB left of ${i} MB${l}${u}. To replay part of it, ${Nd.fewerObjects}; or free data storage in ${o.target}. Nothing was written.`}:o.pilot===!0?{storage:c,message:`The pilot was refused before it wrote anything: the records of its root folder take about ${tn(c.estimateMB)} MB of data storage${f}, and ${o.target} has ${s} MB left of ${i} MB${l}. Extract a smaller dataset, with a lower budget in the configuration, a new selection and a new extraction; or free data storage in ${o.target}. Nothing was written.`}:{storage:c,message:`The load was refused before it wrote anything: the dataset's records take about ${tn(c.estimateMB)} MB of data storage${f}, and ${o.target} has ${s} MB left of ${i} MB${l}${u}. Load a pilot first, one root folder of it; or extract a smaller dataset, with a lower budget in the configuration, a new selection and a new extraction; or free data storage in ${o.target}. Nothing was written.`}}var Ff=ot({sobjects:mt(ot({name:$e().min(1),createable:cn().optional()}).loose())}).loose();function Bs(o,e){return o.objects.reduce((t,r)=>{if(e!==void 0&&!e.takes(r.objectApiName))return t;let n=e===void 0?r.records.length:r.records.filter(s=>!e.byThePlatform.has(s.referenceId)).length;return t+Mo(r.objectApiName,{rows:n})},0)}function sl(o,e,t,r){if(!("objects"in o))return 0;let n=ed(Dt(o,e,r),r),s=new Map(t.objects.map(i=>[i.objectApiName,i.records.length]));return td(n,i=>s.get(i)??0)}function Ef(o){return{estimateMB:o.estimateMB,...o.automationMB!==void 0?{automationMB:o.automationMB}:{},remainingMB:o.remainingMB,maxMB:o.maxMB,...o.freedMB!==void 0?{freedMB:o.freedMB}:{},...o.uncountedWrites?{uncountedWrites:o.uncountedWrites}:{},...o.pilot===!0?{pilot:!0}:{}}}function Es(o,e,t){if(t!==!0)return o;try{return ds(o,e.rootObject)}catch{return o}}function il(o){return o?{replay:o}:{}}function Lf(o,e){let t=0;for(let r of o.perObject){let n=r.reused-(r.writtenByThePlatform??0),s=e.standardPricebook!==void 0&&r.objectApiName==="Pricebook2"&&n>0?1:0;t+=n-s}return t}function Nf(o,e){let t=Ma(o,e,Yi);return{verdict:o.verdict,estimate:o.estimate,...o.verdict==="unread"?{unread:o.unread}:{remaining:o.remaining,max:o.max},...o.parts?{parts:{...o.parts}}:{},...t!==void 0?{refused:{code:$o,message:t}}:{}}}function rn(o,e,t){let r=[...new Set(o.map(s=>s.objectApiName))],n=!!t?.runUserId;return ni({setToDraft:Xi(r),delete:ea(r,[],{userKept:n})},e)}function Ls(o){return o.status==="success"&&(o.left??[]).length===0}function al(o){return o.verdict!=="nothingSends"||o.counted.length>0||o.uncounted!==void 0}function Cf(o,e){if(e.includeChanged||o.refusal!==void 0||o.status!=="partial"&&o.status!=="failure")return o;let t=o.objects.every(s=>s.refused===0&&s.deleted+s.alreadyGone+s.keptChanged===s.found),r=(o.left??[]).some(s=>s.class==="late"&&e.sweepLate||s.class==="untied"&&e.sweepUntied),n=o.objects.some(s=>s.keptChanged>0);return t&&!r&&n?{...o,status:"success"}:o}var nn="frozen",dl="frozen:config",gr="frozen:lastRun",cl="frozen:lastRuns",Ns="frozen:lastVerify",Cs="frozen:lastVerifies",ll="tokens.json",zf="rules.json",yr=class extends Error{constructor(t,r){super(r);this.rulesPath=t;this.name="RulesFileMissingError"}rulesPath},Mf=async o=>{let e=await import("vscode");await e.window.showTextDocument(e.Uri.file(o),{preview:!1})},Df="0.1.0",xf=10*6e4,zs=15*6e4,$f="EXTRACT_TIMEOUT",ul=30*6e4,Ms=6e4,fl=12e4,_f=50;function Bf(o,e){let t=0,r=null,n=null,s=d=>{o(...d),t=Date.now(),r=null},i=((...d)=>{r=d;let a=e-(Date.now()-t);a<=0?(n&&(clearTimeout(n),n=null),s(d)):n||(n=setTimeout(()=>{n=null,r&&s(r)},a))});return i.flush=()=>{n&&(clearTimeout(n),n=null),r&&s(r)},i}function pl(o,e){let t=Bf(o,e);return Object.assign(n=>{if(n.status==="started"){t(n);return}t.flush(),o(n)},{flush:t.flush})}async function at(o){try{return await Pe.access(o),!0}catch{return!1}}function Wf(o){return o.check==="clear-empty"?'residual value under "clear" generator (value redacted at the bridge)':o.detail.length>200?`${o.detail.slice(0,200)}\u2026`:o.detail}function vl(o){return{passed:o.passed,author:o.author,checkedAt:o.checkedAt,checks:o.checks.map(e=>({name:e.name,passed:e.passed,violations:e.violations.slice(0,_f).map(t=>({check:t.check,objectApiName:t.objectApiName,referenceId:t.referenceId,field:t.field,detail:Wf(t)}))}))}}function gl(o){return{version:o.version,status:o.status,frozenAt:o.frozenAt,source:o.source,saltFingerprint:o.saltFingerprint,rulesVersion:o.rulesVersion,volumetry:o.volumetry,controls:{nonReidentification:vl(o.controls.nonReidentification),dryRunLoad:o.controls.dryRunLoad,author:o.controls.author,date:o.controls.date},...o.coverage?{coverage:o.coverage}:{}}}function qf(o,e,t){return{combinations:o.roots.map(r=>({combinationKey:r.combinationKey,axisValues:r.axisValues,edgeCase:r.edgeCase})),uncovered:o.uncovered,volumetry:o.volumetry,selectedAt:o.selectedAt,selectionPath:e,...t?{graph:t}:{},...o.stopped?{stopped:o.stopped}:{}}}function Ds(o,e){if(!e||e.length===0)return o;let t=new Set(e);return{...o,nodes:o.nodes.map(r=>t.has(r.objectApiName)?{...r,included:!1}:r)}}function hl(o,e){return{objects:o.nodes.filter(ja).length,truncated:o.truncated===!0,maxNodes:e}}function Gf(o){return o.length===0?"":` Kept in the org, the platform does not delete them: ${o.map(({objectApiName:t,count:r})=>`${t} (${r})`).join(", ")}.`}function xs(o,e){if(!o)return{message:"No load into this org was recorded in this sas: there is nothing to remove.",code:"NO_LOAD"};if(o.orgId!==e.targetOrgId||o.endedAt!==e.loadedAt)return{message:"Another load was recorded since this one was shown, and nothing was removed: check what a removal takes now, then confirm it again.",code:"LOAD_CHANGED"};if(!o.created)return{message:"This load was recorded before loads kept what they created: its records cannot be told from the ones it linked, and cannot be removed from here, nor replaced by a reload, which would delete what someone changed since. Refresh the sandbox to start again from its copy, or find the records the loading user created that day and delete them yourself.",code:"NOT_RECORDED"};if(it(o).length>0)return;let t=Gf($n(o));return o.removal?{message:`The records this load created were already removed, on ${o.removal.removedAt}.${t}`,code:"ALREADY_REMOVED"}:t?{message:`This load created no record a removal takes.${t}`,code:"NOTHING_TO_REMOVE"}:{message:"This load created no record to remove.",code:"NOTHING_TO_REMOVE"}}function $s(o){let e=o.writtenBetween,t=o.startedAt===void 0?Number.NaN:Date.parse(o.startedAt),r=Date.parse(o.endedAt);return{...e?{runStartedAt:new Date(e.first),runEndedAt:new Date(e.last)}:{...Number.isFinite(t)&&Number.isFinite(r)?{runDurationMs:Math.max(0,r-t)}:{},...Number.isFinite(r)?{runRecordedAt:new Date(r),endedByItsWrites:!0}:{}},removalStamps:o.removalStamps,removalSpans:o.removalSpans,...o.runUserId?{runUserId:o.runUserId}:{}}}function Uf(o,e=!1){let t=new Map;for(let{objects:r}of o)for(let n of r){let s=n.heldByAutomation??0,i=(n.keptDependents??0)-(e?s:0),d=n.heldBy&&n.heldBy.length>0?n.heldBy.join(", "):"",a=[n.keptChanged>0?`${n.keptChanged} changed since the load`:"",i>0?(d?`${i} kept for records that stay under them (${d})`:`${i} kept as what hangs from them could not be read`)+(!e&&s>0?`, ${s} of them for what the target's automation likely made for the load, which a sweep takes first`:""):"",n.undeletable>0?`${n.undeletable} the user may not delete`:"",n.notVisible>0?`${n.notVisible} out of the user's sight`:"",n.unread>0?`${n.unread} that could not be read`:""].filter(Boolean),c=n.keptChanged+Math.max(0,i)+n.undeletable+n.notVisible+n.unread;if(c===0)continue;let l=t.get(n.objectApiName)??{left:0,why:new Set};l.left+=c;for(let u of a)l.why.add(u);t.set(n.objectApiName,l)}return[...t].map(([r,{left:n,why:s}])=>({objectApiName:r,left:n,why:[...s]}))}function Kf(o){return{status:o.status,orgId:o.orgId,mode:o.mode,startedAt:o.startedAt,durationMs:o.durationMs,alignment:{excludedObjects:o.alignment.excludedObjects,removals:o.alignment.removals,adjustments:o.alignment.adjustments,recordTypeIssues:o.alignment.recordTypeIssues},placeholders:o.placeholders,requiredDefaults:o.requiredDefaults,perObject:o.perObject,...o.sentAgainForALock?{sentAgainForALock:o.sentAgainForALock}:{},pass2:o.pass2,personContact:o.personContact,statuses:o.statuses,purge:o.purge,...o.leftToThePlatform?{leftToThePlatform:o.leftToThePlatform}:{},...o.untypedFeedItems?{untypedFeedItems:o.untypedFeedItems}:{},...o.heldForExcludedParents?{heldForExcludedParents:o.heldForExcludedParents}:{},...o.quotesLeftUnsynced?{quotesLeftUnsynced:o.quotesLeftUnsynced}:{},...o.keysLeftEmpty?{keysLeftEmpty:o.keysLeftEmpty}:{},...o.recordTypesGiven?{recordTypesGiven:o.recordTypesGiven}:{},...o.runUserId?{runUserId:o.runUserId}:{},mappingPath:o.mappingPath,contractPath:o.contractPath}}function Vf(o){return o.status==="completed"?"success":o.perObject.reduce((t,r)=>t+r.inserted+r.reused,0)>0?"partial":"failure"}function Hf(o){let e=o.perObject.reduce((t,r)=>t+r.failed.length,0)+o.purge.failures.length;return ho(o)===0&&e===0?"stopped":"cancelled"}function ho(o){let e=t=>Object.values(t).reduce((r,n)=>r+n,0);return o.perObject.reduce((t,r)=>t+r.inserted,0)+o.placeholders.length+e(o.purge.deleted)+e(o.purge.deactivated)}function ml(o){return`frozen:${o}`}var po=(o,e)=>e==="insert"||e==="update",Ht=class extends Error{constructor(t,r){super(r);this.code=t;this.name="CheckpointFirstStop"}code};function yl(o){let e=Bd(o);return e.length>0?{sentAgainForALock:e}:{}}function wl(o){let e=new Map,t=n=>{let s=e.get(n);return s||(s={objectApiName:n,inserted:0,placeholders:0,failed:0,deleted:0,deactivated:0},e.set(n,s)),s};for(let n of o.perObject){let s=t(n.objectApiName);s.inserted+=n.inserted,s.failed+=n.failed.length}for(let n of o.placeholders)t(n.placeholderObjectApiName).placeholders++;for(let[n,s]of Object.entries(o.purge.deleted))t(n).deleted+=s;for(let[n,s]of Object.entries(o.purge.deactivated))t(n).deactivated+=s;let r=[...e.values()].filter(n=>n.inserted+n.placeholders+n.failed+n.deleted+n.deactivated>0);return r.length>0?{writtenPerObject:r}:{}}function _s(o){let e=new Map,t=r=>{let n=e.get(r)??Ti(r);return e.set(r,n),n};for(let r of o.perObject){let n=t(r.objectApiName);n.created+=r.inserted,n.failed+=r.failed.length+r.skippedDuplicates.length,r.notInserted&&(n.notSent=(n.notSent??0)+r.notInserted),r.writtenWithoutFields&&(n.writtenWithoutFields=(n.writtenWithoutFields??0)+r.writtenWithoutFields.rows)}for(let r of o.placeholders)t(r.placeholderObjectApiName).created+=1;for(let[r,n]of Object.entries(o.purge.deleted))t(r).deleted+=n;for(let[r,n]of Object.entries(o.purge.deactivated))t(r).updated+=n;for(let r of o.purge.failures)t(r.objectApiName).failed+=1;return[...e.values()]}async function Yf(o,e){try{let t=await e.load();return Object.fromEntries(o.objects.map(r=>[r.objectApiName,r.records.filter(n=>t.has(n.referenceId)).length]))}catch{return}}var tt=class extends Error{constructor(t,r,n={}){super(r);this.code=t;this.params=n;this.name="ReplayRefused"}code;params},Ws=class extends _n{constructor(t,r,n){super(t,r);this.registeredAs=n}registeredAs;async recorded(){let t=await super.recorded();return t&&{...t,orgId:this.registeredAs}}async recordedLoads(){return(await super.recordedLoads()).map(t=>({...t,orgId:this.registeredAs}))}};function Jf(){let o=wa();return{checkpoints:()=>[o,Id(o)].flatMap(e=>{if(!Pf(e))return[];let t=ba({root:e});return"store"in t?[t.store]:[]}),replays:new Fd({root:jd()})}}function bl(o,e){let t=Object.fromEntries((e?.link??[]).map(n=>[n.objectApiName,[...n.fields]])),r={...o?.identityKeys,...t};return{rootObject:"",axes:[],edgeCases:[],...o,...Object.keys(r).length>0?{identityKeys:r}:{}}}function go(o){return o.replay?{module:"checkpoint",sasMark:Xn(o.replay.folder.dir)}:{module:"frozen"}}function Xf(o){return o.replay?{action:"checkpoint_replay",module:"checkpoint"}:{action:"frozen_load",module:"frozen"}}var Rl=class{constructor(e){this.deps=e}deps;registry;liveTracker;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;saltKeeper=yc();openInEditor=Mf;otherModuleRuns=()=>Promise.resolve([]);removing=new Set;writing=new la;loading=new Map;beforeRunCheckpoints;describeCache=new Wo({defaultTtl:5*6e4,maxSize:2e3,maxSizeBytes:200*1024*1024,releaseExpired:!0});describeGlobalCache=new Wo({defaultTtl:5*6e4,maxSize:16,maxSizeBytes:50*1024*1024});forgetOrg(e){this.describeCache.invalidateByPrefix(`${e}::`),this.describeGlobalCache.invalidate(e)}setRegistry(e){this.registry=e}setRulesEditor(e){this.openInEditor=e}setLiveOperationTracker(e){this.liveTracker=e}setBeforeRunCheckpoints(e){this.beforeRunCheckpoints=e}setTargetAutomation(e){this.targetAutomation=e}setMuteLeases(e){this.muteLeases=e}muteLeases={};setMuteOffered(e){this.muteOffered=e}muteOffered=!0;setRemovalAsker(e){this.removalAsker=e}removalAsker;ownReader(){return this.reader??=import("./chunk-UK3QLBHW.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>Se(r,this.deps.orgRegistry,this.deps.orgManager)))),this.reader}setSaltKeeper(e){this.saltKeeper=e}isWritingTo(e,t){if(this.writing.has(e))return!0;for(let[r,n]of this.loading)if(n===e&&(t===void 0||t!==ml(r)))return!0;return!1}async loadingDuring(e,t){let r=jn(e,"targetOrgId");if(r===void 0)return t();this.loading.set(e.id,r);try{await t()}finally{this.loading.delete(e.id)}}async handle(e){if(!jf.has(e.type))return!1;switch(this.deps.log(`[RX] ${e.type} id=${e.id}`),e.type){case"frozen:config:get":return this.handleConfigGet(e),!0;case"frozen:config:save":return this.handleConfigSave(e),!0;case"frozen:select":return await this.handleSelect(e),!0;case"frozen:extract":return await this.handleExtract(e),!0;case"frozen:load":return await this.loadingDuring(e,()=>this.handleLoad(e)),!0;case"frozen:load:preview":return await this.handlePreview(e),!0;case"frozen:verify":return await this.handleVerify(e),!0;case"frozen:remove":return await this.writing.during(jn(e,"targetOrgId"),()=>this.handleRemove(e)),!0;case"frozen:remove:sweep":return await this.writing.during(jn(e,"targetOrgId"),()=>this.handleRemoveSweep(e)),!0;case"frozen:remove:automation":return await this.handleRemoveAutomation(e),!0;case"frozen:remove:preview":return await this.handleRemovePreview(e),!0;case"frozen:status":return await this.handleStatus(e),!0;case"frozen:rules:clear":return await this.handleRulesClear(e),!0;case"frozen:rules:create":return await this.handleRulesCreate(e),!0;default:return!1}}loadConfig(){return this.deps.configStore.get(dl)??null}handleConfigGet(e){let t=this.loadConfig(),r=Ae(this.deps,e,"frozen:config:get:response",{config:t,sasDir:this.resolveSasDir(t),datasetDir:this.resolveDatasetDir(t)});this.deps.broker.postToWebview(r)}handleConfigSave(e){let t=st(xi,e,"frozen:config:save:error",this.deps);if(!t)return;this.deps.configStore.set(dl,t.config,nn);let r=Ae(this.deps,e,"frozen:config:save:response",{success:!0});this.deps.broker.postToWebview(r)}resolveSasDir(e){return e?.sasDir??je.join(kl.homedir(),".sandforge-sas")}resolveDatasetDir(e){return e?.datasetDir??je.join(this.resolveSasDir(e),"dataset")}resolveRulesPath(e){return je.resolve(e?.rulesFilePath??je.join(this.resolveSasDir(e),zf))}async rulesFileInfo(e){let t=this.resolveRulesPath(e),r=null;try{r=await at(t)?await Pe.readFile(t,"utf8"):null}catch(n){return{path:t,found:!0,invalid:ee(n)}}return{path:t,...Pc(r)}}async loadTokens(e,t){return await at(je.join(e,ll))?zc(e,ll,t):{}}async describeObject(e,t){let r=`${e}::${t}`,n=this.describeCache.get(r);if(n)return n;let s=await new St(3e4).withTimeout(`frozen:describe:${t}`,async()=>{let d=await(await Se(e,this.deps.orgRegistry,this.deps.orgManager)).describe(t);return{name:d.name,fields:d.fields.map(a=>({name:a.name,label:a.label,type:a.type,referenceTo:a.referenceTo??[],relationshipName:a.relationshipName??null,isMasterDetail:a.cascadeDelete===!0,nillable:a.nillable!==!1,createable:a.createable!==!1,updateable:a.updateable!==!1,restrictedPicklist:a.restrictedPicklist===!0,defaultedOnCreate:a.defaultedOnCreate===!0,...a.compoundFieldName?{compoundFieldName:a.compoundFieldName}:{}})),childRelationships:(d.childRelationships??[]).map(a=>({childSObject:a.childSObject,field:a.field,relationshipName:a.relationshipName??a.field,isCascadeDelete:a.cascadeDelete===!0}))}},3e4);return this.describeCache.set(r,s),s}buildDiscoveryService(){return new Fa({describeObject:(e,t)=>this.describeObject(e,t),queryCount:async(e,t)=>(await(await Se(e,this.deps.orgRegistry,this.deps.orgManager)).query(t)).totalSize,detectPII:e=>{let t=this.deps.infraServices?.piiDetector;return t?In(t,e):[]},describeGlobal:e=>this.describeGlobal(e)})}async describeGlobal(e){let t=this.describeGlobalCache.get(e);if(t)return t;let s=(await(await Se(e,this.deps.orgRegistry,this.deps.orgManager)).describeGlobal()).sobjects.map(i=>({name:i.name,keyPrefix:i.keyPrefix??null}));return this.describeGlobalCache.set(e,s),s}async keyPrefixes(e){let t=new Map;for(let{name:r,keyPrefix:n}of await this.describeGlobal(e))n&&t.set(r,n);return t}discoveryConfig(e,t){return{inputMode:"record",recordId:t,depth:"full",sourceOrgId:e,targetOrgId:e,anonymizePII:!1,skipEmpty:!0,batchSize:"auto"}}discoveryOptions(e){return{maxNodes:e.maxNodes??Ta}}async graphOfStep(e){let{sourceOrgId:t,config:r,sasDir:n,guard:s}=e,{maxNodes:i}=this.discoveryOptions(r),d={sourceOrgId:t,rootObject:r.rootObject,maxNodes:i},a=await _c(n,s),c;if("kept"in a){let p=a.kept,g=Bc(p,d)??await this.schemaChangeSince(t,p);if(g===void 0)return this.holdKeptDescribes(t,p),{graph:p.graph,origin:{reusedFrom:p.step,discoveredAt:p.discoveredAt}};c=g}else c=a.none;let l;try{let p=await Se(t,this.deps.orgRegistry,this.deps.orgManager);l=Wc((await p.soap.getServerTimestamp()).timestamp)}catch(p){this.deps.log(`[WARN] frozen: the source did not give its clock: ${String(p)}`)}let u=await this.buildDiscoveryService().discover(this.discoveryConfig(t,e.rootRecordId),{maxNodes:i,...e.signal?{signal:e.signal}:{},...e.onProgress?{onProgress:e.onProgress}:{}}),f=new Date().toISOString();return{graph:u,origin:{rediscovered:c},keep:async p=>{let g=new Set([...u.nodes.filter(m=>m.included).map(m=>m.objectApiName),...p]),h={};for(let m of g){let y=this.describeCache.get(`${t}::${m}`);y&&(h[m]=y)}await $c(n,{fileVersion:1,...d,step:e.step,discoveredAt:f,...l?{schemaStamp:l}:{},graph:u,describes:h,objects:this.describeGlobalCache.get(t)??[]},s)}}}async schemaChangeSince(e,t){if(!t.schemaStamp)return"the graph kept carries no stamp of the org";try{let n=await(await Se(e,this.deps.orgRegistry,this.deps.orgManager)).request({method:"GET",url:"/sobjects",headers:{"If-Modified-Since":new Date(t.schemaStamp).toUTCString()}}),s=typeof n=="object"&&n!==null?n.sobjects:void 0;return Array.isArray(s)?(this.forgetOrg(e),this.describeGlobalCache.set(e,s.flatMap(i=>{let{name:d,keyPrefix:a}=i??{};return typeof d=="string"?[{name:d,keyPrefix:typeof a=="string"?a:null}]:[]})),`the source's schema changed since the graph kept was discovered, on ${t.discoveredAt}`):void 0}catch(r){return`the source could not say whether its schema changed: ${ee(r)}`}}holdKeptDescribes(e,t){for(let[r,n]of Object.entries(t.describes))this.describeCache.set(`${e}::${r}`,n,ul);t.objects.length>0&&this.describeGlobalCache.set(e,t.objects,ul)}async describeScopableFields(e,t){return(await this.describeObject(e,t)).fields.map(n=>({name:n.name,type:n.type,referenceTo:n.referenceTo,nillable:n.nillable!==!1}))}async ruleSchemaOf(e,t){let r=new Map;for(let{objectApiName:n}of t)try{let s=await this.describeObject(e,n);r.set(n,s.fields)}catch(s){this.deps.log(`[WARN] frozen: ${n} could not be described for the rules: ${String(s)}`)}return r}mappingStoreFor(e,t,r){let n=async()=>{try{let[s]=await this.buildTargetOrgAccess().query(t,"SELECT Id FROM Organization");return typeof s?.Id=="string"?s.Id:void 0}catch(s){this.deps.log(`[WARN] frozen: the target did not say which org it is: ${String(s)}`);return}};return new _n(e,{orgId:t,organizationId:n,guard:r})}buildTargetOrgAccess(){return{query:async(e,t)=>{let r=await Se(e,this.deps.orgRegistry,this.deps.orgManager);return On(r,t)},count:async(e,t)=>(await(await Se(e,this.deps.orgRegistry,this.deps.orgManager)).query(t)).totalSize,describe:async(e,t)=>{let n=await(await Se(e,this.deps.orgRegistry,this.deps.orgManager)).describe(t);return{name:n.name,createable:n.createable,cascadeChildren:(n.childRelationships??[]).flatMap(s=>s.cascadeDelete===!0&&typeof s.field=="string"&&s.field!==""?[{childSObject:s.childSObject,field:s.field}]:[]),fields:n.fields.map(s=>({name:s.name,type:s.type,createable:s.createable??!1,nillable:s.nillable??!0,defaultedOnCreate:s.defaultedOnCreate??!1,referenceTo:s.referenceTo??[],restrictedPicklist:s.restrictedPicklist??!1,picklistValues:(s.picklistValues??[]).map(i=>({value:i.value,active:i.active??!0})),updateable:s.updateable!==!1,unique:s.unique===!0,nameField:s.nameField===!0,...typeof s.filteredLookupInfo=="object"&&s.filteredLookupInfo!==null?{lookupFilter:{optional:s.filteredLookupInfo.optionalFilter===!0}}:{}})),recordTypeInfos:(n.recordTypeInfos??[]).flatMap(s=>{let{developerName:i,active:d}=s;return i?[{developerName:i,recordTypeId:s.recordTypeId,available:s.available,name:s.name,master:s.master,defaultRecordTypeMapping:s.defaultRecordTypeMapping,...d===void 0?{}:{active:d}}]:[]})}},picklistValues:async(e,t,r,n)=>{let s=await Se(e,this.deps.orgRegistry,this.deps.orgManager);return cd(s,t,r,n)},userId:async e=>(await(await Se(e,this.deps.orgRegistry,this.deps.orgManager)).soap.getUserInfo()).userId}}toLoadConfig(e){return{protectedOrgIds:e.protectedOrgIds,identityKeys:e.identityKeys,undeletableObjects:e.undeletableObjects,requiredLookupPlaceholders:e.requiredLookupPlaceholders,excludedObjects:e.excludedObjects,requiredFieldDefaults:e.requiredFieldDefaults,picklistRules:e.picklistRules,defaultPicklistRule:e.defaultPicklistRule,duplicateErrorPatterns:e.duplicateErrorPatterns,rootObjectApiName:e.rootObject}}async readFrozenDataset(e,t){let r=t.assertOutsideRepo(e),n=t.assertOutsideRepo(je.join(r,"manifest.json"));if(!await at(n))throw new Error(`No frozen dataset found at ${r} \u2014 run a selection (frozen:select) then an extraction (frozen:extract) first.`);let s=zr(JSON.parse(await Pe.readFile(n,"utf8"))),i=[],d=t.assertOutsideRepo(je.join(r,"data"));if(await at(d))for(let f of(await Pe.readdir(d)).sort()){if(!f.endsWith(".json"))continue;let p=t.assertOutsideRepo(je.join(d,f)),g=JSON.parse(await Pe.readFile(p,"utf8"));i.push({objectApiName:g.objectApiName,records:g.records})}let a=async(f,p)=>{let g=t.assertOutsideRepo(je.join(r,f));return await at(g)?JSON.parse(await Pe.readFile(g,"utf8")):p},c=await a("record-types.json",{}),l=await a("personcontact-sidecar.json",[]),u=await a(Mr,{});return{dataset:{datasetVersion:s.version,objects:i,recordTypes:c,personContactSidecar:l,...u.standardPricebook?{standardPricebook:u.standardPricebook}:{}},manifest:s}}errorCodeFor(e,t){return e instanceof yr?"RULES_MISSING":e instanceof Ve?"GUARD_REFUSED":e instanceof vd?"SAS_PATH_REFUSED":e instanceof Nr?"SALT_MISSING":e instanceof Gt?"BUDGET_EXCEEDED":e instanceof et?"LOAD_CONFIG":e instanceof qr?"MAX_RECORDS":e instanceof lr?fo:e instanceof ut?"TIMEOUT":e instanceof tt?e.code:e instanceof Lo&&e.code==="invalid"?"INVALID_PAYLOAD":t}errorDetailOf(e){if(e instanceof tt)return{params:e.params};if(e instanceof yr)return{rulesPath:e.rulesPath};if(e instanceof Ve)return{guard:e.code,...e.params};if(e instanceof Gt)return{total:e.total,budgetMax:e.budgetMax,heaviest:e.heaviest};if(e instanceof et&&e.gaps)return{gaps:e.gaps,...(e.refusedBeside??[]).length>0?{refusedBeside:e.refusedBeside}:{}};if(e instanceof et&&e.recordTypesUntold)return{recordTypesUntold:e.recordTypesUntold};if(e instanceof mr)return{emails:e.emails,orgId:e.orgId};if(e instanceof on)return{automation:e.automation,orgId:e.orgId};if(e instanceof sn)return{apiRequests:e.apiRequests,orgId:e.orgId};if(e instanceof an)return{storage:e.storage,orgId:e.orgId}}loadEmailsFor(e){return Ic({read:e.read,...e.plan?{plan:e.plan}:{},writes:e.writes,inserts:e.dataset.objects.map(t=>({objectApiName:t.objectApiName,rows:t.records.length})).filter(t=>t.rows>0),readLimits:()=>Ba(e.conn),readDeliverability:()=>e.orgTier==="production"?Promise.resolve(ua):fa(e.conn),accepted:e.accepted,target:this.orgNameOf(e.orgId),mayMute:e.mayMute})}async loadApiCheck(e){let t=await Ca(e.conn).catch(s=>({unread:ee(s)})),r=dd(e.read),n=za({run:Hc({inserts:e.dataset.objects.map(s=>({objectApiName:s.objectApiName,rows:s.records.length})),...e.purged?{purged:e.purged}:{},threshold:Oo(this.deps).bulk.threshold,...r?{duplicateRules:r}:{},automationRead:Va(e.read)})+(e.replayReads??0),...Da(e.checkpoint),...ha(e.plan),...Ha(e.emails?.run.ofRun)},t);return n.verdict==="unread"&&this.deps.log(`[WARN] ${e.operation}: the daily API requests the target has left could not be read (${n.unread})`),Nf(n,this.orgNameOf(e.orgId))}async purgedOf(e,t){if(await e.isStale())return[];let r=t.undeletableObjects??{};return(await e.recordedLoads()).flatMap(n=>it(n)).map(({objectApiName:n,ids:s})=>({objectApiName:n,rows:s.length,deletes:!Object.hasOwn(r,n)}))}orgNameOf(e){let t=this.deps.orgManager.getOrg(e);return ti(t,e)}requireConfig(e,t){let r=this.loadConfig();return r||(te(this.deps,e.type,t,e,new Error("No frozen dataset configuration saved \u2014 save the project configuration first (frozen:config:save: coverage axes, root object, budget, load rules)."),{code:"CONFIG_MISSING"}),null)}setReplayStores(e){this.replayStores=e}replayStores;replayStoresInUse(){return this.replayStores??=Jf(),this.replayStores}async sourceOf(e,t,r,n,s){if(t.replay===void 0){let i=this.requireConfig(e,r);return i?this.datasetSource(i,t.targetOrgId):void 0}try{if(t.pilot===!0)throw new tt("REPLAY_NO_PILOT","A replay loads no pilot: simulate it, then replay it whole. Nothing was read or written.");return await this.replaySourceOf(t.targetOrgId,t.replay,n)}catch(i){let d=this.errorCodeFor(i,"REPLAY_ERROR");s?.(d);let a=this.errorDetailOf(i);te(this.deps,e.type,r,e,i,{code:d,retryable:i instanceof ut,...a?{extraPayload:a}:{}});return}}datasetSource(e,t){let r=n=>n.assertOutsideRepo(this.resolveSasDir(e));return{config:e,sasDir:r,mappingStore:n=>this.mappingStoreFor(r(n),t,n),read:async n=>{let s=n.assertOutsideRepo(this.resolveDatasetDir(e)),{dataset:i,manifest:d}=await this.readFrozenDataset(s,n);return{dataset:i,manifest:d,datasetDir:s,label:d.version}}}}async replaySourceOf(e,t,r){let n=this.targetTier(e),s=n==="staging"?this.stagingReplayOf(e,t,r):void 0;Qo({orgId:e,orgName:this.orgNameOf(e),orgTier:n,...s?{stagingReplay:s}:{}});let i=this.replayStoresInUse(),d=i.replays.folderOf(t.organizationId,t.checkpointId),a=await this.replayTargetOf(e),c=En(a.organizationId),l={folder:d,target:a,contractPath:i.replays.contractPathOf(d,c),...s?{stagingReplay:s}:{}},u=m=>new Ws(d.dir,{guard:m,orgId:c,organizationId:a.organizationId},e);if(r==="mapping")return{config:bl(t.config,void 0),sasDir:()=>d.dir,mappingStore:u,read:()=>Promise.reject(new Error("A removal of a replay reads no checkpoint")),replay:l};let f=await this.replayedCheckpointOf(i,t),p=t.choices??(await i.replays.read(d))?.targets.find(m=>m.organizationId===c)?.choices;if(p===void 0)throw new tt("NO_LOAD",`No replay of checkpoint ${t.checkpointId} into ${a.name} is recorded on this machine: replay it there first, then verify. Nothing was read or written.`,{checkpoint:t.checkpointId,target:a.name});let g=Cd({checkpoint:f.checkpoint,checkpointId:t.checkpointId,choices:p,target:a});if(g)throw new tt(g.code,g.message,g.params);if(f.checkpoint===void 0)throw new tt("REPLAY_CHECKPOINT_UNUSABLE","The checkpoint does not read.");let h=f.checkpoint;return l.checkpoint={checkpoint:h,folder:f.folder,annex:f.annex},l.choices=p,{config:bl(t.config,p),sasDir:()=>d.dir,mappingStore:u,read:async()=>(l.converted??=await this.convertReplay(l,p,e),{dataset:l.converted.conversion.dataset,label:h.name}),replay:l}}stagingReplayOf(e,t,r){if(r!=="load")return!0;let n=this.orgNameOf(e);if(t.confirmStaging===n)return!0;throw new tt("REPLAY_STAGING_UNCONFIRMED",`${n} is a sandbox marked Staging, which may hold real data: a replay goes into it once its name is typed to confirm it. Nothing was read or written.`,{target:n})}async replayedCheckpointOf(e,t){for(let r of e.checkpoints()){let n=(await r.checkpointsOf(t.organizationId)).find(s=>s.folder.checkpointId===t.checkpointId);if(n!==void 0){if(n.checkpoint===void 0)return{folder:n.folder,annex:void 0};try{return{checkpoint:n.checkpoint,folder:n.folder,annex:await Na(n.folder)}}catch(s){throw s instanceof Lo?new tt("REPLAY_CHECKPOINT_UNUSABLE",`${s.message}: what checkpoint '${n.checkpoint.name}' says of its record types, users and catalogue cannot be told. Nothing was read or written.`,{checkpoint:n.checkpoint.name,why:"damaged"}):s}}}throw new tt("CHECKPOINT_NOT_FOUND",`No checkpoint ${t.checkpointId} of org ${t.organizationId} is kept on this machine: import its file first, or name one the checkpoint list shows. Nothing was read or written.`,{checkpoint:t.checkpointId})}async replayTargetOf(e){let t=this.buildTargetOrgAccess(),r=this.orgNameOf(e),[n]=await t.query(e,"SELECT Id FROM Organization");if(typeof n?.Id!="string")throw new Error(`${r} did not say which org it is: nothing was read or written.`);let s=n.Id,i=await t.userId?.(e);if(i===void 0)throw new Error(`${r} did not say which user the replay writes as.`);let d=this.deps.orgManager.getOrg(e),a=this.deps.sandboxRefreshes,c=[d?.orgId,a?.organizationIdOf(e),...a?.refreshesOf(e).map(l=>l.previousOrganizationId)??[]].filter(l=>typeof l=="string"&&l.slice(0,15)!==s.slice(0,15));return{name:r,organizationId:s,runningUserId:i,...d?.username?{username:d.username}:{},...d?.instanceUrl?{instanceUrl:d.instanceUrl}:{},formerOrganizationIds:[...new Set(c)],tier:d?.orgType==="Sandbox"?"sandbox":d?.orgType==="Scratch"?"scratch":"developer"}}async convertReplay(e,t,r){let n=e.checkpoint;if(n===void 0)throw new Error("The checkpoint of the replay was not read");let s=await rl({folder:n.folder,checkpoint:n.checkpoint,annex:n.annex,choices:t,access:this.buildTargetOrgAccess(),orgId:r,organizationId:e.target.organizationId,runningUserId:e.target.runningUserId,tier:e.target.tier,...e.target.username!==void 0?{username:e.target.username}:{},targetName:e.target.name});if("refusal"in s)throw new tt(s.refusal.code,s.refusal.message,{users:s.refusal.users.join(", ")});return{conversion:s.conversion,target:s.target}}replayInfoOf(e,t,r){let n=e.checkpoint,s=e.converted;if(n===void 0||s===void 0||e.choices===void 0)return;let{checkpoint:i}=n,{summary:d,filesLeft:a}=s.conversion;return{checkpoint:{checkpointId:i.checkpointId,name:i.name,organizationId:i.org.organizationId,...i.org.alias!==void 0?{alias:i.org.alias}:{},takenAt:i.takenAt,tier:i.org.tier,annex:n.annex!==void 0},target:{organizationId:En(e.target.organizationId),name:e.target.name},choices:e.choices,summary:{...d,records:{...d.records,toCreate:Math.max(0,d.records.toCreate-t),linkedByKey:t}},filesLeft:a.map(({objectApiName:c,name:l})=>({objectApiName:c,...l!==void 0?{name:l}:{}})),...r?{storage:r}:{},requests:s.target.requests}}async loadSentOf(e,t){let r;try{r=await e.request({method:"GET",url:"/sobjects"})}catch{return}let n=Ff.safeParse(r);if(!n.success)return;let s=new Set(n.data.sobjects.filter(i=>i.createable!==!1).map(i=>i.name.toLowerCase()));return{takes:i=>s.has(i.toLowerCase()),byThePlatform:lc(t)}}async loadStorageOf(e){let t=await xo(Do(e.conn,e.targetOrgId)).catch(()=>{});if(t===void 0)return;let r=Math.max(0,e.automationBytes??0),n=ol({dataset:e.dataset,storage:t,...e.sent?{sent:e.sent}:{},...e.purged?{purged:e.purged}:{},automationBytes:r,target:this.orgNameOf(e.targetOrgId),...e.replay===!0?{replay:!0}:{},...e.pilot===!0?{pilot:!0}:{}}),s=1024*1024;return{estimateMB:n?.storage.estimateMB??(Bs(e.dataset,e.sent)+r)/s,...r>0?{automationMB:r/s}:{},remainingMB:t.remainingMB,maxMB:t.maxMB,...n?.storage.freedMB!==void 0?{freedMB:n.storage.freedMB}:{},...t.uncountedWrites?{uncountedWrites:t.uncountedWrites}:{},...e.pilot===!0?{pilot:!0}:{},...n?{refusal:{code:Il,message:n.message}}:{}}}async handleSelect(e){let t=st($i,e,"frozen:select:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:select:error");if(!r)return;let n=`frozen-select-${this.deps.nextId()}`;Pr(this.deps,n,"frozen","Running coverage-matrix selection");let s="Coverage-matrix selection",i=new AbortController,d=setTimeout(()=>i.abort("timeout"),xf),a=()=>{},c=new Promise((u,f)=>{a=p=>p===void 0?u():f(p)});c.catch(()=>{}),this.registry?.register(e.id,"frozen",s,c,i),this.liveTracker?.register(e.id,"frozen",s);let l=u=>{this.deps.broker.postToWebview(Ae(this.deps,e,"frozen:select:progress",{...u})),u.phase==="combination"&&u.index!==void 0&&u.of&&this.liveTracker?.updateProgress(e.id,Math.round((u.index-1)/u.of*100),u.index-1,u.of,u.combinationKey??"")};try{let u=new pe,f=u.assertOutsideRepo(this.resolveSasDir(r)),p=await Se(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),g=new Map,h=async B=>{let D=g.get(B);return D||(D=On(p,B),g.set(B,D),D.catch(()=>g.delete(B))),(await D).map(G=>({...G}))},m=await this.loadTokens(f,u),y=this.discoveryOptions(r),R=new Set,j=new Jr({query:h,describeFields:B=>(R.add(B),this.describeScopableFields(t.sourceOrgId,B)),keyPrefixes:()=>this.keyPrefixes(t.sourceOrgId)}),T=new Date().toISOString(),P,_=0,q=async B=>(P??=this.graphOfStep({step:"select",sourceOrgId:t.sourceOrgId,config:r,sasDir:f,guard:u,rootRecordId:B,signal:i.signal,onProgress:D=>{D.phase==="object"&&(D.discoveredCount-_<10&&D.queueRemaining>0||(_=D.discoveredCount,l({phase:"discovery",objects:D.discoveredCount})))}}),Ds((await P).graph,r.excludedObjects)),C=async B=>{if(B.length===0)return{};let D=await q(B[0]),G=await j.extract({graph:D,rootObject:r.rootObject,rootRecordIds:B,asOf:T,sasDir:f,excludedFields:r.excludedFields,excludedObjects:r.excludedObjects,tokens:m,guard:u}),X={};for(let K of G.objects)X[K.objectApiName]=K.records.length;return X},I=new eo(C,r.expectedObjects??[]),w=async(B,D)=>(await this.describeObject(t.sourceOrgId,B)).fields.find(G=>G.name.toLowerCase()===D.toLowerCase())?.type,F=await new Qn({query:h,checkHealth:I,measureVolumetry:C,fieldType:w}).select({rootObject:r.rootObject,axes:r.axes,edgeCases:r.edgeCases,budgetMaxRecords:r.budgetMaxRecords,candidatesPerCombination:r.candidatesPerCombination,tokens:m},{signal:i.signal,onProgress:l}),v=await Dc(f,F,u),A=P&&!F.stopped?await P.catch(()=>{}):void 0;A?.keep&&await A.keep(R).catch(B=>{this.deps.log(`[WARN] frozen: the graph could not be kept in the sas: ${String(B)}`)});let L=A?Ds(A.graph,r.excludedObjects):void 0,x=Ae(this.deps,e,"frozen:select:response",{selection:{...qf(F,v,L?hl(L,y.maxNodes):void 0),...A?{discovery:A.origin}:{}}});this.deps.broker.postToWebview(x),bt(this.deps,n,{roots:F.roots.length,total:F.volumetry.total,...F.stopped?{stopped:F.stopped.reason}:{}}),F.stopped?.reason==="cancelled"?this.liveTracker?.cancel(e.id):this.liveTracker?.complete(e.id),a()}catch(u){this.liveTracker?.fail(e.id,ee(u)),a(u),te(this.deps,"frozen:select","frozen:select:error",e,u,{code:this.errorCodeFor(u,"SELECT_ERROR"),retryable:u instanceof ut,extraPayload:this.errorDetailOf(u)})}finally{clearTimeout(d)}}async handleExtract(e){let t=st(Bi,e,"frozen:extract:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:extract:error");if(!r)return;let n=`frozen-extract-${this.deps.nextId()}`;Pr(this.deps,n,"frozen","Extracting + pseudonymizing dataset");try{let s=new pe,i=s.assertOutsideRepo(this.resolveSasDir(r)),d=s.assertOutsideRepo(this.resolveDatasetDir(r)),a=await this.saltKeeper.forExtraction(),c=new Cn(a.salt);if(a.created&&this.sayTheSaltWasMade(c.saltFingerprint),!await at(je.join(i,Hr))){te(this.deps,"frozen:extract","frozen:extract:error",e,new Error(`No selection found in ${i} \u2014 run the coverage-matrix selection first (frozen:select).`),{code:"SELECTION_MISSING"});return}let l=await ms(i,s),u=l.roots.map(G=>G.rootRecordId);if(u.length===0){te(this.deps,"frozen:extract","frozen:extract:error",e,new Error("The last selection kept no root: every combination was uncovered, and the selection says why for each. Adjust the axes or the expected objects, then run the selection again."),{code:"SELECTION_EMPTY"});return}let f=await this.loadTokens(i,s),p=this.resolveRulesPath(r);if(!await at(p))throw new yr(p,`Pseudonymization rules file not found at ${p} \u2014 it is the source of truth (object.field \u2192 generator). Create it, or set rulesFilePath in the configuration. The smallest is ${JSON.stringify(fs)}: with no rule, the extraction clears every field, the platform's own words aside, then lists what it kept without a rule and the required fields it left empty, which a load asks a value for.`);let g=Zn(JSON.parse(await Pe.readFile(p,"utf8"))),h=await Se(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),m=this.discoveryOptions(r),y=await this.graphOfStep({step:"extract",sourceOrgId:t.sourceOrgId,config:r,sasDir:i,guard:s,rootRecordId:u[0]}),R=Ds(y.graph,r.excludedObjects),j=new Set,T,P=new Jr({query:G=>T?.aborted?Promise.reject(new Error("The extraction ran out of time and stopped.")):On(h,G),describeFields:G=>(j.add(G),this.describeScopableFields(t.sourceOrgId,G)),keyPrefixes:()=>this.keyPrefixes(t.sourceOrgId)}),_=t.author??"sandforge",q=r.datasetVersion??Df,{extracted:C,frozen:I,report:w,requiredLeftEmpty:O,keptUnruled:F}=await new St(zs).withTimeout("frozen:extract",async G=>{T=G;let X=await P.extract({graph:R,rootObject:r.rootObject,rootRecordIds:u,asOf:new Date().toISOString(),sasDir:i,excludedFields:r.excludedFields,excludedObjects:r.excludedObjects,tokens:f,guard:s}),K=await this.ruleSchemaOf(t.sourceOrgId,X.objects),H=Tc(g,K,this.deps.infraServices?.piiDetector??new vn),N=new no().anonymize({extracted:X,rules:H,pseudonymizer:c,datasetVersion:q}),Z=new oo().run(X,N,H,{author:_});return{extracted:X,frozen:N,report:Z,requiredLeftEmpty:Fc(X,H,K),keptUnruled:jc(X,H)}});O.length>0&&this.deps.log(`[WARN] frozen: the rules leave ${O.length} required field(s) empty, which a load will ask a value for: ${O.join(", ")}`),y.keep&&await y.keep(j).catch(G=>{this.deps.log(`[WARN] frozen: the graph could not be kept in the sas: ${String(G)}`)});let v=Ae(this.deps,e,"frozen:control:result",{report:vl(w)});if(this.deps.broker.postToWebview(v),!w.passed){te(this.deps,"frozen:extract","frozen:extract:error",e,new Error("Non-reidentification control FAILED \u2014 nothing was written. Fix the rules file and re-run the extraction (see frozen:control:result for the failing checks)."),{code:"CONTROL_FAILED"});return}let A={};for(let G of I.objects)A[G.objectApiName]=G.records.length;let L=this.deps.orgManager.getOrg(t.sourceOrgId),x=Md({version:q,source:{orgId:t.sourceOrgId,orgAlias:L?.alias,decisionDate:l.selectedAt},saltFingerprint:c.saltFingerprint,rulesVersion:g.rulesVersion,volumetry:{budgetMax:l.volumetry.budgetMax,measured:A,measuredAt:new Date().toISOString()},nonReidentification:w,author:_,coverage:{...hl(R,m.maxNodes),unboundedObjects:C.unboundedObjects,filesLeftOut:I.filesLeftOut??[],...(C.leftToThePlatform??[]).length>0?{leftToThePlatform:Bn(C.leftToThePlatform??[])}:{},...C.exclusionCosts?{exclusionCosts:C.exclusionCosts}:{},...O.length>0?{requiredLeftEmpty:O}:{},...F.length>0?{keptWithoutARule:F}:{},encryptedNotKept:C.encryptedNotKept??[]}}),B=await new qn(s).write(d,I,x,w),D=Ae(this.deps,e,"frozen:extract:response",{datasetDir:B.dir,files:B.files,recordCount:cr(I),manifest:gl(x),discovery:y.origin});this.deps.broker.postToWebview(D),bt(this.deps,n,{records:cr(I),version:x.version})}catch(s){let i=s instanceof ut,d=i?new Error(`The extraction ran out of its ${zs/6e4} minutes and stopped, and nothing was written: it reads every record of the roots the selection kept, so run again it would stop again. Keep fewer roots: lower the budget in the configuration, or narrow the axes, then run the selection and the extraction again.`):s;te(this.deps,"frozen:extract","frozen:extract:error",e,d,{code:i?$f:this.errorCodeFor(s,"EXTRACT_ERROR"),retryable:!1,extraPayload:i?{minutes:zs/6e4}:this.errorDetailOf(s)})}}async handleRulesClear(e){let t=st(_i,e,"frozen:rules:clear:error",this.deps);if(!t)return;let r=this.requireConfig(e,"frozen:rules:clear:error");if(r)try{let n=this.resolveRulesPath(r);if(!await at(n))throw new yr(n,`Pseudonymization rules file not found at ${n} \u2014 nothing was written. Create it, or set rulesFilePath in the configuration.`);let s=Ec(JSON.parse(await Pe.readFile(n,"utf8")),t.fields);if(s.cleared.length>0){let d=`${n}.${process.pid}.writing`;await Pe.writeFile(d,`${JSON.stringify(s.payload,null,2)}
|
|
21
|
+
`,"utf8"),await Pe.rename(d,n),this.deps.log(`[INFO] frozen: ${s.cleared.length} field(s) given a clear rule in ${n} (rules ${s.rulesVersion}): ${s.cleared.join(", ")}`)}let i=Ae(this.deps,e,"frozen:rules:clear:response",{rulesPath:n,rulesVersion:s.rulesVersion,cleared:s.cleared,alreadyRuled:s.alreadyRuled});this.deps.broker.postToWebview(i)}catch(n){te(this.deps,"frozen:rules:clear","frozen:rules:clear:error",e,n,{code:this.errorCodeFor(n,"RULES_CLEAR_ERROR"),extraPayload:this.errorDetailOf(n)})}}async handleRulesCreate(e){let t=this.resolveRulesPath(this.loadConfig()),r=!1;try{await Pe.mkdir(je.dirname(t),{recursive:!0});try{await Pe.writeFile(t,Ac(fs),{encoding:"utf8",flag:"wx"}),r=!0,this.deps.log(`[INFO] frozen: empty rules file written at ${t}`)}catch(s){if(s.code!=="EEXIST")throw s;if(!(await Pe.stat(t)).isFile())throw new Error(`${t} is not a file: no rules file can be written there.`)}}catch(s){te(this.deps,"frozen:rules:create","frozen:rules:create:error",e,s,{code:"RULES_CREATE_ERROR"});return}let n=!1;try{await this.openInEditor(t),n=!0}catch(s){this.deps.log(`[WARN] frozen: rules file not opened: ${ee(s)}`)}this.deps.broker.postToWebview(Ae(this.deps,e,"frozen:rules:create:response",{rulesPath:t,created:r,opened:n}))}targetTier(e){let t=this.deps.orgManager.getOrg(e);return ei(t)}async handleLoad(e){let t=this.registry?.holdUntilStart(e.id);try{await this.runLoad(e,t)}finally{t?.release()}}async runLoad(e,t){let r=st(jo,e,"frozen:load:error",this.deps);if(!r)return;let n=await this.sourceOf(e,r,"frozen:load:error","load",N=>Ze(this.deps,{action:"checkpoint_replay",module:"checkpoint",operationId:e.id,orgId:r.targetOrgId,outcome:"stopped",code:N}));if(!n)return;let{config:s}=n,i=Xf(n),d=n.replay,a=this.deps.infraServices?.productionGuard;if(!a){Ze(this.deps,{...i,operationId:e.id,orgId:r.targetOrgId,outcome:"stopped",code:Ot.code}),te(this.deps,"frozen:load","frozen:load:error",e,new Error(Ot.message),{code:Ot.code});return}let c=await this.replaceRefusal(r,n),l=c&&"error"in c?c:void 0,u=c&&"cameAlong"in c?c.cameAlong:void 0;if(l){l.code===fo&&Ze(this.deps,{...i,operationId:e.id,orgId:r.targetOrgId,outcome:"stopped",code:fo}),te(this.deps,"frozen:load","frozen:load:error",e,l.error,{code:l.code,retryable:l.retryable});return}let f=e.id,p=d?`Replaying checkpoint '${d.checkpoint?.checkpoint.name??""}'`:r.pilot?"Pilot load (one root folder)":"Loading frozen dataset";Pr(this.deps,f,i.module,p),this.liveTracker?.register(f,i.module,p);let g=!1,h=!1,m=new AbortController,y=()=>{},R=new Promise((N,Z)=>{y=$=>$===void 0?N():Z($)});R.catch(()=>{}),this.registry?.register(f,i.module,p,R,m),t?.signal.aborted&&m.abort();let j=()=>{if(m.signal.aborted)throw new Qe({perObject:[],placeholders:[],purge:{deleted:{},deactivated:{},failures:[]}},!1)},T=pl(N=>{let Z=Ae(this.deps,e,"frozen:load:progress",{...N});this.deps.broker.postToWebview(Z),!g&&!h&&this.liveTracker?.updateProgress(f,N.progress,0,0,N.message)},100),P,_=!1,q=!1,C,I=new Date().toISOString(),w,O,F,v,A,L=(N,Z,$,U)=>{if(q)return;q=!0;let oe=N!=="stopped"&&w!==void 0,se=F?ya(ma(F.run.gate,F.info.accepted&&F.info.verdict==="asks").emails):{},me=d?.checkpoint&&d.choices?{replayCheckpoint:d.checkpoint.checkpoint.checkpointId,...zd(d.checkpoint.checkpoint,d.choices,d.target),...d.stagingReplay?{replayIntoStaging:!0}:{}}:{},de={...oe?{sas:w,startedAt:I,...O?{lastWriteAt:O}:{}}:{},...se,...me};Ze(this.deps,{...i,operationId:f,orgId:r.targetOrgId,outcome:N,guard:P,objects:Z,source:{origin:d?"checkpoint":"dataset",label:C},carried:$,...U?{code:U}:{},...x?{muted:yn(x)}:{},...D?.state==="taken"?{checkpointId:D.checkpointId}:{},...Object.keys(de).length>0?{details:de}:{}})},x,B,D,G=!1,X=!1,K=!1,H=[];try{j();let N=new pe,Z=n.sasDir(N);w=Xn(Z);let{dataset:$,manifest:U,datasetDir:oe,label:se}=await n.read(N);C=se;let me=this.buildTargetOrgAccess(),de=await Se(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),Fe=Oo(this.deps),k=Fi(this.deps),E=z=>new Rd({connection:de,bulkExecutor:new Hi(Fe.bulk.threshold),bulkManager:k,retryConfig:Fe.retry,...z?{signal:z}:{},onProgress:()=>{},log:ae=>this.deps.log(ae)}),S=E(m.signal),Y=s.mockDetection?new $r(me,s.mockDetection):{areCalloutsMocked:async()=>!0},J=n.mappingStore(N),re=Bt(de,"frozen:load"),Ie=new Gr({orgAccess:me,writer:vs(S),restoringWriter:vs(E(void 0)),guard:a,mockDetector:Y,recordTypeResolver:new Xr(me),mappingStore:J,config:this.toLoadConfig(s),sasGuard:N,serverTime:()=>re.serverTime()});if(r.sweep===!0&&r.reload===!0&&!r.pilot){H=await this.reloadSweepsOf({conn:de,store:J,sweepLate:r.sweepLate===!0,sweepUntied:r.sweepUntied===!0,includeChanged:r.includeChanged===!0,signal:m.signal,guard:a,operationId:f,audit:go(n)});for(let{sweep:z}of H)await z.ask()}let Q=rn([],H.flatMap(({sweep:z})=>z.takes)),Ee=(Q.delete??[]).length>0?this.removalAsker:void 0,M=$.objects.map(z=>z.objectApiName),we=r.reload===!0&&!r.pilot?await this.purgeStepsOf(J,s):void 0,We=await this.targetAutomation.read(r.targetOrgId,[...new Set([...M,...we?.delete??[],...Q.delete??[]])]).catch(z=>({unread:ee(z)})),He=we?Or(we):void 0,V=Or(Q),ie=(z,ae)=>po(z,ae)||He?.(z,ae)===!0||V(z,ae),Le=r.muteAutomation===!0?await Fr(async()=>jr(de),We,{...this.muteLeases,writes:ie}):void 0;if(x=Le?.muted,Ee&&!m.signal.aborted){let z=await Ee({read:We,steps:Q,mute:Le});if(z)throw new hr(z)}let he=this.targetTier(r.targetOrgId),jt=await Ie.gateLoad({orgId:r.targetOrgId,orgName:this.orgNameOf(r.targetOrgId),orgTier:he,...d?.stagingReplay?{stagingReplay:!0}:{},dataset:$,manifest:U,reload:r.reload,pilot:r.pilot?{}:void 0,onProgress:z=>T(z),onGuardDecision:z=>{P=Eo(P,z)}}),rt=ls({read:We,...Le?.plan?{plan:Le.plan}:{},written:M,accepted:r.acceptAutomation===!0,target:this.orgNameOf(r.targetOrgId),mayMute:r.muteAutomation!==!0&&this.muteOffered});if(v=rt.info,rt.stop&&rt.info)throw new on(rt.stop.code,rt.stop.message,rt.info,r.targetOrgId);let Ye=r.acceptEmails===!0,ge=Es($,s,r.pilot),ve=await this.loadEmailsFor({conn:de,orgId:r.targetOrgId,orgTier:he,read:We,...Le?.plan?{plan:Le.plan}:{},writes:ie,dataset:ge,accepted:Ye,mayMute:r.muteAutomation!==!0&&this.muteOffered});if(F=ve,ve.stop)throw new mr(ve.stop.code,ve.stop.message,ve.info,r.targetOrgId);let Ft=r.checkpointFirst!==void 0?await this.scopeLoadCheckpoint({msg:e,orgId:r.targetOrgId,written:M,read:We,mute:Le,request:r.checkpointFirst,replay:d!==void 0}):void 0,dt=we?await this.purgedOf(J,s):void 0,kt=Promise.resolve().then(()=>de.request({method:"GET",url:"/limits"}));kt.catch(()=>{});let dn={request:()=>kt},mo=await xo(Do(dn,r.targetOrgId)).catch(z=>({unread:ee(z)})),wr=await this.loadSentOf(de,ge),br=sl(We,Le?.plan,ge,ie),Et=ol({dataset:ge,storage:mo,...wr?{sent:wr}:{},...dt?{purged:dt}:{},automationBytes:br,target:this.orgNameOf(r.targetOrgId),...d?{replay:!0}:{},...r.pilot===!0?{pilot:!0}:{}});if(Et)throw new an(Et.message,Et.storage,r.targetOrgId);if(A=await this.loadApiCheck({conn:dn,dataset:ge,...dt?{purged:dt}:{},read:We,...Ft?{checkpoint:Ft.estimate}:{},...Le?.plan?{plan:Le.plan}:{},emails:ve,orgId:r.targetOrgId,operation:`frozen:load ${f}`,...d?.converted?{replayReads:d.converted.target.requests}:{}}),A.refused)throw new sn(A.refused.message,A,r.targetOrgId);j(),d?.checkpoint&&d.choices&&await this.replayStoresInUse().replays.record(d.checkpoint.checkpoint,{organizationId:d.target.organizationId,name:d.target.name},d.choices),Ft&&(B=await this.takeLoadCheckpoint(Ft,m.signal)),j();let Me=Le?.prepared?await Le.prepared.acquire(f):void 0;Me&&(x=Me.outcome,K=!0);let Yt=Me?ve.run.afterLease(Me.outcome,Ye):void 0;if(Me&&Yt)throw x=await Me.release(),new mr(Yt.code,Yt.message,ve.info,r.targetOrgId);Pi({action:i.action,orgId:r.targetOrgId,operationId:f},(Bs(ge,wr)+Math.max(0,br))/(1024*1024)),G=!0;let Lt=()=>Ie.load({orgId:r.targetOrgId,orgName:this.orgNameOf(r.targetOrgId),orgTier:he,...d?.stagingReplay?{stagingReplay:!0}:{},dataset:$,manifest:U,sasDir:Z,reload:r.reload,pilot:r.pilot?{}:void 0,...r.writeEncrypted?{writeEncrypted:!0}:{},...r.maxRecords!==void 0?{maxRecords:r.maxRecords}:{},...d?{linkByKeys:!0,contractOrgId:En(d.target.organizationId)}:{},onProgress:z=>T(z),onGuardDecision:z=>{P=Eo(P,z),(z==="allowed"||z==="confirmed")&&(_=!0)},signal:m.signal,...Me?{lease:{giveBack:()=>Me.release()}}:{},...H.length>0?{purgeSweep:{first:async()=>{for(let{sweep:z}of H)await z.first()},afterPurge:async()=>{for(let{sweep:z}of H)await z.afterRemoval()},stillToSweep:()=>H.filter(({sweep:z})=>!Ls(z.result())).map(({loadedAt:z})=>z)}}:{}}),nt=await(jt==="confirmed"?da({approved:!0},Lt):Lt()).finally(async()=>{Me&&(x=await Me.release())});X=!0,T.flush();let Nt=await this.settleReloadSweeps(H),Rr=Nt.some(z=>z.result.status!=="success");B&&(D=await this.settleCheckpoint(B,ho(nt)>0)),O=wc(await J.recorded().catch(()=>{}),I);let vt=oe!==void 0?je.join(oe,"manifest.json"):void 0;h=!0;let kr=await this.verifyLoad({orgId:r.targetOrgId,contractPath:nt.contractPath,...vt!==void 0?{manifestPath:vt}:{},dataset:$,mappingStore:J,config:s,onProgress:T}),Ir="verdict"in kr?kr.verdict.status:void 0,Jt=Ir==="failed"||Ir==="partial"?Ir:void 0,Ct=nt.status==="completed"&&(Rr||Jt!==void 0)?"partial":nt.status,vr=Vf(nt);if(L(Jt!==void 0&&vr==="success"?"partial":vr,_s(nt),await Yf($,J)),oe!==void 0&&vt!==void 0){let z={contractPath:nt.contractPath,datasetDir:oe,manifestPath:vt,targetOrgId:r.targetOrgId,status:Ct,at:new Date().toISOString()};this.recordLastRun(z)}let zt=Kf(nt),b=Object.fromEntries(Object.entries(u??{}).filter(([z])=>(zt.purge.deleted[z]??0)>0)),W=Ae(this.deps,e,"frozen:load:response",{report:{...zt,...Object.keys(b).length>0?{purge:{...zt.purge,cameAlong:b}}:{},status:Ct,...Jt?{verification:Jt}:{},...x?{mutedAutomation:x}:{},...D?{checkpoint:D}:{},...Nt.length>0?{sweeps:Nt}:{},...F&&al(F.info)?{emails:F.info}:{},...v?{automation:v}:{},...A?{apiRequests:A}:{}},...d?il(this.replayInfoOf(d,Lf(nt,$))):{}});this.deps.broker.postToWebview(W),bt(this.deps,f,{status:Ct}),g=!0,Ct!=="completed"?this.liveTracker?.partial(f):this.liveTracker?.complete(f),this.postVerification(e,kr),y()}catch(N){T.flush();let Z=await this.settleReloadSweeps(H).catch(()=>[]),$=Z.length>0?{sweeps:Z}:{};if(B&&D===void 0){let J=N instanceof Qe||N instanceof qt?N.written:void 0;D=await this.settleCheckpoint(B,J?ho(J)>0:G&&!Fn(N))}let U=D?{checkpoint:D}:{},oe=K&&x?{mutedAutomation:x}:{};if(N instanceof Ht){L("stopped",void 0,void 0,N.code),te(this.deps,"frozen:load","frozen:load:error",e,N,{code:N.code,...N.code==="LOAD_CANCELLED"?{extraPayload:{written:0}}:{}}),N.code==="LOAD_CANCELLED"?(this.registry?.abort(f),bt(this.deps,f,{aborted:!0}),this.liveTracker?.cancel(f),y()):(So(this.deps,f,N.message,!0),this.liveTracker?.fail(f,N.message),y(N));return}if(N instanceof Qe){let J=Hf(N.written);L(J,_s(N.written),void 0,J==="stopped"?"LOAD_CANCELLED":void 0),this.registry?.abort(f),bt(this.deps,f,{aborted:!0}),this.liveTracker?.cancel(f),te(this.deps,"frozen:load","frozen:load:error",e,N,{code:"LOAD_CANCELLED",extraPayload:{written:ho(N.written),...U,...$,...oe,...wl(N.written),...yl(N.written)}}),y();return}let se=Fn(N)||N instanceof tt||N instanceof hr||N instanceof mr||N instanceof on||N instanceof sn||N instanceof an?N:void 0,me=se!==void 0||(P==="refused"||P==="declined")&&!_,de=N instanceof qt?N:void 0,Fe=de?de.cause:N,k=se?.code??this.errorCodeFor(Fe,"LOAD_ERROR"),E=de===void 0&&!X&&!_;L(me||E?"stopped":"failure",de?_s(de.written):void 0,void 0,se?.code??(E?k:void 0));let Y={...de&&Fe instanceof Ve?{guard:Fe.code}:this.errorDetailOf(Fe),...U,...$,...oe,...E?{written:0}:{},...de?wl(de.written):{},...de?yl(de.written):{}};te(this.deps,"frozen:load","frozen:load:error",e,N,{code:k,retryable:Fe instanceof ut,extraPayload:Object.keys(Y).length>0?Y:void 0}),g||(So(this.deps,f,ee(N),!0),this.liveTracker?.fail(f,ee(N))),y(N)}}loadCheckpointAsk(e){let{read:t}=e;return{module:e.replay===!0?"replay":"frozen",orgId:e.orgId,operationId:e.operationId,written:[...e.written],running:"objects"in t?Dt(t,e.mute?.plan,po):{firing:[]},request:e.request}}async previewCheckpoint(e){let t=this.beforeRunCheckpoints;if(!t)return;let r=await this.targetAutomation.read(e.orgId,e.written).catch(i=>({unread:ee(i)})),n=e.muteAutomation?await Fr(async()=>jr(e.conn),r,{...this.muteLeases,writes:po}).catch(i=>{xt.warn(`Frozen preview: the mute could not be planned (${ee(i)})`)}):void 0,s=this.loadCheckpointAsk({...e,operationId:e.msg.id,read:r,...n?{mute:n}:{}});return t.scope(s,{}).catch(i=>{xt.warn(`Frozen preview: ${Nn(i)}`)})}async scopeLoadCheckpoint(e){let t=this.beforeRunCheckpoints;if(!t)throw new Ht(Lr,Nn(new Error("SandForge's checkpoints are not set up in this window")));let r=this.loadCheckpointAsk({...e,operationId:e.msg.id}),n={operationId:ml(e.msg.id)},s;try{s=await t.scope(r,n)}catch(d){throw new Ht(Lr,Nn(d))}let i=xa(s);if(i)throw new Ht(i.code,i.message);return{checkpoints:t,ask:r,own:n,estimate:s}}async takeLoadCheckpoint(e,t){let{checkpoints:r,ask:n,own:s,estimate:i}=e,d=await $a(()=>r.take(n,s,{planned:i,signal:t}));if("stop"in d)throw new Ht(d.stop.code===Lr?Lr:"LOAD_CANCELLED",d.stop.message);return d.checkpoint}async settleCheckpoint(e,t){let r=this.beforeRunCheckpoints;if(!r)return e;try{return await r.settle(e,t)}catch(n){return xt.warn(`Frozen load: the checkpoint '${e.name}' taken before it is kept, as it could not be settled (${ee(n)})`),e}}recordLastRun(e){this.moveOldVerify();let t={...this.lastRuns()},r=this.deps.configStore.get(gr);r&&t[r.targetOrgId]===void 0&&(t[r.targetOrgId]=r),t[e.targetOrgId]=e,this.deps.configStore.set(cl,t,nn),this.deps.configStore.set(gr,e,nn)}recordLastVerify(e,t){this.moveOldVerify(),this.deps.configStore.set(Cs,{...this.lastVerifies(),[e]:t},nn)}lastVerifies(){return this.deps.configStore.get(Cs)??{}}orgOfOldVerify(e){let t=this.deps.configStore.get(gr);return!t||Date.parse(t.at)>Date.parse(e.measuredAt)?void 0:Object.keys(this.lastRuns()).filter(n=>n!==t.targetOrgId).length===0?t.targetOrgId:void 0}moveOldVerify(){let e=this.deps.configStore.get(Ns);if(!e)return;let t=this.orgOfOldVerify(e),r=this.lastVerifies();t!==void 0&&r[t]===void 0&&this.deps.configStore.set(Cs,{...r,[t]:e},nn),this.deps.configStore.delete(Ns)}lastVerifyInfos(){let e={...this.lastVerifies()},t=this.deps.configStore.get(Ns),r=t?this.orgOfOldVerify(t):void 0;return t&&r!==void 0&&e[r]===void 0&&(e[r]=t),Object.entries(e).map(([n,s])=>({orgId:n,status:s.status,measuredAt:s.measuredAt}))}lastRuns(){return this.deps.configStore.get(cl)??{}}lastRunOf(e){let t=this.lastRuns()[e];if(t)return t;let r=this.deps.configStore.get(gr);return r?.targetOrgId===e?r:void 0}lastLoadInfos(){let e={...this.lastRuns()},t=this.deps.configStore.get(gr);return t&&e[t.targetOrgId]===void 0&&(e[t.targetOrgId]=t),Object.values(e).map(r=>({status:r.status,orgId:r.targetOrgId,at:r.at}))}async handlePreview(e){let t=st(jo,e,"frozen:load:preview:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:load:preview:error","checkpoint");if(!r)return;let{config:n,replay:s}=r,i=await this.replaceRefusal(t,r,t.goneFirst),d=i&&"error"in i?i:void 0;if(d){te(this.deps,"frozen:load:preview","frozen:load:preview:error",e,d.error,{code:d.code,retryable:d.retryable});return}try{let a=new pe,c=r.sasDir(a),{dataset:l,manifest:u}=await r.read(a),f=this.buildTargetOrgAccess(),p=await Se(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),g=Bt(p,"frozen:load:preview"),m=await new Gr({orgAccess:f,writer:Tf,guard:this.deps.infraServices?.productionGuard??new ca,mockDetector:n.mockDetection?new $r(f,n.mockDetection):{areCalloutsMocked:async()=>!0},recordTypeResolver:new Xr(f),mappingStore:r.mappingStore(a),config:this.toLoadConfig(n),sasGuard:a,serverTime:()=>g.serverTime(),readValidationRules:async w=>{let{toolingQueriesOver:O,toolingValidationRules:F}=await import("./chunk-RQW5S67A.mjs"),{toolingRetrievesOver:v}=await import("./chunk-UK3QLBHW.mjs"),A=p.tooling;return F(async L=>(await Ci({query:async x=>A.query(x),queryMore:async x=>A.queryMore(x)},L)).records,O(p),v(p))(w)}}).planLoad({orgId:t.targetOrgId,orgName:this.orgNameOf(t.targetOrgId),orgTier:this.targetTier(t.targetOrgId),...s?.stagingReplay?{stagingReplay:!0}:{},dataset:l,manifest:u,sasDir:c,reload:t.reload,pilot:t.pilot?{}:void 0,...t.writeEncrypted?{writeEncrypted:!0}:{},...s?{linkByKeys:!0}:{}}).catch(async w=>{throw w instanceof et&&w.gaps!==void 0&&(w.refusedBeside=await this.refusedBesideOf({conn:p,orgId:t.targetOrgId,dataset:l,store:r.mappingStore(a),config:n,parsed:t,...s?{replay:s}:{}}).catch(()=>[])),w}),y=t.checkpointFirst!==void 0?await this.previewCheckpoint({msg:e,orgId:t.targetOrgId,written:l.objects.map(w=>w.objectApiName),request:t.checkpointFirst,muteAutomation:t.muteAutomation===!0,conn:p,replay:s!==void 0}):void 0,R=r.mappingStore(a),j=nl(p),{emails:T,automation:P,apiRequests:_,automationBytes:q}=await this.previewWhatRuns({conn:p,limits:j,orgId:t.targetOrgId,dataset:l,store:R,config:n,parsed:t,...y?{checkpoint:y}:{},...s?.converted?{replayReads:s.converted.target.requests}:{}}),C=await this.previewStorageOf({conn:j,org:p,dataset:l,store:R,config:n,parsed:t,...q!==void 0?{automationBytes:q}:{},targetOrgId:t.targetOrgId,replay:s!==void 0}),I=s?this.replayInfoOf(s,m.perObject.reduce((w,O)=>w+O.reusedByKeys,0),C):void 0;this.deps.broker.postToWebview(Ae(this.deps,e,"frozen:load:preview:response",{plan:{...m,...y?{checkpoint:y}:{},...T?{emails:T}:{},...P?{automation:P}:{},..._?{apiRequests:_}:{},...C&&!s?{storage:C}:{}},...il(I)}))}catch(a){te(this.deps,"frozen:load:preview","frozen:load:preview:error",e,a,{code:this.errorCodeFor(a,"PREVIEW_ERROR"),retryable:a instanceof ut,extraPayload:this.errorDetailOf(a)})}}async refusedBesideOf(e){let{replay:t,...r}=e,n=nl(e.conn),{emails:s,automation:i,apiRequests:d,automationBytes:a}=await this.previewWhatRuns({...r,limits:n,...t?.converted?{replayReads:t.converted.target.requests}:{}}),c=await this.previewStorageOf({conn:n,org:e.conn,dataset:e.dataset,store:e.store,config:e.config,parsed:e.parsed,...a!==void 0?{automationBytes:a}:{},targetOrgId:e.orgId,replay:t!==void 0}),{orgId:l}=e,u=[];return i?.refused&&u.push({...i.refused,orgId:l,automation:i}),s?.refused&&u.push({...s.refused,orgId:l,emails:s}),c?.refusal&&u.push({...c.refusal,orgId:l,storage:Ef(c)}),d?.refused&&u.push({...d.refused,orgId:l,apiRequests:d}),u}async previewStorageOf(e){let t=e.parsed.pilot===!0,r=Es(e.dataset,e.config,e.parsed.pilot),n=await this.loadSentOf(e.org,r);return this.loadStorageOf({conn:e.conn,dataset:r,...n?{sent:n}:{},...e.parsed.reload===!0&&!t?{purged:await this.purgedOf(e.store,e.config).catch(()=>[])}:{},...e.automationBytes!==void 0?{automationBytes:e.automationBytes}:{},targetOrgId:e.targetOrgId,replay:e.replay,...t?{pilot:!0}:{}})}async previewWhatRuns(e){let{parsed:t}=e;try{let r=t.reload===!0&&!t.pilot?await this.purgeStepsOf(e.store,e.config):void 0,n=r?Or(r):void 0,s=(f,p)=>po(f,p)||n?.(f,p)===!0,i=await this.targetAutomation.read(e.orgId,[...new Set([...e.dataset.objects.map(f=>f.objectApiName),...r?.delete??[]])]).catch(f=>({unread:ee(f)})),d=t.muteAutomation===!0?await Fr(async()=>jr(e.conn),i,{...this.muteLeases,writes:s}).catch(()=>{}):void 0,{info:a}=ls({read:i,...d?.plan?{plan:d.plan}:{},written:e.dataset.objects.map(f=>f.objectApiName),accepted:t.acceptAutomation===!0,target:this.orgNameOf(e.orgId),mayMute:t.muteAutomation!==!0&&this.muteOffered}),c=Es(e.dataset,e.config,t.pilot),l=await this.loadEmailsFor({conn:e.conn,orgId:e.orgId,orgTier:this.targetTier(e.orgId),read:i,...d?.plan?{plan:d.plan}:{},writes:s,dataset:c,accepted:t.acceptEmails===!0,mayMute:t.muteAutomation!==!0&&this.muteOffered}).catch(f=>{xt.warn(`Frozen preview: the emails could not be judged (${ee(f)})`)}),u=await this.loadApiCheck({conn:e.limits,dataset:c,...r?{purged:await this.purgedOf(e.store,e.config)}:{},read:i,...e.checkpoint?{checkpoint:e.checkpoint}:{},...d?.plan?{plan:d.plan}:{},...l?{emails:l}:{},orgId:e.orgId,operation:"frozen:load:preview",...e.replayReads!==void 0?{replayReads:e.replayReads}:{}}).catch(f=>{xt.warn(`Frozen preview: the API requests could not be judged (${ee(f)})`)});return{...l&&al(l.info)?{emails:l.info}:{},...a?{automation:a}:{},...u?{apiRequests:u}:{},automationBytes:sl(i,d?.plan,c,s)}}catch(r){return xt.warn(`Frozen preview: what the target runs could not be judged (${ee(r)})`),{}}}async handleVerify(e){let t=st(Wi,e,"frozen:verify:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:verify:error","checkpoint");if(!r)return;let{config:n,replay:s}=r,i=s?void 0:this.lastRunOf(t.targetOrgId);if(!s&&!i){te(this.deps,"frozen:verify","frozen:verify:error",e,new Error("No load into this org is recorded \u2014 run a load (frozen:load) into it before verifying."),{code:"NO_LOAD"});return}let d=pl(a=>{let c=Ae(this.deps,e,"frozen:load:progress",{...a});this.deps.broker.postToWebview(c)},100);try{let a=new pe,c=i?.contractPath??s?.contractPath??"";if(s&&!await at(c)){te(this.deps,"frozen:verify","frozen:verify:error",e,new Error(`No replay of this checkpoint into ${s.target.name} wrote its counting contract on this machine: replay it there, then verify.`),{code:"NO_LOAD"});return}if(i){let g=a.assertOutsideRepo(this.resolveSasDir(n)),h=je.dirname(i.contractPath)!==je.dirname(Dn(a,g,t.targetOrgId)),m=await at(i.contractPath);if(h||!m){let y=je.dirname(i.contractPath),R;h?m?R=`The sas directory changed since the last load: its counting contract is in ${y}, and the mapping read is the one in ${g}. Set sasDir back to the sas the load wrote to, or load the dataset again, then verify.`:R=`The sas directory changed since the last load: the load wrote to ${y}, which no longer holds its counting contract, and the mapping read is the one in ${g}. Move the sas back to ${y} and set sasDir to it, or load the dataset again, then verify.`:R=`The sas changed since the last load: ${g} no longer holds the counting contract the last load wrote there. Load the dataset again, then verify.`,te(this.deps,"frozen:verify","frozen:verify:error",e,new Error(R),{code:"SAS_CHANGED",extraPayload:{sasDir:g,loadSas:y,sasMoved:h,contractThere:m}});return}}let l=r.mappingStore(a);if(await l.isStale()){te(this.deps,"frozen:verify","frozen:verify:error",e,new Error("The target org was refreshed after the last load: the records that load wrote are gone. Load the dataset again, then verify."),{code:"TARGET_REFRESHED"});return}let u=await l.recorded(),f=u?.removal;if(u&&f){let g=it(u).reduce((h,m)=>h+m.ids.length,0);te(this.deps,"frozen:verify","frozen:verify:error",e,new Error(g>0?`The removal of ${f.removedAt} took part of the records the last load created and left ${g} in the org: a verification would read the ones it took as missing. Remove what is left, or reload the dataset, which purges or finds it again; then verify.`:`The records the last load created were removed on ${f.removedAt}. Load the dataset again, then verify.`),{code:"LOAD_REMOVED",extraPayload:{left:g}});return}if(!u){te(this.deps,"frozen:verify","frozen:verify:error",e,new Error("The sas holds no mapping of the last load: nothing names the records to verify. Load the dataset again, then verify."),{code:"NO_LOAD"});return}if(!Sd(xn(a,c),u)){te(this.deps,"frozen:verify","frozen:verify:error",e,new Error("The last load stopped part way \u2014 it was cancelled, or failed once it had written \u2014 and wrote no counting contract: the one in the sas counts an earlier load, and would judge this one by it. Reload the dataset, which purges or finds again what the stopped load wrote, or remove that load before loading the dataset again; then verify. Loaded again without a reload, the dataset would go in beside what the stopped load wrote."),{code:"LOAD_STOPPED"});return}let{dataset:p}=i?await this.readFrozenDataset(i.datasetDir,a):await r.read(a);await this.runVerification(e,{orgId:t.targetOrgId,contractPath:c,...i?{manifestPath:i.manifestPath}:{},dataset:p,mappingStore:l,config:n,onProgress:d})}catch(a){te(this.deps,"frozen:verify","frozen:verify:error",e,a,{code:this.errorCodeFor(a,"VERIFY_ERROR"),retryable:a instanceof ut})}}async runVerification(e,t){this.postVerification(e,await this.verifyLoad(t))}async verifyLoad(e){try{let t=new so({orgAccess:this.buildTargetOrgAccess(),sasGuard:new pe}),r=await e.mappingStore.load(),n=await t.verify({orgId:e.orgId,contractPath:e.contractPath,dataset:e.dataset,mapping:r,mandatoryLookups:e.config.mandatoryLookups,presenceKeys:e.config.presenceKeys,...e.manifestPath!==void 0?{manifestPath:e.manifestPath}:{},author:"sandforge",onProgress:e.onProgress});return this.recordLastVerify(e.orgId,{status:n.status,measuredAt:n.measuredAt}),{verdict:n}}catch(t){return{error:t}}}postVerification(e,t){if("verdict"in t){let{verdict:n}=t,s=Ae(this.deps,e,"frozen:verify:result",{verdict:n});this.deps.broker.postToWebview(s);return}let r=t.error;te(this.deps,"frozen:verify","frozen:verify:error",e,r,{code:this.errorCodeFor(r,"VERIFY_ERROR"),retryable:r instanceof ut})}async handleRemove(e){let t=st(qi,e,"frozen:remove:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:remove:error","mapping");if(!r)return;let n=(p,g)=>this.refuseRemove(e,p,g),s,i,d;try{s=r.mappingStore(new pe),i=await s.recordedLoads(),d=dr(i)}catch(p){te(this.deps,"frozen:remove","frozen:remove:error",e,p,{code:this.errorCodeFor(p,"REMOVE_ERROR")});return}let a=xs(d,t),c=t.sweep===!0&&a?.code==="ALREADY_REMOVED";if(a&&!c||!d){a&&n(a.message,a.code);return}let l=it(d),u=s.filePath;if(this.removing.has(u)){n("The records of this load are being removed already.","DUPLICATE");return}this.removing.add(u);let f=this.registry?.holdUntilStart(e.id);try{await this.removeLoad(e,{store:s,load:d,plan:l,includeChanged:t.includeChanged===!0,sweep:t.sweep===!0,sweepLate:t.sweep===!0&&t.sweepLate===!0,sweepUntied:t.sweep===!0&&t.sweepUntied===!0,alongside:t.sweep===!0?Ko(i,d):[],muteAutomation:t.muteAutomation===!0,pending:f,audit:go(r)})}finally{this.removing.delete(u),f?.release()}}async handleRemoveAutomation(e){let t=st(Ui,e,"frozen:remove:automation:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:remove:automation:error","mapping");if(!r)return;let{config:n}=r;try{let s=r.mappingStore(new pe),i,d;if(t.reload===!0)i=await this.purgeStepsOf(s,n,t.sweptObjects??[]),(t.sweptObjects??[]).length>0&&(d=await this.purgeStepsOf(s,n));else{let l=dr(await s.recordedLoads()),u=xs(l,t),f=t.sweptObjects!==void 0&&u?.code==="ALREADY_REMOVED";if(u&&!f||!l){u&&te(this.deps,"frozen:remove:automation","frozen:remove:automation:error",e,new Error(u.message),{code:u.code});return}i=rn(it(l),t.sweptObjects??[],l)}let a=this.targetAutomation,c=await new St(Ms).withTimeout("frozen:remove:automation",()=>a.read(t.targetOrgId,i.delete??[]));this.deps.broker.postToWebview(Ae(this.deps,e,"frozen:remove:automation:response",{loadedAt:t.loadedAt,automation:c,steps:i,...d?{purge:d}:{}}))}catch(s){te(this.deps,"frozen:remove:automation","frozen:remove:automation:error",e,s,{code:s instanceof ut?"TIMEOUT":this.errorCodeFor(s,"AUTOMATION_ERROR"),retryable:!0})}}async purgeStepsOf(e,t,r=[]){if(await e.isStale())return rn([],[]);let n=t.undeletableObjects??{},s=(await e.recordedLoads()).flatMap(i=>it(i)).filter(({objectApiName:i})=>!Object.hasOwn(n,i));return rn(s,r)}async handleRemovePreview(e){let t=st(Ki,e,"frozen:remove:preview:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:remove:preview:error","mapping");if(!r)return;let n=(s,i,d=!1)=>te(this.deps,"frozen:remove:preview","frozen:remove:preview:error",e,s,{code:i,retryable:d});try{let s=r.mappingStore(new pe),i=dr(await s.recordedLoads()),d=xs(i,t);if(d||!i){d&&n(new Error(d.message),d.code);return}let a=it(i).reduce((u,f)=>u+f.ids.length,0),c=this.removalGuardRefusals(i.orgId,a),l;if(await s.isStale())c.push({code:"TARGET_REFRESHED",message:"The target org was refreshed after the load: the records it created went with the refresh, and a removal removes nothing."}),l={...this.unreadPreviewOf(i,t.includeChanged===!0),planned:a};else{let u=await Se(i.orgId,this.deps.orgRegistry,this.deps.orgManager);l=await this.previewRemovalOf(u,i,t.includeChanged===!0)}this.deps.broker.postToWebview(Ae(this.deps,e,"frozen:remove:preview:response",{preview:{...l,refusals:c.map(({message:u})=>u),refusalCodes:c.map(({code:u})=>u)}}))}catch(s){n(s,this.errorCodeFor(s,"REMOVE_PREVIEW_ERROR"),!0)}}removalGuardRefusals(e,t){let r=this.deps.infraServices?.productionGuard;if(!r)return[{...Ot}];let n=this.targetTier(e),s=r.check({orgId:e,orgTier:n,operation:"delete",objectName:"the records a Frozen load created",recordCount:t,module:"frozen"});if(!s.allowed)return[{code:"GUARD_BLOCKED",message:`Operation blocked by Production Guard: ${s.blockedReason??s.impactSummary}`}];let i=r.declinedWithoutAsking(s,n);return i===void 0?[]:[{code:"GUARD_DECLINED",message:`Production Guard asks before this delete, and its question is answered no: ${i} (${s.impactSummary}). Nothing would be deleted.`}]}async previewRemovalOf(e,t,r){let n=it(t),s=await Pn(Bt(e,"frozen:remove:preview"),n,{...$s(t),includeChanged:r,previewOnly:!0});if(!s.preview)throw new Error("The removal preview stopped before it was through.");return{...this.unreadPreviewOf(t,r),planned:n.reduce((i,d)=>i+d.ids.length,0),objects:s.preview.objects.map(i=>({objectApiName:i.objectApiName,planned:i.planned,toDelete:i.toDelete,alreadyGone:i.alreadyGone,changedSince:i.changedSince,keptChanged:i.keptChanged,changedBy:i.changedBy,undeletable:i.undeletable,notVisible:i.notVisible,unread:i.unread,reasons:i.reasons})),userNames:s.preview.userNames}}unreadPreviewOf(e,t){let r=$n(e);return{loadedAt:e.endedAt,includeChanged:t,planned:0,objects:[],userNames:{},...e.removal?{leftBy:e.removal.removedAt}:{},...r.length>0?{keptByThePlatform:r}:{}}}async replaceRefusal(e,t,r=[]){if(e.reload!==!0||e.pilot===!0)return;let n,s={};try{let i=t.mappingStore(new pe),d=await i.recordedLoads();if(d.length===0||await i.isStale())return;if(d.some(a=>!a.created))n="A load recorded before loads kept what they created is in this sas: which of its records it created cannot be told, and a reload leaves in place those it may have linked, so it would not replace that load whole, and no removal takes it. Refresh the sandbox to start again from its copy, or find the records the loading user created that day and delete them yourself, then load without reloading. Nothing was written.";else{let a=await Se(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),c=d.filter(p=>it(p).length>0),l=new Set([...c.flatMap(p=>it(p).flatMap(g=>g.ids.map(h=>h.slice(0,15)))),...r.map(p=>p.slice(0,15))]),u=[];for(let p of c){let g=await Pn(Bt(a,"frozen:load:replace"),it(p),{...$s(p),includeChanged:!1,previewOnly:!0,previewHeld:!0,goesWithParent:h=>typeof h.Id=="string"&&l.has(h.Id.slice(0,15))});if(!g.preview)throw new Error("The removal preview stopped before it was through.");u.push(g.preview);for(let{objectApiName:h,cameAlong:m}of g.preview.objects){if(!m)continue;let y=s[h];s[h]={count:(y?.count??0)+m.count,objects:[...new Set([...y?.objects??[],...m.objects])]}}}let f=Uf(u,e.sweep===!0);f.length>0&&(n=`A removal of the loads this reload replaces would leave ${f.reduce((g,h)=>g+h.left,0)} of their records in the org \u2014 ${f.map(g=>`${g.objectApiName} (${g.left}: ${g.why.join(", ")})`).join("; ")}: loaded again, the dataset would stand beside them, and the reload would delete what was changed since, and what stays under them along with them. Nothing was written. Take the load back first with a removal \u2014 records changed since, and what was added under them since, go too when it is told to include them \u2014 then load the dataset again.`)}}catch(i){return{error:i,code:this.errorCodeFor(i,"LOAD_ERROR"),retryable:!0}}return n!==void 0?{error:new Error(n),code:fo,retryable:!1}:Object.keys(s).length>0?{cameAlong:s}:void 0}refuseRemove(e,t,r){te(this.deps,"frozen:remove","frozen:remove:error",e,new Error(t),{code:r})}async removeLoad(e,t){let{store:r,load:n,plan:s,includeChanged:i,sweep:d,pending:a}=t,c=t.audit??{module:"frozen"},l=n.orgId,u=s.reduce((O,F)=>O+F.ids.length,0),f=(O,F)=>this.refuseRemove(e,O,F),p=this.deps.infraServices?.productionGuard;if(!p){Ze(this.deps,{action:"cleanup_delete",module:c.module,operationId:e.id,orgId:l,outcome:"stopped",code:Ot.code}),f(Ot.message,Ot.code);return}let{check:g,decision:h}=u>0?await Tn(p,{orgId:l,orgTier:this.targetTier(l),operation:"delete",objectName:s.map(O=>O.objectApiName).join(", "),recordCount:u,module:"frozen"}):{check:void 0,decision:"allowed"};if(g&&(h==="refused"||h==="declined")){Ze(this.deps,{action:"cleanup_delete",module:c.module,operationId:e.id,orgId:l,outcome:"stopped",guard:h}),h==="refused"?f(`Operation blocked by Production Guard: ${g.blockedReason??g.impactSummary}`,"GUARD_BLOCKED"):te(this.deps,"frozen:remove","frozen:remove:error",e,new Error("Operation cancelled by user (confirmation declined)."),{code:"GUARD_DECLINED",retryable:!0});return}let m=()=>{if(!a?.signal.aborted)return!1;Ze(this.deps,{action:"cleanup_delete",module:c.module,operationId:e.id,orgId:l,outcome:"stopped",guard:h,code:Ai});let O={status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};return this.deps.broker.postToWebview(Ae(this.deps,e,"frozen:remove:response",{result:O,operationId:e.id})),!0};if(m())return;let y;try{y=await r.isStale()}catch(O){Ze(this.deps,{action:"cleanup_delete",module:c.module,operationId:e.id,orgId:l,outcome:"failure",guard:h}),te(this.deps,"frozen:remove","frozen:remove:error",e,O,{code:this.errorCodeFor(O,"REMOVE_ERROR"),retryable:!0});return}if(y){Ze(this.deps,{action:"cleanup_delete",module:c.module,operationId:e.id,orgId:l,outcome:"stopped",guard:h,code:"TARGET_REFRESHED"}),f("The target org was refreshed after the load: the records it created went with the refresh, and nothing is removed.","TARGET_REFRESHED");return}if(m())return;let R=e.id,j=u>0?`Removing ${u} record(s) a Frozen load created`:"Sweeping what the target's automation made for a Frozen load",T=new AbortController,P=()=>{},_=new Promise((O,F)=>{P=v=>v===void 0?O():F(v)});_.catch(()=>{}),Pr(this.deps,R,"frozen",j),this.registry?.register(R,"frozen",j,_,T),this.liveTracker?.register(R,"frozen",j,u);let q,C,I=[],w;try{let O=await Se(l,this.deps.orgRegistry,this.deps.orgManager),F=new Set([n,...t.alongside].map(S=>S.endedAt));C=d?await this.sweepOfRemoval({conn:O,load:n,store:r,includeChanged:i,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,audit:c,signal:T.signal,guard:p,operationId:R,muted:()=>u===0?w:void 0,sweptWith:F}):void 0;for(let[S,Y]of(C?t.alongside:[]).entries())I.push({loadedAt:Y.endedAt,sweep:await this.sweepOfRemoval({conn:O,load:Y,store:r,includeChanged:i,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,audit:c,signal:T.signal,guard:p,operationId:`${R}-${S+2}`,muted:()=>{},sweptWith:F})});let v=C,A=[...C?[C]:[],...I.map(({sweep:S})=>S)],L=async S=>{let Y=!1;for(let J of A)await S(J)&&(Y=!0);return Y};for(let S of A)await S.ask();let x,B=this.removalAsker,D=rn(s,A.flatMap(S=>S.takes),n);if((t.muteAutomation||B)&&!T.signal.aborted&&(D.delete??[]).length>0){let S=this.targetAutomation,Y=await new St(Ms).withTimeout("frozen:remove automation",()=>S.read(l,D.delete??[])).catch(re=>({unread:ee(re)}));t.muteAutomation&&(x=await Fr(async()=>jr(O),Y,{...this.muteLeases,writes:Or(D)}));let J=await B?.({read:Y,steps:D,mute:x});if(J)throw new hr(J)}w=x?.muted;let G,X=async()=>{let S=x?.prepared;!S||T.signal.aborted||(G=await S.acquire(R),w=G.outcome)},H=await(u===0?(async()=>(await X(),await L(S=>S.first()),await L(S=>S.afterRemoval()),Qi))():Pn(Bt(O,"frozen:remove"),s,{...$s(n),...v?{sweep:S=>L(Y=>Y.first(S)),afterRemoval:S=>L(Y=>Y.afterRemoval(S)),automationMade:v.automationMade}:{},onUndeletable:ji(this.deps,l,"frozen:remove"),beforeFirstWrite:X,includeChanged:i,signal:T.signal,onProgress:(S,Y,J)=>{let re=Math.min(100,Math.round(S/Math.max(Y,1)*100));Li(this.deps,R,re,S,Y,J),T.signal.aborted||this.registry?.updateProgress(R,re),this.liveTracker?.updateProgress(R,re,S,Y,J)}})).finally(async()=>{G&&(w=await G.release())}),N=await C?.settle(),Z=await this.settleReloadSweeps(I),$=n.removal?.removedAt,U=$n(n),oe=ta(H.objects,H.cancelled),se={status:Z.reduce((S,Y)=>Fo(S,Y.result),Fo(oe,N)),includeChanged:i,objects:H.objects,finishedAt:new Date().toISOString(),...$?{leftBy:$}:{},...N?{sweep:N}:{},...Z.length>0?{otherLoadSweeps:Z}:{},...U.length>0?{keptByThePlatform:U}:{},...w?{mutedAutomation:w}:{}};u>0&&Ze(this.deps,{action:"cleanup_delete",module:c.module,operationId:R,orgId:l,outcome:ra({status:oe}),guard:h,objects:na(se.objects),...$?{leftBy:$}:{},...w?{muted:yn(w)}:{}});let me=oa(se,u,n.removal);(H.gone.length>0||Object.keys(H.stamps).length>0||H.span||me)&&(await r.recordRemoval(n.endedAt,{gone:H.gone,stamps:H.stamps,...H.span?{span:H.span}:{},...me?{mark:me}:{}})||this.deps.log("[WARN] frozen:remove: a load wrote its own mapping during the removal; the removal is not recorded in it"));let de=[...N&&Ls(N)?[n.endedAt]:[],...Z.filter(S=>Ls(S.result)).map(S=>S.loadedAt)];await r.letSweptGo(de).catch(()=>!1);let Fe=Ae(this.deps,e,"frozen:remove:response",{result:se,operationId:R});this.deps.broker.postToWebview(Fe);let k=[N,...Z.map(S=>S.result)].find(S=>S!==void 0&&S.status!=="success"),E=se.status==="failure"?"No record this load created could be removed.":u===0&&k?k.refusal??"The sweep left records in the org.":void 0;se.status==="cancelled"||N?.status==="cancelled"||Z.some(S=>S.result.status==="cancelled")?(bt(this.deps,R,{aborted:!0}),this.liveTracker?.cancel(R)):(bt(this.deps,R,{status:E&&u===0?"failure":se.status}),E?(q=new Error(E),this.liveTracker?.fail(R,E)):se.status==="partial"?this.liveTracker?.partial(R):this.liveTracker?.complete(R))}catch(O){q=O,await C?.settle().catch(()=>{});for(let{sweep:v}of I)await v.settle().catch(()=>{});let F=Fn(O)||O instanceof hr?O:void 0;Ze(this.deps,{action:"cleanup_delete",module:c.module,operationId:R,orgId:l,outcome:F?"stopped":"failure",guard:h,...F?{code:F.code}:{}}),te(this.deps,"frozen:remove","frozen:remove:error",e,O,{code:F?.code??"REMOVE_ERROR",retryable:!0}),bt(this.deps,R,{status:"failure"}),this.liveTracker?.fail(R,ee(O))}finally{P(q)}}async reloadSweepsOf(e){if(await e.store.isStale())return[];let t=(await e.store.recordedLoads()).filter(d=>d.created),r=new Set(t.map(d=>d.endedAt)),n={includeChanged:e.includeChanged,sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},s=d=>Cf(d,n),i=[];for(let[d,a]of t.entries())i.push({loadedAt:a.endedAt,judged:s,sweep:await this.sweepOfRemoval({conn:e.conn,load:a,store:e.store,includeChanged:e.includeChanged,sweepLate:e.sweepLate,sweepUntied:e.sweepUntied,signal:e.signal,guard:e.guard,operationId:d===0?e.operationId:`${e.operationId}-${d+1}`,muted:()=>{},sweptWith:r,judged:s,...e.audit?{audit:e.audit}:{}})});return i}async settleReloadSweeps(e){let t=[];for(let{loadedAt:r,sweep:n,judged:s}of e){let i=await n.settle();t.push({loadedAt:r,result:s?s(i):i})}return t}sweepOfRemoval(e){let{conn:t,load:r}=e;return hd({input:()=>this.sweepInputOfLoad(Bt(t,"frozen:remove sweep"),r,e.signal,e.store,e.sweptWith,e.audit?.sasMark),org:Mn(t,"frozen:remove sweep",e.signal),options:{includeChanged:e.includeChanged,removalSpans:r.removalSpans,sweepLate:e.sweepLate,sweepUntied:e.sweepUntied},guard:e.guard,guardOf:{orgId:r.orgId,orgTier:this.targetTier(r.orgId),operation:"delete",module:"frozen"},onGuardDecision:(n,s)=>{let i=e.judged?e.judged(n):n,d=fd(i,"");delete d.forgeId;let a=e.muted();Ze(this.deps,{action:"cleanup_delete",module:e.audit?.module??"frozen",operationId:`${e.operationId}-sweep`,orgId:r.orgId,outcome:i.status==="refused"?"stopped":i.status,...s?{guard:s}:{},...i.status==="refused"?{code:md(s)}:{},objects:ud(i),details:{...d,loadedAt:r.endedAt},...a?{muted:yn(a)}:{}})},keepMade:async(n,s,i)=>{await e.store.recordMade(r.endedAt,n,s,i)}})}async sweepInputOfLoad(e,t,r,n,s=new Set,i=this.sasMarkInUse()){let d=Uo(t),a=this.targetAutomation,c;try{c=await new St(Ms).withTimeout("frozen:remove sweep automation",()=>a.read(t.orgId,d.map(g=>g.objectApiName)))}catch(g){c={error:ee(g)}}let l=t.writtenBetween??await pd(e,d,r),{ties:u,sweptAlong:f}=await this.tiesOfLoad(t,l,n,s,i),p=new Set([...t.mapping.values(),...f].map(g=>g.slice(0,15)));return gd({writtenBetween:l,created:d,remap:p,automation:ld(c),...t.runUserId?{runUserId:t.runUserId}:{},ties:u,...r?{signal:r}:{}},e)}setOtherModuleRuns(e){this.otherModuleRuns=e}auditedLoadsInto(e){try{return kc(new Si(this.deps.configStore).list({orgId:e,limit:Js}).entries)}catch{return[]}}sasMarkInUse(){let e=this.loadConfig();return e?Xn(this.resolveSasDir(e)):void 0}async tiesOfLoad(e,t,r,n,s){let i=[],d=[],a=await r?.recordedLoads().catch(()=>[])??[];for(let l of a){if(l.endedAt===e.endedAt||l.orgId!==e.orgId)continue;let u=Uo(l).flatMap(g=>g.ids);if(n.has(l.endedAt)){d.push(...u);continue}let f=Date.parse(l.writtenBetween?.first??l.startedAt??l.endedAt),p=Date.parse(l.writtenBetween?.last??l.endedAt);i.push({ids:u,from:f,to:Number.isFinite(p)?p:f})}i.push(...await this.otherModuleRuns(e.orgId,t).catch(()=>[])),i.push(...bc(this.auditedLoadsInto(e.orgId),{sasMark:s,own:a.filter(l=>l.orgId===e.orgId)}));let c=wd(e.removalSpans);return{ties:{otherRuns:yd(t,i),...c?{removalBegan:c}:{},...e.madeEarlier?{madeEarlier:e.madeEarlier}:{},...e.lateEarlier?{lateEarlier:e.lateEarlier}:{}},sweptAlong:d}}async handleRemoveSweep(e){let t=st(Gi,e,"frozen:remove:sweep:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:remove:sweep:error","mapping");if(!r)return;let n=(s,i)=>te(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,new Error(s),{code:i});try{let s=r.mappingStore(new pe);if(t.reload===!0){await this.listReloadSweeps(e,s,t,go(r).sasMark);return}let i=await s.recordedLoads(),d=dr(i);if(!d){n("No load into this org was recorded in this sas: there is nothing to sweep.","NO_LOAD");return}if(d.orgId!==t.targetOrgId||d.endedAt!==t.loadedAt){n("Another load was recorded since this one was shown: check what a removal takes now.","LOAD_CHANGED");return}let a=Ko(i,d),c=new Set([d,...a].map(f=>f.endedAt)),{listing:l,otherLoads:u}=await new St(fl).withTimeout("frozen:remove:sweep",async()=>{let f=await Se(d.orgId,this.deps.orgRegistry,this.deps.orgManager),p=Mn(f,"frozen:remove:sweep"),g=async m=>qo(p,await this.sweepInputOfLoad(p,m,void 0,s,c,go(r).sasMark),m.removalSpans),h=[];for(let m of a)h.push({loadedAt:m.endedAt,listing:await g(m)});return{listing:await g(d),otherLoads:h}});this.deps.broker.postToWebview(Ae(this.deps,e,"frozen:remove:sweep:response",{loadedAt:d.endedAt,listing:l,...u.length>0?{otherLoads:u}:{}}))}catch(s){te(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,s,{code:s instanceof ut?"TIMEOUT":this.errorCodeFor(s,"SWEEP_ERROR"),retryable:!0})}}async listReloadSweeps(e,t,r,n){let s=await t.isStale()?void 0:await t.recordedLoads(),i=(s??[]).filter(a=>a.created);if(s&&!s.some(a=>a.endedAt===r.loadedAt)){te(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,new Error("Another load was recorded since this one was shown: check what a reload replaces now."),{code:"LOAD_CHANGED"});return}let d=await new St(fl).withTimeout("frozen:remove:sweep",async()=>{if(i.length===0)return[];let a=await Se(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),c=Mn(a,"frozen:remove:sweep"),l=new Set(i.map(f=>f.endedAt)),u=[];for(let f of i)u.push({loadedAt:f.endedAt,listing:await qo(c,await this.sweepInputOfLoad(c,f,void 0,t,l,n),f.removalSpans)});return u});this.deps.broker.postToWebview(Ae(this.deps,e,"frozen:remove:sweep:response",{loadedAt:r.loadedAt,reload:!0,loads:d}))}sayTheSaltWasMade(e){Ei(this.deps,"info","Frozen dataset salt",`This first extraction made the salt every pseudonym is drawn with (fingerprint ${e}) and keeps it in VS Code's secret storage: every later extraction pseudonymizes the same records the same way. A teammate who extracts this dataset needs the same salt: copy it with "SandForge: Copy Frozen Dataset Salt" and give it to them as you would a password; they set it with "SandForge: Use a Frozen Dataset Salt". Whoever holds it can tell which source value a pseudonym was drawn from.`,{autoDismissMs:null,code:"FROZEN_SALT_CREATED"})}async handleStatus(e){let t=this.loadConfig(),r=this.resolveSasDir(t),n=this.resolveDatasetDir(t),s={present:!1};try{let f=await this.saltKeeper.read();f&&(s={present:!0,fingerprint:new Cn(f.salt).saltFingerprint,source:f.source})}catch{s={present:!1}}let i=null;try{let f=new pe;if(await at(je.join(r,Hr))){let p=await ms(r,f);i={selectedAt:p.selectedAt,rootCount:p.roots.length,total:p.volumetry.total,budgetMax:p.volumetry.budgetMax}}}catch{i=null}let d=null;try{let p=new pe().assertOutsideRepo(je.join(n,"manifest.json"));await at(p)&&(d=gl(zr(JSON.parse(await Pe.readFile(p,"utf8")))))}catch{d=null}let a=this.deps.configStore.get(gr),c=[];try{let f=new pe,p=f.assertOutsideRepo(r);for(let g of await Td(p,f))try{let h=dr(await new _n(p,{guard:f,orgId:g}).recordedLoads());h&&c.push(Pd(h))}catch{}}catch{c.length=0}let l={configured:t!==null,sasDir:r,datasetDir:n,salt:s,mockDetectionConfigured:t?.mockDetection!==void 0,selection:i,manifest:d,lastLoad:a?{status:a.status,orgId:a.targetOrgId,at:a.at}:null,lastLoads:this.lastLoadInfos(),lastVerifies:this.lastVerifyInfos(),...c.length>0?{loadRecords:c}:{},rules:await this.rulesFileInfo(t)},u=Ae(this.deps,e,"frozen:status:response",{status:l});this.deps.broker.postToWebview(u)}};export{np as a,El as b,Ll as c,$p as d,yc as e,Xn as f,wc as g,bc as h,Gp as i,Up as j,Xp as k,rg as l,Rl as m};
|