sandforge 1.84.1 → 1.86.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/lib/{chunk-S42RBRH2.mjs → chunk-22L43JMK.mjs} +1 -1
- package/lib/{chunk-Y2DRK37K.mjs → chunk-2LSGWTWX.mjs} +1 -1
- package/lib/{chunk-24RFOFYT.mjs → chunk-2YJJTQNC.mjs} +1 -1
- package/lib/chunk-34SMB5PA.mjs +10 -0
- package/lib/chunk-35B73566.mjs +7 -0
- package/lib/{chunk-3TZSBHEY.mjs → chunk-35IJ4WEU.mjs} +1 -1
- package/lib/chunk-3EHPAFKV.mjs +7 -0
- package/lib/{chunk-6YL7BNYD.mjs → chunk-3HAVVEXF.mjs} +1 -1
- package/lib/{chunk-6JWWSDM6.mjs → chunk-3I6FXFCN.mjs} +1 -1
- package/lib/{chunk-WUUKFE2U.mjs → chunk-3KJCSYXY.mjs} +1 -1
- package/lib/{chunk-2HVOZUM4.mjs → chunk-3L6DVNCR.mjs} +1 -1
- package/lib/chunk-3LRFPGYZ.mjs +7 -0
- package/lib/{chunk-GWZRR3MM.mjs → chunk-3MVWGL5A.mjs} +1 -1
- package/lib/{chunk-KGU4SVIT.mjs → chunk-4CSBZZAL.mjs} +1 -1
- package/lib/{chunk-JE6SCT6R.mjs → chunk-4NSXPONF.mjs} +1 -1
- package/lib/{chunk-UIOMAX56.mjs → chunk-4VLP6RHC.mjs} +1 -1
- package/lib/{chunk-YA6ATMTB.mjs → chunk-4XROG5CT.mjs} +1 -1
- package/lib/chunk-54V4FVEY.mjs +7 -0
- package/lib/chunk-55OJJT2Q.mjs +7 -0
- package/lib/{chunk-6QE6R6RL.mjs → chunk-5EHHQ5UX.mjs} +1 -1
- package/lib/{chunk-FITPY3L4.mjs → chunk-5JMQXHJ2.mjs} +1 -1
- package/lib/{chunk-W6PN6TJG.mjs → chunk-65AMXOQU.mjs} +1 -1
- package/lib/{chunk-3Q353S2R.mjs → chunk-6HHSAPIM.mjs} +1 -1
- package/lib/chunk-6KVBCFVS.mjs +7 -0
- package/lib/chunk-6NG7C2U3.mjs +476 -0
- package/lib/chunk-6ROL3KBM.mjs +7 -0
- package/lib/{chunk-2JDAOWUW.mjs → chunk-72AWCN7U.mjs} +1 -1
- package/lib/{chunk-JLSIWO4Z.mjs → chunk-7KHA5UIQ.mjs} +1 -1
- package/lib/chunk-7O6EFNQS.mjs +10 -0
- package/lib/{chunk-WWTCWWZI.mjs → chunk-A2CH2QGX.mjs} +1 -1
- package/lib/chunk-A2TXLAC3.mjs +276 -0
- package/lib/chunk-ALWVNR34.mjs +7 -0
- package/lib/{chunk-D4GF4FAB.mjs → chunk-ATBQIE2V.mjs} +1 -1
- package/lib/{chunk-NED4MBIM.mjs → chunk-ATQML7ZK.mjs} +1 -1
- package/lib/chunk-AVY742BJ.mjs +7 -0
- package/lib/{chunk-YWEQQL3C.mjs → chunk-AXTB2HJS.mjs} +1 -1
- package/lib/chunk-BBZUGKBZ.mjs +10 -0
- package/lib/chunk-BIDXK7KA.mjs +7 -0
- package/lib/{chunk-O677VOGO.mjs → chunk-BLMJ4WVI.mjs} +1 -1
- package/lib/{chunk-RE7RYF3B.mjs → chunk-BNHJCJJM.mjs} +1 -1
- package/lib/{chunk-5M5FQ7RP.mjs → chunk-BNPQEQXC.mjs} +1 -1
- package/lib/chunk-C5AUNG6T.mjs +37 -0
- package/lib/{chunk-ETDCBLGU.mjs → chunk-C5EQ7GFC.mjs} +1 -1
- package/lib/{chunk-MJZU3U5O.mjs → chunk-C7CKDZMC.mjs} +61 -61
- package/lib/{chunk-HCGXK7G7.mjs → chunk-CB4U22NR.mjs} +1 -1
- package/lib/chunk-CJAWKLAL.mjs +7 -0
- package/lib/chunk-CL75DEMQ.mjs +9 -0
- package/lib/{chunk-VCUXCK36.mjs → chunk-CLUNF4FK.mjs} +1 -1
- package/lib/chunk-CSMGP53U.mjs +7 -0
- package/lib/{chunk-7YNM6KFZ.mjs → chunk-CT324C7I.mjs} +1 -1
- package/lib/{chunk-7UVKIWKV.mjs → chunk-CZXDJXQP.mjs} +1 -1
- package/lib/{chunk-43TOMFV4.mjs → chunk-D2X6U3MS.mjs} +1 -1
- package/lib/{chunk-M6K34KGF.mjs → chunk-DAUX63UB.mjs} +1 -1
- package/lib/chunk-DB7JNALQ.mjs +10 -0
- package/lib/chunk-DDNCJVZ2.mjs +17 -0
- package/lib/{chunk-FP7CYB2F.mjs → chunk-DLSU66MY.mjs} +1 -1
- package/lib/{chunk-JKJ74BX5.mjs → chunk-DO6PSHQZ.mjs} +1 -1
- package/lib/{chunk-MDMPJEV3.mjs → chunk-DUBECLZV.mjs} +1 -1
- package/lib/{chunk-KZTZDC7H.mjs → chunk-DYHF6DNT.mjs} +1 -1
- package/lib/chunk-E5FSPXYH.mjs +930 -0
- package/lib/{chunk-Q7GIJBCD.mjs → chunk-EGL3I3IX.mjs} +1 -1
- package/lib/chunk-EIYMQPMG.mjs +7 -0
- package/lib/{chunk-RHNTHGNU.mjs → chunk-EUIALBMX.mjs} +1 -1
- package/lib/{chunk-NCZKWSC7.mjs → chunk-FI3R5ZOQ.mjs} +1 -1
- package/lib/{chunk-PAXNWTYK.mjs → chunk-FM4QCTO7.mjs} +1 -1
- package/lib/{chunk-HV7VPEXP.mjs → chunk-FRSIEASH.mjs} +1 -1
- package/lib/{chunk-QAFPQ3YB.mjs → chunk-FV6MOSHD.mjs} +1 -1
- package/lib/chunk-FYG47CNA.mjs +7 -0
- package/lib/chunk-GB6W4Q56.mjs +7 -0
- package/lib/chunk-GEV2DCMK.mjs +7 -0
- package/lib/{chunk-NSQWI7ZY.mjs → chunk-GFB2DNCB.mjs} +1 -1
- package/lib/chunk-GFGMGFSH.mjs +7 -0
- package/lib/{chunk-RGUQOSBU.mjs → chunk-GIFQXB2Q.mjs} +1 -1
- package/lib/{chunk-JAEDM4SI.mjs → chunk-GP5J3DGS.mjs} +1 -1
- package/lib/chunk-GQZEX7LH.mjs +231 -0
- package/lib/{chunk-JSAJS3MY.mjs → chunk-GYDTM62J.mjs} +1 -1
- package/lib/{chunk-OPMO6I45.mjs → chunk-GYFIXUJG.mjs} +1 -1
- package/lib/chunk-GZW2GNFK.mjs +7 -0
- package/lib/chunk-H6BHWAX7.mjs +8 -0
- package/lib/{chunk-EAC5QCE3.mjs → chunk-HDDJ3CVN.mjs} +1 -1
- package/lib/{chunk-5SMWFNE7.mjs → chunk-HDWB4ZOG.mjs} +1 -1
- package/lib/chunk-HGVPBJR6.mjs +7 -0
- package/lib/{chunk-BBRWFKS5.mjs → chunk-HLROVOR6.mjs} +1 -1
- package/lib/{chunk-LKTNQEBS.mjs → chunk-HUOR4M2L.mjs} +1 -1
- package/lib/chunk-HZCS6EED.mjs +8 -0
- package/lib/{chunk-36JOHEJL.mjs → chunk-HZUI56KZ.mjs} +1 -1
- package/lib/chunk-IAB5H7WN.mjs +7 -0
- package/lib/{chunk-X4BXESMQ.mjs → chunk-IQ5UKRHU.mjs} +1 -1
- package/lib/{chunk-54WZUS7J.mjs → chunk-IRQ4WANV.mjs} +1 -1
- package/lib/{chunk-5IZTFMJM.mjs → chunk-IT3DGX37.mjs} +1 -1
- package/lib/chunk-J347SPU6.mjs +49 -0
- package/lib/{chunk-QO53K5W2.mjs → chunk-JANBNTR5.mjs} +1 -1
- package/lib/chunk-JFXQZPRY.mjs +9 -0
- package/lib/{chunk-KAZS5Z6W.mjs → chunk-JRLYWVF4.mjs} +1 -1
- package/lib/{chunk-GKY2JMHY.mjs → chunk-JSNMUTY6.mjs} +1 -1
- package/lib/chunk-JTNJKSAA.mjs +7 -0
- package/lib/{chunk-7WATA4SB.mjs → chunk-JV2LAKWQ.mjs} +1 -1
- package/lib/{chunk-WAPSSYMT.mjs → chunk-JV7K2ZHK.mjs} +1 -1
- package/lib/{chunk-ZBAWJUG2.mjs → chunk-K4TQ7YHX.mjs} +1 -1
- package/lib/chunk-K5PUMHZU.mjs +7 -0
- package/lib/chunk-KH4KLCYG.mjs +7 -0
- package/lib/{chunk-OLCVHL7I.mjs → chunk-KQVLZVOP.mjs} +1 -1
- package/lib/chunk-KWUS7UAV.mjs +19 -0
- package/lib/{chunk-JGZPD4IM.mjs → chunk-L6G73FXM.mjs} +1 -1
- package/lib/{chunk-BAWCOKRW.mjs → chunk-LG466Q5H.mjs} +1 -1
- package/lib/{chunk-GMIGWR6U.mjs → chunk-LHNAR6FC.mjs} +1 -1
- package/lib/chunk-LT4GHEI2.mjs +7 -0
- package/lib/{chunk-EC72TIEG.mjs → chunk-MR262Y3B.mjs} +1 -1
- package/lib/{chunk-LA4KIATH.mjs → chunk-NCCHOV2N.mjs} +1 -1
- package/lib/chunk-NICRSGLS.mjs +7 -0
- package/lib/chunk-NV5QA2HY.mjs +7 -0
- package/lib/{chunk-PR3XCSPO.mjs → chunk-O3GIN5TU.mjs} +1 -1
- package/lib/chunk-O6FHK6NQ.mjs +13 -0
- package/lib/{chunk-M4BLK6HJ.mjs → chunk-O7YIEFG7.mjs} +1 -1
- package/lib/chunk-OCUVAA5E.mjs +7 -0
- package/lib/chunk-OLCS7JCT.mjs +14 -0
- package/lib/chunk-ON7Y63FK.mjs +9 -0
- package/lib/{chunk-N4WPCWJO.mjs → chunk-OO2WY3UB.mjs} +1 -1
- package/lib/{chunk-MSIEU5MR.mjs → chunk-OT2NHL2V.mjs} +1 -1
- package/lib/{chunk-6WX5ZU7Q.mjs → chunk-P2M5ZXWU.mjs} +1 -1
- package/lib/{chunk-GNRSF65U.mjs → chunk-P4YOHLZ4.mjs} +1 -1
- package/lib/chunk-PBHDPTT6.mjs +343 -0
- package/lib/chunk-PE7CHD2W.mjs +7 -0
- package/lib/{chunk-PBY2O6OF.mjs → chunk-PIQ2I67B.mjs} +1 -1
- package/lib/chunk-PKYDNZJK.mjs +7 -0
- package/lib/chunk-PVZ72OOQ.mjs +7 -0
- package/lib/chunk-QACFTHJM.mjs +8 -0
- package/lib/{chunk-J3DND3BC.mjs → chunk-QGVL5EW3.mjs} +1 -1
- package/lib/chunk-QHE2RUWX.mjs +7 -0
- package/lib/{chunk-QKEKG2LD.mjs → chunk-RCW5BZNW.mjs} +1 -1
- package/lib/{chunk-4JE4BYXK.mjs → chunk-RJ6HHG7J.mjs} +1 -1
- package/lib/{chunk-ZQWIVYVM.mjs → chunk-RPTEEI4R.mjs} +1 -1
- package/lib/chunk-RQW5S67A.mjs +7 -0
- package/lib/chunk-RTCMYMED.mjs +7 -0
- package/lib/chunk-RWVX7XSD.mjs +7 -0
- package/lib/{chunk-WY5V5PR3.mjs → chunk-RZOINFNL.mjs} +1 -1
- package/lib/chunk-SOOTWGMQ.mjs +7 -0
- package/lib/chunk-STQ2JMIZ.mjs +7 -0
- package/lib/{chunk-6PD6K7LP.mjs → chunk-SUIPDW5O.mjs} +1 -1
- package/lib/{chunk-TNT27RBG.mjs → chunk-SZOJ7BEJ.mjs} +1 -1
- package/lib/{chunk-4EOHEDFP.mjs → chunk-T542Z54E.mjs} +1 -1
- package/lib/chunk-TAN2CIRI.mjs +21 -0
- package/lib/{chunk-A3MYSOOC.mjs → chunk-TCNBINOG.mjs} +1 -1
- package/lib/chunk-TFDF3DBN.mjs +7 -0
- package/lib/chunk-TICZXC53.mjs +9 -0
- package/lib/chunk-TLX45X5U.mjs +7 -0
- package/lib/{chunk-QTG6LUZT.mjs → chunk-TMIV3IWH.mjs} +1 -1
- package/lib/chunk-TQ6HEJ73.mjs +11 -0
- package/lib/chunk-TTU5EQZ6.mjs +7 -0
- package/lib/chunk-TYUYPFDJ.mjs +7 -0
- package/lib/chunk-TZXYVMZC.mjs +7 -0
- package/lib/chunk-UCUFLFNK.mjs +7 -0
- package/lib/chunk-UK3QLBHW.mjs +7 -0
- package/lib/{chunk-IZGCEOYO.mjs → chunk-UM2B4GR7.mjs} +1 -1
- package/lib/chunk-UZFTTNOP.mjs +7 -0
- package/lib/chunk-V3AXSKSU.mjs +7 -0
- package/lib/chunk-VA6EEI6X.mjs +21 -0
- package/lib/{chunk-OFTT7J2M.mjs → chunk-VFKG2G37.mjs} +1 -1
- package/lib/chunk-VJNEW5MQ.mjs +7 -0
- package/lib/{chunk-L53JWJ3S.mjs → chunk-VKREON6Q.mjs} +1 -1
- package/lib/{chunk-NOBQTEQD.mjs → chunk-VNNDYPBL.mjs} +1 -1
- package/lib/{chunk-ZJW6YOMV.mjs → chunk-VRBETPHY.mjs} +1 -1
- package/lib/{chunk-EPFCERGL.mjs → chunk-VT6P3X6R.mjs} +1 -1
- package/lib/{chunk-ZV7ZFQQC.mjs → chunk-VUTQY76O.mjs} +1 -1
- package/lib/chunk-WF5S4FW5.mjs +7 -0
- package/lib/{chunk-Z4LKKOFY.mjs → chunk-WJGK6VGU.mjs} +1 -1
- package/lib/{chunk-5CRLRHOJ.mjs → chunk-WJHMB3SL.mjs} +1 -1
- package/lib/{chunk-OUZQPYT3.mjs → chunk-WQCXOZEJ.mjs} +1 -1
- package/lib/{chunk-L2E5WBGD.mjs → chunk-WVVFR4E3.mjs} +1 -1
- package/lib/{chunk-PWRJRL5U.mjs → chunk-XBYXT74L.mjs} +1 -1
- package/lib/chunk-XJE3LJHP.mjs +7 -0
- package/lib/{chunk-CPQIZGG5.mjs → chunk-XV4CVZYD.mjs} +1 -1
- package/lib/chunk-Y37ED7AS.mjs +7 -0
- package/lib/{chunk-YTLUYSMF.mjs → chunk-YGBNZYT4.mjs} +1 -1
- package/lib/{chunk-4CVUUVGJ.mjs → chunk-YGTOX7IL.mjs} +1 -1
- package/lib/{chunk-OMNMLKDT.mjs → chunk-YJ27WHKR.mjs} +1 -1
- package/lib/chunk-YRULC27A.mjs +7 -0
- package/lib/{chunk-RMFU4BAL.mjs → chunk-YSVAHT4Q.mjs} +4 -4
- package/lib/chunk-YTOTMJTY.mjs +15 -0
- package/lib/{chunk-B63POIPQ.mjs → chunk-YZKZC62O.mjs} +1 -1
- package/lib/{chunk-DPMRIMUC.mjs → chunk-YZQN7BRB.mjs} +1 -1
- package/lib/{chunk-7SQSWVAU.mjs → chunk-Z5IUK2QO.mjs} +1 -1
- package/lib/{chunk-M2ABR4JM.mjs → chunk-ZEGSMW5A.mjs} +1 -1
- package/lib/{chunk-PR42EZSR.mjs → chunk-ZIKLQZBG.mjs} +1 -1
- package/lib/chunk-ZVU7MD2S.mjs +7 -0
- package/lib/sandforge-autopilot.mjs +33 -27
- package/lib/sandforge-backup.mjs +19 -19
- package/lib/sandforge-checkpoint.mjs +1 -1
- package/lib/sandforge-cleanup.mjs +1 -1
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +32 -14
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +11 -13
- package/lib/sandforge-env.mjs +105 -105
- package/lib/sandforge-frozen.mjs +1 -1
- package/lib/sandforge-mcp.mjs +2 -2
- package/lib/sandforge-monitor.mjs +1 -1
- package/lib/sandforge-pipeline.mjs +13 -13
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge-users.mjs +13 -15
- package/lib/sandforge.mjs +1 -1
- package/lib/sf/sandforge/dataops.mjs +2 -2
- package/lib/sfPlugin.mjs +1 -1
- package/oclif.manifest.json +1 -1
- package/package.json +1 -1
- package/lib/chunk-23SEDORH.mjs +0 -11
- package/lib/chunk-26POJDIT.mjs +0 -7
- package/lib/chunk-2AZQHBEF.mjs +0 -7
- package/lib/chunk-2METQHGG.mjs +0 -7
- package/lib/chunk-2WFIVO4F.mjs +0 -13
- package/lib/chunk-2YHZBUZE.mjs +0 -7
- package/lib/chunk-326AJTIU.mjs +0 -272
- package/lib/chunk-3PVRGTVK.mjs +0 -7
- package/lib/chunk-5XTUSN72.mjs +0 -8
- package/lib/chunk-6I6TWNV5.mjs +0 -7
- package/lib/chunk-6O222PW6.mjs +0 -7
- package/lib/chunk-6ZLKIT3H.mjs +0 -7
- package/lib/chunk-7QYHEHMA.mjs +0 -9
- package/lib/chunk-B3FBHVNN.mjs +0 -21
- package/lib/chunk-BEA27DLS.mjs +0 -7
- package/lib/chunk-BRY3PLIZ.mjs +0 -7
- package/lib/chunk-CBH3TOWK.mjs +0 -341
- package/lib/chunk-CVHNXJH3.mjs +0 -7
- package/lib/chunk-DGDRQRCW.mjs +0 -7
- package/lib/chunk-DUN2EPRC.mjs +0 -7
- package/lib/chunk-E3A3LOCY.mjs +0 -7
- package/lib/chunk-F2424IKX.mjs +0 -7
- package/lib/chunk-F3AQW6IU.mjs +0 -7
- package/lib/chunk-FNJ4SGWO.mjs +0 -7
- package/lib/chunk-GOOVPVWX.mjs +0 -7
- package/lib/chunk-H2BHESDA.mjs +0 -9
- package/lib/chunk-H4CGM6YO.mjs +0 -7
- package/lib/chunk-HIDW7FNV.mjs +0 -9
- package/lib/chunk-HSBXRQTI.mjs +0 -7
- package/lib/chunk-HUZPBE47.mjs +0 -7
- package/lib/chunk-I6E6T6YY.mjs +0 -7
- package/lib/chunk-IUM4NFKI.mjs +0 -10
- package/lib/chunk-IVFVNNGB.mjs +0 -37
- package/lib/chunk-JCFBFF4Y.mjs +0 -7
- package/lib/chunk-JTJK2D36.mjs +0 -7
- package/lib/chunk-KB4ZHM4Q.mjs +0 -10
- package/lib/chunk-KJWFYBMU.mjs +0 -15
- package/lib/chunk-LC3NDW4N.mjs +0 -7
- package/lib/chunk-OM5NORJG.mjs +0 -7
- package/lib/chunk-OVNMB6Q2.mjs +0 -7
- package/lib/chunk-PEDQPM2P.mjs +0 -926
- package/lib/chunk-PH7SP4YK.mjs +0 -21
- package/lib/chunk-PMN4PAC3.mjs +0 -19
- package/lib/chunk-PMWAFDUB.mjs +0 -48
- package/lib/chunk-PPLVFX6N.mjs +0 -7
- package/lib/chunk-PZBZ7MNC.mjs +0 -7
- package/lib/chunk-QROPNEGY.mjs +0 -14
- package/lib/chunk-RGBGUCJA.mjs +0 -156
- package/lib/chunk-RKTFFCNS.mjs +0 -7
- package/lib/chunk-ROV3QXEF.mjs +0 -475
- package/lib/chunk-RT47RKLY.mjs +0 -7
- package/lib/chunk-SI267LYR.mjs +0 -8
- package/lib/chunk-SRPWW4A2.mjs +0 -10
- package/lib/chunk-T3G6VZNS.mjs +0 -7
- package/lib/chunk-T63U4OZJ.mjs +0 -7
- package/lib/chunk-TEIBWMJM.mjs +0 -7
- package/lib/chunk-TW3N6W5Z.mjs +0 -7
- package/lib/chunk-UBIKR5VO.mjs +0 -7
- package/lib/chunk-UI3JQVRU.mjs +0 -8
- package/lib/chunk-UX3BVH2Y.mjs +0 -7
- package/lib/chunk-VINGECAJ.mjs +0 -10
- package/lib/chunk-VOXJHJIE.mjs +0 -7
- package/lib/chunk-WB2RIVO3.mjs +0 -7
- package/lib/chunk-WXDLQT2O.mjs +0 -10
- package/lib/chunk-XBQGZGWR.mjs +0 -7
- package/lib/chunk-XGGOUNPP.mjs +0 -7
- package/lib/chunk-XKWW3GKF.mjs +0 -7
- package/lib/chunk-YHR4WQPR.mjs +0 -7
- package/lib/chunk-ZQQXSCVI.mjs +0 -7
- package/lib/chunk-ZRUDYB7O.mjs +0 -7
package/lib/chunk-B3FBHVNN.mjs
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
import { createRequire as __sandforgeRequire } from 'node:module';
|
|
2
|
-
import { fileURLToPath as __sandforgePath } from 'node:url';
|
|
3
|
-
import { dirname as __sandforgeDirname } from 'node:path';
|
|
4
|
-
const require = __sandforgeRequire(import.meta.url);
|
|
5
|
-
const __filename = __sandforgePath(import.meta.url);
|
|
6
|
-
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{a as Dn,b as Od,c as xn,d as Fr}from"./chunk-YWEQQL3C.mjs";import{a as Nn,b as fd,c as Cn,d as pd,f as md,g as Mn,i as yd,j as wd}from"./chunk-LA4KIATH.mjs";import{a as jr,b as gd,c as xo,d as ot,e as zn,f as sr,g as $o,h as hd}from"./chunk-Y2DRK37K.mjs";import{j as bd,k as Rd,n as kd,o as Id,p as vd}from"./chunk-GMIGWR6U.mjs";import{l as ka}from"./chunk-PWRJRL5U.mjs";import{c as ud,d as ue}from"./chunk-UV74P4H2.mjs";import{k as ld}from"./chunk-IZGCEOYO.mjs";import{i as Ia}from"./chunk-24RFOFYT.mjs";import{e as Ra,f as jo}from"./chunk-UIOMAX56.mjs";import{G as dd,N as Do,O as cd,i as td,l as Ln,m as rd,n as nd,o as od,p as sd,v as id}from"./chunk-6I6TWNV5.mjs";import{l as ad}from"./chunk-UX3BVH2Y.mjs";import{a as Qi,b as Sn}from"./chunk-XCA5AONB.mjs";import{$a as vo,Dc as On,Ec as So,Xa as Ai,Ya as Pi,Za as Ti,_a as ji,a as yi,ab as Fi,b as Ot,bb as Ei,cb as Li,db as Ni,eb as Ci,g as wo,h as wi,j as Se,k as bi,l as vr,m as Ri,n as bt,o as te,s as bo,wc as nt}from"./chunk-XGGOUNPP.mjs";import{a as wn}from"./chunk-CE6ZDGBB.mjs";import{a as sa,b as ia}from"./chunk-BOGNK4LV.mjs";import{$a as ed,Ia as Ja,Oa as Xa,R as Ya,Va as Za,Xa as Mo,_a as Qa,a as Ys,b as Js,i as qa,j as Wa,o as Co,va as zo}from"./chunk-IVFVNNGB.mjs";import{a as Gi,b as Oo,c as Ui,d as Ki,e as Vi,l as Xi,m as Zi}from"./chunk-VINGECAJ.mjs";import{A as $i,B as _i,I as Bi,M as Mt,N as qi,O as kn,P as Wi}from"./chunk-H4CGM6YO.mjs";import{a as Ga,b as No,c as Tr,d as Fn,h as Ua,i as En,j as Ka,l as Va,m as Ha}from"./chunk-TEIBWMJM.mjs";import{c as In,d as vn}from"./chunk-T63U4OZJ.mjs";import{e as ya,h as wa,j as ba}from"./chunk-5XTUSN72.mjs";import{f as ma,i as To,j as Tn}from"./chunk-26POJDIT.mjs";import{a as Hi,c as Yi,d as Ji,r as Po}from"./chunk-FP7CYB2F.mjs";import{H as Ao,L as da,i as aa,k as Pn}from"./chunk-KGU4SVIT.mjs";import{r as Oe}from"./chunk-MSIEU5MR.mjs";import{b as ea,c as ta,g as ra}from"./chunk-LC3NDW4N.mjs";import{Cc as xa,Dc as $a,Ec as _a,Oc as Ba,Ya as Fo,Zb as ja,dc as Fa,fc as Ea,gb as Eo,gc as La,hb as va,i as Or,j as An,k as na,kc as Na,lb as Oa,lc as Ca,mb as Lo,nb as Sa,o as oa,oc as za,pb as Pr,pc as Ma,q as Sr,qb as Aa,qc as Da,rb as Pa,tb as Ta}from"./chunk-KB4ZHM4Q.mjs";import{e as gi,f as hi,i as Xe,j as mi}from"./chunk-23SEDORH.mjs";import{q as jn}from"./chunk-3Q353S2R.mjs";import{a as lt,b as St}from"./chunk-VV3B6IC3.mjs";import{a as Nt}from"./chunk-4TLYUZD5.mjs";import{b as ca,d as la,f as Ar,g as ua,h as fa,i as pa,j as ga,p as ha}from"./chunk-RHNTHGNU.mjs";import{i as ki}from"./chunk-INIT2UKJ.mjs";import{h as Mi}from"./chunk-D4GF4FAB.mjs";import{b as Di,d as xi}from"./chunk-CVHNXJH3.mjs";import{b as bn}from"./chunk-HFSBDM7B.mjs";import{b as vi,c as ct,e as Ro,g as Oi,h as ko,i as Si,j as Io}from"./chunk-OHEOJISY.mjs";import{a as Ii}from"./chunk-EADHKH3A.mjs";import{h as or}from"./chunk-M6K34KGF.mjs";import{$ as di,E as ni,F as Ct,G as wt,I as mo,L as oi,M as si,N as ii,Y as yo,Z as ai,a as kr,b as Je,c as Qt,d as gn,da as zt,ea as ci,f as er,fa as li,g as Xs,ga as ui,ha as fi,ia as pi,ja as rr,k as Zs,ka as nr,l as ho,m as Qs,n as ei,o as ti,p as ri,q as Ve,r as Ue,s as hn,t as Ir,u as mn,v as tr,z as yn}from"./chunk-TNT27RBG.mjs";import{a as Me,h as me}from"./chunk-TZE3Y7IQ.mjs";import{b as Q}from"./chunk-CA5NAXSU.mjs";import{a as zi}from"./chunk-S42RBRH2.mjs";import{b as Rn}from"./chunk-UNDIBZWG.mjs";import{Cc as sn,Ec as qe,Fc as an,Gc as yt,Hc as Et,Ic as dn,Lc as Ge,Mc as Ye,Nc as cn,Oc as ze,Pc as Zt,Pd as Vs,Qc as Ws,Sc as Gs,Tc as ln,Wd as Hs,Yd as Rr,Zc as Us,dd as Ks,ee as Lt,fe as pn,id as un,jd as fn,s as Bs,yc as qs,zc as Xt}from"./chunk-PMWAFDUB.mjs";import{b as Ce,e as Ds,f as on,k as mt,l as rt,s as xs,u as $s,v as _s,z as go}from"./chunk-WZQEK4WT.mjs";import{createHash as Sd}from"node:crypto";import*as _n from"node:fs/promises";import*as Lr from"node:path";import*as Rt from"node:fs/promises";import*as At from"node:path";var Er="platform-records.json",_o=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"}},$n=class{guard;constructor(e){this.guard=e??new ue}async write(e,t,r,n){if(!n.passed)throw new _o(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,c)=>{let f=this.guard.assertOutsideRepo(l);await Rt.writeFile(f,`${JSON.stringify(c)}
|
|
8
|
-
`,"utf8"),d.push(f)},u=this.guard.assertOutsideRepo(At.join(s,"manifest.json"));await Rt.writeFile(u,xn(r),"utf8"),d.push(u);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,Er),{...t.standardPricebook?{standardPricebook:t.standardPricebook}:{}}),{dir:s,files:d}}};var Bo="manifest.json",ll=["record-types.json","personcontact-sidecar.json",Er],qo="data",ul="sha256:";async function Bf(o){let e=await Wo(Lr.join(o,Bo));if(e===void 0)throw new Error(`No frozen dataset at ${o}: it holds no ${Bo}.`);let t=[{name:Bo,content:pl(e)}];for(let n of ll){let s=await Wo(Lr.join(o,n));s!==void 0&&t.push({name:n,content:s})}for(let n of await fl(Lr.join(o,qo))){let s=await Wo(Lr.join(o,qo,n));s!==void 0&&t.push({name:`${qo}/${n}`,content:s})}let r=Sd("sha256");for(let{name:n,content:s}of t.sort((i,d)=>Ad(i.name,d.name)))r.update(`${n}\0${Sd("sha256").update(s).digest("hex")}
|
|
9
|
-
`);return`${ul}${r.digest("hex")}`}async function fl(o){let e;try{e=await _n.readdir(o)}catch(t){if(t.code==="ENOENT")return[];throw t}return e.filter(t=>t.endsWith(".json"))}async function Wo(o){try{return await _n.readFile(o)}catch(e){if(e.code==="ENOENT")return;throw e}}function pl(o){let e;try{e=JSON.parse(o.toString("utf8"))}catch{return o}if(Uo(e)&&Uo(e.controls)){let t={...e.controls};delete t.dryRunLoad,e={...e,controls:t}}return Buffer.from(Go(e),"utf8")}function Go(o){return Array.isArray(o)?`[${o.map(Go).join(",")}]`:Uo(o)?`{${Object.keys(o).sort(Ad).map(t=>`${JSON.stringify(t)}:${Go(o[t])}`).join(",")}}`:JSON.stringify(o)??"null"}function Uo(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function Ad(o,e){return o===e?0:o<e?-1:1}var He=class extends Error{constructor(t,r,n={}){super(r);this.code=t;this.params=n;this.name="LoadGuardError"}code;params};function ir(o){return o.objects.reduce((e,t)=>e+t.records.length,0)}function Nr(o){return o.orgName??o.orgId}async function Pd(o){if(Ko(o),o.protectedOrgIds?.includes(o.orgId))throw new He("protected-environment",`Refusing frozen-dataset load on protected environment ${Nr(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 He("source-is-target",`Refusing frozen-dataset load on ${Nr(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 He("unmocked-callouts",`Refusing frozen-dataset load on ${Nr(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(ir(o.dataset)===0)throw new He("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 Ko(o){if(!(o.orgTier==="staging"&&o.stagingReplay===!0)){if(o.orgTier==="staging")throw new He("non-sandbox",`Refusing frozen-dataset load on ${Nr(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 He("non-sandbox",`Refusing frozen-dataset load on ${o.orgTier} org ${Nr(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 Cr=class{constructor(e,t){this.orgAccess=e;this.config=t}orgAccess;config;async areCalloutsMocked(e){let t=`SELECT Id FROM ${me(this.config.metadataTypeApiName)} WHERE ${me(this.config.isMockedFieldApiName)} = true LIMIT 1`;try{return(await this.orgAccess.query(e,t)).length>0}catch{return!1}}};var Bn=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={},u=e.accountKindOf?.(d.referenceId);for(let[l,c]of Object.entries(d.fields)){if(u!==void 0&&un(Ve,l,u))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===Hi){c!=null&&c!==""&&this.countRemoval(r,l,"may-hold-masks");continue}let p=c;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,u)=>!e.linked?.has(e.records[u].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 u=s?fn(Ve,a.name):void 0;if(!a.createable||a.nillable&&u===void 0||a.defaultedOnCreate)continue;let l=r.filter((f,p)=>u===void 0||tr(u,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}:{},...u?{accountKind:u}:{},...!p&&a.type?{fieldType:a.type}:{},...!p&&g.length>0?{activeValues:g}:{}})}}let d=ln(e.objectApiName,a=>e.describe.fields.some(u=>u.name===a&&u.createable),a=>r.some(u=>u[a]!==void 0&&u[a]!==null&&u[a]!==""));if(d!==void 0&&!n.some(a=>a.field===d)){let a=e.describe.fields.find(u=>u.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",u=a?s.split(";"):[s],l=e.describe.fields.find(y=>y.name===t),c=new Set((l?.picklistValues??[]).filter(y=>y.active).map(y=>y.value)),f=u.filter(y=>!c.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,u,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=u.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,u,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})}};var zr="Opportunity",Mr="SyncedQuoteId",gl="OpportunityLineItem",Vo="QuoteLineItem";function Ho(o,e){let t=(d,a)=>{let u=new Map;for(let{referenceId:l,fields:c}of o.get(d)??[]){let f=c[a];typeof f!="string"||f===""||!e(l)||u.set(f,(u.get(f)??0)+1)}return u},r=t(gl,"OpportunityId"),n=t(Vo,"QuoteId"),s=new Set((o.get("Quote")??[]).map(d=>d.referenceId)),i=[];for(let{referenceId:d,fields:a}of o.get(zr)??[]){let u=a[Mr];if(typeof u!="string"||!s.has(u)||!e(d)||!e(u))continue;let l=r.get(d)??0,c=n.get(u)??0;l>c&&i.push({opportunity:d,quote:u,products:l,lines:c})}return i}function Td(o,e,t=!1){if(o.length===0)return;let r=o.length===1,n=o.reduce((l,c)=>l+c.products,0),s=o.reduce((l,c)=>l+c.lines,0),i=r?"its":"their",d=r?"the quote's":"the quotes'",a=s===0?`none of ${d} lines`:`${s} of ${d} lines`,u=e&&s===0?", which excludedObjects leaves out":"";return{objectApiName:zr,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}${u} \u2014 synced, the platform replaces an opportunity's products with its quote's lines; ${Mr} left empty, the products kept`}}var Ze=class extends Error{constructor(t,r,n){super(t);this.gaps=r;this.recordTypesUntold=n;this.name="LoadConfigError"}gaps;recordTypesUntold;refusedBeside},xr=class extends Error{constructor(e){super(e),this.name="LoadRecordsExceededError"}},ar=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 hl(o){return o.perObject.reduce((e,t)=>e+t.toInsert,0)}function ml(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 st=class extends Error{constructor(t,r=!0){super(r?`The load was cancelled ${Bd(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},xt=class extends Error{constructor(t,r,n){super(yl(t,r,n),{cause:t});this.written=r;this.name="FrozenLoadFailedError",this.mappingKept=n===void 0}written;mappingKept};function yl(o,e,t){return`${Q(o)}
|
|
10
|
-
The load failed ${Bd(e,t)}`}function Bd(o,e){let t=new Map,r=(a,u)=>{u!==0&&t.set(a,(t.get(a)??0)+u)};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,u)=>a+u,0),s=[...Object.values(o.purge.deleted),...Object.values(o.purge.deactivated)].reduce((a,u)=>a+u,0),i=[...n>0?[`created ${n} record(s) (`+[...t].map(([a,u])=>`${a}: ${u}`).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 qd(o,e){let t=[];for(let[r,n]of o.givenRules){let s=[],i={};for(let{referenceId:a,fields:u}of o.alignedByObject.get(r)??[]){if(!gt(u.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 Wd(o){return{namespacePrefix:o.namespacePrefix,developerName:o.developerName}}function wl(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`}async function bl(o,e){if(!e.mappingKept())try{await e.keepMapping()}catch(t){return new xt(o,e.written,Q(t))}return new xt(o,e.written)}function Gd(o,e,t){let r=t.map(n=>ct(n.namespacePrefix,n.developerName));return new Ze(`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 Rl(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=ko(n.recordTypeDeveloperName,r,Wd);if(d&&"found"in d)continue}let i=r.filter(d=>d.name===s);if(i.length>1)return Gd(e,s,i)}}}var Ud="Opportunity",Wn="placeholder:",Jo=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 kl(o){if(o.startsWith(Wn))return o.split(":")[1]??"Unknown";let e=o.lastIndexOf("-");return e>0?o.slice(0,e):"Unknown"}function Il(o){return typeof o=="number"?String(o):typeof o=="boolean"?o?"TRUE":"FALSE":`'${Me(String(o))}'`}var Pt=200;function pe(o){return o.slice(0,15)}var vl=["CreatedDate","LastModifiedDate"],Ol=[["CreatedDate","LastModifiedDate","SystemModstamp"],["SystemModstamp"]];function Dt(o){return typeof o=="string"?Date.parse(o):Number.NaN}function jd(o){return o.success||o.errors.some(e=>e.includes("ENTITY_IS_DELETED"))}function Fd(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 Ed(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&&pe(s.recordId)===pe(e.id));n?n.errors=[...n.errors,r]:o.failures.push({objectApiName:e.objectApiName,recordId:e.id,errors:[r]})}function Yo(o,e){let t=(o.notInserted??0)+(e.notInserted??0),r=[o.writtenWithoutFields,e.writtenWithoutFields].reduce((s,i)=>i?To(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 Sl(o){if(o.size===0)return;let e=0,t=0;for(let r of o.values())r.success?e++:xi(r.errors,r.errorDetails)&&t++;return{rows:o.size,written:e,stillLocked:t}}function Ld(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 Gn(o,e="inserted"){return o>0?`, ${o} not ${e}: the load was cancelled first`:""}function Xo(o,e="inserted"){return o>0?`, ${o} not ${e}: the load failed`:""}function Al(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 ${Q(r)}`}}var Nd={phase:"guards",status:"started",progress:0,message:"Running the safety checks"};function qn(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}${Xo(i,d)}${a} \u2014 ${Q(e.cause)}`}:{phase:t,status:Al(s,i),progress:r,message:`${n}${Gn(i,d)}${a}`}}var Dr={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 Pl(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 Kd(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)||!Ir(r.fields))continue;let n=r.fields.AccountId;t.set(r.referenceId,typeof n=="string"&&e.get(n)===Ve?n:"")}return t}function Tl(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===Ve)?.records??[]){let r=t.fields.LastName;(Ir(t.fields)||r!=null)&&e.add(t.referenceId)}return e}function Un(o,e,t){let r=o.accountKind;return r===void 0?[...e]:e.filter(n=>tr(r,t(n.referenceId)))}var $r=class{constructor(e){this.deps=e;this.config=e.config??{},this.sasGuard=e.sasGuard??new ue}deps;config;sasGuard;journal;async gateLoad(e){try{await this.passEntryGuards(e)}catch(s){throw e.onProgress?.(Nd),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=Rl(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:ir(e.dataset)},module:"frozendataset"})}passEntryGuards(e){return Pd({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}}async loadKeeping(e,t){try{return await this.loadInto(e,t)}catch(r){t.endOpenLine?.(r);let n=t.load;throw r instanceof st||!n?.wroteSome()?r:await bl(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 ar(d)}let i=zd(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:u,...l}of await t(n))u?i.set(a,[...i.get(a)??[],l.name]):s.set(a,[...s.get(a)??[],l])}catch(a){return{...e,validationRulesUnread:Q(a)}}let d=new Set(r);return{...e,perObject:e.perObject.map(a=>{if(a.toInsert===0)return a;let u=s.get(a.objectApiName)??[],l=i.get(a.objectApiName)??[];return{...a,...u.length>0?{validationRules:u}:{},...l.length>0?{validationRulesOnChange:l}:{}}}),placeholders:e.placeholders.map(a=>{let u=d.has(a.placeholderObjectApiName)?[]:s.get(a.placeholderObjectApiName)??[];return u.length>0?{...a,validationRules:u}:a})}}async prepare(e,t,r){let{orgId:n}=e;t(Nd);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(K){throw t(pt("pilot",4,"Root folder not selected",K)),K}let _=i.objects.reduce((K,Z)=>K+Z.records.length,0);t({phase:"pilot",status:"done",progress:4,message:`Root folder selected: ${_} record(s)`})}let d=es(i),a=Ll(e.dataset),u=Kd(i,d),l=$l(i,d,u),c=Ys(l),f=c.flat(),p=new er,g=new er(xl),h={...i,objects:i.objects.map(_=>({..._,records:_.records.filter(K=>!p.leaveOut(_.objectApiName,K.referenceId,Zs(_.objectApiName,K.fields,typeof K.fields.RelationId=="string"?d.get(K.fields.RelationId):void 0))&&!g.leaveOut(_.objectApiName,K.referenceId,K.fields))}))},m=new Map,y=new Set,k=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)k.add(_);t({phase:"reload",status:"done",progress:10,message:`Reference data: ${y.size} reused`}),r.endOpenLine=void 0}if(h.standardPricebook||xd(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(K){throw t(pt("catalog",11,"Catalog not looked up",K)),K}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 N=[],T=new Map,P=new Map,x=new Map;for(let _ of h.objects){let K=[];for(let Z of _.records)K.push(await this.resolveRecordType(e,i,_.objectApiName,Z,P,N,x));T.set(_.objectApiName,K)}let U=new Bn(this.deps.orgAccess),C={objectResults:[],excludedObjects:[],removals:[],adjustments:[],recordTypeIssues:N},I=new Map,w=new Map,O=new Map,j=new Map,v=new Map,A,F=Tl(i),$=_=>F.has(_)?A===!1?"personAsBusiness":"person":"business",D=new Map,G=new Map,V=e.writeEncrypted!==!0&&e.manifest?.coverage?.encryptedNotKept===void 0;for(let _ of h.objects){let K=_.objectApiName;if(_.records.length===0)continue;let Z=_.records.filter(S=>!y.has(S.referenceId)),re=(S,J,ne)=>{C.excludedObjects.push({objectApiName:K,reason:S,cause:ne}),v.set(K,{objectApiName:K,fromFiles:i.objects.find(X=>X.objectApiName===K)?.records.length??_.records.length,inserted:0,reused:_.records.length-Z.length,skippedDuplicates:[],failed:Z.map(X=>({objectApiName:K,referenceId:X.referenceId,errors:[J]}))}),Z.length!==0&&t({phase:"align",objectName:K,status:"error",progress:12,message:`Skipped ${K} \u2014 ${S}`})},ge;try{ge=await this.deps.orgAccess.describe(n,K)}catch(S){let J=`Not present in target org: ${S instanceof Error?S.message:String(S)}. 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`;re(J,J,"notInTarget");continue}if(K===Ve&&(A=ge.fields.some(S=>S.name===hn)),ge.createable===!1&&Z.length>0){re(`Not createable in target org: ${Z.length} record${Z.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","notCreateable");continue}O.set(K,new Set(ge.fields.filter(S=>S.updateable===!1).map(S=>S.name)));let _e=ge.fields.filter(S=>S.lookupFilter!==void 0&&S.createable&&(S.referenceTo?.length??0)>0).map(S=>({field:S.name,referenceTo:[...S.referenceTo??[]]}));_e.length>0&&j.set(K,_e);let De=bn(ge.recordTypeInfos);if(De.some(S=>!S.master)){let S=Ka(En(De));G.set(K,{types:De,...S?{predicted:S}:{}})}let R=zl(K,ge,this.config);R.length>0&&D.set(K,R),w.set(K,new Set(ge.fields.filter(S=>S.createable&&!S.nillable&&!S.defaultedOnCreate&&(S.referenceTo?.length??0)>0).map(S=>S.name)));let L=await U.alignObject({orgId:n,objectApiName:K,records:T.get(K)??[],describe:ge,resolvedRecordTypes:P,ruleFor:(S,J)=>this.picklistRuleFor(S,J),linked:y,...K===Ve?{accountKindOf:$}:{},...V?{leaveOutEncrypted:V}:{}});C.objectResults.push(L),C.removals.push(...L.removals),C.adjustments.push(...L.adjustments),I.set(K,L.alignedRecords.map((S,J)=>({referenceId:(T.get(K)??[])[J].referenceId,fields:S})))}let H=await this.linkWhatThePlatformKeeps(n,C.objectResults,I,a,m,y,$),E=e.reload||e.linkByKeys?await this.reuseByKeysAsWritten(n,h,C.objectResults,I,a,m,y,$):{linked:[],said:[],leftEmpty:[]};for(let _ of[...H.linked,...E.linked])k.add(_);let W=[...H.said,...E.said];t({phase:"align",status:"done",progress:20,message:`Schema aligned${W.length>0?` \u2014 ${W.join("; ")}`:""}`}),r.endOpenLine=void 0;let Y=new er(Ml(D));Cl(I,w,[p,g,Y]);for(let _ of C.objectResults){let K=(I.get(_.objectApiName)??[]).filter(Z=>!y.has(Z.referenceId));_.missingRequired=_.missingRequired.filter(Z=>Un(Z,K,$).some(re=>gt(re.fields[Z.field])))}t({phase:"placeholders",status:"started",progress:22,message:"Checking required fields"});let ie=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:u,groups:c,groupOrder:f,leftToThePlatform:p,untypedFeedItems:g,heldForExclusions:Y,loading:h,mapping:m,reused:y,reusedByKeys:k,ranks:a,recordTypeIssues:N,alignment:C,alignedByObject:I,requiredLookups:w,fixedAtInsert:O,filteredLookups:j,lostObjects:v,targetHasPersonAccounts:A,accountKindOf:$,plans:ie,givenRules:G,withoutRecordType:x,keysLeftEmpty:[...H.leftEmpty,...E.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=await this.prepare(e,s,t),{previousLoads:a,working:u,refIndex:l,personContacts:c,groups:f,groupOrder:p,leftToThePlatform:g,untypedFeedItems:h,heldForExclusions:m,mapping:y,reused:k,ranks:N,recordTypeIssues:T,alignment:P,alignedByObject:x,requiredLookups:U,fixedAtInsert:C,lostObjects:I,targetHasPersonAccounts:w,accountKindOf:O,plans:j}=d,v=ml(hl(zd(d,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(v)throw new xr(v);let A=await this.runUserIdOf(i);A&&this.journal?.writtenAs(A);let F={deleted:{},deactivated:{},failures:[]},$=[],D=[],G=new Jo,V=new Map,H=[],E=new Set,W,Y=new Map,ie=!1,_=async()=>{let b=await this.readWrittenBetween(i,G,y),B=W?.linked??new Map,z=e.pilot?void 0:e.purgeSweep?.stillToSweep?.();await this.deps.mappingStore.persist(y,{created:G.list(H),startedAt:n,...b?{writtenBetween:b}:{},earlier:{settled:[...E],...z&&z.length>0?{stillToSweep:[...z]}:{}},...B.size>0?{personContacts:Object.fromEntries(B)}:{},...Y.size>0?{withTheirRecord:Object.fromEntries(Y)}:{},...A?{runUserId:A}:{}}),ie=!0},K=()=>G.list().length>0||Object.keys(F.deleted).length>0||Object.keys(F.deactivated).length>0,Z=async()=>{if(!e.signal?.aborted)return;let b=K();throw b&&await _(),new st({perObject:D,placeholders:$,purge:F},b)};t.load={keepMapping:_,mappingKept:()=>ie,wroteSome:K,written:{perObject:D,placeholders:$,purge:F}};let re=[];if(e.reload){let b="",B={residuals:0},z={tried:0,went:0},se=be=>{let Pe=je=>Object.values(je).reduce((Re,ce)=>Re+ce,0);return qn({phase:"reload",progress:24,did:`Purge: ${Pe(F.deleted)} deleted, ${Pe(F.deactivated)} deactivated, ${F.failures.length} failed`,refused:F.failures.length,notDone:B.residuals,done:"purged",notes:`${Fd(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,a,y),Pe=await this.foundUnderThePurge(i,be.residuals,y,l);if(Pe.length>0){let ce=new ar(Pe);throw s(se({cause:ce})),ce}H=be.carried;for(let ce of H.flatMap(oe=>oe.referenceIds)){let oe=y.get(ce);oe&&E.add(pe(oe))}let je=Object.values(be.leftUnrecorded).reduce((ce,oe)=>ce+oe,0);je>0&&(F.leftUnrecorded=be.leftUnrecorded,b=` \u2014 ${je} 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&&(F.keptByThePlatform=be.keptByThePlatform,b+=" \u2014 kept, the platform does not delete them: "+Re.map(([ce,oe])=>`${ce} (${oe})`).join(", "));try{e.purgeSweep&&(await Z(),await e.purgeSweep.first()),await this.purgeResiduals(e,be,[...p].reverse(),F,Z,E,B,z),e.purgeSweep&&!e.signal?.aborted&&await e.purgeSweep.afterPurge()}catch(ce){throw s(se(ce instanceof st?void 0:{cause:ce})),ce}for(let ce of a)if(!ce.created)for(let oe of ce.mapping.values())E.add(pe(oe));s(B.residuals>0||F.failures.length>0?se():{phase:"reload",status:"done",progress:24,message:`Reload pass done${Fd(z)}${b}`})}}let ge=b=>(x.get(b)??[]).filter(B=>!k.has(B.referenceId)),_e=j.filter(b=>b.kind==="placeholder").length,De=b=>qn({phase:"placeholders",progress:25,did:`Placeholders: ${$.length} created`,refused:0,notDone:_e-$.length,done:"created"},b);_e>0&&(await Z(),s({phase:"placeholders",status:"started",progress:24,message:"Creating placeholders"}));try{for(let b of j)b.kind==="placeholder"?(await Z(),await this.createPlaceholder(e,b,ge(b.missing.objectApiName),y,$,G)):this.applyScalarDefault(b.missing,Un(b.missing,ge(b.missing.objectApiName),O),re,N)}catch(b){throw s(De(b instanceof st?void 0:{cause:b})),b}_e>0&&s(De());let R=f.flatMap(b=>b.length>1?Js(b,_l(x,U,l,c)):b),L=[],S=[],J=this.config.duplicateErrorPatterns??gd,ne=new Set(R.includes(Qt)?(x.get(Qt)??[]).map(b=>b.referenceId):[]),X=[],he=null,ee=0,Be=!1,M=b=>b===Je&&X.length>0?`, ${X.length} on a case waiting for ${X.length===1?"its task":"their tasks"}`:"",we=new Set,et=async()=>{if(W)return W;let b=await this.linkPersonContacts(i,c,y,k,w,T);for(let B of b.linked.keys())k.add(B);return we=new Set(b.unlinked.map(B=>B.contactReferenceId).filter(B=>!k.has(B))),W=b,b},tt=b=>{if(b.objectApiName!==Ue||!W)return b;let B=W.unlinked.filter(z=>we.has(z.contactReferenceId));return B.length===0?b:{...b,failed:[...b.failed,...B.map(z=>({objectApiName:Ue,referenceId:z.contactReferenceId,errors:[Pl(z)]}))]}},q=()=>{if(W)for(let[b,B]of W.own)y.has(b)||(W.own.delete(b),W.unlinked.push({accountReferenceId:B.accountReferenceId,contactReferenceId:b,cause:"target-not-loaded",detail:`contact ${b} was not loaded (skipped, failed or excluded)`}))},ae=()=>{let b=W?.linked.size??0,B=W?.own.size??0,z=we.size;return[...b>0?[`${b} linked to the contact the platform wrote with ${b===1?"its":"their"} person account`]:[],...B>0?[`${B} sent as ${B===1?"a contact of its own":"contacts of their own"}: the target holds ${B===1?"its":"their"} account as a business account`]:[],...z>0?[`${z} not written: a person account's contact goes in with its account`]:[]]},kt=(b,B)=>[...b===Ue?ae():[],...B?[B]:[],...g.counts(b).map(({why:z,count:se})=>Xs(se,z)),...h.counts(b).map(({why:z,count:se})=>Dd(se,z)),...m.counts(b).map(({why:z,count:se})=>Qd(se,z))].map(z=>`, ${z}`).join(""),fe=(b,B,z,se,be)=>{let Pe=D.findIndex(Yt=>Yt.objectApiName===b),je=Pe>=0?D[Pe]:void 0,Re=z.filter(Yt=>k.has(Yt.referenceId)).length,ce=je?.inserted??0,oe=je?.skippedDuplicates??[],Le=je?.failed??[],dt=je?.writtenWithoutFields,ve=je?.sentAgainForALock,Ht=z.length-Re-ce-oe.length-Le.length,ht=tt({objectApiName:b,fromFiles:B,inserted:ce,reused:Re,skippedDuplicates:oe,failed:Le,...dt?{writtenWithoutFields:dt}:{},...Ht>0?{notInserted:Ht}:{},...ve?{sentAgainForALock:ve}:{}});je?D[Pe]=ht:D.push(ht),s({phase:"insert",objectName:b,status:"error",progress:25+Math.round(55*ee/Math.max(R.length,1)),message:`${b}: ${ce} inserted, ${ht.reused} reused, ${oe.length} duplicates skipped, ${ht.failed.length} failed${M(b)}${Xo(Ht)}${Tn(dt)}${kt(b,se)} \u2014 ${Q(be)}`})},ft,We=(b,B,z)=>{if(b.waiting>0){let Re=D.find(ce=>ce.objectApiName===Je);Re&&(Re.notInserted=(Re.notInserted??0)+b.waiting)}let se=B==="cancel"&&b.waiting>0,be="";se?be=Gn(b.waiting):b.waiting>0&&(be=Xo(b.waiting));let Pe=b.status;z?Pe="error":se&&b.status!=="error"&&(Pe="stopped");let je=z?` \u2014 ${Q(z.cause)}`:"";s({phase:"insert",objectName:Je,status:Pe,progress:25+Math.round(55*ee/Math.max(R.length,1)),message:`${b.message}${be}${b.notes}${je}`})},xe=async()=>{let b=he;b&&e.signal?.aborted&&(he=null,We(b,"cancel")),await Z()};t.endOpenLine=b=>{let B=ft;ft=void 0,B&&!(b instanceof st)&&B(b);let z=he;he=null,z&&We(z,b instanceof st?"cancel":"failure")};let ye=async()=>{Be=!0;let b=X.splice(0,X.length),B=he;if(he=null,b.length===0)return;let z=25+Math.round(55*ee/Math.max(R.length,1)),se;try{await Z()}catch(oe){throw B&&We(B,oe instanceof st?"cancel":"failure"),oe}let be=oe=>`${oe.inserted} inserted, ${oe.reused} reused, ${oe.skippedDuplicates.length} duplicates skipped, ${oe.failed.length} failed${Gn(oe.notInserted??0)}${Tn(oe.writtenWithoutFields)}`,Pe=oe=>{let Le=D.findIndex(dt=>dt.objectApiName===Je);Le>=0?D[Le]=Yo(D[Le],oe):D.push(oe)},je={};try{se=await this.insertObject(e,Je,0,b,l,y,k,L,J,G,V,Cd(D),oe=>{je.result=oe})}catch(oe){let Le=je.result;if(Le&&Pe(Le),B&&Le){let dt=Le.inserted+Le.skippedDuplicates.length+Le.failed.length;We({...B,waiting:Math.max(B.waiting-dt,0),message:`${B.message}; after their task: ${be(Le)}`},"failure",{cause:oe})}else B&&We(B,"failure",{cause:oe});throw oe}Pe(se);let Re=be(se),ce="done";se.failed.length>0||B?.status==="error"?ce="error":(se.notInserted??0)>0&&(ce="stopped"),s({phase:"insert",objectName:Je,status:ce,progress:z,message:B?`${B.message}; after their task: ${Re}${B.notes}`:`${Je} after their task: ${Re}`})};for(let b of R){await xe();let B=x.get(b);if(!B){let le=I.get(b);if(le&&b===Ue&&c.size>0){try{await et()}catch(Ne){throw s({phase:"insert",objectName:b,status:"error",progress:25+Math.round(55*ee/Math.max(R.length,1)),message:`${b}: person accounts' contacts not linked \u2014 ${Q(Ne)}`}),Ne}q();let Fe=W?.linked??new Map,Ee=le.failed.filter(Ne=>!Fe.has(Ne.referenceId));D.push({...le,reused:le.reused+le.failed.length-Ee.length,failed:Ee})}else le&&D.push(le);continue}ee++,s({phase:"insert",objectName:b,status:"started",progress:25+Math.round(55*ee/Math.max(R.length,1)),message:`Inserting ${b}`});let z,se=u.objects.find(le=>le.objectApiName===b)?.records.length??B.length,be=B;if(ft=le=>fe(b,se,be,z,le),b===Ue&&c.size>0){let le=await et();be=B.filter(Fe=>!we.has(Fe.referenceId));for(let Fe of be){let Ee=le.own.get(Fe.referenceId),Ne=Fe.fields.AccountId;Ee&&(Ne==null||Ne==="")&&(Fe.fields.AccountId=Ee.accountReferenceId)}}b===kr&&await this.matchDirectRelations(i,u,B,y,k,Y),b===Qt&&await this.matchTasksWrittenWithEmails(i,u,B,y,k,Y),yo[b]!==void 0&&(z=await this.matchActivityRelations(e,b,B,y,k,C.get(b)??new Set));let Pe=0;if(b===Ct){let le=await this.matchContactRolesWrittenWithOpportunities(e,{working:u,aligned:B,refIndex:l,mapping:y,reused:k,withTheirRecord:Y,pendingFk:L,fixedAtInsert:C.get(b)??new Set});Pe=le.linked,z=le.note}let je=zt[b],Re=je?await this.startAsDrafts(i,b,je,be,S):be;if(b===Je&&!Be&&ne.size>0){let le=Fe=>ti(Fe,Ee=>l.get(Ee))&&ne.has(String(Fe.ActivityId));X.push(...Re.filter(Fe=>le(Fe.fields))),Re=Re.filter(Fe=>!le(Fe.fields))}let ce=Re.filter(le=>!k.has(le.referenceId)).length,oe=e.signal?.aborted===!0&&ce>0,Le=(le,Fe,Ee=Ne=>D.push(Ne))=>this.insertObject(e,b,Fe,le,l,y,k,L,J,G,V,Cd(D),Ee),dt=u.standardPricebook,ve;if(oe)ve={objectApiName:b,fromFiles:se,inserted:0,reused:Re.length-ce,skippedDuplicates:[],failed:[],notInserted:ce};else if(dn(b)&&dt){let le=await Le(Re.filter(Ee=>Ee.fields[yt]===dt),0),Fe=Re.filter(Ee=>Ee.fields[yt]!==dt);if(e.signal?.aborted){let Ee=Fe.filter(cl=>k.has(cl.referenceId)).length,Ne={...le,fromFiles:se,reused:le.reused+Ee},Jt=Re.length-Ne.inserted-Ne.reused-Ne.skippedDuplicates.length-Ne.failed.length;ve={...Ne,...Jt>0?{notInserted:Jt}:{}}}else{let Ee={},Ne=await Le(Fe,se,Jt=>{Ee.result=Jt}).catch(Jt=>{throw D.push(Ee.result?Yo(le,Ee.result):{...le,fromFiles:se}),Jt});ve=Yo(le,Ne)}}else ve=await Le(Re,se);ft=void 0,b===Ue&&q(),ve=tt(ve),Pe>0&&(ve={...ve,writtenByThePlatform:Pe});let Ht=b===Je?X.filter(le=>!k.has(le.referenceId)).length:0;(ve.notInserted??0)>0&&(ve.notInserted=(ve.notInserted??0)+Ht);let ht=ve.notInserted??0;D.push(ve);let Yt=kt(b,z),Cs=M(b),fo=ve.failed.length>0,zs=fo?"error":"done";!fo&&ht>0&&(zs="stopped");let Ms=25+Math.round(55*ee/Math.max(R.length,1)),po=`${b}: ${ve.inserted} inserted, ${ve.reused} reused, ${ve.skippedDuplicates.length} duplicates skipped, ${ve.failed.length} failed${Cs}${Gn(ht)}${Tn(ve.writtenWithoutFields)}`;Cs&&ht===0?(he={status:fo?"error":"done",message:po,notes:Yt,waiting:Ht},s({phase:"insert",objectName:b,status:"started",progress:Ms,message:po})):s({phase:"insert",objectName:b,status:zs,progress:Ms,message:`${po}${Yt}`}),b===Qt&&await ye(),ht>0&&await xe()}await ye(),await Z(),s({phase:"pass2",status:"started",progress:82,message:"Patching cycle FKs"});let Ie={report:{resolved:0,unresolved:[]},unanswered:0},It=Ho(x,b=>y.has(b)),rn=new Set(It.map(b=>b.opportunity)),uo=L.filter(b=>b.objectApiName!==zr||b.field!==Mr||!rn.has(b.referenceId)),nn=It.length>0?`, ${It.length} synced quote${It.length===1?"":"s"} left unset`:"",Gt=b=>qn({phase:"pass2",progress:88,did:`Pass 2: ${Ie.report.resolved} resolved, ${Ie.report.unresolved.length} unresolved${nn}`,refused:Ie.report.unresolved.length,notDone:Ie.unanswered,done:"resolved"},b);try{await this.patchCycleFks(e,uo,y,Ie)}catch(b){throw s(Gt({cause:b})),b}s(Gt());let Ke=Ie.report;await Z();let at={report:{restored:0,refused:[]},unanswered:0},hr=b=>qn({phase:"pass2",progress:89,did:`Statuses: ${at.report.restored} applied, ${at.report.refused.length} refused`,refused:at.report.refused.length,notDone:at.unanswered,done:"applied"},b);try{await this.applyDeferredStatuses(e,S,y,at)}catch(b){throw s(hr({cause:b})),b}let mr=at.report;mr.restored+mr.refused.length+at.unanswered>0&&s(hr()),await Z();let $e=await et(),Ut={restored:$e.linked.size,sent:[...$e.own.values()],unresolved:$e.unlinked};c.size>0&&s({phase:"personcontact",status:$e.unlinked.length>0?"error":"done",progress:94,message:`Person contacts: ${$e.linked.size} linked to the contact the platform wrote with their account, ${$e.own.size} sent as contacts of their own, ${$e.unlinked.length} not linked`}),await Z(),await e.lease?.giveBack().catch(()=>{}),s({phase:"persist",status:"started",progress:96,message:"Persisting mapping and contract"}),await _();let yr=g.counts(),vt=h.counts(),jt=m.counts(),wr=this.writeContract(e,u,D,$,{now:r,startedAt:n},new Set(I.keys()),[...yr.map(({objectApiName:b,count:B})=>({objectApiName:b,count:B,reason:"left-to-the-platform"})),...vt.map(({objectApiName:b,count:B})=>({objectApiName:b,count:B,reason:"untyped-feed-item"})),...jt.map(({objectApiName:b,count:B})=>({objectApiName:b,count:B,reason:"excluded-parent"}))],we.size,V,Ke.unresolved.filter(b=>b.cause==="target-not-loaded"));s({phase:"persist",status:"done",progress:98,message:"Sas artifacts written"});let Kt=D.some(b=>b.failed.length>0)||Ke.unresolved.length>0||Ut.unresolved.length>0||mr.refused.length>0||F.failures.length>0,Vt=new Set(G.list().flatMap(({referenceIds:b})=>b)),br=await this.readBackRecordTypes(i,qd(d,b=>Vt.has(b)),y),Ft={status:Kt?"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:P,placeholders:$,requiredDefaults:re,perObject:D,pass2:Ke,personContact:Ut,statuses:mr,purge:F,...yr.length>0?{leftToThePlatform:Dn(yr)}:{},...vt.length>0?{untypedFeedItems:vt.map(({objectApiName:b,why:B,count:z})=>({objectApiName:b,count:z,note:Dd(z,B)}))}:{},...jt.length>0?{heldForExcludedParents:ec(jt)}:{},...Zd(It,this.config),...Hd(d.keysLeftEmpty),...br.length>0?{recordTypesGiven:br}:{},...A?{runUserId:A}:{},mappingPath:this.deps.mappingStore.filePath,contractPath:wr};return s({phase:"done",status:Ft.status==="completed"?"done":"error",progress:100,message:`Load ${Ft.status}`}),Ft}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 On(this.deps.guard,t);if(e.onGuardDecision?.(n),n==="refused"||n==="declined")throw new He("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 ts(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,u]of await this.findByKeys(e.orgId,s,i,d))r.set(a,u),n.add(a)}}async findByKeys(e,t,r,n){let s=new Map,i=n.filter(l=>r.every(c=>!gt(l.fields[c])));if(i.length===0)return s;let d=["Id",...r].map(me).join(", "),a=new Map,u=100;for(let l=0;l<i.length;l+=u){let c=i.slice(l,l+u).map(p=>`(${r.map(g=>`${me(g)} = ${Il(p.fields[g])}`).join(" AND ")})`).join(" OR "),f=`SELECT ${d} FROM ${me(t)} WHERE ${c}`;for(let p of await this.deps.orgAccess.query(e,f))typeof p.Id=="string"&&a.set($d(r.map(g=>p[g])),p.Id)}for(let l of i){let c=a.get($d(r.map(f=>l.fields[f])));c&&s.set(l.referenceId,c)}return s}async linkWhatThePlatformKeeps(e,t,r,n,s,i,d){let a={linked:[],said:[],leftEmpty:[]};for(let[u,l]of Object.entries(jr)){let c=this.config.identityKeys?.[u]??l,f=(r.get(u)??[]).filter(g=>!i.has(g.referenceId));if(f.length===0)continue;let p=await this.linkByKeysAsWritten(e,{objectApiName:u,keyFields:c,records:f,missingRequired:t.find(g=>g.objectApiName===u)?.missingRequired??[],ranks:n,accountKindOf:d},s,i,a);p>0&&a.said.push(`${u}: ${p} found by ${c.join(", ")}, which the platform does not delete`)}return a}async reuseByKeysAsWritten(e,t,r,n,s,i,d,a){let u={linked:[],said:[],leftEmpty:[]};for(let[l,c]of Object.entries(this.config.identityKeys??{})){if(Object.prototype.hasOwnProperty.call(jr,l))continue;let f=new Set((t.objects.find(h=>h.objectApiName===l)?.records??[]).filter(h=>c.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:c,records:p,missingRequired:r.find(h=>h.objectApiName===l)?.missingRequired??[],ranks:s,accountKindOf:a},i,d,u);g>0&&u.said.push(`${l}: ${g} found by ${c.join(", ")}, as the load writes `+(g===1?"it":"them"))}return u}async linkByKeysAsWritten(e,t,r,n,s){let{objectApiName:i,keyFields:d}=t,a=El(t,this.config.requiredFieldDefaults??{}),u=a.flatMap(c=>{let f=d.filter(p=>gt(c.fields[p]));return f.length>0?[f]:[]});if(u.length>0){let c=d.filter(f=>u.some(p=>p.includes(f)));s.leftEmpty.push({objectApiName:i,fields:c,count:u.length}),s.said.push(`${i}: ${u.length} not looked up, ${c.join(", ")} left empty`)}let l=await this.findByKeys(e,i,d,a);for(let[c,f]of l)r.set(c,f),n.add(c),s.linked.push(c);return l.size}async lookUpTheCatalog(e,t,r,n){let s=[],i=t.standardPricebook;if(i){let[u]=await this.deps.orgAccess.query(e,Et);typeof u?.Id=="string"?(r.set(i,u.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);xd(t).includes(ze)&&d.push({objectApiName:ze,linked:a});for(let{objectApiName:u,linked:l,notAsked:c}of d)c===void 0&&s.push(`${u}: ${l} linked`);for(let{objectApiName:u,notAsked:l}of d)l!==void 0&&s.push(`${u} not looked up \u2014 ${l}`);return s}async matchByNaturalKey(e,t,r,n){let s=[];for(let[i,d]of Object.entries(gn)){let a=t.objects.find(f=>f.objectApiName===i)?.records??[];if(a.length===0)continue;let u=a.filter(f=>!r.has(f.referenceId)&&d.every(p=>f.fields[p]!==void 0&&f.fields[p]!=="")),l=[];if(u.length>0)try{l=await pi(f=>this.deps.orgAccess.query(e,f),i,d,u.map(f=>f.fields))}catch(f){s.push({objectApiName:i,linked:0,notAsked:Q(f)});continue}let c=0;u.forEach((f,p)=>{let g=l[p];g!==void 0&&(r.set(f.referenceId,g),n.add(f.referenceId),c++)}),s.push({objectApiName:i,linked:c})}return s}async matchSellingModelOptions(e,t,r,n){let s=[];for(let d of t.objects.find(a=>a.objectApiName===ze)?.records??[]){if(r.has(d.referenceId))continue;let a=d.fields[Ge],u=d.fields[Ye],l=typeof a=="string"?r.get(a):void 0,c=typeof u=="string"?r.get(u):void 0;l===void 0||c===void 0||s.push({referenceId:d.referenceId,pair:{[Ge]:l,[Ye]:c}})}if(s.length===0)return 0;let i=await fi(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(pe(h))||s.set(pe(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]})},u=g=>{n.leftUnrecorded[g]=(n.leftUnrecorded[g]??0)+1},l=[],c=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,k]of g.mapping)m.has(y)||h.add(pe(k));return h}),p=new Set(f.flatMap(g=>[...g]));if(t.forEach((g,h)=>{if(!g.created){for(let[k,N]of g.mapping){let T=pe(N);if(s.has(T)||i.has(T))continue;i.add(T);let P=kl(k);this.mayHaveLinked(P,k)||p.has(T)?u(P):P==="Pricebook2"&&!k.startsWith(Wn)?l.push(N):d(P,N)}return}let m=g.writtenBetween?Dt(g.writtenBetween.last):Dt(g.endedAt)+c+Bi,y=new Map(Object.entries(g.removalStamps??{}).map(([k,N])=>[pe(k),Dt(N)]));for(let{objectApiName:k,referenceIds:N}of g.created)for(let T of N){let P=g.mapping.get(T);if(P===void 0)continue;let x=pe(P);if(f[h].has(x)||i.has(x))continue;i.add(x);let U=s.get(x);if(U!==void 0){a(k,U);continue}if(this.keptByThePlatform(k)){n.keptByThePlatform[k]=(n.keptByThePlatform[k]??0)+1;continue}d(k,P);let C=[m,y.get(x)??Number.NaN].filter(Number.isFinite);C.length>0&&n.datedBy.set(x,Math.max(...C))}}),l.length>0){let g;try{let[h]=await this.deps.orgAccess.query(e,Et);g=typeof h?.Id=="string"?pe(h.Id):""}catch{g=void 0}for(let h of l)g===void 0||pe(h)===g?u("Pricebook2"):d("Pricebook2",h)}return n}async targetClockAheadMs(){let e=this.deps.serverTime;if(!e)return Number.NaN;let t=Date.now();try{return Dt(await e())-(t+Date.now())/2}catch{return Number.NaN}}async foundUnderThePurge(e,t,r,n){let s=new Set([...t.values()].flat().map(pe)),i=new Map;for(let[u,l]of r){let c=n.get(u);c===void 0||s.has(pe(l))||i.set(c,[...i.get(c)??[],l])}if(s.size===0||i.size===0)return[];let d=new Map,a=(u,l,c)=>{let f=d.get(u)??{keys:new Set,under:new Set};f.keys.add(pe(l)),f.under.add(c),d.set(u,f)};for(let u of t.keys()){let l;try{l=(await this.deps.orgAccess.describe(e,u)).cascadeChildren??[]}catch{continue}for(let{childSObject:c,field:f}of l){let p=i.get(c);if(!p)continue;let g;try{g=await this.readRecords(e,c,[f],p)}catch{for(let h of p)a(c,h,u);continue}for(let h of g){let m=h[f];typeof h.Id!="string"||typeof m!="string"||s.has(pe(m))&&a(c,h.Id,u)}}}return[...d].map(([u,{keys:l,under:c}])=>({objectApiName:u,count:l.size,under:[...c]}))}mayHaveLinked(e,t){return t.startsWith(Wn)?!1:e==="Unknown"||e===ze||Object.prototype.hasOwnProperty.call(gn,e)||Object.prototype.hasOwnProperty.call(jr,e)||Object.prototype.hasOwnProperty.call(this.config.identityKeys??{},e)}keptByThePlatform(e){return Object.prototype.hasOwnProperty.call(jr,e)&&this.config.undeletableObjects?.[e]===void 0}async purgeResiduals(e,t,r,n,s,i,d,a){let u=t.residuals,l=[],c=[...u.values()].reduce((T,P)=>T+P.length,0),f=0,p=()=>{d.residuals=c-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=>u.has(T)),y=[...u.keys()].filter(T=>!r.includes(T)).sort(),k=[...m,...y],N=new Set;try{N=await this.residualsInSight(e.orgId,u),await this.draftResiduals(e,t,l,h);for(let T of k){let P=u.get(T)??[],x=this.config.undeletableObjects?.[T];if(x!==void 0){await h(),await this.checkGuard(e,"update",T,P.length);let U=await this.deps.writer.update(e.orgId,T,P.map(C=>({Id:C,[x]:!1})));U.forEach((C,I)=>{C.success?(n.deactivated[T]=(n.deactivated[T]??0)+1,i.add(pe(P[I]))):n.failures.push({objectApiName:T,recordId:P[I],errors:C.errors})}),f+=U.length}else{let U=dn(T)?await this.customPricesFirst(e.orgId,P):T===kr?[await this.withoutDirectRelations(e.orgId,P)]:[P];f+=P.length-U.reduce((C,I)=>C+I.length,0);for(let C of U){if(C.length===0)continue;await h(),await this.checkGuard(e,"delete",T,C.length);let I=await this.deps.writer.delete(e.orgId,T,C);I.forEach((w,O)=>{jd(w)?(n.deleted[T]=(n.deleted[T]??0)+1,i.add(pe(C[O]))):n.failures.push({objectApiName:T,recordId:C[O],errors:w.errors})}),f+=I.length}}}await this.purgeAgain(e,k,n,i,h,a)}catch(T){throw await g(),p(),T}e.signal?.aborted||await this.settleTakenAlong(e.orgId,n,i,N),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(pe(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 u=dn(d)?await this.customPricesFirst(e.orgId,a).catch(()=>[a]):[a];for(let l of u){if(l.length===0)continue;await s(),await this.checkGuard(e,"delete",d,l.length),(await this.deps.writer.delete(e.orgId,d,l)).forEach((f,p)=>{let g=r.failures.findIndex(h=>h.objectApiName===d&&h.recordId===l[p]);g<0||(i.tried++,jd(f)?(r.failures.splice(g,1),r.deleted[d]=(r.deleted[d]??0)+1,n.add(pe(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:u,failure:l}=await $i(i,d,h=>n.has(pe(h))),c=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(u.map(pe));for(let h of t.failures)h.objectApiName!==s||!f.has(pe(h.recordId))||h.errors.includes(c)||(h.errors=[...h.errors,c]);let p=new Set(a.map(pe));if(p.size===0)continue;let g=t.failures.filter(h=>h.objectApiName!==s||!p.has(pe(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(zt)){if(ci.has(s))continue;let d=t.residuals.get(s);if(!d||d.length===0)continue;let a=await this.statusCategories(e.orgId,i),u=a?.draft;if(!a||!u)continue;let l;try{l=await this.readRecords(e.orgId,s,["Status","LastModifiedDate"],d)}catch{continue}let c=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(pe(f.Id))??Number.NaN;return[{objectApiName:s,id:f.Id,draft:u,status:String(f.Status),unchanged:Dt(f.LastModifiedDate)<=g}]});c.length!==0&&(await n(),await this.checkGuard(e,"update",s,c.length),r.push(...c),await this.deps.writer.update(e.orgId,s,c.map(({id:f})=>({Id:f,Status:u}))))}}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),u=new Map(a.map(p=>[pe(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)Ed(r,g,`its status was not read back: ${Q(p)}`);continue}let c=l.flatMap(p=>{let g=typeof p.Id=="string"?u.get(pe(p.Id)):void 0;return g&&p.Status===g.draft?[g]:[]});for(let p=0;p<c.length;p+=Pt){let g=c.slice(p,p+Pt),h;try{await this.checkGuard(e,"update",d,g.length),h=await n.update(e.orgId,d,g.map(({id:m,status:y})=>({Id:m,Status:y})))}catch(m){let y=Q(m);h=g.map(()=>({success:!1,errors:[y]}))}g.forEach((m,y)=>{let k=h[y];k?.success||Ed(r,m,k?.errors.join("; ")||"the org gave no reason")})}let f=c.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"&&pe(g.LastModifiedById)===s&&(i[g.Id]=g.LastModifiedDate)}catch{}}if(Object.keys(i).length!==0)try{await this.deps.mappingStore.recordStamps(i)}catch{}}async runningUser(e){let t=await this.runUserIdOf(e);return t?pe(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(u=>r.get(u)??[]);try{let u=await this.deps.orgAccess.query(e,Va(s.objectApiName,a));n.push({...s,readBack:Ha(u,i.types)})}catch(u){let l=Q(u);n.push({...s,readBack:{read:0,types:[],unread:l}})}}return n}async readRecords(e,t,r,n){let s=["Id",...r].map(me).join(", "),i=[];for(let d=0;d<n.length;d+=Pt){let a=n.slice(d,d+Pt).map(u=>`'${Me(u)}'`).join(", ");i.push(...await this.deps.orgAccess.query(e,`SELECT ${s} FROM ${me(t)} WHERE Id IN (${a})`))}return i}async resolveRecordType(e,t,r,n,s,i,d){let a={...n.fields};r===Ve&&delete a[hn];let u=a.RecordTypeId;if(typeof u!="string"||u==="")return"RecordTypeId"in a&&d.set(n.referenceId,"masterInSource"),delete a.RecordTypeId,{referenceId:n.referenceId,fields:a};let l=t.recordTypes[r]??[],c=n.recordTypeDeveloperName===void 0?void 0:ko(n.recordTypeDeveloperName,l,Wd),f=c&&"found"in c?[c.found]:l.filter(m=>m.name===u),p=f[0];if(!p)return delete a.RecordTypeId,d.set(n.referenceId,"dropped"),i.push({objectApiName:r,referenceId:n.referenceId,recordTypeName:u,detail:"RecordType name absent from the dataset recordTypes map \u2014 RecordTypeId dropped"}),{referenceId:n.referenceId,fields:a};if(f.length>1)throw Gd(r,u,f);let g=ct(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 Ze(`The dataset names ${r} record type ${p.developerName} without its namespace \u2014 it was extracted before SandForge read one \u2014 and ${Io(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=>ct(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:u,detail:`RecordType ${g} is in the target org but not available to the running user \u2014 RecordTypeId dropped, ${wl(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:u,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 c=i.accountKind?` of a ${i.accountKind} account`:"";n.push(`requiredFieldDefaults["${d}"]: ${Nl(i)} for this required field${c}`)}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 u=a.targetObjectApiName??i.referenceTo[0];if(!u){n.push(`requiredLookupPlaceholders["${d}"].targetObjectApiName: the target describe names no object this lookup points at`);continue}let l;if(a.recordTypeDeveloperName){let c=await this.deps.recordTypeResolver.resolveByDeveloperName(e.orgId,u,a.recordTypeDeveloperName);if(c!==null&&typeof c=="object"&&"ambiguous"in c){let f=c.carriers.find(p=>p.namespacePrefix);n.push(`requiredLookupPlaceholders["${d}"]: `+Io(u,a.recordTypeDeveloperName,"the target org",c.carriers)+(f?" \u2014 a package's is named with its namespace: "+ct(f.namespacePrefix,f.developerName):""));continue}if(c!==null&&typeof c=="object"){n.push(`requiredLookupPlaceholders["${d}"]: record type ${a.recordTypeDeveloperName} on ${u} is not available to the running user`);continue}if(l=c??void 0,!l){n.push(`requiredLookupPlaceholders["${d}"]: record type ${a.recordTypeDeveloperName} is not on ${u} in the target org \u2014 deploy it before loading`);continue}}r.push({kind:"placeholder",missing:i,key:d,name:a.name,targetObject:u,recordTypeId:l})}if(n.length>0)throw new Ze(`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:u}=t,l={Name:t.name};t.recordTypeId&&(l.RecordTypeId=t.recordTypeId),await this.checkGuard(e,"insert",u,1);let[c]=await this.deps.writer.insert(e.orgId,u,[l]);if(c===void 0&&e.signal?.aborted)return;if(!c?.success||!c.id)throw new Ze(`Placeholder insert failed for required lookup ${a} on ${u}: ${c?.errors.join("; ")||"no id returned"}. Fix the target org configuration and retry.`);let f=`${Wn}${u}:${a}`;n.set(f,c.id),i.add(u,f),this.journal?.created(u,[[f,c.id]]);let p=0;for(let g of r){let h=g.fields[d.field];(h==null||h==="")&&(g.fields[d.field]=c.id,p++)}s.push({objectApiName:d.objectApiName,field:d.field,placeholderObjectApiName:u,placeholderName:t.name,placeholderId:c.id,affectedRecords:p})}applyScalarDefault(e,t,r,n){let s=`${e.objectApiName}.${e.field}`,i=this.config.requiredFieldDefaults?.[s],d=Zo(i,e.distinct),a=0;for(let u of t)gt(u.fields[e.field])&&(u.fields[e.field]=Qo(i,d,{referenceId:u.referenceId,rank:n.get(u.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,u,l,c,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=jl(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={},j=[];for(let[A,F]of Object.entries(w.fields))if(!(F===""||F===null||F===void 0))if(typeof F=="string"&&s.has(F)){let $=i.get(F);$&&!(t===zr&&A===Mr)?O[A]=$:j.push({objectApiName:t,referenceId:w.referenceId,field:A,targetReferenceId:F})}else O[A]=F;let v=Qs(t,O);for(let A of v)delete O[A];a.push(...j.filter(A=>!v.includes(A.field)));for(let A of Gs(t,O))delete O[A];return O}),k=(w,O,j)=>{i.set(w,O),l.add(t,w,vl.some(v=>v in j)),g.inserted++};await this.checkGuard(e,"insert",t,y.length);let N=await this.deps.writer.insert(e.orgId,t,y,(w,O)=>this.journalBatch(t,m,w,O)),T=[],P=new Map;N.forEach((w,O)=>{let j=m[O].referenceId;if(w.lockResends!==void 0&&P.set(j,w),w.success&&w.id){k(j,w.id,y[O]);return}if(_d(w.errors,u)){g.skippedDuplicates.push({objectApiName:t,referenceId:j,errors:w.errors});return}let v=this.sentAgain(t,y[O],w);v?T.push({...v,referenceId:j,errors:w.errors}):g.failed.push({objectApiName:t,referenceId:j,errors:w.errors})});let x=m.length-N.length;x>0&&e.signal?.aborted&&(g.notInserted=x);let U=()=>{let w=Sl(P);w&&(g.sentAgainForALock=w)};if(U(),T.length===0)return g;let C=(w,O)=>{for(let j of w)g.failed.push({objectApiName:t,referenceId:j.referenceId,errors:[...j.errors,`Not written again ${Ld(j.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,Q(w)),p?.(g),w}return T.forEach((w,O)=>{let j=I[O];if(!j){C([w],e.signal?.aborted?"the load was cancelled first":"no answer came for it");return}if((j.lockResends!==void 0||P.has(w.referenceId))&&P.set(w.referenceId,j),j.success&&j.id){k(w.referenceId,j.id,w.payload),g.writtenWithoutFields=To(g.writtenWithoutFields,{rows:1,fields:w.fields.map(A=>({...A,rows:1}))});for(let{field:A,replacedWith:F}of w.fields){if(F!==void 0)continue;let $=c.get(t)??new Map;$.set(A,[...$.get(A)??[],w.referenceId]),c.set(t,$)}return}let v=[...j.errors,`Sent again ${Ld(w.fields)} after the first refusal: ${w.errors.join("; ")}`];_d(j.errors,u)?g.skippedDuplicates.push({objectApiName:t,referenceId:w.referenceId,errors:v}):g.failed.push({objectApiName:t,referenceId:w.referenceId,errors:v})}),U(),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=ma(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(c=>c.objectApiName==="Contact")?.records??[])d.set(l.referenceId,l.fields.AccountId);let a=r.filter(l=>{let c=l.fields.ContactId;return typeof c=="string"&&l.fields.AccountId!==void 0&&d.get(c)===l.fields.AccountId&&n.has(c)&&typeof l.fields.AccountId=="string"&&n.has(l.fields.AccountId)});if(a.length===0)return;let u=await li(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,c]of a.entries()){let f=u.get(l);typeof f=="string"&&(n.set(c.referenceId,f),s.add(c.referenceId),i.set(c.referenceId,c.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(c=>c.objectApiName===Je)?.records??[]){let c=l.fields.ActivityId;if(typeof c!="string"||!d.has(c)||s.has(l.referenceId))continue;let f=n.get(l.referenceId);f&&a.set(c,{id:f,key:l.referenceId})}if(a.size===0)return;let u=await ri(l=>this.deps.orgAccess.query(e,l),[...new Set([...a.values()].map(l=>l.id))]);for(let[l,c]of a){let f=u.get(c.id);f!==void 0&&(n.set(l,f),s.add(l),i.set(l,c.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===Ud)?.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 u=r.map(I=>({OpportunityId:d(I.fields.OpportunityId),[wt]:d(I.fields[wt]),IsPrimary:I.fields.IsPrimary})),l=mo(u,I=>a.get(I)).filter(I=>!i.has(r[I].referenceId));if(l.length===0)return{linked:0};let c=I=>{let w={},O=[];for(let[j,v]of Object.entries(I.fields))if(!(j==="OpportunityId"||j===wt)&&!t.fixedAtInsert.has(j)&&!(v===""||v===null||v===void 0))if(typeof v=="string"&&n.has(v)){let A=s.get(v);A?w[j]=A:O.push({objectApiName:Ct,referenceId:I.referenceId,field:j,targetReferenceId:v})}else w[j]=v;return{fields:w,owed:O}},f=new Map(l.map(I=>[I,{opportunity:String(u[I].OpportunityId),contact:String(u[I][wt])}])),p=[...new Set(l.flatMap(I=>Object.keys(c(r[I]).fields)))],g=await oi(I=>this.deps.orgAccess.query(e.orgId,I),[...new Set([...f.values()].map(({opportunity:I})=>I))],p),{found:h,alike:m}=si(f,g),y=m.length>0?ii(m.length):void 0;if(h.size===0)return y?{linked:0,note:y}:{linked:0};let k=I=>y?`${I}; ${y}`:I,N=[];for(let[I,w]of h){let O=r[I],j=String(w.Id);s.set(O.referenceId,j),i.add(O.referenceId),t.withTheirRecord.set(O.referenceId,String(O.fields.OpportunityId));let{fields:v,owed:A}=c(O);t.pendingFk.push(...A);let F=Object.entries(v).filter(([$,D])=>String(w[$]??"")!==String(D));F.length>0&&N.push({Id:j,...Object.fromEntries(F)})}let T=h.size,P=`${T} written by the platform with ${ni(Ct)}`;if(N.length===0)return{linked:T,note:k(P)};let x=(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:k(x(N.length,"the load was cancelled before the update"))};await this.checkGuard(e,"update",Ct,N.length);let U=await this.deps.writer.update(e.orgId,Ct,N),C=N.flatMap((I,w)=>{let O=U[w];return O?.success?[]:[O?O.errors.join("; ")||"refused":"no answer came for it"]});return C.length===0?{linked:T,note:k(P)}:{linked:T,note:k(x(C.length,C[0]))}}async matchActivityRelations(e,t,r,n,s,i){let{orgId:d}=e,a=yo[t],u=c=>typeof c=="string"?n.get(c):void 0,l=await ai(c=>this.deps.orgAccess.query(d,c),t,r.map(c=>({[a]:u(c.fields[a]),RelationId:u(c.fields.RelationId)})));for(let[c,f]of l)n.set(r[c].referenceId,f),s.add(r[c].referenceId);return di(t,[...l].map(([c,f])=>[r[c].fields,f]),c=>!i.has(c),async c=>(await this.checkGuard(e,"update",t,c.length),this.deps.writer.update(d,t,c)),()=>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=nr(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=>`'${Me(d)}'`).join(", "),i=await this.deps.orgAccess.query(e,`SELECT Id FROM ${kr} 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 ui(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 c=r.get(l);return c?[c]:[]}))],u=t.sentAuditDates(i);for(let l=0;l<a.length;l+=Pt){let c=await this.writtenDatesOf(e,i,a.slice(l,l+Pt));if(!c)return;for(let f of c){let p=Dt(f.SystemModstamp),g=y=>{let k=u?Number.NaN:Dt(f[y]);return Number.isFinite(k)?k: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=>`'${Me(s)}'`).join(", ");for(let s of Ol)try{return await this.deps.orgAccess.query(e,`SELECT Id, ${s.join(", ")} FROM ${me(t)} WHERE Id IN (${n})`)}catch{}}async statusCategories(e,t){return rr(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 u=a.map(c=>({Id:c.id,Status:c.status}));await this.checkGuard(e,"update",d,u.length);let l=await this.deps.writer.update(e.orgId,d,u);l.forEach((c,f)=>{c.success?n.report.restored++:s.push({objectApiName:d,referenceId:a[f].referenceId,status:a[f].status,detail:c.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 u of t){let l=r.get(u.referenceId),c=r.get(u.targetReferenceId);if(!l||!c){s.push({objectApiName:u.objectApiName,referenceId:u.referenceId,field:u.field,cause:l?"target-not-loaded":"record-not-loaded",detail:l?`referenced record ${u.targetReferenceId} was not loaded (skipped, failed or excluded)`:"child record was not loaded (see perObject failures/skips)"});continue}d.set(l,u.referenceId);let f=i.get(u.objectApiName)??new Map,p=f.get(l)??{Id:l};p[u.field]=c,f.set(l,p),i.set(u.objectApiName,f)}let a=u=>u.reduce((l,c)=>l+Object.keys(c).length-1,0);n.unanswered=[...i.values()].reduce((u,l)=>u+a([...l.values()]),0);for(let[u,l]of i){let c=[...l.values()];if(e.signal?.aborted)continue;await this.checkGuard(e,"update",u,c.length);let f=await this.deps.writer.update(e.orgId,u,c);f.forEach((p,g)=>{p.success?n.report.resolved+=Object.keys(c[g]).length-1:s.push({objectApiName:u,referenceId:d.get(String(c[g].Id))??String(c[g].Id),field:Object.keys(c[g]).filter(h=>h!=="Id").join(","),cause:"update-refused",detail:p.errors.join("; ")})}),n.unanswered-=a(c.slice(0,f.length))}}async linkPersonContacts(e,t,r,n,s,i){let d={linked:new Map,own:new Map,unlinked:[]},a=new Map,u=[...t].map(([f,p])=>({accountReferenceId:p,contactReferenceId:f}));for(let f of u){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 yn(f=>this.deps.orgAccess.query(e,f),[...a.keys()]),c=new Map;for(let[f,p]of a){let g=l.get(f);if(g!==void 0)for(let h of p)c.set(h.contactReferenceId,g)}for(let f of u){let p=c.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===""?Dr.accountNotInDataset:Dr.accountNotLoaded});continue}if(n.has(f.contactReferenceId))continue;let g=i.find(m=>m.objectApiName===Ve&&m.referenceId===f.accountReferenceId),h=Dr.noPersonAccounts;s!==!1&&(h=g?`${Dr.businessAccount}: ${g.detail}`:`${Dr.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,u=new Map,l=[]){let c=new Map;for(let{objectApiName:h,referenceId:m,field:y}of l){let k=c.get(h)??{};k[y]=[...k[y]??[],m],c.set(h,k)}let f=new Map;for(let{objectApiName:h,count:m,reason:y}of d){let k=f.get(h)??{};k[y]=(k[y]??0)+m,f.set(h,k)}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,k)=>y+k,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,k=h.failed.filter(C=>Fl(C.errors)).length;if(k>0&&(m["parent-refused"]=k),h.failed.length-k>y){let C=i.has(h.objectApiName)?"object-not-loaded":"dml-failed";m[C]=h.failed.length-k-y}y>0&&(m["person-contact-not-sent"]=y);let N=0;for(let[C,I]of Object.entries(f.get(h.objectApiName)??{}))m[C]=I,N+=I;let T=h.skippedDuplicates.length+h.failed.length+N,P=n.filter(C=>C.placeholderObjectApiName===h.objectApiName).length,x=u.get(h.objectApiName),U=c.get(h.objectApiName);g[h.objectApiName]={fromFiles:h.fromFiles,exclusionReasons:m,excluded:T,added:P,expected:h.inserted+h.reused+P,...x&&x.size>0?{writtenWithout:Object.fromEntries(x)}:{},...U?{parentNotLoaded:U}:{}}}return fd(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 Nn(this.sasGuard,e,t)}};function Cd(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 jl(o,e,t,r){if(r.size===0)return;let n=new Set(o===Je&&!ho(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 Fl(o){return o.length===1&&o[0].startsWith("PARENT_REFUSED:")}function gt(o){return o==null||o===""}var Vd=/\{(n|referenceId)\}/g;function Zo(o,e){if(typeof o=="string")return o.match(Vd)?"token":e}function Qo(o,e,t){return typeof o!="string"||e===void 0?o:e==="token"?o.replace(Vd,(r,n)=>n==="n"?String(t.rank):t.referenceId):`${o} ${t.rank}`}function El(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 u of i){let l=e[`${t}.${u.field}`];l===void 0||!gt(a[u.field])||Un(u,[d],s).length!==0&&(a[u.field]=Qo(l,Zo(l,u.distinct),{referenceId:d.referenceId,rank:n.get(d.referenceId)??0}))}return{referenceId:d.referenceId,fields:a}})}function Hd(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 Ll(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 Yd(o){let e=es(o),t=new Map(o.objects.map(n=>[n.objectApiName,n.records])),r=new Set;return new Set([...Jd(t,r),...Xd(t,r,Kd(o,e),n=>e.get(n))])}function Jd(o,e){let t=(o.get(Ct)??[]).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 u=r.get(a);return u===void 0&&(u=String(r.size+1).padStart(15,"0"),r.set(a,u)),u},s=new Set((o.get(Ue)??[]).map(a=>a.referenceId)),i=new Map;for(let a of o.get(Ud)??[]){if(e.has(a.referenceId))continue;let u=a.fields[wt];typeof u!="string"||!s.has(u)||i.set(n(a.referenceId),n(u))}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(mo(d,a=>i.get(a)).map(a=>t[a].referenceId))}function Xd(o,e,t,r){let n=l=>(o.get(l)??[]).filter(c=>!e.has(c.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(kr)){let{AccountId:c,ContactId:f}=l.fields;typeof c!="string"||typeof f!="string"||i.get(f)===c&&d.has(c)&&s.add(l.referenceId)}let a=new Set([...o.values()].flatMap(l=>l.map(c=>c.referenceId))),u=new Set(n(Qt).map(l=>l.referenceId));for(let l of n(Je)){let c=l.fields.ActivityId,f=l.fields.RelatedToId;typeof c!="string"||!u.has(c)||typeof f!="string"||!a.has(f)||ho(l.fields,r)||s.add(c)}return s}function zd(o,e,t){let{working:r,loading:n,alignedByObject:s,reused:i,reusedByKeys:d,alignment:a,ranks:u}=o,l=o.targetHasPersonAccounts===!1?new Set:o.personContacts,c=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=Jd(s,i),h=Xd(s,i,l,I=>o.refIndex.get(I)),m=[];for(let I of f){let w=r.objects.find(E=>E.objectApiName===I)?.records.length??0,O=e?.residuals.get(I)?.length??0;if(w===0&&O===0)continue;let j=s.get(I),A=(j??n.objects.find(E=>E.objectApiName===I)?.records??[]).filter(E=>i.has(E.referenceId)),F=A.filter(E=>d.has(E.referenceId)).length,$=j?c(I):[],D=$.filter(E=>l.has(E.referenceId)).length;p+=D;let G=$.filter(E=>g.has(E.referenceId)||h.has(E.referenceId)).length,V=(o.filteredLookups.get(I)??[]).flatMap(({field:E,referenceTo:W})=>{let Y=$.filter(ie=>!gt(ie.fields[E])).length;return Y>0?[{field:E,referenceTo:W,records:Y}]:[]}),H=t.undeletableObjects[I]!==void 0;m.push({objectApiName:I,fromFiles:w,toInsert:$.length-D-G,reusedByKeys:F,reusedFromCatalog:A.length-F,...G>0?{writtenByThePlatform:G}:{},fieldsDropped:a.removals.filter(E=>E.objectApiName===I).length,picklistsRewritten:a.adjustments.filter(E=>E.objectApiName===I).length,notSent:w-(j?j.length:A.length),toPurge:H?0:O,toDeactivate:H?O:0,...V.length>0?{lookupFilters:V}:{}})}let y=(I,w)=>c(I).filter(O=>gt(O.fields[w])),k=(I,w)=>y(I,w).length,N=I=>{let w=Un(I,y(I.objectApiName,I.field),o.accountKindOf),O=t.requiredFieldDefaults[`${I.objectApiName}.${I.field}`],j=Zo(O,I.distinct),v=w[0];return{objectApiName:I.objectApiName,field:I.field,affectedRecords:w.length,...j?{perRecord:j}:{},...j&&v?{example:String(Qo(O,j,{referenceId:v.referenceId,rank:u.get(v.referenceId)??0}))}:{}}},T=e?.leftUnrecorded??{},P=e?.keptByThePlatform??{},x=o.heldForExclusions.counts(),U=qd(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:k(I.missing.objectApiName,I.missing.field)}]:[]),requiredDefaults:o.plans.flatMap(I=>I.kind==="default"?[N(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}:{},...x.length>0?{heldForExcludedParents:ec(x)}:{},...Zd(Ho(s,I=>C.has(I)),t,!0),...Hd(o.keysLeftEmpty,!0),...U.length>0?{recordTypesGiven:U}:{}}}var Md=5;function Nl(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,Md).join(", ")}${e.length>Md?", \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 Zd(o,e,t=!1){let r=Td(o,(e.excludedObjects??[]).includes(Vo),t);return r?{quotesLeftUnsynced:[r]}:{}}function Cl(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(u=>u.leaveOut(n,a.referenceId,a.fields,i)));d.length!==s.length&&(o.set(n,d),r=!0)}}}function zl(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||Xt(o,s.name,s.nillable)&&(t.requiredLookupPlaceholders?.[`${o}.${s.name}`]||n.push({field:s.name,excludedObject:i[0]}))}return n}function Ml(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 Qd(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 ec(o){return o.map(({objectApiName:e,why:t,count:r})=>({objectApiName:e,count:r,note:Qd(r,t)}))}var Dl={field:"Type",value:"",noun:"feed item whose type the dataset does not carry"};function xl(o,e){if(o!=="FeedItem")return;let t=e.Type;return typeof t=="string"&&t!==""?void 0:Dl}function Dd(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 es(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 $l(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===Ve&&d===hn)&&typeof a=="string"){let u=e.get(a);u&&u!==n.objectApiName&&s.add(u)}r.set(n.objectApiName,s)}t.size>0&&r.has(Ve)&&r.get(Ue)?.add(Ve);for(let{sourceObject:n,targetObject:s}of ha(new Set(r.keys()),[]))r.get(s)?.add(n);for(let{sourceObject:n,targetObject:s}of ei(new Set(r.keys())))r.get(n)?.delete(s),r.get(s)?.add(n);return r}function _l(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 u of i)for(let l of d){let c=u.fields[l],f=typeof c=="string"?t.get(c):void 0;f&&f!==s&&a.add(f)}n.set(s,a)}return r.size>0&&n.set(Ue,new Set([...n.get(Ue)??[],Ve])),n}function Bl(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,Ye,Zt],s=[Ge,Ye],i=(h,m)=>typeof h[m]=="string"&&h[m]!=="",d=t(qe),a=d.filter(h=>e.has(h.referenceId)&&i(h.fields,Ge)),u=o.standardPricebook,l=h=>u!==void 0&&h.fields[yt]===u,c=new Set(a.filter(h=>!l(h)).map(h=>r(h.fields,n))),f=d.filter(h=>l(h)&&c.has(r(h.fields,n))),p=new Set([...a,...f].filter(h=>i(h.fields,Ye)).map(h=>r(h.fields,s))),g=t(ze).filter(h=>p.has(r(h.fields,s)));return[...f,...g].map(h=>h.referenceId)}function xd(o){return[...Object.keys(gn),ze].filter(e=>o.objects.some(t=>t.objectApiName===e&&t.records.length>0))}function ql(o,e){for(let t of o.objects){let r=t.records.find(n=>n.referenceId===e);if(r)return r}}function $d(o){return JSON.stringify(o.map(e=>e===void 0?null:e))}function _d(o,e){return o.some(t=>e.some(r=>t.toLowerCase().includes(r.toLowerCase())))}function ts(o,e,t){if(!e)throw new Ze("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 Ze(`Pilot root ${t??"<first>"} not found in ${e} records (${r.length} in dataset). Provide pilot.rootReferenceId of an existing root record.`);let s=es(o),i=new Set([n]),d=!0;for(;d;){d=!1;for(let l of o.objects)for(let c of l.records)i.has(c.referenceId)||Object.values(c.fields).some(f=>typeof f=="string"&&i.has(f))&&(i.add(c.referenceId),d=!0)}let a=l=>{for(;l.length>0;){let c=l.pop(),f=ql(o,c);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 u=Bl(o,i).filter(l=>!i.has(l));for(let l of u)i.add(l);return a(u),{...o,objects:o.objects.map(l=>({...l,records:l.records.filter(c=>i.has(c.referenceId))})).filter(l=>l.records.length>0)}}import{randomBytes as Wl}from"node:crypto";import{readFile as Gl}from"node:fs/promises";var rs="frozen.salt";function Ul(){return Wl(32).toString("base64url")}function tc(o){let e=o[Ga];return e?{salt:e,source:"environment"}:void 0}function Rp(o,e=process.env){let t=async()=>{let r=tc(e);if(r)return r;let n=await o.getSecret(rs);return n?{salt:n,source:"secretStorage"}:void 0};return{read:t,forExtraction:async()=>{let r=await t();if(r)return r;let n=Ul();if(await o.storeSecret(rs,n),await o.getSecret(rs)!==n)throw new Tr;return{salt:n,source:"secretStorage",created:!0}}}}function rc(o=process.env,e){let t=async()=>{let r=tc(o);if(r)return r;if(e===void 0)return;let n=(await Gl(e,"utf8")).trim();return n?{salt:n,source:"file"}:void 0};return{read:t,forExtraction:async()=>{let r=await t();if(!r)throw new Tr;return r}}}import{createHash as Kl}from"node:crypto";import{appendFileSync as Vl,mkdirSync as Hl,readFileSync as Yl}from"node:fs";import*as _r from"node:path";var Jl=15*6e4;function Kn(o){return`sha256:${Kl("sha256").update(_r.resolve(o)).digest("hex").slice(0,16)}`}function nc(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 Xl(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+Jl})}function oc(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:Xl(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 sc="frozen-loads.ndjson";function Op(o,e){Hl(o,{recursive:!0}),Vl(_r.join(o,sc),`${JSON.stringify(e)}
|
|
13
|
-
`)}function Zl(o,e){return o.slice(0,15)===e.slice(0,15)}function Sp(o,e){let t;try{t=Yl(_r.join(o,sc),"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:u,lastWriteAt:l}=s??{};typeof i!="string"||typeof u!="string"||Zl(i,e)&&r.push({endedAt:u,...typeof d=="string"?{sas:d}:{},...typeof a=="string"?{startedAt:a}:{},...typeof l=="string"?{lastWriteAt:l}:{}})}return r}function ic(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 Ql="FROZEN_EMAILS_EXCEEDED";function Ep(o,e){return[...Ca(o.counted,e),...o.uncounted!==void 0?[` emails: not counted, ${o.uncounted} could not be read`]:[],...o.deliverability?[` ${Da(o.deliverability.reading)}`]:[]]}function eu(o){return typeof o.unread=="string"}async function ac(o){let{read:e,plan:t,writes:r,target:n}=o,s=await ra({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(eu(e))d=`the target's automation: ${e.unread}`;else{let c=Lt(e,t,r).automation,f={objects:o.inserts.map(g=>({...g,storageBytes:0}))};d=La(c,Ea(f));let p=Vs(c);if(p.length>0){let g=await o.readLimits().catch(h=>({unread:Q(h)}));i=Fa(f,p,g)}}let a=Na(i,n),u=a?{code:Ql,message:`${a} Nothing was written.`}:s.gate.stop,{deliverability:l}=s.gate;return{run:s,info:{counted:i.map(c=>({...c,objects:[...c.objects]})),...d!==void 0?{uncounted:d}:{},verdict:s.gate.verdict,...l?{deliverability:l}:{},accepted:o.accepted,...u?{refused:{code:u.code,message:u.message}}:{}},...u?{stop:u}:{}}}var tu="AUTOMATION_NOT_ACCEPTED";function ru(o){let e=new Set(o);return(t,r)=>e.has(t)&&(r==="insert"||r==="update")}function nu(o){return typeof o.unread=="string"}function ou({kind:o,name:e}){return o==="flow"?`flow "${e}"`:o==="process"?`process "${e}"`:o==="workflowRule"?`workflow rule "${e}"`:`Apex trigger ${e}`}var dc={flows:"the flows",triggers:"the Apex triggers",processes:"the Process Builder processes",workflowRules:"the workflow rules",automation:"what runs"};function cc(o){return`${o.objectApiName}: ${ou(o)} (${o.writes.join(", ")})`}function su(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(cc).join("; ")}.`);for(let{part:n,reason:s}of o.unread??[]){let i=dc[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 ns(o){let{read:e,target:t}=o,r=ru(o.written),n=[],s=[],i=[];if(nu(e))s=[{part:"automation",reason:e.unread}];else{let u=Lt(e,o.plan,r),l=new Map;for(let p of u.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=_a(e);let c=$a(u.automation,xa(u.automation,[...o.written])),f=[...new Set(c.flatMap(p=>p.permissionSet??[]))];i=[...Ba(c,t,"the load"),...o.mayMute&&f.length>0?[e.cannotAssign===!0?`--mute-automation would be refused: ${na}.`:`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:tu,message:su(d,t,i)};return{info:{...d,refused:a},stop:a}}function Mp(o,e){return[`target automation: what ${e} runs as the load inserts its records and updates them`,...o.firing.map(t=>` ${cc(t)}`),...(o.unread??[]).map(({part:t,reason:r})=>` ${dc[t]} could not be read: ${r}`),...o.accepted?[" accepted (--accept-automation): the load writes all the same"]:[]]}import{existsSync as uf}from"node:fs";import*as Ae from"node:fs/promises";import*as sl from"node:os";import*as Te from"node:path";var dr=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+$/,lc=/^[A-Za-z][A-Za-z0-9_]*\.[A-Za-z][A-Za-z0-9_]*$/,au=new Set(No);function os(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function Vn(o){let e=[];if(!os(o))throw new dr("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(!os(r))throw e.push('rules is required and must be an object keyed by "Object.Field"'),new dr("Invalid rules file",e);let n={};for(let[s,i]of Object.entries(r)){if(!lc.test(s)){e.push(`"${s}": key must match "ObjectApiName.FieldApiName"`);continue}if(!os(i)){e.push(`"${s}": rule must be an object with a "generator" property`);continue}let d=i.generator;if(typeof d!="string"||!au.has(d)){e.push(`"${s}": unknown generator ${JSON.stringify(d)} (supported: ${No.join(", ")})`);continue}let a=i.approved===!0;if(d==="keep"&&!a){e.push(`"${s}": generator "keep" requires "approved": true (explicit human review)`);continue}let u={generator:d};i.approved!==void 0&&(u.approved=a),typeof i.comment=="string"&&(u.comment=i.comment),n[s]=u}if(e.length>0)throw new dr("Invalid rules file",e);return{rulesVersion:t,rules:n}}function uc(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 fc={rulesVersion:"1.0.0",rules:{}};function pc(o){if(o===null)return{found:!1};try{let e=Vn(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 du=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],cu=new Set(["FeedItem.Type","Pricebook2.IsActive","PricebookEntry.IsActive","Product2.IsActive",...du.flatMap(o=>[`BusinessHours.${o}StartTime`,`BusinessHours.${o}EndTime`]),"BusinessHours.TimeZoneSidKey","OperatingHours.TimeZone","TimeSlot.DayOfWeek","TimeSlot.StartTime","TimeSlot.EndTime","TimeSlot.Type"]),lu=new Set(["TimeZoneSidKey","LocaleSidKey","LanguageLocaleKey","CurrencyIsoCode","EmailEncodingKey"]);function ut(o,e,t){let r=`${e}.${t}`,n=o.rules[r]?.generator;return n||(o.personalBySchema?.has(r)===!0?"clear":cu.has(r)||lu.has(t)||o.keptBySchema?.has(r)===!0?"keep":"clear")}function gc(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 u=`${s}.${a.name}`;d.has(a.name)?n.add(u):a.type==="picklist"&&(a.restrictedPicklist===!0||a.nillable===!1)&&a.compoundFieldName===void 0&&r.add(u)}}return{...o,keptBySchema:r,personalBySchema:n}}function hc(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&&ut(e,r.objectApiName,s)==="keep"&&t.add(i)}return[...t].sort()}function mc(o,e,t){let r=[];for(let n of o.objects){let s=t.get(n.objectApiName)??[];for(let l of s){let c=fn(n.objectApiName,l.name);if(l.name==="Id"||l.createable===!1||l.nillable!==!1&&c===void 0||l.defaultedOnCreate===!0||l.type==="reference"||(l.referenceTo?.length??0)>0||ut(e,n.objectApiName,l.name)!=="clear")continue;n.records.some(p=>{if(c!==void 0&&!tr(c,mn(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=ln(i,l=>s.some(c=>c.name===l&&c.createable!==!1),l=>ut(e,i,l)!=="clear"),a=`${i}.${d}`;d!==void 0&&n.records.some(l=>{let c=l.fields[d];return c!=null&&c!==""})&&!r.includes(a)&&r.push(a)}return r.sort()}var uu="Cleared on review of the extraction result: kept in clear text without a rule before.";function yc(o,e){let t=Vn(o),r=e.filter(u=>!lc.test(u));if(r.length>0)throw new dr('Fields to clear must be named "ObjectApiName.FieldApiName"',r.map(u=>JSON.stringify(u)));let n=o,s={...n.rules},i=[],d=[];for(let u of[...new Set(e)].sort()){if(t.rules[u]!==void 0){d.push(u);continue}s[u]={generator:"clear",comment:uu},i.push(u)}let a=i.length>0?fu(t.rulesVersion):t.rulesVersion;return{payload:{...n,rulesVersion:a,rules:s},rulesVersion:a,cleared:i,alreadyRuled:d}}function fu(o){let[e,t]=o.split(".").map(Number);return`${e}.${t+1}.0`}import*as wc from"node:fs/promises";import*as bc from"node:path";var ss=/\{\{([A-Z][A-Z0-9_]*)\}\}/g,Rc=/^[A-Z][A-Z0-9_]*$/,Tt=class extends Error{constructor(e){super(e),this.name="QueryTemplateError"}};function Br(o,e){for(let i of Object.keys(e))if(!Rc.test(i))throw new Tt(`Invalid token name ${JSON.stringify(i)}`);let t=new Set;for(let i of o.matchAll(ss))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(ss,(i,d)=>e[d]),s=n.match(ss);if(s)throw new Tt(`Unresolved placeholder(s) after render: ${s.join(", ")}`);return n}async function kc(o,e,t){let n=(t??new ue).assertOutsideRepo(bc.join(o,e)),s=JSON.parse(await wc.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(!Rc.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 qr=class extends Error{constructor(){super("Selection stopped"),this.name="SelectionStopped"}};function pu(o,e){return e?e.aborted?(o.catch(()=>{}),Promise.reject(new qr)):new Promise((t,r)=>{let n=()=>r(new qr);e.addEventListener("abort",n,{once:!0}),o.then(s=>{e.removeEventListener("abort",n),t(s)},s=>{e.removeEventListener("abort",n),r(s)})}):o}var gu=2500,hu=3,mu=5;function yu(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,mu).map(([t,r])=>({objectApiName:t,count:r}))}var $t=class extends Error{constructor(t,r,n,s){let i=yu(t,s),d=i.map(u=>`${u.objectApiName} ${u.count}`),a=i.length>0?`The heaviest: ${d.join(", ")}. Leave out those the dataset does not need with excludedObjects (${JSON.stringify(i.map(u=>u.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},is=class extends Error{constructor(e){super(e),this.name="CoverageSelectionError"}},Hn=class{deps;constructor(e){this.deps=e}async select(e,t={}){let r=e.budgetMaxRecords??gu,n=e.candidatesPerCombination??hu,s=me(e.rootObject),{signal:i}=t,d=p=>t.onProgress?.(p),a=[],u=[],l=[],c={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 $t(p,g,r,s);return{roots:a,uncovered:u,volumetry:{measured:p,total:g,budgetMax:r,summed:!0},selectedAt:(this.deps.now?.()??new Date).toISOString(),stopped:{reason:i?.reason==="timeout"?"timeout":"cancelled",during:c.during,...c.combinationKey!==void 0?{combinationKey:c.combinationKey}:{},...c.candidate!==void 0?{candidate:c.candidate,candidates:n}:{},notProbed:c.pending}}};try{return await this.run(e,{rootObject:s,budgetMax:r,candidateLimit:n,signal:i,tell:d},{roots:a,uncovered:u,ownMeasures:l,at:c})}catch(p){if(p instanceof qr)return f();throw p}}async run(e,t,r){let{rootObject:n,budgetMax:s,candidateLimit:i,signal:d,tell:a}=t,{roots:u,uncovered:l,ownMeasures:c,at:f}=r,p=P=>pu(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?[[]]:Ru(e.axes.map(P=>({axis:P.name,values:g.get(P.name)??[]}))),y=P=>P.length===0?"all":P.map(x=>`${x.axis}=${x.value??"NULL"}`).join("|");f.pending=[...m.map(y),...e.edgeCases.map(P=>`edge:${P.name}`)];let k=async(P,x)=>(f.during="combination",f.combinationKey=P,f.candidate=void 0,f.pending=f.pending.filter(U=>U!==P),this.pickHealthyRoot(n,x,i,e.tokens,{step:p,onCandidate:U=>{f.candidate=U,a({phase:"candidate",combinationKey:P,candidate:U,candidates:i})}}));for(let[P,x]of m.entries()){let U=y(x);a({phase:"combination",combinationKey:U,index:P+1,of:m.length});let C=x.map(O=>{let j=me(e.axes.find(v=>v.name===O.axis)?.filterField??"");return O.value===null?`${j} = NULL`:`${j} = ${bu(O.value,h.get(O.axis))}`}).join(" AND "),I=await k(U,C),w={};for(let O of x)w[O.axis]=O.value;I.id?(u.push({rootRecordId:I.id,combinationKey:U,axisValues:w}),I.measured&&c.push(I.measured)):l.push({combinationKey:U,reason:Ic(I,i)})}for(let[P,x]of e.edgeCases.entries()){let U=`edge:${x.name}`;a({phase:"combination",combinationKey:U,index:P+1,of:e.edgeCases.length});let C=await k(U,`(${x.whereFragment})`);C.id?(u.push({rootRecordId:C.id,combinationKey:U,axisValues:{},edgeCase:x.name}),C.measured&&c.push(C.measured)):l.push({combinationKey:`edge:${x.name}`,reason:C.probed===0?"no record matches the edge-case marker":Ic(C,i)})}f.during="measure",f.combinationKey=void 0,f.candidate=void 0,u.length>0&&a({phase:"measure",roots:u.length});let N=u.length===0?{}:await p(this.deps.measureVolumetry(u.map(P=>P.rootRecordId))),T=Object.values(N).reduce((P,x)=>P+x,0);if(T>s)throw new $t(N,T,s,n);return{roots:u,uncovered:l,volumetry:{measured:N,total:T,budgetMax:s},selectedAt:(this.deps.now?.()??new Date).toISOString()}}async enumerateAxisValues(e,t){let r=Br(e.valuesSoql,t??{}),n=await this.deps.query(r),s=[];for(let i of n){if(!("axisValue"in i))throw new is(`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(Br(i,n??{}))),a=0,u;for(let l of d){let c=l.Id;if(typeof c!="string"||c==="")continue;a++,s.onCandidate(a);let f=await s.step(this.deps.checkHealth.check(c));if(f.healthy)return{id:c,probed:a,...f.measured?{measured:f.measured}:{}};u=f.reason}return{id:null,probed:a,lastReason:u}}};function Ic(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 wu=new Set(["int","long","double","currency","percent"]);function bu(o,e){let t=`'${Me(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&&wu.has(e)&&/^-?\d+(\.\d+)?$/.test(o)?o:t}}function Ru(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 Yn=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 cr from"node:fs/promises";import*as as from"node:path";var Wr="selection.json";async function vc(o,e,t){let r=t??new ue,n=r.assertOutsideRepo(o);await cr.mkdir(n,{recursive:!0});let s=r.assertOutsideRepo(as.join(n,Wr));return await cr.writeFile(s,`${JSON.stringify({fileVersion:1,selection:e},null,2)}
|
|
18
|
-
`,"utf8"),s}async function ds(o,e){let r=(e??new ue).assertOutsideRepo(as.join(o,Wr)),n=JSON.parse(await cr.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 lr from"node:fs/promises";import*as cs from"node:path";var Oc="discovery.json",Iu=1440*6e4,vu=rt({name:Ce(),fields:mt(rt({name:Ce(),type:Ce(),referenceTo:mt(Ce())}).loose()),childRelationships:mt(rt({childSObject:Ce(),field:Ce(),relationshipName:Ce()}).loose())}).loose(),Ou=rt({fileVersion:_s(1),sourceOrgId:Ce().min(1),rootObject:Ce().min(1),maxNodes:Ds().int().positive(),step:$s(["select","extract"]),discoveredAt:go.datetime(),schemaStamp:go.datetime().optional(),graph:rt({nodes:mt(rt({objectApiName:Ce(),included:on()}).loose()),edges:mt(rt({sourceObject:Ce(),targetObject:Ce()}).loose())}).loose(),describes:xs(Ce(),vu),objects:mt(rt({name:Ce(),keyPrefix:Ce().nullable()}))});async function Sc(o,e,t=new ue){let r=t.assertOutsideRepo(o);await lr.mkdir(r,{recursive:!0});let n=t.assertOutsideRepo(cs.join(r,Oc));return await lr.writeFile(n,`${JSON.stringify(e)}
|
|
19
|
-
`,"utf8"),n}async function Ac(o,e=new ue){let t=e.assertOutsideRepo(cs.join(o,Oc)),r;try{r=await lr.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=Ou.safeParse(n);return s.success?{kept:s.data}:{none:"the graph kept in the sas could not be read"}}function Pc(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<=Iu))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 Tc(o){let e=Date.parse(o);if(!Number.isNaN(e))return new Date(Math.floor(e/1e3)*1e3-1e3).toISOString()}import*as Xn from"node:fs/promises";import*as jc from"node:path";var Su="SELECT Id, SobjectType, DeveloperName, NamespacePrefix, Name FROM RecordType ORDER BY SobjectType, DeveloperName",Au="rt-map.json",Pu=10;function Tu(o,e){return Ar.has(o)?e:e.map(t=>t.type==="reference"&&t.referenceTo.some(r=>Ar.has(r))?{...t,nillable:!0}:t)}function _t(o){if(!("attributes"in o))return o;let e={...o};return delete e.attributes,e}var ls=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),ga(e,t,this.prefixes))}note(e,t){this.prefixes.set(e,t),this.known.add(t)}};function Gr(o,e){return e.filter(t=>t.type==="reference"&&Xt(o,t.name,t.nillable)).map(t=>t.name)}function ju(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 Fu=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/,Jn=class extends Error{constructor(e){super(e),this.name="FrozenExtractionError"}},Ur=class{deps;soqlBuilder=new ca;constructor(e){this.deps=e}query(e){return ki(e,t=>this.deps.query(t))}async extract(e){if(!Fu.test(e.asOf))throw new Jn(`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 Jn("No root record IDs provided \u2014 empty selection refused");let t=e.guard??new ue,r=t.assertOutsideRepo(e.sasDir),n=`CreatedDate <= ${e.asOf}`,s=new Co;s.add(e.rootObject,e.rootRecordIds),s.addReached(e.rootObject,e.rootRecordIds);let i=new Map,d=new er,a=new Set,u={},l=new ls(this.deps.keyPrefixes),c=new Map,f=async w=>{let O=c.get(w);if(O)return O;let j=await this.deps.describeFields(w);return c.set(w,j),j},p=async w=>{let O=await f(w);O.some(v=>v.name==="CreatedDate")||a.add(w);let j=O.filter(v=>v.type==="base64").map(v=>v.name);return j.length>0&&(u[w]=j),O},g=new Set(e.excludedObjects??[]),h=await this.withWhatStatusesNeed(pa(e.graph,g),f,g),m=h.graph,y=[...m.nodes].filter(w=>w.included).sort((w,O)=>w.level-O.level),k=new Set(y.map(w=>w.objectApiName));for(let w of y){let O=await p(w.objectApiName),j=this.selectFields(w.objectApiName,O,e.excludedFields),v=O.some(E=>E.name==="CreatedDate"),A=this.soqlBuilder.build({node:w,fields:Tu(w.objectApiName,O),selectFields:j,edges:m.edges,cache:s,rootObjectApiName:`__frozen_root_${e.rootObject}__`,rootRecordId:e.rootRecordIds[0],extraWhere:v?n:void 0,everyEdge:!Ar.has(w.objectApiName),readObjects:k,catalog:Ar,fromAboveOnly:!0});if(!A.scoped)continue;let F=[],$=[];for(let[E,W]of A.statements.entries()){let Y=await this.query(W);if(F.push(...Y),!(E<A.byIdCount))for(let ie of Y)typeof ie.Id=="string"&&$.push(ie.Id)}let D=d.keep(w.objectApiName,await this.keepWhatStatusesNeed(h.added.get(w.objectApiName),F,i),Gr(w.objectApiName,O)),G=i.get(w.objectApiName);G||(G=new Map,i.set(w.objectApiName,G));let V=[];for(let E of D){let W=E.Id;typeof W!="string"||W===""||(V.push(W),G.has(W)||G.set(W,_t(E)))}s.addRead(w.objectApiName,V);let H=new Set(V);s.addReached(w.objectApiName,$.filter(E=>H.has(E))),l.learnFrom(i);for(let E of O)if(E.type==="reference")for(let W of D){let Y=W[E.name];if(!(typeof Y!="string"||Y===""))for(let ie of await l.objectsOf(Y,E.referenceTo))s.add(ie,[Y])}w.objectApiName===e.rootObject&&await this.readWhatTheRootsName({rootObject:e.rootObject,fields:O,selectFields:j,bucket:G,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 Eu(i,p,d);let N=await this.addStandardPrices(e,i,n);await this.addSellingModelOptions({...e,graph:m},i,p,n,g);let T=(i.get(cn)?.size??0)>0,P=await this.exclusionCosts(i,p,g,T),x=await this.leaveOutWhatReadsMasked(i,f),U=[...i.entries()].sort(([w],[O])=>w.localeCompare(O)).map(([w,O])=>{let j=[...O.values()].sort((A,F)=>String(A.Id).localeCompare(String(F.Id)));w===qe&&(j=Ws(j,{sellingModel:T}));let v=j.map((A,F)=>({referenceId:`${w}-${String(F+1).padStart(6,"0")}`,sourceId:String(A.Id),fields:A}));return{objectApiName:w,records:v}}),C=await this.pullRecordTypes(e);await Xn.mkdir(r,{recursive:!0});let I=t.assertOutsideRepo(jc.join(r,Au));return await Xn.writeFile(I,`${JSON.stringify(C,null,2)}
|
|
20
|
-
`,"utf8"),{objects:U,asOf:e.asOf,recordTypeMap:C,unboundedObjects:[...a],fileFields:u,...N?{standardPricebookSourceId:N}:{},leftToThePlatform:d.counts(),...P.length>0?{exclusionCosts:P}:{},...x.length>0?{encryptedNotKept:x}:{}}}async leaveOutWhatReadsMasked(e,t){let r=Ji(Yi(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 u of i.values())d in u&&(a||=u[d]!==null&&u[d]!==void 0,delete u[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 u=sn[a.objectApiName];if(!a.included||!u||n.has(u.object)||s.has(u.object)||r.has(u.object))continue;let l;try{l=await t(u.object)}catch{continue}let c=l.find(f=>f.name===u.lookup&&f.type==="reference"&&f.referenceTo.includes(a.objectApiName));c&&(s.set(u.object,{parent:a.objectApiName,lookup:c.name}),i.push(ju(u.object,l,a.level+1)),d.push({sourceObject:a.objectApiName,targetObject:u.object,relationshipName:c.name,type:"lookup",required:Xt(u.object,c.name,c.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,Gr(t,e.fields));for(let a of d)typeof a.Id=="string"&&!r.has(a.Id)&&r.set(a.Id,_t(a));e.owners.learnFrom(e.recordsByObject);for(let a of e.fields)if(a.type==="reference")for(let u of d){let l=u[a.name];if(!(typeof l!="string"||l===""))for(let c of await e.owners.objectsOf(l,a.referenceTo))n.add(c,[l])}}async keepWhatStatusesNeed(e,t,r){if(!e)return t;let n=zt[e.parent],s=n?await rr(d=>this.query(d),n):void 0,i=new Set;for(let[d,a]of r.get(e.parent)??[])s&&nr(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(sn)){let n=e.nodes.find(m=>m.objectApiName===r.object),s=e.recordsByObject.get(t),i=zt[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 u=await rr(m=>this.query(m),i);if(!u)continue;let l=a.filter(([,m])=>nr(m.Status,u)).map(([m])=>m);if(l.length===0)continue;let c=await e.describe(r.object),f=new Co;f.addRead(t,l);let p=this.soqlBuilder.build({node:n,fields:c,selectFields:this.selectFields(r.object,c,e.excludedFields),edges:e.edges,cache:f,rootObjectApiName:`__frozen_root_${t}__`,rootRecordId:l[0],extraWhere:c.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=Gr(r.object,c);for(let m of p.statements){let y=e.leftToThePlatform.keep(r.object,await this.query(m),h);for(let k of y)typeof k.Id=="string"&&!g.has(k.Id)&&g.set(k.Id,_t(k))}}}async completeRequiredParents(e,t,r,n,s,i,d){let a=new Set(e.graph.nodes.filter(f=>f.included).map(f=>f.objectApiName)),u=fa(e.graph,d),l=f=>a.has(f)||u.has(f),c=new Map;for(let f=0;f<Pu;f++){s.learnFrom(t);let p=new Map;for(let[g,h]of t){let m=(await r(g)).filter(y=>y.type==="reference"&&ua(g,y));for(let y of h.values())for(let k of m){let N=y[k.name];if(typeof N!="string"||N===""||i.has(N)||!k.referenceTo.some(l))continue;let T=(await s.objectsOf(N,k.referenceTo)).filter(l);for(let P of T)t.get(P)?.has(N)||c.get(P)?.has(N)||p.set(P,(p.get(P)??new Set).add(N))}}if(p.size===0)return;for(let[g,h]of p){c.set(g,new Set([...c.get(g)??[],...h]));let m=await r(g),y=t.get(g);y||(y=new Map,t.set(g,y));let k=this.soqlBuilder.buildById({objectApiName:g,selectFields:this.selectFields(g,m,e.excludedFields),ids:h,extraWhere:m.some(T=>T.name==="CreatedDate")?n:void 0}),N=Gr(g,m);for(let T of k)for(let P of i.keep(g,await this.query(T),N))typeof P.Id=="string"&&!y.has(P.Id)&&y.set(P.Id,_t(P))}}}async addStandardPrices(e,t,r){let n=t.get(qe);if(!n||n.size===0)return;let[s]=await this.query(Et),i=typeof s?.Id=="string"?s.Id:void 0;if(!i)return;let d=g=>[Ge,Ye,Zt].map(h=>String(g[h]??"")).join("|"),a=new Set,u=new Set;for(let g of n.values()){if(g[yt]===i)continue;let h=g[Ge];typeof h=="string"&&h!==""&&(a.add(h),u.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(N=>me(N)).join(", "),k=m.some(N=>N.name==="CreatedDate")?` AND ${r}`:"";return this.query(`SELECT ${y} FROM ${g} WHERE ${h}${k}`)},c=t.get(an);if(c||(c=new Map,t.set(an,c)),!c.has(i))for(let g of await l(an,`Id = '${Me(i)}'`))c.set(i,_t(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)||u.has(d(h))&&n.set(h.Id,_t(h));return i}async addSellingModelOptions(e,t,r,n,s){if(s.has(ze)||e.graph.nodes.some(m=>m.objectApiName===ze&&!m.included))return;let i=t.get(qe),d=t.get(la),a=t.get(cn);if(!i||!d||!a)return;let u=m=>`${String(m[Ge]??"")}|${String(m[Ye]??"")}`,l=new Set,c=new Set,f=new Set;for(let m of i.values()){let y=m[Ge],k=m[Ye];typeof y!="string"||!d.has(y)||typeof k!="string"||!a.has(k)||(l.add(y),c.add(k),f.add(u(m)))}if(f.size===0)return;let p=await r(ze),g=this.soqlBuilder.buildJoining({objectApiName:ze,selectFields:this.selectFields(ze,p,e.excludedFields),split:{field:Ge,ids:l},whole:{field:Ye,ids:c},extraWhere:p.some(m=>m.name==="CreatedDate")?n:void 0}),h=t.get(ze);h||(h=new Map,t.set(ze,h));for(let m of g)for(let y of await this.query(m))typeof y.Id!="string"||h.has(y.Id)||f.has(u(y))&&h.set(y.Id,_t(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,u]of e){if(u.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])&&Xt(a,g.name,g.nillable)),c=a===qe&&n&&r.has(ze);if(l.length===0&&!c)continue;let f=new Map,p=new Map;for(let[g,h]of u){let m;for(let N of l){let T=h[N.name],P=N.referenceTo[0];if(!(typeof T!="string"||T==="")&&!e.get(P)?.has(T)){m={field:N.name,excluded:P};break}}let y=h[Ye];if(!m&&c&&typeof y=="string"&&e.get(cn)?.has(y)&&(m={field:Ye,excluded:ze}),!m)continue;f.set(g,m.excluded);let k=p.get(m.excluded)??{field:m.field,count:0};k.count++,p.set(m.excluded,k)}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===ze?`${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,u]of Object.entries(sn)){let l=e.get(a),c=zt[a];if(!l||l.size===0||!c)continue;let f=await rr(y=>this.query(y),c);if(!f)continue;let p=new Set,g=new Map,h=d.get(u.object);for(let[y,k]of e.get(u.object)??[]){let N=k[u.lookup];if(typeof N!="string")continue;let T=h?.get(y);T?g.has(N)||g.set(N,T):p.add(N)}let m=new Map;for(let[y,k]of l){if(!nr(k.Status,f))continue;let N=r.has(u.object)?u.object:p.has(y)?void 0:g.get(y);N&&m.set(N,(m.get(N)??0)+1)}for(let[y,k]of m){let N=k===1;s.push({objectApiName:a,excludedObject:y,count:k,note:`${k} ${a} ${i(k)} past Draft will be loaded as ${N?"a draft":"drafts"} and stay so: `+(y===u.object?`the platform gives ${a} this status only with ${u.object} records under it, and excludedObjects leaves ${u.object} out`:`none of ${N?"its":"their"} ${u.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??Su,r=Br(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 Eu(o,e,t){for(let r=!0;r;){r=!1;for(let[n,s]of o){let i=[...s.values()],d=Gr(n,await e(n)),a=t.keep(n,i,d);if(a.length===i.length)continue;r=!0;let u=new Set(a.map(l=>l.Id));for(let l of s.keys())u.has(l)||s.delete(l)}}}var Zn=class{anonymize(e){let{rules:t,pseudonymizer:r}=e,n=Object.entries(e.extracted.fileFields??{}).filter(([c,f])=>f.some(p=>ut(t,c,p)!=="keep")).map(([c])=>c).filter(c=>e.extracted.objects.some(f=>f.objectApiName===c&&f.records.length>0)).sort(),s={...e.extracted,objects:e.extracted.objects.filter(c=>!n.includes(c.objectApiName))},i=new Map;for(let c of s.objects)for(let f of c.records)i.set(f.sourceId,f.referenceId);let d=new Map(s.recordTypeMap.map(c=>[c.id,c])),a={};for(let c of s.objects)a[c.objectApiName]=s.recordTypeMap.filter(f=>f.sobjectType===c.objectApiName).map(f=>({name:f.name,developerName:f.developerName,...f.namespacePrefix!==void 0?{namespacePrefix:f.namespacePrefix}:{}}));let u=[];for(let c of s.objects){let f=c.records.map(p=>{let g=this.anonymizeRecordFields(c.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:ct(m.namespacePrefix,m.developerName)}:{}}});u.push({objectApiName:c.objectApiName,records:f})}let l=s.standardPricebookSourceId?i.get(s.standardPricebookSourceId):void 0;return{datasetVersion:e.datasetVersion,objects:u,recordTypes:a,personContactSidecar:Lu(s,i),...l?{standardPricebook:l}:{},...n.length>0?{filesLeftOut:n}:{}}}anonymizeRecordFields(e,t,r,n,s,i){let d={};for(let[a,u]of Object.entries(t)){if(a==="Id")continue;if(u==null){d[a]=u;continue}if(a==="RecordTypeId"&&typeof u=="string"){let c=n.get(u);d[a]=c?c.name:"";continue}if(typeof u=="string"){let c=r.get(u);if(c!==void 0){d[a]=c;continue}}let l=ut(s,e,a);d[a]=i.pseudonymize(l,u)}for(let[a,u]of Object.entries(d))typeof u=="string"&&Rn(u)&&(d[a]="");return d}};function Lu(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 Nu=/^[A-Z]{2}-\d{3}-[A-Z]{2}$/,Cu=/^\+3363998\d{4}$/,zu=/^[a-z0-9-]+@example\.invalid$/,Mu=/^\d{2}0+$/,Du=3,Qn=class{run(e,t,r,n={}){let s=new Set,i=new Map;for(let c of t.objects)for(let f of c.records)s.add(f.referenceId),i.set(f.referenceId,{objectApiName:c.objectApiName,record:f});let d={substitution:[],"clear-empty":[],formats:[],"no-residual-id":[]},a=new Map(e.recordTypeMap.map(c=>[c.id,[c.name,c.developerName]])),u=new Set(t.filesLeftOut??[]);for(let c of e.objects)if(!u.has(c.objectApiName))for(let f of c.records){let p=i.get(f.referenceId);if(!p){d.substitution.push({check:"substitution",objectApiName:c.objectApiName,referenceId:f.referenceId,detail:"record missing from the frozen dataset"});continue}let g=f.fields.RecordTypeId;this.checkSubstitution(c.objectApiName,f,p.record,r,d.substitution,new Set(typeof g=="string"?a.get(g)??[]:[]))}for(let c of t.objects)for(let f of c.records)this.checkClearEmpty(c.objectApiName,f,r,s,d["clear-empty"]),this.checkNoResidualId(c.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(c=>({name:c,passed:d[c].length===0,violations:d[c]}));return{passed:l.every(c=>c.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===""||ut(n,e,d)==="keep")continue;let l=r.fields[d];if(xu(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>=Du)for(let[c,f]of Object.entries(r.fields))c===d||typeof f!="string"||f!==a||ut(n,e,c)==="keep"||c==="RecordTypeId"&&i.has(f)||s.push({check:"substitution",objectApiName:e,referenceId:t.referenceId,field:c,detail:`transversal leak: original value of "${d}" found in "${c}"`})}}checkClearEmpty(e,t,r,n,s){for(let[i,d]of Object.entries(t.fields))i!=="RecordTypeId"&&(typeof d=="string"&&n.has(d)||ut(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=>Nu.test(d),phoneE164:d=>Cu.test(d),email:d=>zu.test(d),postalCodeGeneralize:(d,a)=>Mu.test(d)&&d.length===a.trim().length};for(let d of e.objects)for(let a of d.records){let u=n.get(a.referenceId);if(u)for(let[l,c]of Object.entries(a.fields)){if(typeof c!="string"||c==="")continue;let f=ut(r,d.objectApiName,l),p=i[f];if(!p)continue;let g=u.record.fields[l];typeof g!="string"||g===""||p(g,c)||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"&&Rn(i)&&n.push({check:"no-residual-id",objectApiName:e,referenceId:t.referenceId,field:s,detail:"checksum-valid Salesforce ID survived the sweep"})}};function xu(o,e){return o===e?!0:o==null||e===null||e===void 0?!1:String(o)===String(e)}var Kr=class{constructor(e){this.orgAccess=e}orgAccess;cache=new Map;describes=new Map;async resolveByDeveloperName(e,t,r,n){let s=n===void 0?Oi(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 = '${Me(t)}' AND DeveloperName = '${Me(s.developerName)}'`,u=vi(await this.orgAccess.query(e,a)),l=Si(s,u,Ro),c;if("ambiguous"in l)c={ambiguous:!0,carriers:l.ambiguous.map(Ro)};else if("found"in l){let f=l.found.id;c=await this.isUnavailable(e,t,f)?{unavailable:!0,id:f}:f}else c=null;return this.cache.set(i,c),c}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 En(bn((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 ro from"node:fs";var $u=2e3,_u=3,Bu=10,qu=o=>new Promise(e=>setTimeout(e,o)),eo=class{constructor(e){this.deps=e;this.sasGuard=e.sasGuard??new ue}deps;sasGuard;personAccounts=new Map;async verify(e){let t=e.now??(()=>new Date),r=e.sleep??qu,n=g=>e.onProgress?.(g),s=e.measurementIntervalMs??$u,i=e.maxAttempts??_u,d=Cn(this.sasGuard,e.contractPath);n({phase:"verify",status:"started",progress:0,message:"Measuring org state"});let a=null,u=null,l=null,c=0;for(let g=1;g<=i;g++){c=g,l=await this.measure(e,d);let h=us(l);if(a!==null&&h===a){u=l;break}a=h,g<i&&await r(s)}let f=this.buildChecks(e,d,u??l,u!==null),p={status:Hu(f,d,u),checks:f,attempts:c,measuredAt:t().toISOString(),objects:Yu(d,u??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} (${c} 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?Ec(e.mapping):void 0,n={};for(let s of Object.keys(t.objects).sort()){let i=`SELECT COUNT() FROM ${me(s)}`;if(!r){n[s]=await this.deps.orgAccess.count(e.orgId,i);continue}let d=0;for(let a of Lc(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??Bu,s=e.mapping?Ec(e.mapping):void 0;for(let[i,d]of Object.entries(e.mandatoryLookups??{}))for(let a of d){let u=new Set([...Fc(t,i,a),...fs(t.objects[i]?.parentNotLoaded,a)].flatMap(f=>{let p=e.mapping?.get(f);return p===void 0?[]:[p]})),l=s?Lc((s.get(i)??[]).filter(f=>!u.has(f))):[""],c=[];for(let f of l){let p=`SELECT Id FROM ${me(i)} WHERE ${me(a)} = null${f?` AND ${f}`:""} ORDER BY Id LIMIT ${n}`,g=await this.deps.orgAccess.query(e.orgId,p);c.push(...g.map(h=>String(h.Id)))}r[`${i}.${a}`]=c.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 yn(a=>this.deps.orgAccess.query(e.orgId,a),n),i=[],d=0;for(let a of r){let u=e.mapping.get(a.accountReferenceId),l=s.get(u);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(Fc(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 u=new Set;for(let l=0;l<a.length;l+=to){let c=a.slice(l,l+to).map(p=>`'${Me(p)}'`).join(", "),f=await this.deps.orgAccess.query(e.orgId,`SELECT ${me(s)} k FROM ${me(n)} WHERE ${me(s)} IN (${c})`);for(let p of f)u.add(String(p.k))}r[n]=a.filter(l=>!u.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=Nc(t),a=Wu(t,r);s.push({name:"load",passed:d.records===0&&a.length===0,detail:Uu(d,a)});let u=Object.entries(r.orphans).filter(([,f])=>f.length>0),l=Vu(t),c=[...u.length>0?[`Orphans \u2014 ${u.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:c.length===0,detail:c.length===0?"No orphans on the mandatory lookups of the graph":c.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=Fr(JSON.parse(ro.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(", ")},ro.writeFileSync(n,xn(s),"utf8")}};function us(o){return Array.isArray(o)?`[${o.map(us).join(",")}]`:typeof o=="object"&&o!==null?`{${Object.entries(o).sort(([t],[r])=>t.localeCompare(r)).map(([t,r])=>`${JSON.stringify(t)}:${us(r)}`).join(",")}}`:JSON.stringify(o)}function Fc(o,e,t){return fs(o.objects[e]?.writtenWithout,t)}function fs(o,e){let t=o?.[e];return Array.isArray(t)?t.filter(r=>typeof r=="string"):[]}var Vr={refused:["dml-failed","person-contact-not-sent"],heldBack:["parent-refused"],notLoadable:["object-not-loaded"]};function Nc(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=u=>u.reduce((l,c)=>l+(r.exclusionReasons[c]??0),0),s=n(Vr.notLoadable);s>0&&e.notLoadable.push({objectApiName:t,records:s});let i=n(Vr.refused),d=n(Vr.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 Wu(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 Gu(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 Uu(o,e=[]){let t=Ku(o),r=Gu(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 Ku(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 Vu(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=fs(r.parentNotLoaded,n).length;s>0&&e.push({link:`${t}.${n}`,count:s})}return e}function Hu(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&&Nc(e).whole.length===0?"partial":"failed"}function Yu(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=[...Vr.refused,...Vr.heldBack].reduce((c,f)=>c+(n.exclusionReasons[f]??0),0),i=e?.counts[r]??0,d=Object.entries(e?.orphans??{}).filter(([c])=>t(c)===r).reduce((c,[,f])=>c+f.length,0),a=e?.presence[r]?.length??0,u=r==="Account"?e?.personContact.unrestored.length??0:0,l=e!==null&&i===n.expected&&s===0&&d===0&&a===0&&u===0;return{objectApiName:r,status:l?"passed":"failed",expected:n.expected,found:i,notLoaded:s,orphans:d,missingKeys:a,...u>0?{personContactsUnlinked:u}:{}}})}var to=200;function Ec(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 Lc(o){let e=[];for(let t=0;t<o.length;t+=to){let r=o.slice(t,t+to).map(n=>`'${Me(n)}'`);e.push(`Id IN (${r.join(", ")})`)}return e}var gs=200;function hs(o,e=gs){return{insert:(t,r,n,s)=>ps(o.insert(r,n,e,s?Ju(s):void 0)),update:(t,r,n)=>ps(o.update(r,n,e)),delete:(t,r,n)=>ps(o.delete(r,n,e))}}function Ju(o){let e=0,t=0;return{sending:(r,n,s)=>{t=s},answered:(r,n,s,i)=>{i?s.forEach((d,a)=>{let u=i[a];u!==void 0&&o(u,[d])}):(o(e,s),e+=t),t=0}}}async function ps(o){try{return await o}catch(e){if(e instanceof ad)return e.written;throw e}}var Xu=200;function Cc(o){let e={threshold:o.threshold,perCall:gs,...o.duplicateRules?{duplicateRules:o.duplicateRules}:{}},t=o.inserts.filter(({rows:n})=>n>0),r=t.reduce((n,{rows:s})=>n+Math.ceil(s/Xu),0);return Do(t,e)+Do((o.purged??[]).filter(({rows:n})=>n>0),e)+cd(t.length,o.automationRead??0)+r}function de(o){return o.slice(0,15)}var Dc=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function ke(o){return zi(o)??o}function zc(o,e){return`${o}-${ke(e)}`}var ms="005",ys="00G",xc="00D",ws="00e",$c="OwnerId",Is="RecordTypeId",bs="SetupOwnerId",Yr="CurrencyIsoCode",oo="Pricebook2",Bt=200,Rs=new Set([...Ra,jo]),Zu=["Title","Name"];async function*ks(o,e){let t=await Po.read(o.folder,o.checkpoint.snapshotId,e);for await(let r of t.records())typeof r.Id=="string"&&(yield r)}async function Qu(o,e){let t=await Po.read(o.folder,o.checkpoint.snapshotId,e),r=[];for(let n=0;n<t.size;n++)r.push(t.idAt(n));return r}function so(o,e){return o!==void 0&&!o.unread.some(t=>t.part===e)}async function ef(o){let e=Rd(o.checkpoint,o.choices),t=new Map;for(let p of o.checkpoint.objects)for(let g of await Qu(o,p.objectApiName))t.set(de(g),p.objectApiName);let r=new Set,n=new Set,s=new Set,i=new Set,d=new Map,a=new Set,u=[],l=new Set;for(let p of e.replayed)for await(let g of ks(o,p.objectApiName)){l.add(de(g.Id));for(let[h,m]of Object.entries(g)){if(Rs.has(h)||typeof m!="string"||(h===Yr&&m!==""&&a.add(m),!Dc.test(m)))continue;let y=de(m);if(h===Is)s.add(y);else if(y.startsWith(ms))r.add(y);else if(y.startsWith(ys)&&h===$c)n.add(y);else if(y.startsWith(ws)&&h===bs)i.add(y);else if(!t.has(y)&&!y.startsWith(xc)){let k=`${p.objectApiName}.${h}`,N=d.get(k)??new Set;N.add(y),d.set(k,N)}}if(p.objectApiName===qe){let h=g[yt],m=g[Ge];if(typeof h=="string"&&typeof m=="string"){let y=g[Zt];u.push({book:de(h),product:de(m),currency:typeof y=="string"?y:""})}}}let c=[];if((o.checkpoint.files?.links??0)>0)for await(let p of ka(o.folder))l.has(de(p.LinkedEntityId))&&c.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 ks(o,p.objectApiName)){let h=Zu.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:tf(o,u,t),fileLinks:c,filesLeft:f}}function tf(o,e,t){let r=o.checkpoint.objects.some(a=>a.objectApiName===oo||a.objectApiName===qe);if(so(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 u=i.get(a.book)??new Set;u.add(`${a.product}|${a.currency}`),i.set(a.book,u)}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 Hr(o,e){let t=[];for(let r=0;r<o.length;r+=e)t.push(o.slice(r,r+e));return t}function no(o){return o.map(e=>`'${Me(e)}'`).join(", ")}function _c(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 rf(o){if(o===void 0)return;let e=_c(o);return e===o?void 0:o.slice(e.length)}async function nf(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,u=async v=>{s++;try{d.set(v,await e.describe(t,v))}catch(A){a.set(v,Q(A))}};for(let v of r.objects.replayed)await u(v.objectApiName);r.fileLinks.length>0&&await u(or);let l=new Map,c=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(de)])].sort();for(let v of Hr(f,Bt))for(let A of await i(`SELECT Id, Username, IsActive, UserType FROM User WHERE Id IN (${no(v)})`)){let F=c(A);F&&l.set(de(F.id),F)}let p=new Map;if(so(n.annex,"users")){let v=o.tier==="sandbox"?rf(o.username):void 0,A=new Map;for(let D of n.annex.users){let G=de(D.id),V=l.get(G);if(V?.isActive===!0&&V.userType==="Standard")continue;let H=n.checkpoint.org.tier==="sandbox"?_c(D.username):D.username,E=[D.username,H,...v!==void 0?[`${H}${v}`]:[]];A.set(G,[...new Set(E.map(W=>W.toLowerCase()))])}let F=[...new Set([...A.values()].flat())].sort(),$=new Map;for(let D of Hr(F,Bt)){let G=D.map(V=>`'${Me(V)}'`).join(", ");for(let V of await i(`SELECT Id, Username, IsActive, UserType FROM User WHERE Username IN (${G})`)){let H=c(V);H&&$.set(H.username.toLowerCase(),H)}}for(let[D,G]of A){let V=G.map(H=>$.get(H)).find(H=>H!==void 0);V&&p.set(D,V)}}let g=[],h=[...d.keys()].filter(v=>d.get(v)?.fields.some(A=>A.name===Is));if(h.length>0){let v=Bc(d),A=await i(`SELECT Id, SobjectType, DeveloperName, NamespacePrefix, Name, IsActive${v?", IsPersonType":""} FROM RecordType WHERE SobjectType IN (${h.map(F=>`'${me(F)}'`).join(", ")})`);for(let F of A)typeof F.Id!="string"||typeof F.SobjectType!="string"||typeof F.DeveloperName!="string"||g.push({id:ke(F.Id),sobjectType:F.SobjectType,developerName:F.DeveloperName,...typeof F.NamespacePrefix=="string"&&F.NamespacePrefix!==""?{namespacePrefix:F.NamespacePrefix}:{},name:typeof F.Name=="string"?F.Name:F.DeveloperName,isActive:F.IsActive!==!1,...typeof F.IsPersonType=="boolean"?{isPersonType:F.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(de(A.QueueId),[...v.get(de(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(de(A.Id))??[]})}let y;if([...d.values()].some(v=>v.fields.some(A=>A.name===Yr))&&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 N;if(r.standardPricebook.id!==void 0){let[v]=await i(Et);typeof v?.Id=="string"&&(N=ke(v.Id))}let T=new Set,P=new Map;for(let[v,A]of r.heldBy){let F=P.get(A);F?F.push(v):P.set(A,[v])}let x=async(v,A)=>{let F=0;for(let $ of Hr(A,Bt))for(let D of await i(`SELECT Id FROM ${me(v)} WHERE Id IN (${no($)})`))typeof D.Id=="string"&&(T.add(de(D.Id)),F++);return F},U=new Set(r.objects.replayed.map(v=>v.objectApiName));for(let[v,A]of P){if(a.has(v)||bd(v))continue;let F=[...A].sort(),$=F.slice(0,Bt);try{await x(v,$)>0&&await x(v,F.slice(Bt))}catch(D){if(U.has(v))throw D}}let C=new Map;for(let[v,A]of r.notHeld){let[F,$]=v.split("."),D=d.get(F)?.fields.find(H=>H.name===$),G=D?.type==="reference"?D.referenceTo??[]:[];if(G.length!==1)continue;let V=C.get(G[0])??new Set;for(let H of A)V.add(H);C.set(G[0],V)}for(let[v,A]of C)try{await x(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 F of await i(`SELECT Id, Name, SetupOwnerId FROM ${me(v.objectApiName)}`))typeof F.Name=="string"&&A.names.add(F.Name),typeof F.SetupOwnerId=="string"&&A.owners.add(de(F.SetupOwnerId));I.set(v.objectApiName,A)}let w=new Set;for(let v of Hr([...r.profiles].sort(),Bt))for(let A of await i(`SELECT Id FROM Profile WHERE Id IN (${no(v)})`))typeof A.Id=="string"&&w.add(de(A.Id));let O=new Set,j=[...new Set(r.fileLinks.map(v=>de(v.ContentDocumentId)))];if(!a.has(or))for(let v of Hr(j.sort(),Bt))for(let A of await i(`SELECT Id FROM ContentDocument WHERE Id IN (${no(v)})`))typeof A.Id=="string"&&O.add(de(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}:{},...N!==void 0?{standardPricebookId:N}:{},sameIds:T,customSettings:I,profiles:w,files:O,requests:s}}function Bc(o){return o.get("Account")?.fields.some(e=>e.name===jo)===!0}function of(o,e,t){let r=[...new Set(Object.values(o.ownerMap??{}).map(de))].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 qt=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 sf(o,e){return e.createable&&e.nillable===!1&&e.defaultedOnCreate!==!0||qs(o,e.name)}function af(o){let e=o.length;return typeof e=="number"&&e>0?e:void 0}var df=new Set(["id","reference","boolean","double","int","long","percent","currency","date","datetime","time","picklist","multipicklist"]);async function cf(o){let{survey:e,target:t,choices:r,annex:n}=o,s=of(r,t,o.targetName);if(s)return{refusal:s};let i=new qt(R=>`${R.object}|${R.reason}`);for(let R of e.objects.leftOut)i.add({object:R.objectApiName,reason:R.reason},R.records);let d=e.objects.replayed.filter(R=>t.missing.has(R.objectApiName)?(i.add({object:R.objectApiName,reason:"notInTarget"},R.records),!1):t.describes.get(R.objectApiName)?.createable===!1?(i.add({object:R.objectApiName,reason:"notCreateable"},R.records),!1):!0),a=new Set(d.map(R=>R.objectApiName)),u=new qt(R=>`${R.field}|${R.reason}`),l={kept:0,toRunningUser:0,reasons:{notInTarget:0,inactive:0,queueMissing:0}},c=new qt(R=>`${R.object}|${R.recordType}|${R.outcome}`),f=new qt(R=>R),p=new Map,g=!1,h={inserted:0,alreadyThere:0},m=new Map,y=new Map,k=Bc(t.describes),N=new Set,T=e.standardPricebook,P=T.id!==void 0?de(T.id):void 0,x=new Map(Object.entries(r.ownerMap??{}).map(([R,L])=>[de(R),ke(L)])),U=R=>{let L=t.usersById.get(R);if(L?.userType==="Standard"&&L.isActive)return{id:L.id};let S=t.usersByUsername.get(R);return S?.userType==="Standard"&&S.isActive?{id:S.id}:{why:L!==void 0||S!==void 0?"inactive":"notInTarget"}},C=(R,L)=>{let S=X=>X.sobjectTypes.includes(R),J=t.queues.find(X=>de(X.id)===L&&S(X));if(J)return J.id;let ne=so(n,"queues")?n.queues.find(X=>de(X.id)===L):void 0;if(ne!==void 0)return t.queues.find(X=>X.developerName===ne.developerName&&S(X))?.id},I=(R,L,S)=>{let J=de(L),ne=so(n,"recordTypes")?n.recordTypes.find(q=>de(q.id)===J):void 0,X=t.recordTypes.filter(q=>q.sobjectType===R&&q.isActive),he,ee="default";if(ne!==void 0&&(he=X.find(q=>q.developerName===ne.developerName&&(q.namespacePrefix??null)===(ne.namespacePrefix??null)),he&&(ee="byName")),he===void 0&&(he=X.find(q=>de(q.id)===J),he&&(ee="byId")),he===void 0&&S){let q=X.filter(ae=>ae.isPersonType===!0);if(q.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`};he=q[0]}let Be={recordType:ne!==void 0?ct(ne.namespacePrefix,ne.developerName):ke(L),outcome:ee};if(he===void 0)return{given:Be};let M=he,we=t.describes.get(R)?.recordTypeInfos?.find(q=>de(q.recordTypeId)===de(M.id));if(we!==void 0&&!we.available)return{refused:`${ct(M.namespacePrefix,M.developerName)} is not assigned to the user who replays in ${o.targetName}: assign it to them, or leave ${R} out`};let et={name:M.name,developerName:M.developerName,namespacePrefix:M.namespacePrefix??null},tt=y.get(R)??new Map;return tt.set(M.id,et),y.set(R,tt),{ref:et,given:Be}},w=[];for(let R of d){let L=R.objectApiName,S=t.describes.get(L);if(S===void 0)continue;let J=new Map(S.fields.map(ee=>[ee.name,ee])),ne=R.fields.filter(ee=>!Rs.has(ee)&&!J.has(ee)&&!(ee===Yr&&t.currencies===void 0));ne.length>0&&p.set(L,new Set(ne));let X=R.customSetting,he=t.customSettings.get(L);for await(let ee of ks(o,L)){let Be=de(ee.Id);if(t.sameIds.has(Be)){m.set(zc(L,ee.Id),ke(ee.Id));continue}let M={objectApiName:L,key:Be,referenceId:zc(L,ee.Id),fields:{},pointsAt:new Map,sourceId:ke(ee.Id),emptied:[]},we=(q,ae)=>{M.refused??={reason:q,...ae!==void 0?{path:ae}:{}}},et=(L==="Account"||L==="Contact")&&Ir(ee);et&&!k&&we("personAccountsUnsupported",`turn person accounts on in ${o.targetName}, or leave ${L} out`),et&&L==="Contact"&&N.add(Be);let tt=L==="Account"?mn(ee,!1):void 0;for(let[q,ae]of Object.entries(ee)){if(Rs.has(q)||tt!==void 0&&un(L,q,tt))continue;let kt=J.get(q);if(kt===void 0){q===Yr&&typeof ae=="string"&&ae!==""&&(g||=t.currencies===void 0);continue}if(ae==null||ae==="")continue;if(q===Yr&&typeof ae=="string"){t.currencies!==void 0&&!t.currencies.has(ae)&&(we("inactiveCurrency",`activate ${ae} in ${o.targetName}, or leave ${L} out`),f.add(ae)),M.fields[q]=ae;continue}if(q===Is&&typeof ae=="string"){let ye=I(L,ae,et);ye.given!==void 0&&(M.recordType=ye.given),ye.refused!==void 0?we("recordTypeUnavailable",ye.refused):ye.ref!==void 0&&(M.fields[q]=ye.ref.name,M.recordTypeDeveloperName=ct(ye.ref.namespacePrefix,ye.ref.developerName));continue}if(kt.type!=="reference"||typeof ae!="string"||!Dc.test(ae)){M.fields[q]=ae;continue}let fe=de(ae),ft=sf(L,kt),We=(ye,Ie)=>{ft?we("requiredLookupMissing",Ie):M.emptied.push({field:`${L}.${q}`,reason:ye})};if(fe.startsWith(xc)){M.fields[q]=t.organizationId;continue}if(q===bs){(fe.startsWith(ws)?t.profiles.has(fe):t.usersById.has(fe))?M.fields[q]=ke(ae):we("requiredLookupMissing",`the ${fe.startsWith(ws)?"profile":"user"} its row is of is not in ${o.targetName}`);continue}if(q===$c&&(fe.startsWith(ms)||fe.startsWith(ys))){let ye=x.get(fe);if(ye!==void 0)M.owner="kept",M.fields[q]=ye;else if(r.owners==="me")M.owner="toRunningUser";else if(fe.startsWith(ys)){let Ie=C(L,fe);M.owner=Ie!==void 0?"kept":"queueMissing",Ie!==void 0&&(M.fields[q]=Ie)}else{let Ie=U(fe);M.owner=Ie.id!==void 0?"kept":Ie.why??"notInTarget",Ie.id!==void 0&&(M.fields[q]=Ie.id)}continue}if(fe.startsWith(ms)){let ye=U(fe);ye.id!==void 0?M.fields[q]=ye.id:ft?M.fields[q]=t.runningUserId:M.emptied.push({field:`${L}.${q}`,reason:"userNotInTarget"});continue}if(P!==void 0&&fe===P){t.sameIds.has(fe)?M.fields[q]=ke(ae):a.has(oo)&&e.heldBy.has(fe)?M.pointsAt.set(q,fe):t.standardPricebookId!==void 0?M.fields[q]=t.standardPricebookId:We("objectNotHeld",`${o.targetName} has no standard price book`);continue}let xe=e.heldBy.get(fe);xe!==void 0&&t.sameIds.has(fe)?M.fields[q]=ke(ae):xe!==void 0&&a.has(xe)?M.pointsAt.set(q,fe):xe!==void 0?We("objectNotReplayed",`replay ${xe} too`):t.sameIds.has(fe)?M.fields[q]=ke(ae):We("objectNotHeld",`the checkpoint holds no record it points at, and ${o.targetName} holds none under its Id`)}if(L===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`),X!==void 0&&he!==void 0){let q=M.fields[bs];if(X==="list"?typeof ee.Name=="string"&&he.names.has(ee.Name):typeof q=="string"&&he.owners.has(de(q))){h.alreadyThere++;continue}}w.push(M)}}let O=new Map(w.map(R=>[R.key,R])),j=new Map;for(let R of w)for(let L of R.pointsAt.values()){let S=j.get(L);S?S.push(R):j.set(L,[R])}let v=w.filter(R=>R.refused!==void 0);for(let R=0;R<v.length;R++){let L=v[R];for(let S of j.get(L.key)??[])S.refused===void 0&&(S.refused={reason:"parentRefused",path:`its ${L.objectApiName} is refused: lift that first`},v.push(S))}let A=new qt(R=>`${R.object}|${R.reason}`),F=new Map,$=[];for(let R of w){if(R.refused!==void 0){A.add({object:R.objectApiName,...R.refused});continue}for(let S of R.emptied)u.add(S);R.recordType!==void 0&&c.add({object:R.objectApiName,...R.recordType}),R.owner==="kept"?l.kept++:R.owner!==void 0&&(l.toRunningUser++,R.owner!=="toRunningUser"&&l.reasons[R.owner]++);for(let[S,J]of R.pointsAt){let ne=O.get(J);ne!==void 0&&ne.refused===void 0?R.fields[S]=ne.referenceId:u.add({field:`${R.objectApiName}.${S}`,reason:"objectNotReplayed"})}N.has(R.key)&&typeof R.fields.AccountId=="string"&&$.push({accountReferenceId:R.fields.AccountId,contactReferenceId:R.referenceId});let L=F.get(R.objectApiName)??[];L.push({referenceId:R.referenceId,fields:R.fields,...R.recordTypeDeveloperName!==void 0?{recordTypeDeveloperName:R.recordTypeDeveloperName}:{}}),F.set(R.objectApiName,L)}for(let R of d)R.customSetting!==void 0&&(h.inserted+=F.get(R.objectApiName)?.length??0);let D=t.describes.get(or);if(D!==void 0&&D.createable!==!1){let R=[];for(let L of e.fileLinks){let S=O.get(de(L.LinkedEntityId));S===void 0||S.refused!==void 0||t.files.has(de(L.ContentDocumentId))&&R.push({referenceId:`${or}-${ke(L.ContentDocumentId)}_${S.sourceId}`,fields:{ContentDocumentId:ke(L.ContentDocumentId),LinkedEntityId:S.referenceId,ShareType:L.ShareType,Visibility:L.Visibility}})}R.length>0&&F.set(or,R)}let G=new Ua(o.salt),V=r.mask?new Ya(void 0,o.salt):void 0,H=r.mask?new vn:void 0,E=[],W=[];for(let[R,L]of F){let S=t.describes.get(R);if(S===void 0)continue;let J=new Set(L.flatMap(M=>Object.keys(M.fields))),ne=S.fields.filter(M=>J.has(M.name)).map(M=>{let we=af(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=G.forObject(R,ne);if(M)for(let we of L)M(we.fields)}if(V===void 0||H===void 0)continue;let X=ne.filter(M=>!df.has((M.type??"").toLowerCase())),he=new Set(In(H,X.map(M=>({name:M.name,type:M.type??"string"})))),ee=X.filter(M=>he.has(M.name)).map(M=>({name:M.name,type:M.type??"string",...M.length!==void 0?{length:M.length}:{}}));for(let M of ee)E.push(`${R}.${M.name}`);for(let M of X)!he.has(M.name)&&(M.type??"").toLowerCase()==="textarea"&&W.push(`${R}.${M.name}`);if(ee.length===0)continue;let Be=V.anonymize({objectApiName:R,records:L.map(M=>M.fields),sourceIds:L.map(M=>M.referenceId),fields:ee,methods:{}});L.forEach((M,we)=>{M.fields=Be[we]??M.fields})}let Y={};for(let[R,L]of y)Y[R]=[...L.values()];let ie=[...F].map(([R,L])=>({objectApiName:R,records:L})),_=P!==void 0?O.get(P):void 0,K=_!==void 0&&_.refused===void 0&&_.objectApiName===oo?_.referenceId:void 0,Z={datasetVersion:"1.0.0",objects:ie,recordTypes:Y,personContactSidecar:$,...K!==void 0?{standardPricebook:K}:{}},re=ie.reduce((R,L)=>R+L.records.length,0),ge=e.objects.replayed.some(R=>R.objectApiName===oo||R.objectApiName===qe),_e=A.entries(),De={records:{toCreate:re-(K!==void 0?1:0),linkedById:m.size,linkedByKey:0,refusedBeforeWrite:_e.reduce((R,L)=>R+L.n,0)},owners:l,recordTypes:c.entries().map(({key:R,n:L})=>({...R,records:L})).sort((R,L)=>Mc(`${R.object}.${R.recordType}`,`${L.object}.${L.recordType}`)),notReplayed:i.entries().map(({key:R,n:L})=>({...R,records:L})),lookupsEmptied:u.entries().map(({key:R,n:L})=>({...R,records:L})).sort((R,L)=>Mc(R.field,L.field)),refused:_e.map(({key:R,n:L})=>({object:R.object,records:L,reason:R.reason,...R.path!==void 0?{path:R.path}:{}})),fieldsNotInTarget:[...p].map(([R,L])=>({object:R,fields:[...L].sort()})),...e.objects.replayed.some(R=>R.customSetting!==void 0)?{customSettings:h}:{},currencies:{refused:f.entries().map(({key:R,n:L})=>({code:R,records:L})),...g?{singleCurrencyTarget:!0}:{}},...ge?{standardPricebook:T.how}:{},masked:{fields:E.sort(),...r.mask?{unmaskedFreeText:W.sort()}:{}},contactPoints:r.contactPoints,degraded:lf(n),auditDates:"new"};return{conversion:{dataset:Z,summary:De,identityKeys:Object.fromEntries(r.link.map(R=>[R.objectApiName,[...R.fields]])),linkedById:m,filesLeft:e.filesLeft}}}function lf(o){return o===void 0?["recordTypes","users","queues","standardPricebook"]:[...new Set(o.unread.map(e=>e.part))]}function Mc(o,e){return o<e?-1:o>e?1:0}async function qc(o){let e={folder:o.folder,checkpoint:o.checkpoint,annex:o.annex,choices:o.choices},t=await ef(e),r=await nf({...o,source:e,survey:t});return{...await cf({...e,survey:t,target:r,targetName:o.targetName,...o.salt!==void 0?{salt:o.salt}:{}}),target:r,survey:t}}var ff={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.")}},pf=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"]),io="REPLACE_LEAVES_RECORDS",fr=class extends Error{constructor(t){super(t.message);this.stop=t;this.name="RemovalStopped"}stop;get code(){return this.stop.code}},pr=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},Qr=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},en=class extends Error{constructor(t,r,n){super(t);this.apiRequests=r;this.orgId=n;this.name="LoadBudgetStop"}apiRequests;orgId;code=Lo},il="FROZEN_STORAGE_EXCEEDED",tn=class extends Error{constructor(t,r,n){super(t);this.storage=r;this.orgId=n;this.name="LoadStorageStop"}storage;orgId;code=il};function Jr(o){let e=o<10?100:10;return String(o<=0?0:Math.ceil(o*e-1e-9)/e)}function Wc(o){let e;return{request:t=>(e===void 0&&(e=Promise.resolve().then(()=>o.request(t)),e.catch(()=>{})),e)}}function Gc(o){if("unread"in o.storage)return;let e=Math.max(0,o.automationBytes??0),t=al(o.dataset,o.sent)+e,r=(o.purged??[]).filter(l=>l.deletes).reduce((l,c)=>l+Fo(c.objectApiName,{rows:c.rows}),0),n=1024*1024,{remainingMB:s,maxMB:i}=o.storage;if(t<=s*n+r)return;let d={estimateMB:t/n,...e>0?{automationMB:e/n}:{},remainingMB:s,maxMB:i,...r>0?{freedMB:r/n}:{},...o.pilot===!0?{pilot:!0}:{}},a=d.freedMB!==void 0?`, and the reload's purge frees about ${Jr(d.freedMB)} MB first`:"",u=d.automationMB!==void 0?`, about ${Jr(d.automationMB)} MB of it for what the target's automation creates under them`:"";return o.replay===!0?{storage:d,message:`The replay was refused before it wrote anything: the checkpoint's records take about ${Jr(d.estimateMB)} MB of data storage${u}, and ${o.target} has ${s} MB left of ${i} MB${a}. To replay part of it, ${kd.fewerObjects}; or free data storage in ${o.target}. Nothing was written.`}:o.pilot===!0?{storage:d,message:`The pilot was refused before it wrote anything: the records of its root folder take about ${Jr(d.estimateMB)} MB of data storage${u}, and ${o.target} has ${s} MB left of ${i} MB. 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:d,message:`The load was refused before it wrote anything: the dataset's records take about ${Jr(d.estimateMB)} MB of data storage${u}, and ${o.target} has ${s} MB left of ${i} MB${a}. 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 gf=rt({sobjects:mt(rt({name:Ce().min(1),createable:on().optional()}).loose())}).loose();function al(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+Fo(r.objectApiName,{rows:n})},0)}function Uc(o,e,t,r){if(!("objects"in o))return 0;let n=qa(Lt(o,e,r),r),s=new Map(t.objects.map(i=>[i.objectApiName,i.records.length]));return Wa(n,i=>s.get(i)??0)}function hf(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.pilot===!0?{pilot:!0}:{}}}function vs(o,e,t){if(t!==!0)return o;try{return ts(o,e.rootObject)}catch{return o}}function Kc(o){return o?{replay:o}:{}}function mf(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 yf(o,e){let t=Sa(o,e,Di);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:Lo,message:t}}:{}}}function Xr(o,e,t){let r=[...new Set(o.map(s=>s.objectApiName))],n=!!t?.runUserId;return Hs({setToDraft:_i(r),delete:Wi(r,[],{userKept:n})},e)}function Os(o){return o.status==="success"&&(o.left??[]).length===0}function Vc(o){return o.verdict!=="nothingSends"||o.counted.length>0||o.uncounted!==void 0}function wf(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 Zr="frozen",Hc="frozen:config",ur="frozen:lastRun",Yc="frozen:lastRuns",Ss="frozen:lastVerify",As="frozen:lastVerifies",Jc="tokens.json",bf="rules.json",gr=class extends Error{constructor(t,r){super(r);this.rulesPath=t;this.name="RulesFileMissingError"}rulesPath},Rf=async o=>{let e=await import("vscode");await e.window.showTextDocument(e.Uri.file(o),{preview:!1})},kf="0.1.0",If=10*6e4,Ps=15*6e4,vf="EXTRACT_TIMEOUT",Xc=30*6e4,Ts=6e4,Zc=12e4,Of=50;function Sf(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 Qc(o,e){let t=Sf(o,e);return Object.assign(n=>{if(n.status==="started"){t(n);return}t.flush(),o(n)},{flush:t.flush})}async function it(o){try{return await Ae.access(o),!0}catch{return!1}}function Af(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 dl(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,Of).map(t=>({check:t.check,objectApiName:t.objectApiName,referenceId:t.referenceId,field:t.field,detail:Af(t)}))}))}}function el(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:dl(o.controls.nonReidentification),dryRunLoad:o.controls.dryRunLoad,author:o.controls.author,date:o.controls.date},...o.coverage?{coverage:o.coverage}:{}}}function Pf(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 js(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 tl(o,e){return{objects:o.nodes.filter(wa).length,truncated:o.truncated===!0,maxNodes:e}}function Tf(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 Fs(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(ot(o).length>0)return;let t=Tf(zn(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 Es(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 jf(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),u=n.keptChanged+Math.max(0,i)+n.undeletable+n.notVisible+n.unread;if(u===0)continue;let l=t.get(n.objectApiName)??{left:0,why:new Set};l.left+=u;for(let c of a)l.why.add(c);t.set(n.objectApiName,l)}return[...t].map(([r,{left:n,why:s}])=>({objectApiName:r,left:n,why:[...s]}))}function Ff(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,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 Ef(o){return o.status==="completed"?"success":o.perObject.reduce((t,r)=>t+r.inserted+r.reused,0)>0?"partial":"failure"}function Lf(o){let e=o.perObject.reduce((t,r)=>t+r.failed.length,0)+o.purge.failures.length;return lo(o)===0&&e===0?"stopped":"cancelled"}function lo(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 rl(o){return`frozen:${o}`}var ao=(o,e)=>e==="insert"||e==="update",Wt=class extends Error{constructor(t,r){super(r);this.code=t;this.name="CheckpointFirstStop"}code};function Ls(o){let e=new Map,t=r=>{let n=e.get(r)??mi(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 Nf(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 Qe=class extends Error{constructor(t,r,n={}){super(r);this.code=t;this.params=n;this.name="ReplayRefused"}code;params},Ns=class extends Mn{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 Cf(){let o=aa();return{checkpoints:()=>[o,ld(o)].flatMap(e=>{if(!uf(e))return[];let t=da({root:e});return"store"in t?[t.store]:[]}),replays:new wd({root:yd()})}}function nl(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 co(o){return o.replay?{module:"checkpoint",sasMark:Kn(o.replay.folder.dir)}:{module:"frozen"}}function zf(o){return o.replay?{action:"checkpoint_replay",module:"checkpoint"}:{action:"frozen_load",module:"frozen"}}var ol=class{constructor(e){this.deps=e}deps;registry;liveTracker;targetAutomation={read:async(e,t)=>(await this.ownReader()).read(e,t)};reader;saltKeeper=rc();openInEditor=Rf;otherModuleRuns=()=>Promise.resolve([]);removing=new Set;writing=new Qi;loading=new Map;beforeRunCheckpoints;describeCache=new zo({defaultTtl:5*6e4,maxSize:2e3,maxSizeBytes:200*1024*1024,releaseExpired:!0});describeGlobalCache=new zo({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-GOOVPVWX.mjs").then(({TargetAutomationReader:e,targetAutomationQueries:t})=>new e(t(r=>Oe(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!==rl(r)))return!0;return!1}async loadingDuring(e,t){let r=Sn(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(!pf.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(Sn(e,"targetOrgId"),()=>this.handleRemove(e)),!0;case"frozen:remove:sweep":return await this.writing.during(Sn(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(Hc)??null}handleConfigGet(e){let t=this.loadConfig(),r=Se(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=nt(Ai,e,"frozen:config:save:error",this.deps);if(!t)return;this.deps.configStore.set(Hc,t.config,Zr);let r=Se(this.deps,e,"frozen:config:save:response",{success:!0});this.deps.broker.postToWebview(r)}resolveSasDir(e){return e?.sasDir??Te.join(sl.homedir(),".sandforge-sas")}resolveDatasetDir(e){return e?.datasetDir??Te.join(this.resolveSasDir(e),"dataset")}resolveRulesPath(e){return Te.resolve(e?.rulesFilePath??Te.join(this.resolveSasDir(e),bf))}async rulesFileInfo(e){let t=this.resolveRulesPath(e),r=null;try{r=await it(t)?await Ae.readFile(t,"utf8"):null}catch(n){return{path:t,found:!0,invalid:Q(n)}}return{path:t,...pc(r)}}async loadTokens(e,t){return await it(Te.join(e,Jc))?kc(e,Jc,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 Oe(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 ba({describeObject:(e,t)=>this.describeObject(e,t),queryCount:async(e,t)=>(await(await Oe(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 Oe(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??ya}}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 Ac(n,s),u;if("kept"in a){let p=a.kept,g=Pc(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}};u=g}else u=a.none;let l;try{let p=await Oe(t,this.deps.orgRegistry,this.deps.orgManager);l=Tc((await p.soap.getServerTimestamp()).timestamp)}catch(p){this.deps.log(`[WARN] frozen: the source did not give its clock: ${String(p)}`)}let c=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:c,origin:{rediscovered:u},keep:async p=>{let g=new Set([...c.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 Sc(n,{fileVersion:1,...d,step:e.step,discoveredAt:f,...l?{schemaStamp:l}:{},graph:c,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 Oe(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: ${Q(r)}`}}holdKeptDescribes(e,t){for(let[r,n]of Object.entries(t.describes))this.describeCache.set(`${e}::${r}`,n,Xc);t.objects.length>0&&this.describeGlobalCache.set(e,t.objects,Xc)}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 Mn(e,{orgId:t,organizationId:n,guard:r})}buildTargetOrgAccess(){return{query:async(e,t)=>{let r=await Oe(e,this.deps.orgRegistry,this.deps.orgManager);return wn(r,t)},count:async(e,t)=>(await(await Oe(e,this.deps.orgRegistry,this.deps.orgManager)).query(t)).totalSize,describe:async(e,t)=>{let n=await(await Oe(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 Oe(e,this.deps.orgRegistry,this.deps.orgManager);return Xa(s,t,r,n)},userId:async e=>(await(await Oe(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(Te.join(r,"manifest.json"));if(!await it(n))throw new Error(`No frozen dataset found at ${r} \u2014 run a selection (frozen:select) then an extraction (frozen:extract) first.`);let s=Fr(JSON.parse(await Ae.readFile(n,"utf8"))),i=[],d=t.assertOutsideRepo(Te.join(r,"data"));if(await it(d))for(let f of(await Ae.readdir(d)).sort()){if(!f.endsWith(".json"))continue;let p=t.assertOutsideRepo(Te.join(d,f)),g=JSON.parse(await Ae.readFile(p,"utf8"));i.push({objectApiName:g.objectApiName,records:g.records})}let a=async(f,p)=>{let g=t.assertOutsideRepo(Te.join(r,f));return await it(g)?JSON.parse(await Ae.readFile(g,"utf8")):p},u=await a("record-types.json",{}),l=await a("personcontact-sidecar.json",[]),c=await a(Er,{});return{dataset:{datasetVersion:s.version,objects:i,recordTypes:u,personContactSidecar:l,...c.standardPricebook?{standardPricebook:c.standardPricebook}:{}},manifest:s}}errorCodeFor(e,t){return e instanceof gr?"RULES_MISSING":e instanceof He?"GUARD_REFUSED":e instanceof ud?"SAS_PATH_REFUSED":e instanceof Tr?"SALT_MISSING":e instanceof $t?"BUDGET_EXCEEDED":e instanceof Ze?"LOAD_CONFIG":e instanceof xr?"MAX_RECORDS":e instanceof ar?io:e instanceof lt?"TIMEOUT":e instanceof Qe?e.code:e instanceof Ao&&e.code==="invalid"?"INVALID_PAYLOAD":t}errorDetailOf(e){if(e instanceof Qe)return{params:e.params};if(e instanceof gr)return{rulesPath:e.rulesPath};if(e instanceof He)return{guard:e.code,...e.params};if(e instanceof $t)return{total:e.total,budgetMax:e.budgetMax,heaviest:e.heaviest};if(e instanceof Ze&&e.gaps)return{gaps:e.gaps,...(e.refusedBeside??[]).length>0?{refusedBeside:e.refusedBeside}:{}};if(e instanceof Ze&&e.recordTypesUntold)return{recordTypesUntold:e.recordTypesUntold};if(e instanceof pr)return{emails:e.emails,orgId:e.orgId};if(e instanceof Qr)return{automation:e.automation,orgId:e.orgId};if(e instanceof en)return{apiRequests:e.apiRequests,orgId:e.orgId};if(e instanceof tn)return{storage:e.storage,orgId:e.orgId}}loadEmailsFor(e){return ac({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:()=>ja(e.conn),readDeliverability:()=>e.orgTier==="production"?Promise.resolve(ea):ta(e.conn),accepted:e.accepted,target:this.orgNameOf(e.orgId),mayMute:e.mayMute})}async loadApiCheck(e){let t=await va(e.conn).catch(s=>({unread:Q(s)})),r=Ja(e.read),n=Oa({run:Cc({inserts:e.dataset.objects.map(s=>({objectApiName:s.objectApiName,rows:s.records.length})),...e.purged?{purged:e.purged}:{},threshold:wo(this.deps).bulk.threshold,...r?{duplicateRules:r}:{},automationRead:za(e.read)})+(e.replayReads??0),...Aa(e.checkpoint),...oa(e.plan),...Ma(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})`),yf(n,this.orgNameOf(e.orgId))}async purgedOf(e,t){if(await e.isStale())return[];let r=t.undeletableObjects??{};return(await e.recordedLoads()).flatMap(n=>ot(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 Ks(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??=Cf(),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 Qe("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 lt,...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;Ko({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),u=Pn(a.organizationId),l={folder:d,target:a,contractPath:i.replays.contractPathOf(d,u),...s?{stagingReplay:s}:{}},c=m=>new Ns(d.dir,{guard:m,orgId:u,organizationId:a.organizationId},e);if(r==="mapping")return{config:nl(t.config,void 0),sasDir:()=>d.dir,mappingStore:c,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===u)?.choices;if(p===void 0)throw new Qe("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=Id({checkpoint:f.checkpoint,checkpointId:t.checkpointId,choices:p,target:a});if(g)throw new Qe(g.code,g.message,g.params);if(f.checkpoint===void 0)throw new Qe("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:nl(t.config,p),sasDir:()=>d.dir,mappingStore:c,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 Qe("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 Ia(n.folder)}}catch(s){throw s instanceof Ao?new Qe("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 Qe("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,u=[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(u)],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 qc({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 Qe(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:Pn(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:u,name:l})=>({objectApiName:u,...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=gf.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:Yd(t)}}async loadStorageOf(e){let t=await Eo(e.conn).catch(()=>{});if(t===void 0)return;let r=Math.max(0,e.automationBytes??0),n=Gc({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??(al(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}:{},...e.pilot===!0?{pilot:!0}:{},...n?{refusal:{code:il,message:n.message}}:{}}}async handleSelect(e){let t=nt(Pi,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()}`;vr(this.deps,n,"frozen","Running coverage-matrix selection");let s="Coverage-matrix selection",i=new AbortController,d=setTimeout(()=>i.abort("timeout"),If),a=()=>{},u=new Promise((c,f)=>{a=p=>p===void 0?c():f(p)});u.catch(()=>{}),this.registry?.register(e.id,"frozen",s,u,i),this.liveTracker?.register(e.id,"frozen",s);let l=c=>{this.deps.broker.postToWebview(Se(this.deps,e,"frozen:select:progress",{...c})),c.phase==="combination"&&c.index!==void 0&&c.of&&this.liveTracker?.updateProgress(e.id,Math.round((c.index-1)/c.of*100),c.index-1,c.of,c.combinationKey??"")};try{let c=new ue,f=c.assertOutsideRepo(this.resolveSasDir(r)),p=await Oe(t.sourceOrgId,this.deps.orgRegistry,this.deps.orgManager),g=new Map,h=async D=>{let G=g.get(D);return G||(G=wn(p,D),g.set(D,G),G.catch(()=>g.delete(D))),(await G).map(V=>({...V}))},m=await this.loadTokens(f,c),y=this.discoveryOptions(r),k=new Set,N=new Ur({query:h,describeFields:D=>(k.add(D),this.describeScopableFields(t.sourceOrgId,D)),keyPrefixes:()=>this.keyPrefixes(t.sourceOrgId)}),T=new Date().toISOString(),P,x=0,U=async D=>(P??=this.graphOfStep({step:"select",sourceOrgId:t.sourceOrgId,config:r,sasDir:f,guard:c,rootRecordId:D,signal:i.signal,onProgress:G=>{G.phase==="object"&&(G.discoveredCount-x<10&&G.queueRemaining>0||(x=G.discoveredCount,l({phase:"discovery",objects:G.discoveredCount})))}}),js((await P).graph,r.excludedObjects)),C=async D=>{if(D.length===0)return{};let G=await U(D[0]),V=await N.extract({graph:G,rootObject:r.rootObject,rootRecordIds:D,asOf:T,sasDir:f,excludedFields:r.excludedFields,excludedObjects:r.excludedObjects,tokens:m,guard:c}),H={};for(let E of V.objects)H[E.objectApiName]=E.records.length;return H},I=new Yn(C,r.expectedObjects??[]),w=async(D,G)=>(await this.describeObject(t.sourceOrgId,D)).fields.find(V=>V.name.toLowerCase()===G.toLowerCase())?.type,j=await new Hn({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 vc(f,j,c),A=P&&!j.stopped?await P.catch(()=>{}):void 0;A?.keep&&await A.keep(k).catch(D=>{this.deps.log(`[WARN] frozen: the graph could not be kept in the sas: ${String(D)}`)});let F=A?js(A.graph,r.excludedObjects):void 0,$=Se(this.deps,e,"frozen:select:response",{selection:{...Pf(j,v,F?tl(F,y.maxNodes):void 0),...A?{discovery:A.origin}:{}}});this.deps.broker.postToWebview($),bt(this.deps,n,{roots:j.roots.length,total:j.volumetry.total,...j.stopped?{stopped:j.stopped.reason}:{}}),j.stopped?.reason==="cancelled"?this.liveTracker?.cancel(e.id):this.liveTracker?.complete(e.id),a()}catch(c){this.liveTracker?.fail(e.id,Q(c)),a(c),te(this.deps,"frozen:select","frozen:select:error",e,c,{code:this.errorCodeFor(c,"SELECT_ERROR"),retryable:c instanceof lt,extraPayload:this.errorDetailOf(c)})}finally{clearTimeout(d)}}async handleExtract(e){let t=nt(ji,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()}`;vr(this.deps,n,"frozen","Extracting + pseudonymizing dataset");try{let s=new ue,i=s.assertOutsideRepo(this.resolveSasDir(r)),d=s.assertOutsideRepo(this.resolveDatasetDir(r)),a=await this.saltKeeper.forExtraction(),u=new Fn(a.salt);if(a.created&&this.sayTheSaltWasMade(u.saltFingerprint),!await it(Te.join(i,Wr))){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 ds(i,s),c=l.roots.map(V=>V.rootRecordId);if(c.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 it(p))throw new gr(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.`);let g=Vn(JSON.parse(await Ae.readFile(p,"utf8"))),h=await Oe(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:c[0]}),k=js(y.graph,r.excludedObjects),N=new Set,T,P=new Ur({query:V=>T?.aborted?Promise.reject(new Error("The extraction ran out of time and stopped.")):wn(h,V),describeFields:V=>(N.add(V),this.describeScopableFields(t.sourceOrgId,V)),keyPrefixes:()=>this.keyPrefixes(t.sourceOrgId)}),x=t.author??"sandforge",U=r.datasetVersion??kf,{extracted:C,frozen:I,report:w,requiredLeftEmpty:O,keptUnruled:j}=await new St(Ps).withTimeout("frozen:extract",async V=>{T=V;let H=await P.extract({graph:k,rootObject:r.rootObject,rootRecordIds:c,asOf:new Date().toISOString(),sasDir:i,excludedFields:r.excludedFields,excludedObjects:r.excludedObjects,tokens:f,guard:s}),E=await this.ruleSchemaOf(t.sourceOrgId,H.objects),W=gc(g,E,this.deps.infraServices?.piiDetector??new vn),Y=new Zn().anonymize({extracted:H,rules:W,pseudonymizer:u,datasetVersion:U}),ie=new Qn().run(H,Y,W,{author:x});return{extracted:H,frozen:Y,report:ie,requiredLeftEmpty:mc(H,W,E),keptUnruled:hc(H,W)}});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(N).catch(V=>{this.deps.log(`[WARN] frozen: the graph could not be kept in the sas: ${String(V)}`)});let v=Se(this.deps,e,"frozen:control:result",{report:dl(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 V of I.objects)A[V.objectApiName]=V.records.length;let F=this.deps.orgManager.getOrg(t.sourceOrgId),$=Od({version:U,source:{orgId:t.sourceOrgId,orgAlias:F?.alias,decisionDate:l.selectedAt},saltFingerprint:u.saltFingerprint,rulesVersion:g.rulesVersion,volumetry:{budgetMax:l.volumetry.budgetMax,measured:A,measuredAt:new Date().toISOString()},nonReidentification:w,author:x,coverage:{...tl(k,m.maxNodes),unboundedObjects:C.unboundedObjects,filesLeftOut:I.filesLeftOut??[],...(C.leftToThePlatform??[]).length>0?{leftToThePlatform:Dn(C.leftToThePlatform??[])}:{},...C.exclusionCosts?{exclusionCosts:C.exclusionCosts}:{},...O.length>0?{requiredLeftEmpty:O}:{},...j.length>0?{keptWithoutARule:j}:{},encryptedNotKept:C.encryptedNotKept??[]}}),D=await new $n(s).write(d,I,$,w),G=Se(this.deps,e,"frozen:extract:response",{datasetDir:D.dir,files:D.files,recordCount:ir(I),manifest:el($),discovery:y.origin});this.deps.broker.postToWebview(G),bt(this.deps,n,{records:ir(I),version:$.version})}catch(s){let i=s instanceof lt,d=i?new Error(`The extraction ran out of its ${Ps/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?vf:this.errorCodeFor(s,"EXTRACT_ERROR"),retryable:!1,extraPayload:i?{minutes:Ps/6e4}:this.errorDetailOf(s)})}}async handleRulesClear(e){let t=nt(Ti,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 it(n))throw new gr(n,`Pseudonymization rules file not found at ${n} \u2014 nothing was written. Create it, or set rulesFilePath in the configuration.`);let s=yc(JSON.parse(await Ae.readFile(n,"utf8")),t.fields);if(s.cleared.length>0){let d=`${n}.${process.pid}.writing`;await Ae.writeFile(d,`${JSON.stringify(s.payload,null,2)}
|
|
21
|
-
`,"utf8"),await Ae.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=Se(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 Ae.mkdir(Te.dirname(t),{recursive:!0});try{await Ae.writeFile(t,uc(fc),{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 Ae.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: ${Q(s)}`)}this.deps.broker.postToWebview(Se(this.deps,e,"frozen:rules:create:response",{rulesPath:t,created:r,opened:n}))}targetTier(e){let t=this.deps.orgManager.getOrg(e);return Us(t)}async handleLoad(e){let t=nt(vo,e,"frozen:load:error",this.deps);if(!t)return;let r=await this.sourceOf(e,t,"frozen:load:error","load",E=>Xe(this.deps,{action:"checkpoint_replay",module:"checkpoint",operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:E}));if(!r)return;let{config:n}=r,s=zf(r),i=r.replay,d=this.deps.infraServices?.productionGuard;if(!d){Xe(this.deps,{...s,operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:Ot.code}),te(this.deps,"frozen:load","frozen:load:error",e,new Error(Ot.message),{code:Ot.code});return}let a=await this.replaceRefusal(t,r),u=a&&"error"in a?a:void 0,l=a&&"cameAlong"in a?a.cameAlong:void 0;if(u){u.code===io&&Xe(this.deps,{...s,operationId:e.id,orgId:t.targetOrgId,outcome:"stopped",code:io}),te(this.deps,"frozen:load","frozen:load:error",e,u.error,{code:u.code,retryable:u.retryable});return}let c=e.id,f=i?`Replaying checkpoint '${i.checkpoint?.checkpoint.name??""}'`:t.pilot?"Pilot load (one root folder)":"Loading frozen dataset";vr(this.deps,c,s.module,f),this.liveTracker?.register(c,s.module,f);let p=!1,g=!1,h=new AbortController,m=()=>{},y=new Promise((E,W)=>{m=Y=>Y===void 0?E():W(Y)});y.catch(()=>{}),this.registry?.register(c,s.module,f,y,h);let k=Qc(E=>{let W=Se(this.deps,e,"frozen:load:progress",{...E});this.deps.broker.postToWebview(W),!p&&!g&&this.liveTracker?.updateProgress(c,E.progress,0,0,E.message)},100),N,T=!1,P=!1,x,U=new Date().toISOString(),C,I,w,O,j,v=(E,W,Y,ie)=>{if(P)return;P=!0;let _=E!=="stopped"&&C!==void 0,K=w?ia(sa(w.run.gate,w.info.accepted&&w.info.verdict==="asks").emails):{},Z=i?.checkpoint&&i.choices?{replayCheckpoint:i.checkpoint.checkpoint.checkpointId,...vd(i.checkpoint.checkpoint,i.choices,i.target),...i.stagingReplay?{replayIntoStaging:!0}:{}}:{},re={..._?{sas:C,startedAt:U,...I?{lastWriteAt:I}:{}}:{},...K,...Z};Xe(this.deps,{...s,operationId:c,orgId:t.targetOrgId,outcome:E,guard:N,objects:W,source:{origin:i?"checkpoint":"dataset",label:x},carried:Y,...ie?{code:ie}:{},...A?{muted:pn(A)}:{},...$?.state==="taken"?{checkpointId:$.checkpointId}:{},...Object.keys(re).length>0?{details:re}:{}})},A,F,$,D=!1,G=!1,V=!1,H=[];try{let E=new ue,W=r.sasDir(E);C=Kn(W);let{dataset:Y,manifest:ie,datasetDir:_,label:K}=await r.read(E);x=K;let Z=this.buildTargetOrgAccess(),re=await Oe(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),ge=wo(this.deps),_e=wi(this.deps),De=z=>new dd({connection:re,bulkExecutor:new Mi(ge.bulk.threshold),bulkManager:_e,retryConfig:ge.retry,...z?{signal:z}:{},onProgress:()=>{},log:se=>this.deps.log(se)}),R=De(h.signal),L=n.mockDetection?new Cr(Z,n.mockDetection):{areCalloutsMocked:async()=>!0},S=r.mappingStore(E),J=Mt(re,"frozen:load"),ne=new $r({orgAccess:Z,writer:hs(R),restoringWriter:hs(De(void 0)),guard:d,mockDetector:L,recordTypeResolver:new Kr(Z),mappingStore:S,config:this.toLoadConfig(n),sasGuard:E,serverTime:()=>J.serverTime()});if(t.sweep===!0&&t.reload===!0&&!t.pilot){H=await this.reloadSweepsOf({conn:re,store:S,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,includeChanged:t.includeChanged===!0,signal:h.signal,guard:d,operationId:c,audit:co(r)});for(let{sweep:z}of H)await z.ask()}let X=Xr([],H.flatMap(({sweep:z})=>z.takes)),he=(X.delete??[]).length>0?this.removalAsker:void 0,ee=Y.objects.map(z=>z.objectApiName),Be=t.reload===!0&&!t.pilot?await this.purgeStepsOf(S,n):void 0,M=await this.targetAutomation.read(t.targetOrgId,[...new Set([...ee,...Be?.delete??[],...X.delete??[]])]).catch(z=>({unread:Q(z)})),we=Be?Rr(Be):void 0,et=Rr(X),tt=(z,se)=>ao(z,se)||we?.(z,se)===!0||et(z,se),q=t.muteAutomation===!0?await Sr(async()=>Or(re),M,{...this.muteLeases,writes:tt}):void 0;if(A=q?.muted,he&&!h.signal.aborted){let z=await he({read:M,steps:X,mute:q});if(z)throw new fr(z)}let ae=this.targetTier(t.targetOrgId),kt=await ne.gateLoad({orgId:t.targetOrgId,orgName:this.orgNameOf(t.targetOrgId),orgTier:ae,...i?.stagingReplay?{stagingReplay:!0}:{},dataset:Y,manifest:ie,reload:t.reload,pilot:t.pilot?{}:void 0,onProgress:z=>k(z),onGuardDecision:z=>{N=So(N,z)}}),fe=ns({read:M,...q?.plan?{plan:q.plan}:{},written:ee,accepted:t.acceptAutomation===!0,target:this.orgNameOf(t.targetOrgId),mayMute:t.muteAutomation!==!0&&this.muteOffered});if(O=fe.info,fe.stop&&fe.info)throw new Qr(fe.stop.code,fe.stop.message,fe.info,t.targetOrgId);let ft=t.acceptEmails===!0,We=vs(Y,n,t.pilot),xe=await this.loadEmailsFor({conn:re,orgId:t.targetOrgId,orgTier:ae,read:M,...q?.plan?{plan:q.plan}:{},writes:tt,dataset:We,accepted:ft,mayMute:t.muteAutomation!==!0&&this.muteOffered});if(w=xe,xe.stop)throw new pr(xe.stop.code,xe.stop.message,xe.info,t.targetOrgId);let ye=t.checkpointFirst!==void 0?await this.scopeLoadCheckpoint({msg:e,orgId:t.targetOrgId,written:ee,read:M,mute:q,request:t.checkpointFirst,replay:i!==void 0}):void 0,Ie=Be?await this.purgedOf(S,n):void 0,It=Promise.resolve().then(()=>re.request({method:"GET",url:"/limits"}));It.catch(()=>{});let rn={request:()=>It},uo=await Eo(rn).catch(z=>({unread:Q(z)})),nn=await this.loadSentOf(re,We),Gt=Gc({dataset:We,storage:uo,...nn?{sent:nn}:{},...Ie?{purged:Ie}:{},automationBytes:Uc(M,q?.plan,We,tt),target:this.orgNameOf(t.targetOrgId),...i?{replay:!0}:{},...t.pilot===!0?{pilot:!0}:{}});if(Gt)throw new tn(Gt.message,Gt.storage,t.targetOrgId);if(j=await this.loadApiCheck({conn:rn,dataset:We,...Ie?{purged:Ie}:{},read:M,...ye?{checkpoint:ye.estimate}:{},...q?.plan?{plan:q.plan}:{},emails:xe,orgId:t.targetOrgId,operation:`frozen:load ${c}`,...i?.converted?{replayReads:i.converted.target.requests}:{}}),j.refused)throw new en(j.refused.message,j,t.targetOrgId);i?.checkpoint&&i.choices&&await this.replayStoresInUse().replays.record(i.checkpoint.checkpoint,{organizationId:i.target.organizationId,name:i.target.name},i.choices),ye&&(F=await this.takeLoadCheckpoint(ye,h.signal));let Ke=q?.prepared?await q.prepared.acquire(c):void 0;Ke&&(A=Ke.outcome,V=!0);let at=Ke?xe.run.afterLease(Ke.outcome,ft):void 0;if(Ke&&at)throw A=await Ke.release(),new pr(at.code,at.message,xe.info,t.targetOrgId);D=!0;let hr=()=>ne.load({orgId:t.targetOrgId,orgName:this.orgNameOf(t.targetOrgId),orgTier:ae,...i?.stagingReplay?{stagingReplay:!0}:{},dataset:Y,manifest:ie,sasDir:W,reload:t.reload,pilot:t.pilot?{}:void 0,...t.writeEncrypted?{writeEncrypted:!0}:{},...t.maxRecords!==void 0?{maxRecords:t.maxRecords}:{},...i?{linkByKeys:!0,contractOrgId:Pn(i.target.organizationId)}:{},onProgress:z=>k(z),onGuardDecision:z=>{N=So(N,z),(z==="allowed"||z==="confirmed")&&(T=!0)},signal:h.signal,...Ke?{lease:{giveBack:()=>Ke.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})=>!Os(z.result())).map(({loadedAt:z})=>z)}}:{}}),$e=await(kt==="confirmed"?Xi({approved:!0},hr):hr()).finally(async()=>{Ke&&(A=await Ke.release())});G=!0,k.flush();let Ut=await this.settleReloadSweeps(H),yr=Ut.some(z=>z.result.status!=="success");F&&($=await this.settleCheckpoint(F,lo($e)>0)),I=nc(await S.recorded().catch(()=>{}),U);let vt=_!==void 0?Te.join(_,"manifest.json"):void 0;g=!0;let jt=await this.verifyLoad({orgId:t.targetOrgId,contractPath:$e.contractPath,...vt!==void 0?{manifestPath:vt}:{},dataset:Y,mappingStore:S,config:n,onProgress:k}),wr="verdict"in jt?jt.verdict.status:void 0,Kt=wr==="failed"||wr==="partial"?wr:void 0,Vt=$e.status==="completed"&&(yr||Kt!==void 0)?"partial":$e.status,br=Ef($e);if(v(Kt!==void 0&&br==="success"?"partial":br,Ls($e),await Nf(Y,S)),_!==void 0&&vt!==void 0){let z={contractPath:$e.contractPath,datasetDir:_,manifestPath:vt,targetOrgId:t.targetOrgId,status:Vt,at:new Date().toISOString()};this.recordLastRun(z)}let Ft=Ff($e),b=Object.fromEntries(Object.entries(l??{}).filter(([z])=>(Ft.purge.deleted[z]??0)>0)),B=Se(this.deps,e,"frozen:load:response",{report:{...Ft,...Object.keys(b).length>0?{purge:{...Ft.purge,cameAlong:b}}:{},status:Vt,...Kt?{verification:Kt}:{},...A?{mutedAutomation:A}:{},...$?{checkpoint:$}:{},...Ut.length>0?{sweeps:Ut}:{},...w&&Vc(w.info)?{emails:w.info}:{},...O?{automation:O}:{},...j?{apiRequests:j}:{}},...i?Kc(this.replayInfoOf(i,mf($e,Y))):{}});this.deps.broker.postToWebview(B),bt(this.deps,c,{status:Vt}),p=!0,Vt!=="completed"?this.liveTracker?.partial(c):this.liveTracker?.complete(c),this.postVerification(e,jt),m()}catch(E){k.flush();let W=await this.settleReloadSweeps(H).catch(()=>[]),Y=W.length>0?{sweeps:W}:{};if(F&&$===void 0){let S=E instanceof st||E instanceof xt?E.written:void 0;$=await this.settleCheckpoint(F,S?lo(S)>0:D&&!An(E))}let ie=$?{checkpoint:$}:{},_=V&&A?{mutedAutomation:A}:{};if(E instanceof Wt){v("stopped",void 0,void 0,E.code),te(this.deps,"frozen:load","frozen:load:error",e,E,{code:E.code,...E.code==="LOAD_CANCELLED"?{extraPayload:{written:0}}:{}}),E.code==="LOAD_CANCELLED"?(this.registry?.abort(c),bt(this.deps,c,{aborted:!0}),this.liveTracker?.cancel(c),m()):(bo(this.deps,c,E.message,!0),this.liveTracker?.fail(c,E.message),m(E));return}if(E instanceof st){let S=Lf(E.written);v(S,Ls(E.written),void 0,S==="stopped"?"LOAD_CANCELLED":void 0),this.registry?.abort(c),bt(this.deps,c,{aborted:!0}),this.liveTracker?.cancel(c),te(this.deps,"frozen:load","frozen:load:error",e,E,{code:"LOAD_CANCELLED",extraPayload:{written:lo(E.written),...ie,...Y,..._}}),m();return}let K=An(E)||E instanceof Qe||E instanceof fr||E instanceof pr||E instanceof Qr||E instanceof en||E instanceof tn?E:void 0,Z=K!==void 0||(N==="refused"||N==="declined")&&!T,re=E instanceof xt?E:void 0,ge=re?re.cause:E,_e=K?.code??this.errorCodeFor(ge,"LOAD_ERROR"),De=re===void 0&&!G&&!T;v(Z||De?"stopped":"failure",re?Ls(re.written):void 0,void 0,K?.code??(De?_e:void 0));let L={...re&&ge instanceof He?{guard:ge.code}:this.errorDetailOf(ge),...ie,...Y,..._,...De?{written:0}:{}};te(this.deps,"frozen:load","frozen:load:error",e,E,{code:_e,retryable:ge instanceof lt,extraPayload:Object.keys(L).length>0?L:void 0}),p||(bo(this.deps,c,Q(E),!0),this.liveTracker?.fail(c,Q(E))),m(E)}}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?Lt(t,e.mute?.plan,ao):{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:Q(i)})),n=e.muteAutomation?await Sr(async()=>Or(e.conn),r,{...this.muteLeases,writes:ao}).catch(i=>{Nt.warn(`Frozen preview: the mute could not be planned (${Q(i)})`)}):void 0,s=this.loadCheckpointAsk({...e,operationId:e.msg.id,read:r,...n?{mute:n}:{}});return t.scope(s,{}).catch(i=>{Nt.warn(`Frozen preview: ${jn(i)}`)})}async scopeLoadCheckpoint(e){let t=this.beforeRunCheckpoints;if(!t)throw new Wt(Pr,jn(new Error("SandForge's checkpoints are not set up in this window")));let r=this.loadCheckpointAsk({...e,operationId:e.msg.id}),n={operationId:rl(e.msg.id)},s;try{s=await t.scope(r,n)}catch(d){throw new Wt(Pr,jn(d))}let i=Pa(s);if(i)throw new Wt(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 Ta(()=>r.take(n,s,{planned:i,signal:t}));if("stop"in d)throw new Wt(d.stop.code===Pr?Pr:"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 Nt.warn(`Frozen load: the checkpoint '${e.name}' taken before it is kept, as it could not be settled (${Q(n)})`),e}}recordLastRun(e){this.moveOldVerify();let t={...this.lastRuns()},r=this.deps.configStore.get(ur);r&&t[r.targetOrgId]===void 0&&(t[r.targetOrgId]=r),t[e.targetOrgId]=e,this.deps.configStore.set(Yc,t,Zr),this.deps.configStore.set(ur,e,Zr)}recordLastVerify(e,t){this.moveOldVerify(),this.deps.configStore.set(As,{...this.lastVerifies(),[e]:t},Zr)}lastVerifies(){return this.deps.configStore.get(As)??{}}orgOfOldVerify(e){let t=this.deps.configStore.get(ur);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(Ss);if(!e)return;let t=this.orgOfOldVerify(e),r=this.lastVerifies();t!==void 0&&r[t]===void 0&&this.deps.configStore.set(As,{...r,[t]:e},Zr),this.deps.configStore.delete(Ss)}lastVerifyInfos(){let e={...this.lastVerifies()},t=this.deps.configStore.get(Ss),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(Yc)??{}}lastRunOf(e){let t=this.lastRuns()[e];if(t)return t;let r=this.deps.configStore.get(ur);return r?.targetOrgId===e?r:void 0}lastLoadInfos(){let e={...this.lastRuns()},t=this.deps.configStore.get(ur);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=nt(vo,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 ue,u=r.sasDir(a),{dataset:l,manifest:c}=await r.read(a),f=this.buildTargetOrgAccess(),p=await Oe(t.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),g=Mt(p,"frozen:load:preview"),m=await new $r({orgAccess:f,writer:ff,guard:this.deps.infraServices?.productionGuard??new Zi,mockDetector:n.mockDetection?new Cr(f,n.mockDetection):{areCalloutsMocked:async()=>!0},recordTypeResolver:new Kr(f),mappingStore:r.mappingStore(a),config:this.toLoadConfig(n),sasGuard:a,serverTime:()=>g.serverTime(),readValidationRules:async w=>{let{toolingQueriesOver:O,toolingValidationRules:j}=await import("./chunk-6O222PW6.mjs"),{toolingRetrievesOver:v}=await import("./chunk-GOOVPVWX.mjs"),A=p.tooling;return j(async F=>(await Ii({query:async $=>A.query($),queryMore:async $=>A.queryMore($)},F)).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:c,sasDir:u,reload:t.reload,pilot:t.pilot?{}:void 0,...t.writeEncrypted?{writeEncrypted:!0}:{},...s?{linkByKeys:!0}:{}}).catch(async w=>{throw w instanceof Ze&&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,k=r.mappingStore(a),N=Wc(p),{emails:T,automation:P,apiRequests:x,automationBytes:U}=await this.previewWhatRuns({conn:p,limits:N,orgId:t.targetOrgId,dataset:l,store:k,config:n,parsed:t,...y?{checkpoint:y}:{},...s?.converted?{replayReads:s.converted.target.requests}:{}}),C=await this.previewStorageOf({conn:N,org:p,dataset:l,store:k,config:n,parsed:t,...U!==void 0?{automationBytes:U}:{},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(Se(this.deps,e,"frozen:load:preview:response",{plan:{...m,...y?{checkpoint:y}:{},...T?{emails:T}:{},...P?{automation:P}:{},...x?{apiRequests:x}:{},...C&&!s?{storage:C}:{}},...Kc(I)}))}catch(a){te(this.deps,"frozen:load:preview","frozen:load:preview:error",e,a,{code:this.errorCodeFor(a,"PREVIEW_ERROR"),retryable:a instanceof lt,extraPayload:this.errorDetailOf(a)})}}async refusedBesideOf(e){let{replay:t,...r}=e,n=Wc(e.conn),{emails:s,automation:i,apiRequests:d,automationBytes:a}=await this.previewWhatRuns({...r,limits:n,...t?.converted?{replayReads:t.converted.target.requests}:{}}),u=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,c=[];return i?.refused&&c.push({...i.refused,orgId:l,automation:i}),s?.refused&&c.push({...s.refused,orgId:l,emails:s}),u?.refusal&&c.push({...u.refusal,orgId:l,storage:hf(u)}),d?.refused&&c.push({...d.refused,orgId:l,apiRequests:d}),c}async previewStorageOf(e){let t=e.parsed.pilot===!0,r=vs(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?Rr(r):void 0,s=(f,p)=>ao(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:Q(f)})),d=t.muteAutomation===!0?await Sr(async()=>Or(e.conn),i,{...this.muteLeases,writes:s}).catch(()=>{}):void 0,{info:a}=ns({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}),u=vs(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:u,accepted:t.acceptEmails===!0,mayMute:t.muteAutomation!==!0&&this.muteOffered}).catch(f=>{Nt.warn(`Frozen preview: the emails could not be judged (${Q(f)})`)}),c=await this.loadApiCheck({conn:e.limits,dataset:u,...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=>{Nt.warn(`Frozen preview: the API requests could not be judged (${Q(f)})`)});return{...l&&Vc(l.info)?{emails:l.info}:{},...a?{automation:a}:{},...c?{apiRequests:c}:{},automationBytes:Uc(i,d?.plan,u,s)}}catch(r){return Nt.warn(`Frozen preview: what the target runs could not be judged (${Q(r)})`),{}}}async handleVerify(e){let t=nt(Fi,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=Qc(a=>{let u=Se(this.deps,e,"frozen:load:progress",{...a});this.deps.broker.postToWebview(u)},100);try{let a=new ue,u=i?.contractPath??s?.contractPath??"";if(s&&!await it(u)){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=Te.dirname(i.contractPath)!==Te.dirname(Nn(a,g,t.targetOrgId)),m=await it(i.contractPath);if(h||!m){let y=Te.dirname(i.contractPath),k;h?m?k=`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.`:k=`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.`:k=`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(k),{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 c=await l.recorded(),f=c?.removal;if(c&&f){let g=ot(c).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(!c){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(!pd(Cn(a,u),c)){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:u,...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 lt})}}async runVerification(e,t){this.postVerification(e,await this.verifyLoad(t))}async verifyLoad(e){try{let t=new eo({orgAccess:this.buildTargetOrgAccess(),sasGuard:new ue}),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=Se(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 lt})}async handleRemove(e){let t=nt(Ei,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 ue),i=await s.recordedLoads(),d=sr(i)}catch(p){te(this.deps,"frozen:remove","frozen:remove:error",e,p,{code:this.errorCodeFor(p,"REMOVE_ERROR")});return}let a=Fs(d,t),u=t.sweep===!0&&a?.code==="ALREADY_REMOVED";if(a&&!u||!d){a&&n(a.message,a.code);return}let l=ot(d),c=s.filePath;if(this.removing.has(c)){n("The records of this load are being removed already.","DUPLICATE");return}this.removing.add(c);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?$o(i,d):[],muteAutomation:t.muteAutomation===!0,pending:f,audit:co(r)})}finally{this.removing.delete(c),f?.release()}}async handleRemoveAutomation(e){let t=nt(Ni,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 ue),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=sr(await s.recordedLoads()),c=Fs(l,t),f=t.sweptObjects!==void 0&&c?.code==="ALREADY_REMOVED";if(c&&!f||!l){c&&te(this.deps,"frozen:remove:automation","frozen:remove:automation:error",e,new Error(c.message),{code:c.code});return}i=Xr(ot(l),t.sweptObjects??[],l)}let a=this.targetAutomation,u=await new St(Ts).withTimeout("frozen:remove:automation",()=>a.read(t.targetOrgId,i.delete??[]));this.deps.broker.postToWebview(Se(this.deps,e,"frozen:remove:automation:response",{loadedAt:t.loadedAt,automation:u,steps:i,...d?{purge:d}:{}}))}catch(s){te(this.deps,"frozen:remove:automation","frozen:remove:automation:error",e,s,{code:s instanceof lt?"TIMEOUT":this.errorCodeFor(s,"AUTOMATION_ERROR"),retryable:!0})}}async purgeStepsOf(e,t,r=[]){if(await e.isStale())return Xr([],[]);let n=t.undeletableObjects??{},s=(await e.recordedLoads()).flatMap(i=>ot(i)).filter(({objectApiName:i})=>!Object.hasOwn(n,i));return Xr(s,r)}async handleRemovePreview(e){let t=nt(Ci,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 ue),i=sr(await s.recordedLoads()),d=Fs(i,t);if(d||!i){d&&n(new Error(d.message),d.code);return}let a=ot(i).reduce((c,f)=>c+f.ids.length,0),u=this.removalGuardRefusals(i.orgId,a),l;if(await s.isStale())u.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 c=await Oe(i.orgId,this.deps.orgRegistry,this.deps.orgManager);l=await this.previewRemovalOf(c,i,t.includeChanged===!0)}this.deps.broker.postToWebview(Se(this.deps,e,"frozen:remove:preview:response",{preview:{...l,refusals:u.map(({message:c})=>c),refusalCodes:u.map(({code:c})=>c)}}))}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=ot(t),s=await kn(Mt(e,"frozen:remove:preview"),n,{...Es(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=zn(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 ue),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 Oe(e.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),u=d.filter(p=>ot(p).length>0),l=new Set([...u.flatMap(p=>ot(p).flatMap(g=>g.ids.map(h=>h.slice(0,15)))),...r.map(p=>p.slice(0,15))]),c=[];for(let p of u){let g=await kn(Mt(a,"frozen:load:replace"),ot(p),{...Es(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.");c.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=jf(c,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:io,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,u=t.audit??{module:"frozen"},l=n.orgId,c=s.reduce((O,j)=>O+j.ids.length,0),f=(O,j)=>this.refuseRemove(e,O,j),p=this.deps.infraServices?.productionGuard;if(!p){Xe(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"stopped",code:Ot.code}),f(Ot.message,Ot.code);return}let{check:g,decision:h}=c>0?await On(p,{orgId:l,orgTier:this.targetTier(l),operation:"delete",objectName:s.map(O=>O.objectApiName).join(", "),recordCount:c,module:"frozen"}):{check:void 0,decision:"allowed"};if(g&&(h==="refused"||h==="declined")){Xe(this.deps,{action:"cleanup_delete",module:u.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;Xe(this.deps,{action:"cleanup_delete",module:u.module,operationId:e.id,orgId:l,outcome:"stopped",guard:h,code:hi});let O={status:"cancelled",includeChanged:i,objects:[],finishedAt:new Date().toISOString()};return this.deps.broker.postToWebview(Se(this.deps,e,"frozen:remove:response",{result:O,operationId:e.id})),!0};if(m())return;let y;try{y=await r.isStale()}catch(O){Xe(this.deps,{action:"cleanup_delete",module:u.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){Xe(this.deps,{action:"cleanup_delete",module:u.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 k=e.id,N=c>0?`Removing ${c} record(s) a Frozen load created`:"Sweeping what the target's automation made for a Frozen load",T=new AbortController,P=()=>{},x=new Promise((O,j)=>{P=v=>v===void 0?O():j(v)});x.catch(()=>{}),vr(this.deps,k,"frozen",N),this.registry?.register(k,"frozen",N,x,T),this.liveTracker?.register(k,"frozen",N,c);let U,C,I=[],w;try{let O=await Oe(l,this.deps.orgRegistry,this.deps.orgManager),j=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:u,signal:T.signal,guard:p,operationId:k,muted:()=>c===0?w:void 0,sweptWith:j}):void 0;for(let[S,J]of(C?t.alongside:[]).entries())I.push({loadedAt:J.endedAt,sweep:await this.sweepOfRemoval({conn:O,load:J,store:r,includeChanged:i,sweepLate:t.sweepLate===!0,sweepUntied:t.sweepUntied===!0,audit:u,signal:T.signal,guard:p,operationId:`${k}-${S+2}`,muted:()=>{},sweptWith:j})});let v=C,A=[...C?[C]:[],...I.map(({sweep:S})=>S)],F=async S=>{let J=!1;for(let ne of A)await S(ne)&&(J=!0);return J};for(let S of A)await S.ask();let $,D=this.removalAsker,G=Xr(s,A.flatMap(S=>S.takes),n);if((t.muteAutomation||D)&&!T.signal.aborted&&(G.delete??[]).length>0){let S=this.targetAutomation,J=await new St(Ts).withTimeout("frozen:remove automation",()=>S.read(l,G.delete??[])).catch(X=>({unread:Q(X)}));t.muteAutomation&&($=await Sr(async()=>Or(O),J,{...this.muteLeases,writes:Rr(G)}));let ne=await D?.({read:J,steps:G,mute:$});if(ne)throw new fr(ne)}w=$?.muted;let V,H=async()=>{let S=$?.prepared;!S||T.signal.aborted||(V=await S.acquire(k),w=V.outcome)},W=await(c===0?(async()=>(await H(),await F(S=>S.first()),await F(S=>S.afterRemoval()),qi))():kn(Mt(O,"frozen:remove"),s,{...Es(n),...v?{sweep:S=>F(J=>J.first(S)),afterRemoval:S=>F(J=>J.afterRemoval(S)),automationMade:v.automationMade}:{},onUndeletable:yi(this.deps,l,"frozen:remove"),beforeFirstWrite:H,includeChanged:i,signal:T.signal,onProgress:(S,J,ne)=>{let X=Math.min(100,Math.round(S/Math.max(J,1)*100));Ri(this.deps,k,X,S,J,ne),T.signal.aborted||this.registry?.updateProgress(k,X),this.liveTracker?.updateProgress(k,X,S,J,ne)}})).finally(async()=>{V&&(w=await V.release())}),Y=await C?.settle(),ie=await this.settleReloadSweeps(I),_=n.removal?.removedAt,K=zn(n),Z=Gi(W.objects,W.cancelled),re={status:ie.reduce((S,J)=>Oo(S,J.result),Oo(Z,Y)),includeChanged:i,objects:W.objects,finishedAt:new Date().toISOString(),..._?{leftBy:_}:{},...Y?{sweep:Y}:{},...ie.length>0?{otherLoadSweeps:ie}:{},...K.length>0?{keptByThePlatform:K}:{},...w?{mutedAutomation:w}:{}};c>0&&Xe(this.deps,{action:"cleanup_delete",module:u.module,operationId:k,orgId:l,outcome:Ui({status:Z}),guard:h,objects:Ki(re.objects),..._?{leftBy:_}:{},...w?{muted:pn(w)}:{}});let ge=Vi(re,c,n.removal);(W.gone.length>0||Object.keys(W.stamps).length>0||W.span||ge)&&(await r.recordRemoval(n.endedAt,{gone:W.gone,stamps:W.stamps,...W.span?{span:W.span}:{},...ge?{mark:ge}:{}})||this.deps.log("[WARN] frozen:remove: a load wrote its own mapping during the removal; the removal is not recorded in it"));let _e=[...Y&&Os(Y)?[n.endedAt]:[],...ie.filter(S=>Os(S.result)).map(S=>S.loadedAt)];await r.letSweptGo(_e).catch(()=>!1);let De=Se(this.deps,e,"frozen:remove:response",{result:re,operationId:k});this.deps.broker.postToWebview(De);let R=[Y,...ie.map(S=>S.result)].find(S=>S!==void 0&&S.status!=="success"),L=re.status==="failure"?"No record this load created could be removed.":c===0&&R?R.refusal??"The sweep left records in the org.":void 0;re.status==="cancelled"||Y?.status==="cancelled"||ie.some(S=>S.result.status==="cancelled")?(bt(this.deps,k,{aborted:!0}),this.liveTracker?.cancel(k)):(bt(this.deps,k,{status:L&&c===0?"failure":re.status}),L?(U=new Error(L),this.liveTracker?.fail(k,L)):re.status==="partial"?this.liveTracker?.partial(k):this.liveTracker?.complete(k))}catch(O){U=O,await C?.settle().catch(()=>{});for(let{sweep:v}of I)await v.settle().catch(()=>{});let j=An(O)||O instanceof fr?O:void 0;Xe(this.deps,{action:"cleanup_delete",module:u.module,operationId:k,orgId:l,outcome:j?"stopped":"failure",guard:h,...j?{code:j.code}:{}}),te(this.deps,"frozen:remove","frozen:remove:error",e,O,{code:j?.code??"REMOVE_ERROR",retryable:!0}),bt(this.deps,k,{status:"failure"}),this.liveTracker?.fail(k,Q(O))}finally{P(U)}}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=>wf(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 nd({input:()=>this.sweepInputOfLoad(Mt(t,"frozen:remove sweep"),r,e.signal,e.store,e.sweptWith,e.audit?.sasMark),org:Ln(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=ed(i,"");delete d.forgeId;let a=e.muted();Xe(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:od(s)}:{},objects:Qa(i),details:{...d,loadedAt:r.endedAt},...a?{muted:pn(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=xo(t),a=this.targetAutomation,u;try{u=await new St(Ts).withTimeout("frozen:remove sweep automation",()=>a.read(t.orgId,d.map(g=>g.objectApiName)))}catch(g){u={error:Q(g)}}let l=t.writtenBetween??await td(e,d,r),{ties:c,sweptAlong:f}=await this.tiesOfLoad(t,l,n,s,i),p=new Set([...t.mapping.values(),...f].map(g=>g.slice(0,15)));return rd({writtenBetween:l,created:d,remap:p,automation:Za(u),...t.runUserId?{runUserId:t.runUserId}:{},ties:c,...r?{signal:r}:{}},e)}setOtherModuleRuns(e){this.otherModuleRuns=e}auditedLoadsInto(e){try{return ic(new gi(this.deps.configStore).list({orgId:e,limit:Bs}).entries)}catch{return[]}}sasMarkInUse(){let e=this.loadConfig();return e?Kn(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 c=xo(l).flatMap(g=>g.ids);if(n.has(l.endedAt)){d.push(...c);continue}let f=Date.parse(l.writtenBetween?.first??l.startedAt??l.endedAt),p=Date.parse(l.writtenBetween?.last??l.endedAt);i.push({ids:c,from:f,to:Number.isFinite(p)?p:f})}i.push(...await this.otherModuleRuns(e.orgId,t).catch(()=>[])),i.push(...oc(this.auditedLoadsInto(e.orgId),{sasMark:s,own:a.filter(l=>l.orgId===e.orgId)}));let u=id(e.removalSpans);return{ties:{otherRuns:sd(t,i),...u?{removalBegan:u}:{},...e.madeEarlier?{madeEarlier:e.madeEarlier}:{},...e.lateEarlier?{lateEarlier:e.lateEarlier}:{}},sweptAlong:d}}async handleRemoveSweep(e){let t=nt(Li,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 ue);if(t.reload===!0){await this.listReloadSweeps(e,s,t,co(r).sasMark);return}let i=await s.recordedLoads(),d=sr(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=$o(i,d),u=new Set([d,...a].map(f=>f.endedAt)),{listing:l,otherLoads:c}=await new St(Zc).withTimeout("frozen:remove:sweep",async()=>{let f=await Oe(d.orgId,this.deps.orgRegistry,this.deps.orgManager),p=Ln(f,"frozen:remove:sweep"),g=async m=>Mo(p,await this.sweepInputOfLoad(p,m,void 0,s,u,co(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(Se(this.deps,e,"frozen:remove:sweep:response",{loadedAt:d.endedAt,listing:l,...c.length>0?{otherLoads:c}:{}}))}catch(s){te(this.deps,"frozen:remove:sweep","frozen:remove:sweep:error",e,s,{code:s instanceof lt?"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(Zc).withTimeout("frozen:remove:sweep",async()=>{if(i.length===0)return[];let a=await Oe(r.targetOrgId,this.deps.orgRegistry,this.deps.orgManager),u=Ln(a,"frozen:remove:sweep"),l=new Set(i.map(f=>f.endedAt)),c=[];for(let f of i)c.push({loadedAt:f.endedAt,listing:await Mo(u,await this.sweepInputOfLoad(u,f,void 0,t,l,n),f.removalSpans)});return c});this.deps.broker.postToWebview(Se(this.deps,e,"frozen:remove:sweep:response",{loadedAt:r.loadedAt,reload:!0,loads:d}))}sayTheSaltWasMade(e){bi(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 Fn(f.salt).saltFingerprint,source:f.source})}catch{s={present:!1}}let i=null;try{let f=new ue;if(await it(Te.join(r,Wr))){let p=await ds(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 ue().assertOutsideRepo(Te.join(n,"manifest.json"));await it(p)&&(d=el(Fr(JSON.parse(await Ae.readFile(p,"utf8")))))}catch{d=null}let a=this.deps.configStore.get(ur),u=[];try{let f=new ue,p=f.assertOutsideRepo(r);for(let g of await md(p,f))try{let h=sr(await new Mn(p,{guard:f,orgId:g}).recordedLoads());h&&u.push(hd(h))}catch{}}catch{u.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(),...u.length>0?{loadRecords:u}:{},rules:await this.rulesFileInfo(t)},c=Se(this.deps,e,"frozen:status:response",{status:l});this.deps.broker.postToWebview(c)}};export{Bf as a,hl as b,ml as c,Rp as d,rc as e,Kn as f,nc as g,oc as h,Op as i,Sp as j,Ep as k,Mp as l,ol as m};
|