sandforge 1.80.0 → 1.81.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/bin/sandforge-pipeline.mjs +12 -0
- package/lib/{chunk-EMNC6YI4.mjs → chunk-2IB7I3IQ.mjs} +1 -1
- package/lib/{chunk-3RZQZHEB.mjs → chunk-2NAIUKVL.mjs} +1 -1
- package/lib/{chunk-AEKONPF4.mjs → chunk-2OIRJEYE.mjs} +1 -1
- package/lib/{chunk-BV6VTP3J.mjs → chunk-2OZG6GRW.mjs} +1 -1
- package/lib/{chunk-JEERQRLW.mjs → chunk-2Z54GB6X.mjs} +1 -1
- package/lib/chunk-2ZMGVBLW.mjs +7 -0
- package/lib/{chunk-FKG7Q3WH.mjs → chunk-33ZX3A56.mjs} +1 -1
- package/lib/{chunk-HLWMJF6Y.mjs → chunk-3AOKLIVE.mjs} +1 -1
- package/lib/{chunk-GGD7ON3M.mjs → chunk-3B5H24ZG.mjs} +1 -1
- package/lib/chunk-43K2C6H2.mjs +7 -0
- package/lib/chunk-4JKR4PTZ.mjs +8 -0
- package/lib/chunk-4L7FBOJS.mjs +8 -0
- package/lib/chunk-5344TZBT.mjs +11 -0
- package/lib/{chunk-SAR5622P.mjs → chunk-54HYHHVL.mjs} +1 -1
- package/lib/chunk-55LQD3Y3.mjs +7 -0
- package/lib/chunk-56MPPWLA.mjs +7 -0
- package/lib/chunk-5C5XEVZN.mjs +11 -0
- package/lib/chunk-5CKWGZX4.mjs +9 -0
- package/lib/{chunk-RSWDYIHY.mjs → chunk-5GBO4KD5.mjs} +1 -1
- package/lib/{chunk-BKDV4ENO.mjs → chunk-5UT2ZBGF.mjs} +1 -1
- package/lib/chunk-5VQNKDFU.mjs +7 -0
- package/lib/{chunk-XAMBCQPU.mjs → chunk-5WGA5CZB.mjs} +1 -1
- package/lib/chunk-5ZKCLBTN.mjs +474 -0
- package/lib/{chunk-UCD54V2M.mjs → chunk-67CC7RAE.mjs} +1 -1
- package/lib/{chunk-TSLJUSLW.mjs → chunk-6CDIIFNX.mjs} +1 -1
- package/lib/{chunk-AV5SWEHP.mjs → chunk-6FARZYMJ.mjs} +1 -1
- package/lib/{chunk-FPKYYFM7.mjs → chunk-6FMLW7PH.mjs} +1 -1
- package/lib/chunk-6IGEASOF.mjs +7 -0
- package/lib/{chunk-XUWL6ZPC.mjs → chunk-6NADW3OI.mjs} +1 -1
- package/lib/chunk-6SEDOIO3.mjs +10 -0
- package/lib/{chunk-PJ5I73CK.mjs → chunk-742SSN7I.mjs} +1 -1
- package/lib/chunk-7DALDJMO.mjs +7 -0
- package/lib/chunk-7PK5QDQI.mjs +7 -0
- package/lib/chunk-AELFEK3G.mjs +7 -0
- package/lib/chunk-AITNZWLB.mjs +9 -0
- package/lib/{chunk-2UZPIMUC.mjs → chunk-AJPSGVMD.mjs} +1 -1
- package/lib/{chunk-GSKCGQIP.mjs → chunk-BNO5GIJ6.mjs} +1 -1
- package/lib/{chunk-K2FBZIXY.mjs → chunk-BWWQXU2B.mjs} +1 -1
- package/lib/{chunk-IC2C2GOF.mjs → chunk-BXZ73A5M.mjs} +1 -1
- package/lib/chunk-BZFIOZS3.mjs +156 -0
- package/lib/{chunk-J525F5KI.mjs → chunk-C4YGSK6W.mjs} +1 -1
- package/lib/chunk-CAFUNR6D.mjs +7 -0
- package/lib/chunk-CULAOP3U.mjs +7 -0
- package/lib/chunk-D62KWDDT.mjs +7 -0
- package/lib/{chunk-OHWNPXWW.mjs → chunk-D7P7DTWL.mjs} +1 -1
- package/lib/{chunk-COFG7Q6R.mjs → chunk-DHGPDSXS.mjs} +1 -1
- package/lib/{chunk-WU3GLFZO.mjs → chunk-DHIW4IO5.mjs} +1 -1
- package/lib/{chunk-6XYKJSGX.mjs → chunk-DMBR24CK.mjs} +1 -1
- package/lib/chunk-DPYTG6DM.mjs +48 -0
- package/lib/{chunk-BY2HJFFG.mjs → chunk-DQR5NDMI.mjs} +1 -1
- package/lib/chunk-DXOXLUZA.mjs +7 -0
- package/lib/{chunk-YRQGKDHM.mjs → chunk-E2OBAWSH.mjs} +1 -1
- package/lib/chunk-E2YJVSX6.mjs +10 -0
- package/lib/{chunk-JWTSEDIQ.mjs → chunk-EAFLDSQ2.mjs} +1 -1
- package/lib/{chunk-MILU7WFN.mjs → chunk-EH5YUA5W.mjs} +1 -1
- package/lib/{chunk-BGUEWRK2.mjs → chunk-EOSEMFPU.mjs} +1 -1
- package/lib/chunk-ETT5GP4P.mjs +13 -0
- package/lib/{chunk-MYW5QNGI.mjs → chunk-FDGFUEK3.mjs} +1 -1
- package/lib/{chunk-NTFIRZP6.mjs → chunk-FLNLG43R.mjs} +1 -1
- package/lib/{chunk-CHYDMRSV.mjs → chunk-FSDO4DJA.mjs} +1 -1
- package/lib/{chunk-MJVTDA5Q.mjs → chunk-FSZTXLNW.mjs} +1 -1
- package/lib/{chunk-SOU4FRYN.mjs → chunk-FTA5LOVX.mjs} +1 -1
- package/lib/chunk-G4VXPS3A.mjs +7 -0
- package/lib/chunk-GF247DA7.mjs +7 -0
- package/lib/{chunk-BTWDMNN3.mjs → chunk-GK7VEYFM.mjs} +1 -1
- package/lib/{chunk-SE4QEZUG.mjs → chunk-GR3NGDVM.mjs} +1 -1
- package/lib/{chunk-3TJON4F3.mjs → chunk-GTIXJCGS.mjs} +1 -1
- package/lib/{chunk-NZC67CGR.mjs → chunk-GWRKS3AL.mjs} +1 -1
- package/lib/{chunk-XLXIPIEW.mjs → chunk-GYKNCYES.mjs} +1 -1
- package/lib/{chunk-WIO4XO4F.mjs → chunk-HFSBDM7B.mjs} +1 -1
- package/lib/{chunk-KDGMAGQR.mjs → chunk-HVC5CYIB.mjs} +1 -1
- package/lib/{chunk-WR4Q363I.mjs → chunk-HYBH5PFM.mjs} +1 -1
- package/lib/chunk-HYOOJVR6.mjs +7 -0
- package/lib/{chunk-5K5VLULK.mjs → chunk-IBURU7T7.mjs} +1 -1
- package/lib/chunk-ICIYL45C.mjs +7 -0
- package/lib/{chunk-QR3WELJQ.mjs → chunk-IKGHRYCN.mjs} +1 -1
- package/lib/chunk-IM2XA6JI.mjs +7 -0
- package/lib/{chunk-IWDREM66.mjs → chunk-J6G23RUI.mjs} +1 -1
- package/lib/{chunk-2BA2XKAY.mjs → chunk-JU2XEKEO.mjs} +1 -1
- package/lib/{chunk-MHMH6MTP.mjs → chunk-K55LH4ZQ.mjs} +1 -1
- package/lib/chunk-K5HV4YRO.mjs +7 -0
- package/lib/{chunk-M3ROUWDX.mjs → chunk-K77NR3UK.mjs} +1 -1
- package/lib/chunk-KE2PGD6C.mjs +7 -0
- package/lib/chunk-KGYXLSQ5.mjs +37 -0
- package/lib/{chunk-E5AHXLS6.mjs → chunk-KNIRA333.mjs} +1 -1
- package/lib/chunk-KOQV4WXC.mjs +8 -0
- package/lib/{chunk-L77FJZEP.mjs → chunk-KRNFVAGC.mjs} +1 -1
- package/lib/{chunk-MTMH6H2A.mjs → chunk-LCDPCUXS.mjs} +1 -1
- package/lib/{chunk-YAZO75G2.mjs → chunk-LNXBCE7E.mjs} +1 -1
- package/lib/{chunk-IZQZ6ZUF.mjs → chunk-LO527YLT.mjs} +1 -1
- package/lib/chunk-MAHZMPMZ.mjs +7 -0
- package/lib/{chunk-F6GUDTOB.mjs → chunk-MHW6DV6T.mjs} +1 -1
- package/lib/{chunk-2YIV2OB2.mjs → chunk-MIDBQ7SD.mjs} +1 -1
- package/lib/{chunk-FGRG7ANU.mjs → chunk-MKNAZPOT.mjs} +1 -1
- package/lib/{chunk-PZPJKATS.mjs → chunk-MNITSYI2.mjs} +8 -8
- package/lib/{chunk-OLSGVAIL.mjs → chunk-MO3N5XVV.mjs} +53 -53
- package/lib/chunk-MWLFFVQV.mjs +8 -0
- package/lib/chunk-N6HHNR6J.mjs +7 -0
- package/lib/chunk-N7J6NJQ6.mjs +7 -0
- package/lib/chunk-NJ3EOEHS.mjs +9 -0
- package/lib/chunk-NWPQF5XR.mjs +7 -0
- package/lib/{chunk-IG2MTQRP.mjs → chunk-NWVVCZUK.mjs} +1 -1
- package/lib/{chunk-2NBYT7GR.mjs → chunk-O6ADMP36.mjs} +1 -1
- package/lib/chunk-O7DAFE6M.mjs +14 -0
- package/lib/chunk-OEHVAJAB.mjs +7 -0
- package/lib/chunk-OETEC3P7.mjs +7 -0
- package/lib/{chunk-GCOB7K5N.mjs → chunk-OHEOJISY.mjs} +1 -1
- package/lib/chunk-OIIL4NVI.mjs +7 -0
- package/lib/chunk-OMZJ37JI.mjs +15 -0
- package/lib/{chunk-CEX3NEZL.mjs → chunk-ONMBSACW.mjs} +1 -1
- package/lib/chunk-OQQHNYR7.mjs +272 -0
- package/lib/{chunk-SOGQW4IG.mjs → chunk-OU5W7SCB.mjs} +1 -1
- package/lib/{chunk-O2HDYYUV.mjs → chunk-OVOLG3AL.mjs} +1 -1
- package/lib/{chunk-DYFALGRT.mjs → chunk-OXKZ4Y3B.mjs} +1 -1
- package/lib/{chunk-2GTBABKU.mjs → chunk-OZNLOV4U.mjs} +1 -1
- package/lib/{chunk-TYYOBZMU.mjs → chunk-PC247GKX.mjs} +1 -1
- package/lib/chunk-PPGDAUEQ.mjs +7 -0
- package/lib/{chunk-IGYH7GMA.mjs → chunk-PYUEHBA6.mjs} +1 -1
- package/lib/{chunk-TLH7AD35.mjs → chunk-PZBZ7MNC.mjs} +1 -1
- package/lib/{chunk-DBFJB2B6.mjs → chunk-QIRO4HTE.mjs} +1 -1
- package/lib/{chunk-BXU6WFMH.mjs → chunk-QXLZINZB.mjs} +1 -1
- package/lib/chunk-R2BJWO5N.mjs +20 -0
- package/lib/chunk-R6TF26V4.mjs +10 -0
- package/lib/{chunk-YKKRIEH4.mjs → chunk-RKALOKAU.mjs} +1 -1
- package/lib/chunk-SQGP46QS.mjs +7 -0
- package/lib/chunk-SW2NUKQL.mjs +9 -0
- package/lib/{chunk-MFG4MUIO.mjs → chunk-T26C576X.mjs} +1 -1
- package/lib/{chunk-LKQ5RKIV.mjs → chunk-T3PLRQ2T.mjs} +1 -1
- package/lib/chunk-T5VAULLQ.mjs +7 -0
- package/lib/{chunk-KYEDBS54.mjs → chunk-TEIBWMJM.mjs} +1 -1
- package/lib/chunk-TKQQVB2D.mjs +9 -0
- package/lib/{chunk-ELFXJHU7.mjs → chunk-TPHXRHOA.mjs} +1 -1
- package/lib/chunk-TQ2TQHTT.mjs +9 -0
- package/lib/{chunk-RPI7LRTW.mjs → chunk-TQM2XJ27.mjs} +1 -1
- package/lib/{chunk-IOIWJ3DJ.mjs → chunk-UCHAZ4ZU.mjs} +1 -1
- package/lib/{chunk-G35N4P7D.mjs → chunk-UIUPPEFB.mjs} +1 -1
- package/lib/{chunk-DBB3EMIN.mjs → chunk-UT27HXE7.mjs} +1 -1
- package/lib/{chunk-KBJ5VERV.mjs → chunk-UUSLTW5V.mjs} +1 -1
- package/lib/chunk-V2QO6KOE.mjs +19 -0
- package/lib/chunk-V473C7LY.mjs +7 -0
- package/lib/chunk-V4RKM4QZ.mjs +8 -0
- package/lib/chunk-VSU74RQ3.mjs +9 -0
- package/lib/chunk-VV3B6IC3.mjs +7 -0
- package/lib/chunk-W2AAGIZF.mjs +7 -0
- package/lib/{chunk-WR2GIKWE.mjs → chunk-WB2RIVO3.mjs} +1 -1
- package/lib/chunk-WD47PGUS.mjs +10 -0
- package/lib/{chunk-HEKAZJRH.mjs → chunk-WEZLXE34.mjs} +1 -1
- package/lib/{chunk-W622GUAW.mjs → chunk-WI4HYWV6.mjs} +1 -1
- package/lib/{chunk-WA7EYLAQ.mjs → chunk-WM5JI4JI.mjs} +1 -1
- package/lib/chunk-WWTXRWNZ.mjs +7 -0
- package/lib/{chunk-7EANH5PY.mjs → chunk-WZQEK4WT.mjs} +1 -1
- package/lib/{chunk-FXXLX4O6.mjs → chunk-X2ZVSQ54.mjs} +1 -1
- package/lib/{chunk-ZVAED4QV.mjs → chunk-XC2QKQT5.mjs} +1 -1
- package/lib/chunk-XC54KKKC.mjs +7 -0
- package/lib/chunk-XEB6HZ34.mjs +7 -0
- package/lib/chunk-XGKSSCW7.mjs +7 -0
- package/lib/chunk-XIZ5LMQM.mjs +7 -0
- package/lib/{chunk-74Q6DORA.mjs → chunk-Y5ZCPY36.mjs} +1 -1
- package/lib/{chunk-UNJA4J37.mjs → chunk-YCSFP6ER.mjs} +4 -4
- package/lib/{chunk-X5JYBPXP.mjs → chunk-YHIOS2PU.mjs} +1 -1
- package/lib/chunk-YIGFYZQY.mjs +7 -0
- package/lib/chunk-YJEXE6HZ.mjs +925 -0
- package/lib/{chunk-TTKXMDBN.mjs → chunk-YOGMP72T.mjs} +4 -4
- package/lib/chunk-ZRUDYB7O.mjs +7 -0
- package/lib/{chunk-CU2INBND.mjs → chunk-ZUA5BNAO.mjs} +1 -1
- package/lib/chunk-ZWCRWF7E.mjs +7 -0
- package/lib/{chunk-N652NMZ4.mjs → chunk-ZWZXQTAK.mjs} +52 -52
- package/lib/sandforge-autopilot.mjs +11 -11
- package/lib/sandforge-backup.mjs +63 -32
- package/lib/sandforge-checkpoint.mjs +1 -348
- package/lib/sandforge-cleanup.mjs +1 -1
- package/lib/sandforge-clone.mjs +1 -1
- package/lib/sandforge-compare.mjs +1 -1
- package/lib/sandforge-dataops.mjs +1 -1
- package/lib/sandforge-empty.mjs +11 -11
- package/lib/sandforge-env.mjs +104 -104
- package/lib/sandforge-frozen.mjs +1 -266
- package/lib/sandforge-mcp.mjs +33 -14
- package/lib/sandforge-monitor.mjs +1 -1
- package/lib/sandforge-pipeline.mjs +88 -0
- package/lib/sandforge-seed.mjs +1 -1
- package/lib/sandforge-sync.mjs +1 -1
- package/lib/sandforge.mjs +6 -6
- package/package.json +2 -1
- package/lib/chunk-2CNCDM56.mjs +0 -7
- package/lib/chunk-3F6Q5E7I.mjs +0 -14
- package/lib/chunk-4VS2V6WU.mjs +0 -25
- package/lib/chunk-5P4PHJRL.mjs +0 -9
- package/lib/chunk-5TC3QB4U.mjs +0 -10
- package/lib/chunk-7ABODJ4G.mjs +0 -7
- package/lib/chunk-7EGQP6S4.mjs +0 -7
- package/lib/chunk-7FFGJWHN.mjs +0 -7
- package/lib/chunk-7YDNUBO5.mjs +0 -7
- package/lib/chunk-A527W53V.mjs +0 -7
- package/lib/chunk-ADOAS63R.mjs +0 -7
- package/lib/chunk-B5QQJ4SI.mjs +0 -7
- package/lib/chunk-CION3VMZ.mjs +0 -7
- package/lib/chunk-CSBS5U5I.mjs +0 -7
- package/lib/chunk-DB7RBE5D.mjs +0 -7
- package/lib/chunk-E5ZB3LU5.mjs +0 -7
- package/lib/chunk-EFR2Y7E4.mjs +0 -7
- package/lib/chunk-EHQ3FX6X.mjs +0 -7
- package/lib/chunk-EQNW3UC2.mjs +0 -7
- package/lib/chunk-F43REJDZ.mjs +0 -10
- package/lib/chunk-GSG7WZHM.mjs +0 -7
- package/lib/chunk-HOJYWTP7.mjs +0 -20
- package/lib/chunk-HS4YRX4J.mjs +0 -7
- package/lib/chunk-I7O6C2B5.mjs +0 -8
- package/lib/chunk-IFETCRWE.mjs +0 -10
- package/lib/chunk-IQXHJEYB.mjs +0 -7
- package/lib/chunk-JPUR2CFX.mjs +0 -10
- package/lib/chunk-K327QKMD.mjs +0 -7
- package/lib/chunk-KRCA6IPH.mjs +0 -8
- package/lib/chunk-LPBMBW3O.mjs +0 -13
- package/lib/chunk-LWW4U276.mjs +0 -7
- package/lib/chunk-MJU2PGZQ.mjs +0 -15
- package/lib/chunk-OAZRPP4I.mjs +0 -7
- package/lib/chunk-OO6CLPEH.mjs +0 -7
- package/lib/chunk-OPXCV2KL.mjs +0 -7
- package/lib/chunk-P33PSCXK.mjs +0 -7
- package/lib/chunk-Q3DM32KF.mjs +0 -11
- package/lib/chunk-QROPNEGY.mjs +0 -14
- package/lib/chunk-QWT2C74M.mjs +0 -7
- package/lib/chunk-R3X3LV64.mjs +0 -14
- package/lib/chunk-RMBPOTD7.mjs +0 -7
- package/lib/chunk-SIHORWVK.mjs +0 -7
- package/lib/chunk-T62WNR54.mjs +0 -7
- package/lib/chunk-TTFDUKUS.mjs +0 -47
- package/lib/chunk-VE6XKGGD.mjs +0 -7
- package/lib/chunk-VGW4MXXZ.mjs +0 -7
- package/lib/chunk-VS7ZXUII.mjs +0 -824
- package/lib/chunk-VXQLDM4R.mjs +0 -7
- package/lib/chunk-VYXMVJL5.mjs +0 -7
- package/lib/chunk-W7U5E5ZL.mjs +0 -9
- package/lib/chunk-WXAQ7FK3.mjs +0 -115
- package/lib/chunk-YS4G22C2.mjs +0 -7
- package/lib/chunk-ZM6OJGIG.mjs +0 -7
- package/lib/chunk-ZUTYVST5.mjs +0 -7
|
@@ -4,10 +4,10 @@ import { dirname as __sandforgeDirname } from 'node:path';
|
|
|
4
4
|
const require = __sandforgeRequire(import.meta.url);
|
|
5
5
|
const __filename = __sandforgePath(import.meta.url);
|
|
6
6
|
const __dirname = __sandforgeDirname(__filename);
|
|
7
|
-
import{c as rr}from"./chunk-N652NMZ4.mjs";import"./chunk-SOGQW4IG.mjs";import"./chunk-W622GUAW.mjs";import"./chunk-WA7EYLAQ.mjs";import"./chunk-LKQ5RKIV.mjs";import"./chunk-XAMBCQPU.mjs";import"./chunk-IG2MTQRP.mjs";import"./chunk-WR4Q363I.mjs";import"./chunk-CHYDMRSV.mjs";import"./chunk-F6GUDTOB.mjs";import"./chunk-BXU6WFMH.mjs";import"./chunk-2GTBABKU.mjs";import"./chunk-P33PSCXK.mjs";import"./chunk-UCD54V2M.mjs";import"./chunk-BV6VTP3J.mjs";import{q as zt}from"./chunk-OLSGVAIL.mjs";import"./chunk-INIQ23K6.mjs";import"./chunk-ELFXJHU7.mjs";import{b as rn}from"./chunk-W7U5E5ZL.mjs";import{a as vo,b as Eo,c as Po,d as Wo,e as Ho,f as Lt,g as Dt,h as $t,i as Ve,j as Ko,k as xe,l as Fe}from"./chunk-E5ZB3LU5.mjs";import"./chunk-EFR2Y7E4.mjs";import"./chunk-O2HDYYUV.mjs";import"./chunk-M3ROUWDX.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-ZM6OJGIG.mjs";import"./chunk-MHMH6MTP.mjs";import"./chunk-COFG7Q6R.mjs";import"./chunk-GMY5427L.mjs";import"./chunk-PJ5I73CK.mjs";import"./chunk-BKDV4ENO.mjs";import"./chunk-X5JYBPXP.mjs";import"./chunk-5P4PHJRL.mjs";import{Na as qt,O as or,a as Co,g as Bt,h as Yo,i as Qo,j as Xo,k as Jo,l as Vo,m as Zo,n as _t,o as er,p as tr,t as je}from"./chunk-VS7ZXUII.mjs";import{a as Io}from"./chunk-SOU4FRYN.mjs";import"./chunk-E5AHXLS6.mjs";import"./chunk-OO6CLPEH.mjs";import"./chunk-YS4G22C2.mjs";import"./chunk-QROPNEGY.mjs";import{b as mt,e as sn}from"./chunk-BZ24IAP5.mjs";import{a as ct}from"./chunk-SCKUIE3R.mjs";import{c as cn,d as dn,f as ln}from"./chunk-AV5SWEHP.mjs";import"./chunk-I7O6C2B5.mjs";import"./chunk-WR2GIKWE.mjs";import"./chunk-2CNCDM56.mjs";import"./chunk-SIHORWVK.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-BOGNK4LV.mjs";import{b as un,c as pn,d as Ue,e as fn,f as yo,g as wo,i as bo,j as Ao,k as ko,l as Ro,m as It,s as So,t as Oo,u as To}from"./chunk-4VS2V6WU.mjs";import{h as Mo,i as Do,j as $o,k as Bo,l as Nt,m as _o,n as qo}from"./chunk-KYEDBS54.mjs";import{h as zo,i as Go,k as Uo}from"./chunk-6XYKJSGX.mjs";import{a as xo,b as xt,c as Ft,d as Fo,e as jo,f as No,g as Lo,h as jt}from"./chunk-K2FBZIXY.mjs";import"./chunk-F43REJDZ.mjs";import"./chunk-JPUR2CFX.mjs";import"./chunk-LPBMBW3O.mjs";import{d as Yn}from"./chunk-T63U4OZJ.mjs";import{d as Kn}from"./chunk-DBFJB2B6.mjs";import"./chunk-IFETCRWE.mjs";import"./chunk-PZPJKATS.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-DYFALGRT.mjs";import"./chunk-M6P5ZZLE.mjs";import"./chunk-7FFGJWHN.mjs";import{o as to,p as no,q as Tt,r as oo,s as Xe}from"./chunk-G35N4P7D.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-SAR5622P.mjs";import{b as ft,c as Ge}from"./chunk-KDGMAGQR.mjs";import{B as Qe,s as Vn,t as Ot,x as Ie,y as Zn,z as eo}from"./chunk-MFG4MUIO.mjs";import"./chunk-EQNW3UC2.mjs";import"./chunk-GSKCGQIP.mjs";import"./chunk-5LFSFYFJ.mjs";import"./chunk-TYYOBZMU.mjs";import{b as pt,c as nn}from"./chunk-HS4YRX4J.mjs";import{a as he,i as Me,k as Fn,n as jn,o as Nn,p as Ln,s as Dn,t as $n,u as Bn,v as _n}from"./chunk-ZUTYVST5.mjs";import"./chunk-CU2INBND.mjs";import"./chunk-YKKRIEH4.mjs";import"./chunk-TUACWKIH.mjs";import{Ba as mo,D as Et,Ia as Te,Ja as ho,K as so,L as io,N as ao,Q as Pt,S as Je,T as co,W as lo,Wa as go,Xa as Mt,_ as Ct,ka as uo,r as Qn,s as Xn,w as Jn,wa as po,xa as fo,y as ro}from"./chunk-VYXMVJL5.mjs";import{q as vt}from"./chunk-AEKONPF4.mjs";import{b as wt,d as bt,e as In}from"./chunk-JWTSEDIQ.mjs";import{a as ae}from"./chunk-4TLYUZD5.mjs";import"./chunk-CION3VMZ.mjs";import{a as qn,b as At,c as kt,f as zn,h as Gn,j as Ke,l as Un,m as Wn}from"./chunk-WIO4XO4F.mjs";import{a as He}from"./chunk-EADHKH3A.mjs";import"./chunk-GCOB7K5N.mjs";import{i as xn}from"./chunk-INIT2UKJ.mjs";import"./chunk-SU65Z2BA.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-L77FJZEP.mjs";import{X as Sn,Y as On,Z as Tn,_ as vn,a as mn,b as oe,c as We,ca as Ce,d as hn,e as gn,ea as En,f as yn,ha as Pn,ia as Cn,ja as Mn,l as gt,m as wn,n as bn,o as An,p as ce,q as fe,r as yt,s as Pe,t as kn,y as Rn}from"./chunk-A527W53V.mjs";import{a as ge,h as ye}from"./chunk-TZE3Y7IQ.mjs";import{b as Ye,c as Rt,j as St,k as Hn}from"./chunk-GGD7ON3M.mjs";import"./chunk-UNDIBZWG.mjs";import{b as ee}from"./chunk-CA5NAXSU.mjs";import{a as on,c as an,e as ht,g as nr}from"./chunk-MTMH6H2A.mjs";import{Bb as Qt,Cb as Xt,Db as Jt,Hb as Oe,Ib as Ae,Jb as _e,Kb as ve,Lb as Vt,Nb as lt,Ob as qe,Pb as Ee,Ub as Zt,Wb as en,ed as ze,ic as tn,ld as ut,yb as dt}from"./chunk-TTFDUKUS.mjs";import"./chunk-7EANH5PY.mjs";import"./chunk-MS4FJDFD.mjs";import"./chunk-NTOVCTRS.mjs";var Ut=Oo,Wt=So,ke=200;function Or(l,e){let t=new Set(e?.fields.map(n=>n.name)??[]),o=new Set(l.split(", "));for(let n of[he,Ee])t.has(n)&&o.add(n);return[...o].join(", ")}var Tr=10,vr=new Set([ce]),we="IsPersonAccount",Ze="IsStandard",et=class{maxConcurrent;constructor(e=10){this.maxConcurrent=e}async listObjects(e,t,o){let[n,r]=await Promise.all([e.describeGlobal(),t.describeGlobal()]),s=new Set(n.sobjects.filter(c=>c.createable).map(c=>c.name)),i=bt(r.sobjects.filter(c=>!s.has(c.name)),await this.toolingObjects(t)),a=new Map(r.sobjects.map(c=>[c.name,c.createable!==!1]));return n.sobjects.filter(c=>c.queryable&&(c.createable||a.get(c.name)===!0)).filter(c=>o||c.custom).filter(c=>!wt(c.name,i)).map(c=>({apiName:c.name,label:c.label,custom:c.custom,...a.has(c.name)?a.get(c.name)===!1?{notCreateableInTarget:!0}:{}:{missingInTarget:!0}}))}async countObjects(e,t){return this.countRecords(e,t)}async scan(e,t,o,n,r={}){let s=Gt(r.maxDepth,Ut),i=Gt(r.maxObjects,Wt),a=Gt(r.maxRecordsPerObject,5e4),c=r.onProgress??(()=>{});if(o.length===0)throw new Error("Choose the objects to copy: a scan starts from them, and with none chosen it would describe and count every object of the org.");let d=await e.describeGlobal(),m=[...o],u=await t.describeGlobal(),p=bt(u.sobjects,await this.toolingObjects(t)),g=A=>wt(A,p);m=m.filter(A=>!g(A)),c(`describing ${m.length} selected object(s)\u2026`);let y=await this.describeAll(e,m),f=new Set(y.keys()),R=new Map(d.sobjects.map(A=>[A.name,A.custom])),w=new Map;for(let A of d.sobjects)A.keyPrefix&&w.set(A.keyPrefix,A.name);let C=await this.walkRecords(e,y,f,{isStandard:A=>R.get(A)===!1||!R.has(A)&&!A.includes("__"),includeStandardObjects:n,leftOut:g,keyPrefixes:w,maxDepth:s,maxObjects:i,maxRecords:a,say:c}),v=new Set(u.sobjects.map(A=>A.name)),z=[...y.keys()].filter(A=>!v.has(A)),K=await this.currenciesOf(e,t,y),E=await this.personAccountsOf(e,y,f,C.parentIds,{cutShort:C.cutShort,cutAt:C.cutAt});return{objectDescribes:y,autoDiscoveredObjects:C.added,missingInTarget:z,recordCounts:C.recordCounts,totalObjectsScanned:y.size,parentIds:C.parentIds,personAccounts:E,scope:{maxDepth:s,maxObjects:i,selected:[...f],parents:C.added.map(A=>({objectApiName:A,records:C.parentIds.get(A)?.length??0})),leftEmpty:C.leftEmpty,standardNeeded:C.standardNeeded,...C.followedByDefault.length>0?{followedByDefault:C.followedByDefault}:{},...K?{currencies:K}:{},...C.cutShort.length>0?{cutShort:C.cutShort}:{}}}}async readFitRows(e,t,o=()=>{}){let n=new Set(t.objectDescribes.keys()),r=new Map;for(let s of t.scope.selected){let i=t.objectDescribes.get(s);if(!i)continue;o(`reading the lookups of ${s} to fit it\u2026`);let a=new Set(i.fields.map(u=>u.name)),c=tt(s,i).filter(u=>u.targets.some(p=>n.has(p))),d=["Id",...new Set(c.map(u=>u.field)),...(s===ce||s===fe)&&a.has(we)?[we]:[],...s===Ae&&a.has(Ze)?[Ze]:[]],m=await xn(`SELECT ${d.map(ye).join(", ")} FROM ${ye(s)} ORDER BY Id`,async u=>(await this.readAll(e,u)).records);r.set(s,m.filter(u=>typeof u.Id=="string"))}return r}async walkFrom(e,t,o,n=()=>{}){let r=new Map(t.objectDescribes),s=new Set(r.keys()),i=new Map;for(let[c,d]of r)d.keyPrefix&&i.set(d.keyPrefix,c);let a=await this.walkRecords(e,r,new Set(t.scope.selected),{isStandard:()=>!1,includeStandardObjects:!0,leftOut:c=>!s.has(c),keyPrefixes:i,maxDepth:t.scope.maxDepth,maxObjects:s.size,say:n},o);return{added:a.added,parentIds:a.parentIds,personAccounts:a.personAccounts,leftEmpty:a.leftEmpty,namingSelected:a.namingSelected}}async personAccountsOf(e,t,o,n,r){let s=new Map;for(let i of[ce,fe]){if(!t.get(i)?.fields.some(d=>d.name===we))continue;let c=`SELECT COUNT() FROM ${ye(i)} WHERE ${we} = true`;try{let d=r.cutShort.find(u=>u.objectApiName===i)?.copied;if(o.has(i)&&d!==void 0){let u=r.cutAt.get(i)??await this.lastIdOfTheFirst(e,i,d);s.set(i,u!==void 0?(await e.query(`${c} AND Id <= '${ge(u)}'`)).totalSize:Math.min((await e.query(c)).totalSize,d));continue}if(o.has(i)){s.set(i,(await e.query(c)).totalSize);continue}let m=0;for(let u of this.chunk([...n.get(i)??[]],ke)){let p=u.map(g=>`'${ge(g)}'`).join(", ");m+=(await e.query(`${c} AND Id IN (${p})`)).totalSize}s.set(i,m)}catch(d){ae.warn("Autopilot could not count the person accounts it copies",{objectApiName:i,error:ee(d)})}}return s}async lastIdOfTheFirst(e,t,o){let{records:n}=await this.readAll(e,`SELECT Id FROM ${ye(t)} ORDER BY Id`),r=n.length>=o?n[o-1]?.Id:void 0;return typeof r=="string"?r:void 0}async currenciesOf(e,t,o){let n=[...o.values()].filter(a=>a.fields.some(c=>c.name===he)).map(a=>a.name).sort();if(n.length===0)return;let r=await Me(async a=>(await e.query(a)).records,async a=>(await t.query(a)).records),s=r?.target.corporate;if(!r||s===void 0)return;let i=[...r.source.active].filter(a=>!r.target.active.has(a));return i.length>0?{notInTarget:i.sort(),writtenIn:s,objects:n}:void 0}async walkRecords(e,t,o,n,r){let s=new Set(o),i=new Set,a=n.maxRecords??5e4,c=n.maxObjects,d=n.maxObjects*To,m=new Map,u=[],p=[],g=[],y=new Map,f=[],R=new Map,w=new Map,C=new Map,v=[],z=T=>{let O=t.get(T);return O?tt(T,O).map(D=>({...D,targets:D.targets.filter(S=>!n.leftOut(S)&&!i.has(S))})).filter(D=>D.targets.length>0):[]},K=T=>["Id",...new Set(z(T).map(O=>O.field)),...r&&(T===ce||T===fe)&&t.get(T)?.fields.some(O=>O.name===we)?[we]:[]].map(ye).join(", "),E=(T,O,D)=>{let S=`${T.objectApiName}.${T.field}>${O}`;m.has(S)||m.set(S,{objectApiName:T.objectApiName,fieldApiName:T.field,target:O,reason:D,...T.required?{required:!0}:{}})},A=new Map,j=(T,O,D)=>{let S=z(T);for(let ne of O)for(let N of S){let _=ne[N.field];if(typeof _!="string"||_==="")continue;let V=Er(_,N.targets,n.keyPrefixes,r!==void 0&&N.polymorphic);if(!V)continue;if(o.has(V)){r&&D>0&&v.push({objectApiName:T,field:N.field,required:N.required,target:V,id:_});continue}let B={objectApiName:T,field:N.field,required:N.required};if(D>=n.maxDepth&&!N.required){s.has(V)||E(B,V,"depth");continue}if(w.get(V)?.has(_))continue;let Z=A.get(V)??{ids:new Set,required:!1,via:[]};Z.ids.add(_),Z.required||=N.required,Z.via.some(Y=>Y.objectApiName===T&&Y.field===N.field)||Z.via.push(B),A.set(V,Z)}},M=[];for(let T of o){if(r){j(T,r.get(T)??[],0);continue}let O=z(T).filter(D=>D.targets.some(S=>!o.has(S)));if(O.length===0){M.push(T);continue}n.say(`reading the lookups of ${T}\u2026`);try{let D=["Id",...new Set(O.map(N=>N.field))].map(ye).join(", "),{records:S,truncated:ne}=await this.readAll(e,`SELECT ${D} FROM ${ye(T)} ORDER BY Id`,a);if(R.set(T,S.length),ne){let N=(await this.countRecords(e,[T])).get(T);g.push({objectApiName:T,copied:S.length,...N!==void 0?{total:N}:{}});let _=S[S.length-1]?.Id;typeof _=="string"&&y.set(T,_)}j(T,S,0)}catch(D){ae.warn("Autopilot could not read the lookups of a selected object",{objectApiName:T,error:ee(D)}),M.push(T)}}for(let[T,O]of await this.countRecords(e,M))O>a?(R.set(T,a),g.push({objectApiName:T,copied:a,total:O})):R.set(T,O);let te=n.maxDepth+Tr;for(let T=1;A.size>0&&T<=te;T++){let O=A;A=new Map;let D=[];for(let[S,ne]of O){if(s.has(S))continue;let N=n.isStandard(S)&&!n.includeStandardObjects,_=N&&!ne.required&&vr.has(S),V;if(N&&!ne.required&&!_?V="standard":s.size>=c&&(ne.required&&c<d?c++:V="objects"),V){for(let B of ne.via)E(B,S,V);O.delete(S);continue}if(s.add(S),D.push(S),_)p.push({objectApiName:S,referencedBy:ne.via.map(B=>`${B.objectApiName}.${B.field}`)});else if(N){let B=ne.via[0];u.push({objectApiName:S,neededBy:`${B.objectApiName}.${B.field}`})}}if(D.length>0){let S=D.filter(N=>!t.has(N));S.length>0&&n.say(`describing ${S.length} parent object(s) at depth ${T}\u2026`);let ne=await this.describeAll(e,S);for(let N of D){let _=t.get(N)??ne.get(N);_?(t.set(N,_),f.push(N)):(s.delete(N),i.add(N),O.delete(N))}}for(let[S,ne]of O){let N=[...ne.ids].filter(Y=>!w.get(S)?.has(Y));if(N.length===0)continue;n.say(`reading ${N.length} ${S} record(s) by id\u2026`);let _=w.get(S)??new Set;w.set(S,_);let V=S===Oe,B=V?Or(K(S),t.get(S)):K(S),Z=[];for(let Y of this.chunk(N,ke)){let me=Y.map(x=>`'${ge(x)}'`).join(", "),b=(await e.query(`SELECT ${B} FROM ${ye(S)} WHERE Id IN (${me})`)).records.filter(x=>typeof x.Id=="string");for(let x of b)_.add(x.Id);Z.push(...b);let k=b.filter(x=>x[we]===!0).length;r&&k>0&&C.set(S,(C.get(S)??0)+k),j(S,b,T)}if(V){let Y=await this.standardPricesOf(e,B,Z,_);if(Y.length>0){n.say(`reading ${Y.length} standard price(s) the prices need\u2026`);for(let me of Y)_.add(me.Id);j(S,Y.map(me=>({...me,[_e]:void 0})),T)}}}}let se=new Map;for(let T of f){let O=[...w.get(T)??[]];se.set(T,O),R.set(T,O.length)}return{added:f,leftEmpty:[...m.values()].filter(T=>!s.has(T.target)),standardNeeded:u,followedByDefault:p.filter(T=>s.has(T.objectApiName)),cutShort:g,cutAt:y,recordCounts:R,parentIds:se,personAccounts:C,namingSelected:v}}async standardPricesOf(e,t,o,n){let r=s=>[s[qe],s[he],s[Ee]].map(i=>String(i??"")).join("|");try{let[s]=(await e.query(ve)).records,i=s?.Id;if(typeof i!="string")return[];let a=o.filter(u=>u[_e]!==i),c=[...new Set(a.flatMap(u=>{let p=u[qe];return typeof p=="string"&&p!==""?[p]:[]}))];if(c.length===0)return[];let d=new Set(a.map(r)),m=[];for(let u of this.chunk(c,ke)){let p=u.map(y=>`'${ge(y)}'`).join(", "),g=await e.query(`SELECT ${t} FROM ${Oe} WHERE ${_e} = '${ge(i)}' AND ${qe} IN (${p})`);for(let y of g.records){let f=y.Id;typeof f!="string"||n.has(f)||!d.has(r(y))||m.push(y)}}return m}catch(s){return ae.warn("Autopilot could not read the standard prices its prices need",{error:ee(s)}),[]}}async readAll(e,t,o=5e4){let{queryMore:n}=e;if(!n){let s=await e.query(t);return{records:s.records,truncated:s.done===!1}}let r=await He({query:s=>e.query(s),queryMore:s=>n.call(e,s)},t,o);return r.truncated&&ae.warn("Autopilot read the lookups of a selected object to its bound only",{records:r.records.length}),{records:r.records,truncated:r.truncated}}async toolingObjects(e){if(!e.tooling)return[];try{return(await e.tooling.describeGlobal()).sobjects.map(o=>o.name)}catch(t){return ae.warn("Autopilot could not ask the Tooling API which objects are metadata",{error:ee(t)}),[]}}async describeAll(e,t){let o=new Map,n=this.chunk(t,this.maxConcurrent);for(let r of n){let s=await Promise.allSettled(r.map(i=>e.describe(i)));for(let i of s)i.status==="fulfilled"&&o.set(i.value.name,i.value)}return o}async countRecords(e,t){let o=new Map,n=this.chunk(t,this.maxConcurrent);for(let r of n){let s=await Promise.allSettled(r.map(async i=>{let a=await e.query(`SELECT COUNT() FROM ${ye(i)}`);return{name:i,count:a.totalSize}}));for(let i of s)i.status==="fulfilled"&&o.set(i.value.name,i.value.count)}return o}chunk(e,t){let o=[];for(let n=0;n<e.length;n+=t)o.push(e.slice(n,n+t));return o}};function Gt(l,e){return l!==void 0&&Number.isInteger(l)&&l>0?l:e}function tt(l,e){return e.fields.filter(t=>t.referenceTo.length>0&&Jt(t)).map(t=>({field:t.name,targets:[...t.referenceTo],required:Xt(l,t.name,t.nillable),polymorphic:t.referenceTo.length>1}))}function Er(l,e,t,o=!1){if(e.length===1&&!o)return e[0];let n=t.get(l.slice(0,3));return n!==void 0&&e.includes(n)?n:void 0}var sr=3,Pr="the source changed since the plan: plan again";function dr(l,e){return{holds:[...l.links.filter(t=>t.kind==="holds"),...l.requiredOfParents,...l.outward.filter(t=>t.required)],kept:e}}function ir(l,e){return typeof l!="string"||l===""?!1:e===void 0||e!==null&&l.startsWith(e)}function lr(l,e,t){let o=new Map(t.map((s,i)=>[s,i])),n=new Set(e),r={links:[],outward:[],requiredOfParents:[]};for(let[s,i]of l)for(let a of tt(s,i))for(let c of a.targets.filter(d=>l.has(d))){let d=a.polymorphic?{prefix:l.get(c)?.keyPrefix??null}:{},m={objectApiName:s,field:a.field,parent:c,...d};if(!n.has(s))n.has(c)&&a.required&&r.requiredOfParents.push({...m,kind:"holds"});else if(!n.has(c))r.outward.push({...m,required:a.required});else if(a.required)r.links.push({...m,kind:"holds"});else if(c===s)r.links.push({...m,kind:"selfReference"});else{let u=(o.get(c)??0)<(o.get(s)??0);r.links.push({...m,kind:u?"holds":"owed"})}}return r}function ur(l,e){let t=new Set(l),o=new Set(e.links.filter(n=>n.kind!=="holds").map(n=>n.objectApiName));return(n,r)=>t.has(n)&&(r==="insert"||r==="update"&&(o.has(n)||Ce[n]!==void 0))}function pr(l,e,t){return typeof l.unread=="string"?{perRecord:[],notCounted:[],unread:l.unread}:bo(ze(l,e,t),t)}function Cr(l){let e=new Map(l.order.map((t,o)=>[t,o]));return l.order.map(t=>{let o=l.rows.get(t)??[],n=l.lookups.links.filter(i=>i.objectApiName===t),r=l.lookups.outward.filter(i=>i.objectApiName===t),s={name:t,rows:o,at:new Map(o.map((i,a)=>[i.Id,a])),heldBefore:[],heldAfter:[],loose:[],named:[],roots:[],followers:[],persons:new Set(t===ce||t===fe?o.flatMap((i,a)=>i[we]===!0?[a]:[]):[])};return o.forEach((i,a)=>{let c=[],d=[],m=[];for(let u of n){let p=i[u.field];if(!ir(p,u.prefix))continue;let g={link:u,id:p};u.kind!=="holds"?m.push(g):(e.get(u.parent)??0)<(e.get(t)??0)?c.push(g):d.push(g)}s.heldBefore.push(c),s.heldAfter.push(d),s.loose.push(m),s.named.push(r.flatMap(u=>{let p=i[u.field];return ir(p,u.prefix)?[{parent:u.parent,id:p}]:[]})),(c.length>0?s.followers:s.roots).push(a)}),s})}function ar(l,e){let t=new Map(l.map(r=>[r.name,r])),o=new Map,n=[...e].flatMap(([r,s])=>[...s].map(i=>({name:r,id:i})));for(let r=n.pop();r;r=n.pop()){let s=t.get(r.name),i=s?.at.get(r.id);if(!s||i===void 0)continue;let a=o.get(r.name)??new Set;if(o.set(r.name,a),!a.has(i)){a.add(i);for(let c of[...s.heldBefore[i],...s.heldAfter[i]])n.push({name:c.link.parent,id:c.id})}}return o}function cr(l){return`${l} record${l===1?"":"s"}`}function Mr(l,e){return[...l.parentIds].every(([t,o])=>{let n=new Set(e.get(t)?.ids??[]);return o.every(r=>n.has(r))})}async function fr(l){let{budget:e,room:t,mode:o,parents:n,maxRecords:r}=l,s=Cr(l),i=b=>{let k=o.caps?.[b]??o.all;return k===void 0?void 0:Math.max(1,Math.floor(k))},a=s.some(b=>b.heldAfter.some(k=>k.length>0)),c=new Map;for(let b of s){if(b.name!==Ae)continue;let k=b.rows.filter(x=>x[Ze]===!0);k.length>0&&c.set(b.name,new Set(k.map(x=>x.Id)))}let d=ar(s,c),m=b=>{let k={kept:new Map,ids:new Map,cut:new Map},x=new Set;for(let $ of s){let L=d.get($.name)??x,X=i($.name),F=$.roots.filter(J=>!L.has(J)),G=F.length===0?0:Math.max(1,Math.round(b*Math.min(F.length,X??1/0))),W=It(F.length,G).map(J=>F[J]),q=new Map;for(let J of $.followers){if(L.has(J))continue;let be=$.heldBefore[J].find(Se=>!k.ids.get(Se.link.parent)?.has(Se.id));be?q.set(J,be.link):W.push(J)}W.sort((J,be)=>J-be);let ie=$.name===fe?W.filter(J=>$.persons.has(J)):[],U=ie.length>0?W.filter(J=>!$.persons.has(J)):W,re=X===void 0?U.length:Math.max(0,X-L.size-ie.length),le=U.length>re?It(U.length,re).map(J=>U[J]):U,ue=new Set([...L,...ie,...le]);k.kept.set($.name,ue),k.ids.set($.name,new Set([...ue].map(J=>$.rows[J].Id))),k.cut.set($.name,q)}if(!a)return k;for(let $=!0;$;){$=!1;for(let L of s){let X=d.get(L.name)??x,F=k.kept.get(L.name)??new Set;for(let G of[...F]){if(X.has(G))continue;let W=[...L.heldAfter[G],...L.heldBefore[G]].find(q=>!k.ids.get(q.link.parent)?.has(q.id));W&&(F.delete(G),k.ids.get(L.name)?.delete(L.rows[G].Id),k.cut.get(L.name)?.set(G,W.link),$=!0)}}}return k},u=b=>{let k=new Map;for(let x of s){let $=0;for(let L of b.kept.get(x.name)??[])x.loose[L].some(F=>b.ids.get(F.link.parent)?.has(F.id))&&$++;$>0&&k.set(x.name,$)}return k},p=(b,k)=>{let x=new Map,$=0;for(let F of s){let G=b.kept.get(F.name)??new Set,W=0;for(let q of G)F.persons.has(q)&&W++;x.set(F.name,G.size),$+=Et(F.name,{rows:G.size,personAccounts:W})}for(let[F,{records:G,personAccounts:W}]of k)x.set(F,(x.get(F)??0)+G),$+=Et(F,{rows:G,...W!==void 0?{personAccounts:W}:{}});let L=u(b),X=Ao(t,(F,G)=>{let W=x.get(F)??0;return G==="insert"||Ce[F]!==void 0?W:L.get(F)??0});return{records:[...x.values()].reduce((F,G)=>F+G,0),bytes:$,roomBytes:X,requests:ao([...x.values()].map(F=>({rows:F})))}},g=new Map;for(let b of s)for(let k of b.named)for(let{parent:x,id:$}of k){let L=g.get(x)??new Set;g.set(x,L),L.add($)}let y=[...g.values()].reduce((b,k)=>b+k.size,0),f=b=>{let k=new Map,x=0;for(let X of s)for(let F of b.kept.get(X.name)??[])for(let{parent:G,id:W}of X.named[F]){let q=k.get(G)??new Set;k.set(G,q),q.has(W)||x++,q.add(W)}let $=y>0?x/y:0,L=new Map;for(let[X,{ids:F,personAccounts:G}]of n){let W=Math.max(0,F.length-(g.get(X)?.size??0)),q=Math.min(F.length,(k.get(X)?.size??0)+Math.ceil(W*$));q!==0&&L.set(X,{records:q,...G!==void 0?{personAccounts:Math.ceil(G*q/F.length)}:{}})}return L},R=b=>new Map(b.added.map(k=>{let x=b.personAccounts.get(k);return[k,{records:b.parentIds.get(k)?.length??0,...x!==void 0?{personAccounts:x}:{}}]})),w=b=>b.bytes+b.roomBytes<=e.bytes,C=b=>e.runRequests===void 0||b.requests<=e.runRequests,v=b=>r===void 0||b.records<=r,z=b=>w(b)&&C(b)&&v(b),K=b=>w(b)?C(b)?"maxTotal":"apiRequests":e.terms.limitedBy,E=b=>w(b)?C(b)?{bound:"maxTotal",records:b.records,allowed:r??0}:{bound:"apiRequests",requests:b.requests,allowed:e.runRequests??0}:{bound:"storage",takesMB:(b.bytes+b.roomBytes)/1048576,fitsMB:e.bytes/1048576},A=b=>{if(!w(b)){let k=ho((b.bytes+b.roomBytes)/1048576,e.bytes/1048576);return`${k.over} MB`+(b.roomBytes>0?", room for what the org's automation creates under them included":"")+`, past the ${k.bound} MB that fit`}return C(b)?`${cr(b.records)}, past the ${r??0} the run may write`:`about ${b.requests} API requests, past the ${e.runRequests??0} that leave the org a tenth of its daily requests`},j=b=>new Map(s.map(k=>[k.name,[...b.kept.get(k.name)??[]].sort((x,$)=>x-$).map(x=>k.rows[x])])),M=(b,k,x,$,L,X)=>{let F=s.map(q=>{let ie=k.cut.get(q.name)??new Map,U=new Map;for(let le of ie.values()){let ue=`${le.field}
|
|
7
|
+
import{c as rr}from"./chunk-ZWZXQTAK.mjs";import"./chunk-WI4HYWV6.mjs";import"./chunk-WM5JI4JI.mjs";import"./chunk-56MPPWLA.mjs";import"./chunk-67CC7RAE.mjs";import"./chunk-OU5W7SCB.mjs";import"./chunk-T3PLRQ2T.mjs";import"./chunk-5WGA5CZB.mjs";import"./chunk-NWVVCZUK.mjs";import"./chunk-HYBH5PFM.mjs";import"./chunk-FSDO4DJA.mjs";import"./chunk-MHW6DV6T.mjs";import"./chunk-QXLZINZB.mjs";import"./chunk-OZNLOV4U.mjs";import"./chunk-2OZG6GRW.mjs";import{q as zt}from"./chunk-MO3N5XVV.mjs";import"./chunk-INIQ23K6.mjs";import"./chunk-TPHXRHOA.mjs";import{b as rn}from"./chunk-TKQQVB2D.mjs";import{a as vo,b as Eo,c as Po,d as Wo,e as Ho,f as Lt,g as Dt,h as $t,i as Ve,j as Ko,k as xe,l as Fe}from"./chunk-XIZ5LMQM.mjs";import"./chunk-AELFEK3G.mjs";import"./chunk-K77NR3UK.mjs";import"./chunk-OVOLG3AL.mjs";import"./chunk-FQGHL7GR.mjs";import"./chunk-IM2XA6JI.mjs";import"./chunk-K55LH4ZQ.mjs";import"./chunk-5UT2ZBGF.mjs";import"./chunk-YHIOS2PU.mjs";import"./chunk-DHGPDSXS.mjs";import"./chunk-GMY5427L.mjs";import"./chunk-742SSN7I.mjs";import{Wa as qt,a as Co,d as Bt,e as Qo,f as Xo,g as Jo,h as Vo,i as Zo,j as er,k as _t,l as tr,m as nr,q as je}from"./chunk-YJEXE6HZ.mjs";import{a as Io}from"./chunk-FTA5LOVX.mjs";import"./chunk-KNIRA333.mjs";import"./chunk-7DALDJMO.mjs";import{a as Yo}from"./chunk-O7DAFE6M.mjs";import{b as mt,e as sn}from"./chunk-BZ24IAP5.mjs";import{a as ct}from"./chunk-SCKUIE3R.mjs";import{c as cn,d as dn,f as ln}from"./chunk-6FARZYMJ.mjs";import"./chunk-WB2RIVO3.mjs";import"./chunk-VSU74RQ3.mjs";import"./chunk-CAFUNR6D.mjs";import"./chunk-AITNZWLB.mjs";import"./chunk-CE6ZDGBB.mjs";import"./chunk-BOGNK4LV.mjs";import{b as un,c as pn,d as Ue,e as fn,f as Ao,g as ko,h as Ro,i as So,j as Oo,k as To,l as It}from"./chunk-KGYXLSQ5.mjs";import{h as Mo,i as Do,j as $o,k as Bo,l as Nt,m as _o,n as qo}from"./chunk-TEIBWMJM.mjs";import{h as zo,i as Go,k as Uo}from"./chunk-DMBR24CK.mjs";import{a as xo,b as xt,c as Ft,d as Fo,e as jo,f as No,g as Lo,h as jt}from"./chunk-BWWQXU2B.mjs";import{e as ro,f as so,g as io}from"./chunk-4L7FBOJS.mjs";import"./chunk-OXKZ4Y3B.mjs";import"./chunk-MAHZMPMZ.mjs";import"./chunk-M6P5ZZLE.mjs";import{o as to,p as no,q as Tt,r as oo,s as Xe}from"./chunk-UIUPPEFB.mjs";import"./chunk-6SEDOIO3.mjs";import"./chunk-ZWCRWF7E.mjs";import{d as Yn}from"./chunk-T63U4OZJ.mjs";import"./chunk-YYZL7UGV.mjs";import"./chunk-54HYHHVL.mjs";import{d as Kn}from"./chunk-QIRO4HTE.mjs";import"./chunk-MNITSYI2.mjs";import"./chunk-QSRAEUGZ.mjs";import"./chunk-NJ3EOEHS.mjs";import"./chunk-ETT5GP4P.mjs";import"./chunk-SW2NUKQL.mjs";import"./chunk-4JKR4PTZ.mjs";import"./chunk-E2YJVSX6.mjs";import{b as ft,c as Ge}from"./chunk-HVC5CYIB.mjs";import{B as Qe,s as Vn,t as Ot,x as Ie,y as Zn,z as eo}from"./chunk-T26C576X.mjs";import"./chunk-BNO5GIJ6.mjs";import"./chunk-5LFSFYFJ.mjs";import{a as ae}from"./chunk-4TLYUZD5.mjs";import{a as pt,b as nn}from"./chunk-SQGP46QS.mjs";import"./chunk-PPGDAUEQ.mjs";import"./chunk-MS4FJDFD.mjs";import{b as Qn,c as Xn,g as Jn}from"./chunk-6IGEASOF.mjs";import{$a as lo,Ac as bo,Bc as Mt,Ma as ao,Pb as mo,Ra as Et,_a as co,ac as ho,bb as uo,bc as go,fb as Pt,fc as yo,hb as Je,ib as po,lb as fo,mc as Te,nc as wo,zb as Ct}from"./chunk-KOQV4WXC.mjs";import"./chunk-VV3B6IC3.mjs";import"./chunk-CULAOP3U.mjs";import{i as xn}from"./chunk-INIT2UKJ.mjs";import"./chunk-HF6LAK3G.mjs";import"./chunk-KRNFVAGC.mjs";import"./chunk-SU65Z2BA.mjs";import{q as vt}from"./chunk-2OIRJEYE.mjs";import{b as on,d as an,f as ht,h as or}from"./chunk-LCDPCUXS.mjs";import"./chunk-XEB6HZ34.mjs";import"./chunk-PC247GKX.mjs";import{a as he,j as Me,l as Fn,o as jn,p as Nn,q as Ln,t as Dn,u as $n,v as Bn,w as _n}from"./chunk-ICIYL45C.mjs";import"./chunk-ZUA5BNAO.mjs";import"./chunk-RKALOKAU.mjs";import"./chunk-TUACWKIH.mjs";import"./chunk-TQ2TQHTT.mjs";import{a as qn,b as At,c as kt,f as zn,h as Gn,j as Ke,l as Un,m as Wn}from"./chunk-HFSBDM7B.mjs";import"./chunk-OHEOJISY.mjs";import{a as He}from"./chunk-EADHKH3A.mjs";import{$ as vn,Y as Sn,Z as On,_ as Tn,a as mn,b as oe,c as We,d as hn,da as Ce,f as gn,fa as En,g as yn,ia as Pn,ja as Cn,ka as Mn,m as gt,n as wn,o as bn,p as An,q as ce,r as fe,s as yt,t as Pe,u as kn,z as Rn}from"./chunk-55LQD3Y3.mjs";import{a as ge,h as ye}from"./chunk-TZE3Y7IQ.mjs";import{b as Ye,c as Rt,j as St,k as Hn}from"./chunk-3B5H24ZG.mjs";import"./chunk-UNDIBZWG.mjs";import{b as wt,d as bt,e as In}from"./chunk-EAFLDSQ2.mjs";import{b as ee}from"./chunk-CA5NAXSU.mjs";import{$b as Qt,Hd as ze,Lc as tn,Y as dt,Yb as lt,ac as Xt,bc as Jt,fc as Oe,gc as Ae,hc as _e,ic as ve,jc as Vt,lc as ut,mc as qe,nc as Ee,tc as Zt,vc as en}from"./chunk-DPYTG6DM.mjs";import"./chunk-WZQEK4WT.mjs";import"./chunk-NTOVCTRS.mjs";var Ut=so,Wt=ro,ke=200;function Or(l,e){let t=new Set(e?.fields.map(n=>n.name)??[]),o=new Set(l.split(", "));for(let n of[he,Ee])t.has(n)&&o.add(n);return[...o].join(", ")}var Tr=10,vr=new Set([ce]),we="IsPersonAccount",Ze="IsStandard",et=class{maxConcurrent;constructor(e=10){this.maxConcurrent=e}async listObjects(e,t,o){let[n,r]=await Promise.all([e.describeGlobal(),t.describeGlobal()]),s=new Set(n.sobjects.filter(c=>c.createable).map(c=>c.name)),i=bt(r.sobjects.filter(c=>!s.has(c.name)),await this.toolingObjects(t)),a=new Map(r.sobjects.map(c=>[c.name,c.createable!==!1]));return n.sobjects.filter(c=>c.queryable&&(c.createable||a.get(c.name)===!0)).filter(c=>o||c.custom).filter(c=>!wt(c.name,i)).map(c=>({apiName:c.name,label:c.label,custom:c.custom,...a.has(c.name)?a.get(c.name)===!1?{notCreateableInTarget:!0}:{}:{missingInTarget:!0}}))}async countObjects(e,t){return this.countRecords(e,t)}async scan(e,t,o,n,r={}){let s=Gt(r.maxDepth,Ut),i=Gt(r.maxObjects,Wt),a=Gt(r.maxRecordsPerObject,5e4),c=r.onProgress??(()=>{});if(o.length===0)throw new Error("Choose the objects to copy: a scan starts from them, and with none chosen it would describe and count every object of the org.");let d=await e.describeGlobal(),m=[...o],u=await t.describeGlobal(),p=bt(u.sobjects,await this.toolingObjects(t)),g=A=>wt(A,p);m=m.filter(A=>!g(A)),c(`describing ${m.length} selected object(s)\u2026`);let y=await this.describeAll(e,m),f=new Set(y.keys()),R=new Map(d.sobjects.map(A=>[A.name,A.custom])),w=new Map;for(let A of d.sobjects)A.keyPrefix&&w.set(A.keyPrefix,A.name);let C=await this.walkRecords(e,y,f,{isStandard:A=>R.get(A)===!1||!R.has(A)&&!A.includes("__"),includeStandardObjects:n,leftOut:g,keyPrefixes:w,maxDepth:s,maxObjects:i,maxRecords:a,say:c}),v=new Set(u.sobjects.map(A=>A.name)),z=[...y.keys()].filter(A=>!v.has(A)),K=await this.currenciesOf(e,t,y),E=await this.personAccountsOf(e,y,f,C.parentIds,{cutShort:C.cutShort,cutAt:C.cutAt});return{objectDescribes:y,autoDiscoveredObjects:C.added,missingInTarget:z,recordCounts:C.recordCounts,totalObjectsScanned:y.size,parentIds:C.parentIds,personAccounts:E,scope:{maxDepth:s,maxObjects:i,selected:[...f],parents:C.added.map(A=>({objectApiName:A,records:C.parentIds.get(A)?.length??0})),leftEmpty:C.leftEmpty,standardNeeded:C.standardNeeded,...C.followedByDefault.length>0?{followedByDefault:C.followedByDefault}:{},...K?{currencies:K}:{},...C.cutShort.length>0?{cutShort:C.cutShort}:{}}}}async readFitRows(e,t,o=()=>{}){let n=new Set(t.objectDescribes.keys()),r=new Map;for(let s of t.scope.selected){let i=t.objectDescribes.get(s);if(!i)continue;o(`reading the lookups of ${s} to fit it\u2026`);let a=new Set(i.fields.map(u=>u.name)),c=tt(s,i).filter(u=>u.targets.some(p=>n.has(p))),d=["Id",...new Set(c.map(u=>u.field)),...(s===ce||s===fe)&&a.has(we)?[we]:[],...s===Ae&&a.has(Ze)?[Ze]:[]],m=await xn(`SELECT ${d.map(ye).join(", ")} FROM ${ye(s)} ORDER BY Id`,async u=>(await this.readAll(e,u)).records);r.set(s,m.filter(u=>typeof u.Id=="string"))}return r}async walkFrom(e,t,o,n=()=>{}){let r=new Map(t.objectDescribes),s=new Set(r.keys()),i=new Map;for(let[c,d]of r)d.keyPrefix&&i.set(d.keyPrefix,c);let a=await this.walkRecords(e,r,new Set(t.scope.selected),{isStandard:()=>!1,includeStandardObjects:!0,leftOut:c=>!s.has(c),keyPrefixes:i,maxDepth:t.scope.maxDepth,maxObjects:s.size,say:n},o);return{added:a.added,parentIds:a.parentIds,personAccounts:a.personAccounts,leftEmpty:a.leftEmpty,namingSelected:a.namingSelected}}async personAccountsOf(e,t,o,n,r){let s=new Map;for(let i of[ce,fe]){if(!t.get(i)?.fields.some(d=>d.name===we))continue;let c=`SELECT COUNT() FROM ${ye(i)} WHERE ${we} = true`;try{let d=r.cutShort.find(u=>u.objectApiName===i)?.copied;if(o.has(i)&&d!==void 0){let u=r.cutAt.get(i)??await this.lastIdOfTheFirst(e,i,d);s.set(i,u!==void 0?(await e.query(`${c} AND Id <= '${ge(u)}'`)).totalSize:Math.min((await e.query(c)).totalSize,d));continue}if(o.has(i)){s.set(i,(await e.query(c)).totalSize);continue}let m=0;for(let u of this.chunk([...n.get(i)??[]],ke)){let p=u.map(g=>`'${ge(g)}'`).join(", ");m+=(await e.query(`${c} AND Id IN (${p})`)).totalSize}s.set(i,m)}catch(d){ae.warn("Autopilot could not count the person accounts it copies",{objectApiName:i,error:ee(d)})}}return s}async lastIdOfTheFirst(e,t,o){let{records:n}=await this.readAll(e,`SELECT Id FROM ${ye(t)} ORDER BY Id`),r=n.length>=o?n[o-1]?.Id:void 0;return typeof r=="string"?r:void 0}async currenciesOf(e,t,o){let n=[...o.values()].filter(a=>a.fields.some(c=>c.name===he)).map(a=>a.name).sort();if(n.length===0)return;let r=await Me(async a=>(await e.query(a)).records,async a=>(await t.query(a)).records),s=r?.target.corporate;if(!r||s===void 0)return;let i=[...r.source.active].filter(a=>!r.target.active.has(a));return i.length>0?{notInTarget:i.sort(),writtenIn:s,objects:n}:void 0}async walkRecords(e,t,o,n,r){let s=new Set(o),i=new Set,a=n.maxRecords??5e4,c=n.maxObjects,d=n.maxObjects*io,m=new Map,u=[],p=[],g=[],y=new Map,f=[],R=new Map,w=new Map,C=new Map,v=[],z=T=>{let O=t.get(T);return O?tt(T,O).map(D=>({...D,targets:D.targets.filter(S=>!n.leftOut(S)&&!i.has(S))})).filter(D=>D.targets.length>0):[]},K=T=>["Id",...new Set(z(T).map(O=>O.field)),...r&&(T===ce||T===fe)&&t.get(T)?.fields.some(O=>O.name===we)?[we]:[]].map(ye).join(", "),E=(T,O,D)=>{let S=`${T.objectApiName}.${T.field}>${O}`;m.has(S)||m.set(S,{objectApiName:T.objectApiName,fieldApiName:T.field,target:O,reason:D,...T.required?{required:!0}:{}})},A=new Map,j=(T,O,D)=>{let S=z(T);for(let ne of O)for(let N of S){let _=ne[N.field];if(typeof _!="string"||_==="")continue;let V=Er(_,N.targets,n.keyPrefixes,r!==void 0&&N.polymorphic);if(!V)continue;if(o.has(V)){r&&D>0&&v.push({objectApiName:T,field:N.field,required:N.required,target:V,id:_});continue}let B={objectApiName:T,field:N.field,required:N.required};if(D>=n.maxDepth&&!N.required){s.has(V)||E(B,V,"depth");continue}if(w.get(V)?.has(_))continue;let Z=A.get(V)??{ids:new Set,required:!1,via:[]};Z.ids.add(_),Z.required||=N.required,Z.via.some(Y=>Y.objectApiName===T&&Y.field===N.field)||Z.via.push(B),A.set(V,Z)}},M=[];for(let T of o){if(r){j(T,r.get(T)??[],0);continue}let O=z(T).filter(D=>D.targets.some(S=>!o.has(S)));if(O.length===0){M.push(T);continue}n.say(`reading the lookups of ${T}\u2026`);try{let D=["Id",...new Set(O.map(N=>N.field))].map(ye).join(", "),{records:S,truncated:ne}=await this.readAll(e,`SELECT ${D} FROM ${ye(T)} ORDER BY Id`,a);if(R.set(T,S.length),ne){let N=(await this.countRecords(e,[T])).get(T);g.push({objectApiName:T,copied:S.length,...N!==void 0?{total:N}:{}});let _=S[S.length-1]?.Id;typeof _=="string"&&y.set(T,_)}j(T,S,0)}catch(D){ae.warn("Autopilot could not read the lookups of a selected object",{objectApiName:T,error:ee(D)}),M.push(T)}}for(let[T,O]of await this.countRecords(e,M))O>a?(R.set(T,a),g.push({objectApiName:T,copied:a,total:O})):R.set(T,O);let te=n.maxDepth+Tr;for(let T=1;A.size>0&&T<=te;T++){let O=A;A=new Map;let D=[];for(let[S,ne]of O){if(s.has(S))continue;let N=n.isStandard(S)&&!n.includeStandardObjects,_=N&&!ne.required&&vr.has(S),V;if(N&&!ne.required&&!_?V="standard":s.size>=c&&(ne.required&&c<d?c++:V="objects"),V){for(let B of ne.via)E(B,S,V);O.delete(S);continue}if(s.add(S),D.push(S),_)p.push({objectApiName:S,referencedBy:ne.via.map(B=>`${B.objectApiName}.${B.field}`)});else if(N){let B=ne.via[0];u.push({objectApiName:S,neededBy:`${B.objectApiName}.${B.field}`})}}if(D.length>0){let S=D.filter(N=>!t.has(N));S.length>0&&n.say(`describing ${S.length} parent object(s) at depth ${T}\u2026`);let ne=await this.describeAll(e,S);for(let N of D){let _=t.get(N)??ne.get(N);_?(t.set(N,_),f.push(N)):(s.delete(N),i.add(N),O.delete(N))}}for(let[S,ne]of O){let N=[...ne.ids].filter(Y=>!w.get(S)?.has(Y));if(N.length===0)continue;n.say(`reading ${N.length} ${S} record(s) by id\u2026`);let _=w.get(S)??new Set;w.set(S,_);let V=S===Oe,B=V?Or(K(S),t.get(S)):K(S),Z=[];for(let Y of this.chunk(N,ke)){let me=Y.map(x=>`'${ge(x)}'`).join(", "),b=(await e.query(`SELECT ${B} FROM ${ye(S)} WHERE Id IN (${me})`)).records.filter(x=>typeof x.Id=="string");for(let x of b)_.add(x.Id);Z.push(...b);let k=b.filter(x=>x[we]===!0).length;r&&k>0&&C.set(S,(C.get(S)??0)+k),j(S,b,T)}if(V){let Y=await this.standardPricesOf(e,B,Z,_);if(Y.length>0){n.say(`reading ${Y.length} standard price(s) the prices need\u2026`);for(let me of Y)_.add(me.Id);j(S,Y.map(me=>({...me,[_e]:void 0})),T)}}}}let se=new Map;for(let T of f){let O=[...w.get(T)??[]];se.set(T,O),R.set(T,O.length)}return{added:f,leftEmpty:[...m.values()].filter(T=>!s.has(T.target)),standardNeeded:u,followedByDefault:p.filter(T=>s.has(T.objectApiName)),cutShort:g,cutAt:y,recordCounts:R,parentIds:se,personAccounts:C,namingSelected:v}}async standardPricesOf(e,t,o,n){let r=s=>[s[qe],s[he],s[Ee]].map(i=>String(i??"")).join("|");try{let[s]=(await e.query(ve)).records,i=s?.Id;if(typeof i!="string")return[];let a=o.filter(u=>u[_e]!==i),c=[...new Set(a.flatMap(u=>{let p=u[qe];return typeof p=="string"&&p!==""?[p]:[]}))];if(c.length===0)return[];let d=new Set(a.map(r)),m=[];for(let u of this.chunk(c,ke)){let p=u.map(y=>`'${ge(y)}'`).join(", "),g=await e.query(`SELECT ${t} FROM ${Oe} WHERE ${_e} = '${ge(i)}' AND ${qe} IN (${p})`);for(let y of g.records){let f=y.Id;typeof f!="string"||n.has(f)||!d.has(r(y))||m.push(y)}}return m}catch(s){return ae.warn("Autopilot could not read the standard prices its prices need",{error:ee(s)}),[]}}async readAll(e,t,o=5e4){let{queryMore:n}=e;if(!n){let s=await e.query(t);return{records:s.records,truncated:s.done===!1}}let r=await He({query:s=>e.query(s),queryMore:s=>n.call(e,s)},t,o);return r.truncated&&ae.warn("Autopilot read the lookups of a selected object to its bound only",{records:r.records.length}),{records:r.records,truncated:r.truncated}}async toolingObjects(e){if(!e.tooling)return[];try{return(await e.tooling.describeGlobal()).sobjects.map(o=>o.name)}catch(t){return ae.warn("Autopilot could not ask the Tooling API which objects are metadata",{error:ee(t)}),[]}}async describeAll(e,t){let o=new Map,n=this.chunk(t,this.maxConcurrent);for(let r of n){let s=await Promise.allSettled(r.map(i=>e.describe(i)));for(let i of s)i.status==="fulfilled"&&o.set(i.value.name,i.value)}return o}async countRecords(e,t){let o=new Map,n=this.chunk(t,this.maxConcurrent);for(let r of n){let s=await Promise.allSettled(r.map(async i=>{let a=await e.query(`SELECT COUNT() FROM ${ye(i)}`);return{name:i,count:a.totalSize}}));for(let i of s)i.status==="fulfilled"&&o.set(i.value.name,i.value.count)}return o}chunk(e,t){let o=[];for(let n=0;n<e.length;n+=t)o.push(e.slice(n,n+t));return o}};function Gt(l,e){return l!==void 0&&Number.isInteger(l)&&l>0?l:e}function tt(l,e){return e.fields.filter(t=>t.referenceTo.length>0&&Jt(t)).map(t=>({field:t.name,targets:[...t.referenceTo],required:Xt(l,t.name,t.nillable),polymorphic:t.referenceTo.length>1}))}function Er(l,e,t,o=!1){if(e.length===1&&!o)return e[0];let n=t.get(l.slice(0,3));return n!==void 0&&e.includes(n)?n:void 0}var sr=3,Pr="the source changed since the plan: plan again";function dr(l,e){return{holds:[...l.links.filter(t=>t.kind==="holds"),...l.requiredOfParents,...l.outward.filter(t=>t.required)],kept:e}}function ir(l,e){return typeof l!="string"||l===""?!1:e===void 0||e!==null&&l.startsWith(e)}function lr(l,e,t){let o=new Map(t.map((s,i)=>[s,i])),n=new Set(e),r={links:[],outward:[],requiredOfParents:[]};for(let[s,i]of l)for(let a of tt(s,i))for(let c of a.targets.filter(d=>l.has(d))){let d=a.polymorphic?{prefix:l.get(c)?.keyPrefix??null}:{},m={objectApiName:s,field:a.field,parent:c,...d};if(!n.has(s))n.has(c)&&a.required&&r.requiredOfParents.push({...m,kind:"holds"});else if(!n.has(c))r.outward.push({...m,required:a.required});else if(a.required)r.links.push({...m,kind:"holds"});else if(c===s)r.links.push({...m,kind:"selfReference"});else{let u=(o.get(c)??0)<(o.get(s)??0);r.links.push({...m,kind:u?"holds":"owed"})}}return r}function ur(l,e){let t=new Set(l),o=new Set(e.links.filter(n=>n.kind!=="holds").map(n=>n.objectApiName));return(n,r)=>t.has(n)&&(r==="insert"||r==="update"&&(o.has(n)||Ce[n]!==void 0))}function pr(l,e,t){return typeof l.unread=="string"?{perRecord:[],notCounted:[],unread:l.unread}:Ro(ze(l,e,t),t)}function Cr(l){let e=new Map(l.order.map((t,o)=>[t,o]));return l.order.map(t=>{let o=l.rows.get(t)??[],n=l.lookups.links.filter(i=>i.objectApiName===t),r=l.lookups.outward.filter(i=>i.objectApiName===t),s={name:t,rows:o,at:new Map(o.map((i,a)=>[i.Id,a])),heldBefore:[],heldAfter:[],loose:[],named:[],roots:[],followers:[],persons:new Set(t===ce||t===fe?o.flatMap((i,a)=>i[we]===!0?[a]:[]):[])};return o.forEach((i,a)=>{let c=[],d=[],m=[];for(let u of n){let p=i[u.field];if(!ir(p,u.prefix))continue;let g={link:u,id:p};u.kind!=="holds"?m.push(g):(e.get(u.parent)??0)<(e.get(t)??0)?c.push(g):d.push(g)}s.heldBefore.push(c),s.heldAfter.push(d),s.loose.push(m),s.named.push(r.flatMap(u=>{let p=i[u.field];return ir(p,u.prefix)?[{parent:u.parent,id:p}]:[]})),(c.length>0?s.followers:s.roots).push(a)}),s})}function ar(l,e){let t=new Map(l.map(r=>[r.name,r])),o=new Map,n=[...e].flatMap(([r,s])=>[...s].map(i=>({name:r,id:i})));for(let r=n.pop();r;r=n.pop()){let s=t.get(r.name),i=s?.at.get(r.id);if(!s||i===void 0)continue;let a=o.get(r.name)??new Set;if(o.set(r.name,a),!a.has(i)){a.add(i);for(let c of[...s.heldBefore[i],...s.heldAfter[i]])n.push({name:c.link.parent,id:c.id})}}return o}function cr(l){return`${l} record${l===1?"":"s"}`}function Mr(l,e){return[...l.parentIds].every(([t,o])=>{let n=new Set(e.get(t)?.ids??[]);return o.every(r=>n.has(r))})}async function fr(l){let{budget:e,room:t,mode:o,parents:n,maxRecords:r}=l,s=Cr(l),i=b=>{let k=o.caps?.[b]??o.all;return k===void 0?void 0:Math.max(1,Math.floor(k))},a=s.some(b=>b.heldAfter.some(k=>k.length>0)),c=new Map;for(let b of s){if(b.name!==Ae)continue;let k=b.rows.filter(x=>x[Ze]===!0);k.length>0&&c.set(b.name,new Set(k.map(x=>x.Id)))}let d=ar(s,c),m=b=>{let k={kept:new Map,ids:new Map,cut:new Map},x=new Set;for(let $ of s){let L=d.get($.name)??x,X=i($.name),F=$.roots.filter(J=>!L.has(J)),G=F.length===0?0:Math.max(1,Math.round(b*Math.min(F.length,X??1/0))),W=It(F.length,G).map(J=>F[J]),q=new Map;for(let J of $.followers){if(L.has(J))continue;let be=$.heldBefore[J].find(Se=>!k.ids.get(Se.link.parent)?.has(Se.id));be?q.set(J,be.link):W.push(J)}W.sort((J,be)=>J-be);let ie=$.name===fe?W.filter(J=>$.persons.has(J)):[],U=ie.length>0?W.filter(J=>!$.persons.has(J)):W,re=X===void 0?U.length:Math.max(0,X-L.size-ie.length),le=U.length>re?It(U.length,re).map(J=>U[J]):U,ue=new Set([...L,...ie,...le]);k.kept.set($.name,ue),k.ids.set($.name,new Set([...ue].map(J=>$.rows[J].Id))),k.cut.set($.name,q)}if(!a)return k;for(let $=!0;$;){$=!1;for(let L of s){let X=d.get(L.name)??x,F=k.kept.get(L.name)??new Set;for(let G of[...F]){if(X.has(G))continue;let W=[...L.heldAfter[G],...L.heldBefore[G]].find(q=>!k.ids.get(q.link.parent)?.has(q.id));W&&(F.delete(G),k.ids.get(L.name)?.delete(L.rows[G].Id),k.cut.get(L.name)?.set(G,W.link),$=!0)}}}return k},u=b=>{let k=new Map;for(let x of s){let $=0;for(let L of b.kept.get(x.name)??[])x.loose[L].some(F=>b.ids.get(F.link.parent)?.has(F.id))&&$++;$>0&&k.set(x.name,$)}return k},p=(b,k)=>{let x=new Map,$=0;for(let F of s){let G=b.kept.get(F.name)??new Set,W=0;for(let q of G)F.persons.has(q)&&W++;x.set(F.name,G.size),$+=Et(F.name,{rows:G.size,personAccounts:W})}for(let[F,{records:G,personAccounts:W}]of k)x.set(F,(x.get(F)??0)+G),$+=Et(F,{rows:G,...W!==void 0?{personAccounts:W}:{}});let L=u(b),X=So(t,(F,G)=>{let W=x.get(F)??0;return G==="insert"||Ce[F]!==void 0?W:L.get(F)??0});return{records:[...x.values()].reduce((F,G)=>F+G,0),bytes:$,roomBytes:X,requests:uo([...x.values()].map(F=>({rows:F})))}},g=new Map;for(let b of s)for(let k of b.named)for(let{parent:x,id:$}of k){let L=g.get(x)??new Set;g.set(x,L),L.add($)}let y=[...g.values()].reduce((b,k)=>b+k.size,0),f=b=>{let k=new Map,x=0;for(let X of s)for(let F of b.kept.get(X.name)??[])for(let{parent:G,id:W}of X.named[F]){let q=k.get(G)??new Set;k.set(G,q),q.has(W)||x++,q.add(W)}let $=y>0?x/y:0,L=new Map;for(let[X,{ids:F,personAccounts:G}]of n){let W=Math.max(0,F.length-(g.get(X)?.size??0)),q=Math.min(F.length,(k.get(X)?.size??0)+Math.ceil(W*$));q!==0&&L.set(X,{records:q,...G!==void 0?{personAccounts:Math.ceil(G*q/F.length)}:{}})}return L},R=b=>new Map(b.added.map(k=>{let x=b.personAccounts.get(k);return[k,{records:b.parentIds.get(k)?.length??0,...x!==void 0?{personAccounts:x}:{}}]})),w=b=>b.bytes+b.roomBytes<=e.bytes,C=b=>e.runRequests===void 0||b.requests<=e.runRequests,v=b=>r===void 0||b.records<=r,z=b=>w(b)&&C(b)&&v(b),K=b=>w(b)?C(b)?"maxTotal":"apiRequests":e.terms.limitedBy,E=b=>w(b)?C(b)?{bound:"maxTotal",records:b.records,allowed:r??0}:{bound:"apiRequests",requests:b.requests,allowed:e.runRequests??0}:{bound:"storage",takesMB:(b.bytes+b.roomBytes)/1048576,fitsMB:e.bytes/1048576},A=b=>{if(!w(b)){let k=wo((b.bytes+b.roomBytes)/1048576,e.bytes/1048576);return`${k.over} MB`+(b.roomBytes>0?", room for what the org's automation creates under them included":"")+`, past the ${k.bound} MB that fit`}return C(b)?`${cr(b.records)}, past the ${r??0} the run may write`:`about ${b.requests} API requests, past the ${e.runRequests??0} that leave the org a tenth of its daily requests`},j=b=>new Map(s.map(k=>[k.name,[...b.kept.get(k.name)??[]].sort((x,$)=>x-$).map(x=>k.rows[x])])),M=(b,k,x,$,L,X)=>{let F=s.map(q=>{let ie=k.cut.get(q.name)??new Map,U=new Map;for(let le of ie.values()){let ue=`${le.field}
|
|
8
8
|
${le.parent}`,J=U.get(ue)??{field:le.field,parent:le.parent,count:0};U.set(ue,{...J,count:J.count+1})}let re=k.kept.get(q.name)?.size??0;return{objectApiName:q.name,inSource:q.rows.length,kept:re,cutSpread:q.rows.length-re-ie.size,cutWithParent:[...U.values()].sort((le,ue)=>ue.count-le.count)}}),G=new Map,W=(q,ie,U)=>{let re=`${q}
|
|
9
9
|
${ie}
|
|
10
|
-
${U}`,le=(G.get(re)?.count??0)+1;G.set(re,{objectApiName:q,field:ie,count:le,why:U})};for(let q of s)for(let ie of k.kept.get(q.name)??[])for(let U of q.loose[ie])k.ids.get(U.link.parent)?.has(U.id)||W(q.name,U.link.field,U.link.kind==="owed"?"owed":"selfReference");for(let q of L?.namingSelected??[])q.required||k.ids.get(q.target)?.has(q.id)||W(q.objectApiName,q.field,"onParent");return{heldBy:$,...X?{cannotFit:X.words}:{},kept:j(k),...L?{walk:L}:{},report:{mode:o,heldBy:$,...X?{cannotFit:X.said}:{},budget:{...ko(e,x.roomBytes,t),...$==="apiRequests"?{limitedBy:"apiRequests"}:{}},...b!==void 0?{share:b}:{},objects:F,emptied:[...G.values()],parents:L?L.added.map(q=>({objectApiName:q,records:L.parentIds.get(q)?.length??0})):[...n].map(([q,{ids:ie}])=>({objectApiName:q,records:ie.length})),records:x.records,estimateMB:x.bytes/1048576}}},te={words:Pr,said:{why:"sourceChanged"}},se=b=>({words:`with these caps the plan takes ${A(b)}: lower them, or fit by share`,said:{why:"caps",over:E(b)}}),T=Object.keys(o.caps??{}).find(b=>!s.some(k=>k.name===b)),O=s.reduce((b,k)=>Math.max(b,Math.min(k.roots.length,i(k.name)??1/0)),0),D=m(1),S=p(D,f(D));if(T!==void 0)return M(void 0,D,S,"caps",void 0,{words:`the plan selects no ${T}: a cap holds an object it selects`,said:{why:"capNotSelected",object:T}});if(s.some(b=>b.rows.length>(l.planned.get(b.name)??0)))return M(void 0,D,S,e.terms.limitedBy,void 0,te);let ne=o.all!==void 0||Object.keys(o.caps??{}).length>0,N=o.share===!0||!ne,_=b=>{let k=m(b/O);return p(k,f(k))};if(s.every(b=>D.kept.get(b.name)?.size===b.rows.length)&&z(S))return M(N?1:void 0,D,S,"whole",void 0);if(O===0)return M(void 0,D,S,e.terms.limitedBy,void 0,te);let B=O;if(!z(S)){if(!N)return M(void 0,D,S,K(S),void 0,se(S));if(B=Ro(O,b=>z(_(b))),B===0){let b=m(1/O),k=p(b,f(b));return M(1/O,b,k,K(k),void 0,{words:`the least it can be cut to \u2014 one record of each object with none to follow, and what follows them, ${cr(k.records)} \u2014 takes ${A(k)}`,said:{why:"least",over:E(k)}})}}let Z=B<O?K(_(B+1)):ne?"caps":e.terms.limitedBy,Y=b=>N?b/O:void 0;if(n.size===0){let b=m(B/O);return M(Y(B),b,p(b,new Map),Z,void 0)}for(let b=1;b<=sr;b++){let k=m(B/O),x=await l.walk(j(k));if(!Mr(x,n)){let F=p(k,R(x));return M(Y(B),k,F,Z,void 0,te)}let $=x.namingSelected.filter(F=>F.required&&s.find(G=>G.name===F.target)?.at.has(F.id)===!0&&!k.ids.get(F.target)?.has(F.id));if($.length>0){for(let{target:F,id:G}of $){let W=c.get(F)??new Set;c.set(F,W),W.add(G)}d=ar(s,c);continue}let L=p(k,R(x));if(z(L))return M(Y(B),k,L,Z,x);if(Z=K(L),!N)return M(void 0,k,L,Z,x,se(L));if(B===1)return M(Y(B),k,L,Z,x,{words:"the least it can be cut to, with the parents its records name, takes "+A(L),said:{why:"least",over:E(L)}});let X=Math.max((L.bytes+L.roomBytes)/Math.max(1,e.bytes),e.runRequests!==void 0?L.requests/Math.max(1,e.runRequests):0,r!==void 0?L.records/Math.max(1,r):0);B=Math.max(1,Math.min(B-1,Math.floor(B/X)))}let me=m(B/O),Be=p(me,f(me));return M(Y(B),me,Be,Z,void 0,{words:`could not fit in ${sr} rounds: fit by caps`,said:{why:"rounds"}})}function mr(l,e,t){let{selected:o}=l.scope,n=e.walk?.added??[],r=new Set([...o,...n]),s=new Map(e.walk?.parentIds??[]),i=new Map,a=new Map;for(let f of o){let R=e.kept.get(f)??[];s.set(f,R.map(w=>w.Id)),i.set(f,R.length),l.personAccounts.has(f)&&a.set(f,R.filter(w=>w[we]===!0).length)}for(let f of n)i.set(f,e.walk?.parentIds.get(f)?.length??0),l.personAccounts.has(f)&&a.set(f,e.walk?.personAccounts.get(f)??0);let c=new Map([...l.scope.leftEmpty,...e.walk?.leftEmpty??[]].filter(f=>r.has(f.objectApiName)&&!r.has(f.target)).map(f=>[`${f.objectApiName}.${f.fieldApiName}>${f.target}`,f])),{maxDepth:d,maxObjects:m,followedByDefault:u,currencies:p}=l.scope,g=u?.filter(f=>r.has(f.objectApiName)),y=p?.objects.filter(f=>r.has(f));return{...l,objectDescribes:new Map([...l.objectDescribes].filter(([f])=>r.has(f))),autoDiscoveredObjects:n,missingInTarget:l.missingInTarget.filter(f=>r.has(f)),recordCounts:i,totalObjectsScanned:r.size,parentIds:s,personAccounts:a,scope:{maxDepth:d,maxObjects:m,selected:o,parents:n.map(f=>({objectApiName:f,records:i.get(f)??0})),leftEmpty:[...c.values()],standardNeeded:l.scope.standardNeeded.filter(f=>r.has(f.objectApiName)),...g!==void 0&&g.length>0?{followedByDefault:g}:{},...p&&y!==void 0&&y.length>0?{currencies:{...p,objects:y}}:{},fitted:t}}}var nt=class{deps;eventListeners=[];runningExecutors=[];pendingSkips=new Set;constructor(e){this.deps=e}onEvent(e){return this.eventListeners.push(e),()=>{this.eventListeners=this.eventListeners.filter(t=>t!==e)}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch{}}listObjects(e,t,o){return this.deps.schemaScanner.listObjects(e,t,o)}countObjects(e,t){return this.deps.schemaScanner.countObjects(e,t)}async scanSchemas(e,t,o,n){this.emitEvent({type:"scan-started",timestamp:new Date().toISOString()});let r=await this.deps.schemaScanner.scan(e,t,o.selectedObjects,o.includeStandardObjects,{...o.maxDepth!==void 0?{maxDepth:o.maxDepth}:{},...o.maxObjects!==void 0?{maxObjects:o.maxObjects}:{},...o.maxRecordsPerObject!==void 0&&o.maxRecordsPerObject>0?{maxRecordsPerObject:o.maxRecordsPerObject}:{},...n?{onProgress:n}:{}});return this.emitEvent({type:"scan-completed",timestamp:new Date().toISOString()}),r}buildGraph(e,t){let o=new Map;for(let[n,r]of e.objectDescribes){let s=r.fields.map(i=>({name:i.name,type:i.type,nillable:i.nillable,referenceTo:i.referenceTo,relationshipName:i.relationshipName}));o.set(n,{name:r.name,fields:s})}return this.deps.graphBuilder.build(o,e.recordCounts,t)}buildCompliance(e,t,o=[]){let n=this.deps.complianceEngine.buildProfile(e,Eo(o,t)),r=this.deps.complianceEngine.generateRules(n);return{profile:n,rules:r}}generatePlan(e,t,o,n){let r=Po(t,e.nodes.map(c=>c.objectApiName),o),s={...this.deps.complianceEngine.buildSummary(o),...r.length>0?{notCovered:r}:{}},i=this.deps.planGenerator.generate(e,t,s),a=n?{...i,scope:n}:i;return this.emitEvent({type:"plan-generated",timestamp:new Date().toISOString()}),a}async fitPlan(e,t){let{scan:o,graph:n,plan:r,rules:s,mode:i,budget:a,maxRecords:c,onProgress:d}=t,{schemaScanner:m}=this.deps,u=0,p={describe:O=>e.describe(O),describeGlobal:()=>e.describeGlobal(),query:O=>(u++,e.query(O)),...e.queryMore?{queryMore:O=>(u++,e.queryMore.call(e,O))}:{}},g=r.waves.map(O=>O.objects),y=new Map,f=g.flatMap(O=>Ue(O,n.edges).groups.filter(D=>D.length>1));for(let O of new Set(f.flat()))y.set(O,await t.describeLookups?.(O).catch(()=>null)??null);let R=fn(g,n.edges,O=>y.get(O)),{selected:w}=o.scope,C=lr(o.objectDescribes,w,R),v=ur(R,C),z=pr(t.automation,t.mutePlan,v),K=await m.readFitRows(p,o,d),E=await fr({order:R.filter(O=>w.includes(O)),rows:K,planned:o.recordCounts,lookups:C,parents:new Map(o.scope.parents.map(({objectApiName:O})=>{let D=o.personAccounts.get(O);return[O,{ids:o.parentIds.get(O)??[],...D!==void 0?{personAccounts:D}:{}}]})),budget:a,room:z,mode:i,...c!==void 0?{maxRecords:c}:{},walk:O=>m.walkFrom(p,o,O,d)}),A=z.unread!==void 0?{automationUnread:z.unread}:{},j={...E.report,requestsRead:u,...A,...t.mutePlan?{countedMuted:!0}:{},...c!==void 0?{maxTotal:c}:{}},M=new Map([...E.kept].map(([O,D])=>[O,D.map(S=>S.Id)])),te={heldBy:E.heldBy,report:j,keptIds:M,...A};if(E.cannotFit!==void 0)return{...te,cannotFit:E.cannotFit};if(E.heldBy==="whole")return te;let se=mr(o,E,j),T=this.buildGraph(se,t.batchSize);return{...te,fitted:{scan:se,graph:T,plan:this.generatePlan(T,r.complianceFramework,s,se.scope),run:dr(C,se.parentIds)}}}async executePlan(e,t,o,n,r,s,i,a){let c=Array.from(n.values()).reduce((R,w)=>R+w,0),d=this.isGrappeActive(c),m=`autopilot-${Date.now()}`;d&&this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:m,totalPartitions:e.waves.length,totalRecords:c}}),this.emitEvent({type:"execution-started",timestamp:new Date().toISOString()});let u=this.deps.createExecutor(),p=()=>{},g=r?u.on("node-completed",r):p,y=r?u.on("node-failed",r):p;for(let R of this.pendingSkips)u.skip(R);this.pendingSkips.clear(),this.runningExecutors.push(u);let f;try{f=await u.execute(e,t.edges,o,n,s,i,a)}finally{this.runningExecutors.splice(this.runningExecutors.indexOf(u),1),g(),y()}return this.emitEvent({type:"execution-completed",timestamp:new Date().toISOString()}),d&&this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:m,totalProcessed:f.totalSuccess+f.totalSkipped,totalFailed:f.totalFailure}}),f}isGrappeActive(e){let t=this.deps.grappeConfig;return!!(t?.enabled&&this.deps.grappeAdapter&&e>=t.autoActivateThreshold)}generateReport(e,t,o,n,r,s){return this.deps.complianceEngine.generateReport(e,t,o,n,r,s)}latestRunningExecutor(){return this.runningExecutors[this.runningExecutors.length-1]}pause(){this.latestRunningExecutor()?.pause()}resume(){this.latestRunningExecutor()?.resume()}skip(e){let t=this.latestRunningExecutor();if(t){t.skip(e);return}this.pendingSkips.add(e)}};var ot=class{build(e,t,o=200){let n=this.extractEdges(e),r=Ir(n,new Set(e.keys())),s=this.tarjanSCC(Array.from(e.keys()),r),i=this.resolveCycles(s,r),{order:a,levels:c}=this.topologicalSort(Array.from(e.keys()),r,s),d=this.buildNodes(e,t,a,c,o),m=this.computeStats(d,n,i);return{nodes:d,edges:n,cycles:i,stats:m}}extractEdges(e){let t=[],o=new Set(e.keys());for(let[n,r]of e)for(let s of r.fields){if(s.type!=="reference"||s.referenceTo.length===0)continue;let i=s.referenceTo.filter(d=>o.has(d));if(i.length===0)continue;if(i.length>1){for(let d of i)t.push({from:d,to:n,fieldApiName:s.name,relationshipType:"polymorphic",required:!s.nillable});continue}let a=i[0],c;a===n?c="hierarchical":s.nillable?c="lookup":c="master_detail",t.push({from:a,to:n,fieldApiName:s.name,relationshipType:c,required:!s.nillable})}return t}tarjanSCC(e,t){let o=new Map;for(let s of e)o.set(s,[]);for(let s of t){let i=o.get(s.to);i&&i.push(s.from)}let n={index:0,stack:[],onStack:new Set,indices:new Map,lowLinks:new Map,sccs:[]},r=[...e].sort();for(let s of r)n.indices.has(s)||this.tarjanStrongConnect(s,o,n);return n.sccs}tarjanStrongConnect(e,t,o){o.indices.set(e,o.index),o.lowLinks.set(e,o.index),o.index++,o.stack.push(e),o.onStack.add(e);let n=t.get(e)??[];for(let r of n)if(o.indices.has(r)){if(o.onStack.has(r)){let s=o.lowLinks.get(e)??0,i=o.indices.get(r)??0;o.lowLinks.set(e,Math.min(s,i))}}else{this.tarjanStrongConnect(r,t,o);let s=o.lowLinks.get(e)??0,i=o.lowLinks.get(r)??0;o.lowLinks.set(e,Math.min(s,i))}if(o.lowLinks.get(e)===o.indices.get(e)){let r=[],s;do s=o.stack.pop(),o.onStack.delete(s),r.push(s);while(s!==e);o.sccs.push(r.sort())}}resolveCycles(e,t){let o=[],n=new Set;for(let r of t)r.from===r.to&&r.relationshipType==="hierarchical"&&n.add(r.from);for(let r of n)o.push({objects:[r],strategy:"two_pass",description:`Insert ${r} without self-lookup, update in 2nd pass`});for(let r of e){if(r.length<=1)continue;let s=new Set(r),i=t.filter(d=>s.has(d.from)&&s.has(d.to)&&d.from!==d.to),a,c;r.length===2&&i.some(m=>!m.required)?(a="nullable_lookup",c=`Insert ${r[0]} without ${r[1]} lookup, insert ${r[1]} with ${r[0]} lookup, update ${r[0]}`):(a="upsert_external_id",c="Decompose cycle into waves with upsert + external ID"),o.push({objects:[...r],strategy:a,description:c})}return o}topologicalSort(e,t,o){let n=new Map;for(let p=0;p<o.length;p++)for(let g of o[p])n.set(g,p);let r=o.length,s=new Map;for(let p=0;p<r;p++)s.set(p,new Set);for(let p of t){let g=n.get(p.from),y=n.get(p.to);g!==void 0&&y!==void 0&&g!==y&&s.get(y).add(g)}let i=new Map;for(let[p,g]of s)i.set(p,new Set(g));let a=[],c=new Map;for(;i.size>0;){let p=[];for(let[g,y]of i)y.size===0&&p.push(g);if(p.length===0){for(let g of i.keys())a.push(g),c.has(g)||c.set(g,0);break}p.sort((g,y)=>g-y);for(let g of p){a.push(g);let y=s.get(g)??new Set,f=-1;for(let R of y)f=Math.max(f,c.get(R)??0);c.set(g,y.size===0?0:f+1),i.delete(g);for(let R of i.values())R.delete(g)}}let d=new Map,m=new Map,u=0;for(let p of a){let g=o[p],y=c.get(p)??0,f=[...g].sort();for(let R of f)d.set(R,u),m.set(R,y),u++}for(let p of e)d.has(p)||(d.set(p,u),m.set(p,0),u++);return{order:d,levels:m}}buildNodes(e,t,o,n,r){let s=[];for(let i of e.keys()){let a=t.get(i)??0;s.push({objectApiName:i,recordCount:a,estimatedApiCalls:a===0?0:Math.ceil(a/r),piiFields:[],anonymizationRules:[],status:"pending",progress:0,insertOrder:o.get(i)??0,level:n.get(i)??0,successCount:0,failureCount:0,errors:[],elapsedMs:0,apiCallsUsed:0})}return s.sort((i,a)=>i.insertOrder-a.insertOrder),s}computeStats(e,t,o){return{totalObjects:e.length,totalRelationships:t.length,cycleCount:o.length,maxDepth:Math.max(0,...e.map(n=>n.level)),totalRecords:e.reduce((n,r)=>n+r.recordCount,0),totalEstimatedApiCalls:e.reduce((n,r)=>n+r.estimatedApiCalls,0)}}};function Ir(l,e){let t=wn(e);return t.length===0?[...l]:[...l.filter(o=>!(o.to===oe&&o.fieldApiName==="ActivityId")),...t.map(o=>({from:o.sourceObject,to:o.targetObject,fieldApiName:o.relationshipName,relationshipType:"lookup",required:!0}))]}import{createHash as xr,randomUUID as Fr}from"node:crypto";var jr=["fake","mask","hash","nullify","redact","shuffle","truncate","preserve_format","age_band","generalize"],rt=class{builtInRules;constructor(){this.builtInRules=new Map,this.builtInRules.set("gdpr",this.buildGDPRRules()),this.builtInRules.set("ccpa",this.buildCCPARules()),this.builtInRules.set("hipaa",this.buildHIPAARules()),this.builtInRules.set("pci_dss",this.buildPCIDSSRules())}buildProfile(e,t,o=[]){let n=this.builtInRules.get(e)??[];return{framework:e,rules:n,autoDetectedPII:t,userOverrides:o,auditRequired:e!=="none"&&e!=="custom"}}generateRules(e){if(e.framework==="none")return[];let t=new Map;for(let n of e.userOverrides){let r=`${n.objectApiName}.${n.fieldApiName}`;t.set(r,n)}let o=[];for(let n of e.autoDetectedPII){let r=`${n.objectApiName}.${n.fieldApiName}`,s=t.get(r);if(s){if(s.method==="skip")continue;o.push({objectApiName:n.objectApiName,fieldApiName:n.fieldApiName,method:s.method,piiCategory:n.piiCategory,aiConfidence:n.confidence,userOverridden:!0,fieldType:n.fieldType});continue}let i=this.findMatchingRule(e.rules,n.piiCategory),a=i&&i.requiredMethod!=="any"?i.requiredMethod:n.suggestedMethod;o.push({objectApiName:n.objectApiName,fieldApiName:n.fieldApiName,method:a,piiCategory:n.piiCategory,aiConfidence:n.confidence,userOverridden:!1,fieldType:n.fieldType})}return o}buildSummary(e){let t={};for(let n of jr)t[n]=0;for(let n of e)t[n.method]++;let o=[...new Set(e.map(n=>n.objectApiName))];return{totalPiiFields:e.length,totalFieldsToAnonymize:e.length,methodBreakdown:t,objectsWithPii:o}}generateReport(e,t,o,n,r,s){let i=new Set(e.userOverrides.map(y=>`${y.objectApiName}.${y.fieldApiName}`)),a=t.map(y=>{let f=this.findMatchingRule(e.rules,y.piiCategory),R=f?f.id:"custom",w=o.get(y.objectApiName)??0,C=`${y.objectApiName}.${y.fieldApiName}`;return{objectApiName:y.objectApiName,fieldApiName:y.fieldApiName,piiCategory:y.piiCategory,anonymizationMethod:y.method,recordsAnonymized:w,ruleApplied:R,userOverridden:i.has(C)||y.userOverridden}}),c=this.buildObjectSummaries(t,o,e),d=this.computeOverallStatus(c),m=new Date().toISOString(),u=Fr(),p=JSON.stringify(a),g=xr("sha256").update(p).digest("hex");return{id:u,framework:e.framework,generatedAt:m,sourceOrgId:n,targetOrgId:r,totalFieldsScanned:s,piiFieldsDetected:e.autoDetectedPII.length,piiFieldsAnonymized:t.length,entries:a,objectSummaries:c,overallStatus:d,checksumSha256:g}}findMatchingRule(e,t){return e.find(o=>o.targetPiiCategories.includes(t))}buildObjectSummaries(e,t,o){let n=new Set;for(let s of e)n.add(s.objectApiName);for(let s of o.autoDetectedPII)n.add(s.objectApiName);let r=[];for(let s of n){let i=e.filter(p=>p.objectApiName===s),a=o.autoDetectedPII.filter(p=>p.objectApiName===s),c=[...new Set(i.map(p=>p.method))],d=t.get(s)??0,m=a.length>0&&a.every(p=>i.some(g=>g.fieldApiName===p.fieldApiName)),u=a.length===0||m?"pass":i.length>0?"partial":"fail";r.push({objectApiName:s,recordCount:d,piiFieldCount:a.length,anonymizationMethods:c,status:u})}return r}computeOverallStatus(e){return e.length===0||e.every(n=>n.status==="pass")?"pass":e.every(n=>n.status==="fail")?"fail":"partial"}buildGDPRRules(){return[{id:"gdpr-01",framework:"gdpr",category:"data_minimization",description:"Anonymize personal identifiers (name, email, phone, address)",targetPiiCategories:["PII"],requiredMethod:"fake",articleReference:"GDPR Art. 25"},{id:"gdpr-02",framework:"gdpr",category:"data_protection",description:"Hash sensitive identifiers for pseudonymization",targetPiiCategories:["SENSITIVE"],requiredMethod:"hash",articleReference:"GDPR Art. 32"},{id:"gdpr-03",framework:"gdpr",category:"health_data",description:"Nullify health-related data",targetPiiCategories:["PHI"],requiredMethod:"nullify",articleReference:"GDPR Art. 9"},{id:"gdpr-04",framework:"gdpr",category:"financial_data",description:"Mask payment card data",targetPiiCategories:["PCI"],requiredMethod:"mask",articleReference:"GDPR Art. 32"}]}buildCCPARules(){return[{id:"ccpa-01",framework:"ccpa",category:"personal_info",description:"Anonymize personal information (name, email, phone)",targetPiiCategories:["PII"],requiredMethod:"fake"},{id:"ccpa-02",framework:"ccpa",category:"commercial_info",description:"Mask commercial and financial data",targetPiiCategories:["PCI","SENSITIVE"],requiredMethod:"mask"},{id:"ccpa-03",framework:"ccpa",category:"biometric",description:"Nullify biometric and health data",targetPiiCategories:["PHI"],requiredMethod:"nullify"}]}buildHIPAARules(){return[{id:"hipaa-01",framework:"hipaa",category:"safe_harbor",description:"Anonymize patient identifiers (name, address, phone)",targetPiiCategories:["PII","PHI"],requiredMethod:"fake",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"},{id:"hipaa-02",framework:"hipaa",category:"safe_harbor_dates",description:"Generalize dates to year only",targetPiiCategories:["SENSITIVE"],requiredMethod:"age_band",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"},{id:"hipaa-03",framework:"hipaa",category:"safe_harbor_ids",description:"Hash medical record numbers and SSNs",targetPiiCategories:["PHI"],requiredMethod:"hash",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"}]}buildPCIDSSRules(){return[{id:"pci-01",framework:"pci_dss",category:"card_data",description:"Mask PAN to show only last 4 digits",targetPiiCategories:["PCI"],requiredMethod:"mask",articleReference:"PCI-DSS Requirement 3.3"},{id:"pci-02",framework:"pci_dss",category:"auth_data",description:"Nullify CVV, expiration, and magnetic strip data",targetPiiCategories:["PCI"],requiredMethod:"nullify",articleReference:"PCI-DSS Requirement 3.2"},{id:"pci-03",framework:"pci_dss",category:"cardholder",description:"Anonymize cardholder personal data",targetPiiCategories:["PII"],requiredMethod:"fake",articleReference:"PCI-DSS Requirement 3.4"}]}};var st=class{avgSecondsPerApiCall;batchSize;constructor(e){this.avgSecondsPerApiCall=e?.avgSecondsPerApiCall??.5,this.batchSize=e?.batchSize??200}getBatchSize(){return this.batchSize}generate(e,t,o){let n=this.buildWaves(e),r=e.stats.totalRecords,s=e.stats.totalEstimatedApiCalls,i=this.estimateDuration(n,e);return{waves:n,totalRecords:r,estimatedDurationSec:i,estimatedApiCalls:s,complianceFramework:t,anonymizationSummary:o,cycleResolutions:e.cycles}}buildWaves(e){if(e.nodes.length===0)return[];let t=[...e.nodes].sort((i,a)=>i.insertOrder-a.insertOrder),o=new Map;for(let i of t){let a=o.get(i.level);a?a.push(i.objectApiName):o.set(i.level,[i.objectApiName])}let n=[...o.keys()].sort((i,a)=>i-a),r=new Map;for(let i=0;i<n.length;i++){let a=n[i],c=o.get(a);if(c)for(let d of c)r.set(d,i)}let s=[];for(let i=0;i<n.length;i++){let a=n[i],c=o.get(a)??[],d=new Set;for(let u of c)for(let p of e.edges)if(p.to===u){let g=r.get(p.from);g!==void 0&&g<i&&d.add(g)}let m=[...d].sort((u,p)=>u-p);s.push({order:i,objects:c,dependsOn:m})}return s}estimateDuration(e,t){let o=new Map;for(let s of t.nodes)o.set(s.objectApiName,s.estimatedApiCalls);let n=new Map;t.cycles.forEach((s,i)=>{for(let a of s.objects)n.set(a,i)});let r=0;for(let s of e){let i=new Map;for(let a of s.objects){let c=n.get(a),d=c===void 0?`object:${a}`:`cycle:${c}`;i.set(d,(i.get(d)??0)+(o.get(a)??0))}r+=Math.max(0,...i.values())*this.avgSecondsPerApiCall}return r}};var De=class{idMaps=new Map;registerMappings(e,t){let o=this.idMaps.get(e);o||(o=new Map,this.idMaps.set(e,o));for(let[n,r]of t)o.set(n,r)}remapRecords(e,t,o){let n=t.filter(c=>c.to===o),r=0,s=0,i=0,a=[];for(let[c,d]of e.entries()){let m=new Set,u=new Map;for(let p of n){let g=d[p.fieldApiName];if(g==null||g===""){i++;continue}if(typeof g!="string"){i++;continue}let f=this.idMaps.get(p.from)?.get(g);if(f!==void 0)d[p.fieldApiName]=f,m.add(p.fieldApiName),r++;else{let R=u.get(p.fieldApiName);R?R.parents.push(p.from):u.set(p.fieldApiName,{sourceId:g,parents:[p.from]}),s++}}for(let[p,{sourceId:g,parents:y}]of u)m.has(p)||(d[p]=null,a.push({index:c,fieldApiName:p,sourceId:g,parents:y}))}return{remapped:r,missing:s,skipped:i,unresolved:a}}getTargetId(e,t){return this.idMaps.get(e)?.get(t)}hasObject(e){return this.idMaps.has(e)}getMappingCount(e){return this.idMaps.get(e)?.size??0}get totalMappings(){let e=0;for(let t of this.idMaps.values())e+=t.size;return e}clear(){this.idMaps.clear()}};var Nr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function Ar(l,e,t){let o=en(l);if(e!==void 0&&!Nr.test(e))throw new Error(`Not a record id to read after: "${e}".`);let n=e===void 0?"":` WHERE Id > '${e}'`;return`SELECT FIELDS(ALL) FROM ${o}${n} ORDER BY Id LIMIT ${Math.trunc(t)}`}var Lr={statusCode:Ye,message:"No result returned for the record",fields:[]},Dr={statusCode:Ye,message:"Refused without a reason",fields:[]},hr="PARENT_REFUSED",gr="PARENT_NOT_WRITTEN",Yt="CUT_WITH_PARENT",yr={skipped:l=>`${l} was skipped in this run`,failed:l=>`the run's write of ${l} failed`},$r="PERSON_ACCOUNT_NOT_WRITTEN",Br="PERSON_CONTACT_NOT_LOOKED_UP",_r=`SELECT Id FROM RecordType WHERE SobjectType = '${ce}' AND IsPersonType = true`;function de(l){return l.slice(0,15)}var Re=class{byReason=new Map;add(e){let t=new Set;for(let o of e){let n=`${o.statusCode}\0${o.fields.join(",")}`;if(t.has(n))continue;t.add(n);let r=this.byReason.get(n);this.byReason.set(n,r?{...r,count:r.count+1}:{statusCode:o.statusCode,fields:[...o.fields],count:1,message:o.message})}}addCounted(e){let t=`${e.statusCode}\0${e.fields.join(",")}`,o=this.byReason.get(t);this.byReason.set(t,o?{...o,count:o.count+e.count}:e)}list(){return[...this.byReason.values()].sort((e,t)=>t.count-e.count)}};function qr(l,e){let[t,...o]=l.errors,[n,...r]=l.errorDetails??[];return{...l,...t===void 0?{}:{errors:[Tt(t,e),...o]},...n===void 0?{}:{errorDetails:[{...n,message:Tt(n.message,e)},...r]}}}function wr(){return{written:0,linked:0,failed:0,errors:[],refusals:new Re,apiCallsUsed:0,defaulted:new Map,cutSinceFit:0,heldForRecordType:new Map,sentAgainForALock:{rows:0,written:0,stillLocked:0}}}function zr(l){return{statusCode:qn,fields:["RecordTypeId"],count:l.recordCount,message:Un(l)}}function Gr(l,e){return{objectApiName:l,rows:e.rows,why:{...e.why},...e.predicted?{predicted:e.predicted}:{},...e.readBack?{readBack:e.readBack}:{}}}function br(l){let e=0;for(let[t,o]of l)Ft(t)&&(e+=o);return e}function Ur(l){let e=new Map;for(let t of l.holds)e.set(t.objectApiName,[...e.get(t.objectApiName)??[],t]);return{holds:e,kept:new Map([...l.kept].map(([t,o])=>[t,new Set(o.map(de))])),stayedOut:new Map}}var $e=class extends Co{deps;batchSize;paused=!1;pausePromise=null;pauseResolve=null;skippedObjects=new Set;signal;contactPoints;creatableByObject=new Map;currencies;currencyChanges=new Bn;pricesSettled=new Map;currencyChangesByWrittenId=new Map;keyPrefixByObject=new Map;lifecycleByObject=new Map;standardPricebook;deferredStatuses=[];lookupsByObject=new Map;recordTypeMappings;targetRecordTypes=[];planned=new Set;parentIds=new Map;owedLookups=[];unmappedRecordTypes=new Set;leftToThePlatform=new gn;taskOfEmail=new Map;emailsAfterTheirTask=[];taskTurnOver=!1;emailsHeldAndNotSent=0;leftByStop=new Map;lookupsLeftEmpty=new Map;refusedRecords=new Map;notWritten=new Map;reached=new Set;personTypes;personContactsLinked=0;recordTypesGiven=new Map;recordTypesUnderTheLease=new Map;givenRules=new Map;lease;fit;async creatableFieldsOf(e){if(!this.deps.describeCreateableFields)return null;let t=this.creatableByObject.get(e);if(t!==void 0)return t;try{let o=await this.deps.describeCreateableFields(e),n=o.size>0?o:null;return this.creatableByObject.set(e,n),n}catch{return this.creatableByObject.set(e,null),null}}lookupsOf(e){let t=this.deps.describeLookups;if(!t)return Promise.resolve(null);let o=this.lookupsByObject.get(e);return o||(o=t(e).catch(()=>null),this.lookupsByObject.set(e,o)),o}keyPrefixOf(e){let t=this.deps.describeKeyPrefix;if(!t)return Promise.resolve(void 0);let o=this.keyPrefixByObject.get(e);return o||(o=t(e).catch(()=>{}),this.keyPrefixByObject.set(e,o)),o}constructor(e){super(),this.deps=e,this.batchSize=e.batchSize??200}async recordTypesHeldBack(e){let{describeRecordTypes:t,countRecordTypes:o}=this.deps;if(!t||!o)return[];let n=await this.creatableFieldsOf(e);if(n&&!n.has("RecordTypeId"))return[];try{let r=await t(e);if(!r.some(i=>!i.available&&!i.master))return[];let s=this.inTargetRecordTypes(await o(e));return zn(e,s,kt(r,this.targetRecordTypes))}catch{return[]}}inTargetRecordTypes(e){let t=new Map;for(let[o,n]of e){if(o===null)continue;let r=this.targetRecordTypeOf(o);t.set(r,(t.get(r)??0)+n)}return t}targetRecordTypeOf(e){return this.recordTypeMappings?.find(t=>t.sourceId===e)?.targetId??e}async recordTypesGivenOf(e,t,o=new Map,n=[]){await this.mapRecordTypes(e);let r=new Map;for(let s of new Set(e.waves.flatMap(i=>i.objects))){let i=t.get(s)??0;if(i===0)continue;let a=await this.givenRuleOf(s);if(!a)continue;let c=await this.creatableFieldsOf(s),d,m="masterInSource";if(c&&!c.has("RecordTypeId"))d=i,m="notRead";else{let u=await this.onMasterInSource(s,o.get(s));if(u===void 0)continue;d=n.find(g=>g.objectApiName===s)?Math.min(u,i):u}d!==0&&r.set(s,{objectApiName:s,rows:d,why:{[m]:d},...a.predicted?{predicted:a.predicted}:{}})}return r}async onMasterInSource(e,t){try{if(t===void 0){let r=this.deps.countRecordTypes;return r?br(await r(e)):void 0}let o=this.deps.querySource;if(!o)return;let n=0;for(let r=0;r<t.length;r+=ke){let s=await o(Nt(e,t.slice(r,r+ke)));n+=br(Ke(s))}return n}catch{return}}givenRuleOf(e){let t=this.givenRules.get(e);return t||(t=(async()=>{let o=this.recordTypesUnderTheLease.get(e)??await this.deps.describeRecordTypes?.(e).catch(()=>{});if(!o?.some(s=>!s.master))return;let n=kt(o,this.targetRecordTypes),r=$o(Do(n));return{types:n,...r?{predicted:r}:{}}})(),this.givenRules.set(e,t)),t}async readAgainUnderTheLease(e,t){let o=this.deps.describeRecordTypesAgain;if(!o||!this.lease||this.lease.assigned===0)return;let n=[...new Set(e.waves.flatMap(r=>r.objects))].filter(r=>(t.get(r)??0)>0);await Promise.all(n.map(async r=>{if((await this.deps.describeRecordTypes?.(r).catch(()=>{}))?.some(i=>!i.master))try{this.recordTypesUnderTheLease.set(r,await o(r))}catch{}}))}countCreatedWithoutRecordType(e,t,o,n){let r=this.recordTypesGiven.get(e);r||(r={...t,rows:0,why:{},ids:[]},this.recordTypesGiven.set(e,r)),r.rows++,r.why[o]=(r.why[o]??0)+1,n&&r.ids.length<Bo&&r.ids.push(n)}async afterTheWrites(e){await this.giveTheLeaseBack(),await this.readBackRecordTypes();for(let[t,o]of this.recordTypesGiven){let n=e[t];n&&(e[t]={...n,recordTypeGiven:Gr(t,o)})}}async giveTheLeaseBack(){let e=this.lease;if(e){this.lease=void 0;try{await e.giveBack()}catch(t){ae.warn(`[autopilot] the mute's lease was not given back as the writes ended: ${ee(t)}`)}}}async readBackRecordTypes(){let e=this.deps.queryTarget;e&&await Promise.all([...this.recordTypesGiven].map(async([t,o])=>{if(o.ids.length!==0)try{let n=await e(Nt(t,o.ids));o.readBack=_o(n,o.types)}catch(n){o.readBack={read:0,types:[],unread:ee(n)}}}))}holdOnClosedRecordTypes(e,t,o){let n=o.closedRecordTypes;if(!n)return t;let r=[];for(let s of t){let i=s.RecordTypeId,a=e===fe&&Pe(s),c=typeof i=="string"&&i.length>=15&&!a?n.get(de(this.targetRecordTypeOf(i))):void 0;if(!c){r.push(s);continue}o.failed++;let d=o.heldForRecordType.get(c.recordTypeId);o.heldForRecordType.set(c.recordTypeId,{...c,recordCount:(d?.recordCount??0)+1});let m=s.Id;typeof m=="string"&&m!==""&&this.refusedRecords.set(de(m),e)}return r}async mapRecordTypes(e){let{querySource:t,queryTarget:o}=this.deps;if(!t||!o)return;let n=[...new Set(e.waves.flatMap(s=>s.objects))];if(n.length===0)return;let r=`${xo} AND SobjectType IN (${n.map(s=>`'${ge(s)}'`).join(", ")})`;try{let[s,i]=await Promise.all([t(r),o(r)]),a=xt(s);this.targetRecordTypes=xt(i),this.recordTypeMappings=new jt().buildMapping(a,this.targetRecordTypes);for(let c of No(a,this.targetRecordTypes))ae.warn(`[autopilot] ${Lo(c)}`)}catch(s){ae.warn("Autopilot could not match the record types of the two orgs",{error:ee(s)})}}async matchStandardPricebooks(e){let{querySource:t,queryTarget:o}=this.deps;if(!t||!o)return;let n=new Set(e.waves.flatMap(r=>r.objects));if(!(!n.has(Ae)&&!n.has(Oe)))try{let[r,s]=await Promise.all([t(ve),o(ve)]),i=r[0]?.Id,a=s[0]?.Id;if(typeof i!="string"||typeof a!="string")return;this.standardPricebook={source:i,target:a},this.deps.remapper.registerMappings(Ae,[[i,a]])}catch(r){ae.warn("Autopilot could not match the standard price books",{error:ee(r)})}}async execute(e,t,o,n,r,s=new Map,i={}){if(!this.deps.queryByIds&&[...s.values()].some(f=>f.length>0))throw new Error("This plan reads the parents its objects reference by id, and the run has no read by id.");this.parentIds=s,this.contactPoints=i.keepContactPoints===!0?void 0:new Mo,this.lease=i.lease,this.fit=i.fit?Ur(i.fit):void 0;let a=Date.now();this.signal=r;let c=()=>this.pauseResolve?.();r?.addEventListener("abort",c,{once:!0});let d={},m={},u={totalSuccess:0,totalFailure:0,totalSkipped:0,totalLinked:0,elapsedMs:0,completedObjects:[],failedObjects:[],skippedObjects:[],nodeErrors:d,objectOutcomes:m},p=[];this.emit("execution-started",this.makeEvent({type:"execution-started",timestamp:""}));let g=async f=>{await y(f),f===We&&await this.writeEmailsAfterTheirTask(t,u)},y=async f=>{if(this.skippedObjects.has(f)){let w=n.get(f)??0;u.skippedObjects.push(f),u.totalSkipped+=w,this.notWritten.set(f,"skipped");return}this.reached.add(f);let R=n.get(f)??0;if(await this.checkPause()){p.push(f),m[f]={written:0,linked:0,failed:0,refusals:[],...R>0?{notSent:R}:{}};return}try{let w=await this.executeObject(f,t,o,R);u.totalSuccess+=w.success,u.totalFailure+=w.failure,u.totalLinked=(u.totalLinked??0)+w.linked,w.cutSinceFit>0&&(u.cutSinceFit=(u.cutSinceFit??0)+w.cutSinceFit);let C=this.leftToThePlatform.counts(f);if(m[f]={written:w.success,linked:w.linked,failed:w.failure,refusals:w.refusals,...w.leftToDefault.length>0?{leftToDefault:w.leftToDefault}:{},...C.length>0?{leftToThePlatform:C}:{},...w.notSent!==void 0&&w.notSent>0?{notSent:w.notSent}:{},...this.currenciesReplacedOf(f),...this.pricesSettledOf(f),...f===fe&&this.personContactsLinked>0?{withTheirPersonAccount:this.personContactsLinked}:{},...w.cutSinceFit>0?{cutSinceFit:w.cutSinceFit}:{},...w.threw!==void 0?{threw:w.threw}:{},...w.sentAgainForALock.rows>0?{sentAgainForALock:w.sentAgainForALock}:{}},w.notSent!==void 0){p.push(f);return}let{threw:v}=w;if(v!==void 0||w.errors.length>0&&w.success+w.linked===0){u.failedObjects.push(f),v!==void 0&&this.notWritten.set(f,"failed");let z=v!==void 0?[v,...w.errors]:w.errors;d[f]=z[0],this.emit("node-failed",this.makeEvent({type:"node-failed",timestamp:"",objectApiName:f,errors:z,partialSuccessCount:w.success,failureCount:w.failure,linkedCount:w.linked,refusals:w.refusals}))}else u.completedObjects.push(f),this.emit("node-completed",this.makeEvent({type:"node-completed",timestamp:"",objectApiName:f,successCount:w.success,failureCount:w.failure,linkedCount:w.linked,refusals:w.refusals,elapsedMs:w.elapsedMs,apiCallsUsed:w.apiCallsUsed}))}catch(w){u.failedObjects.push(f),this.notWritten.set(f,"failed");let C=ee(w);d[f]=C,this.emit("node-failed",this.makeEvent({type:"node-failed",timestamp:"",objectApiName:f,errors:[C],partialSuccessCount:0,failureCount:0,linkedCount:0,refusals:[]}))}};try{await this.matchStandardPricebooks(e),await this.mapRecordTypes(e),await this.readAgainUnderTheLease(e,n),this.planned=new Set(e.waves.flatMap(w=>w.objects));let f={};for(let w of e.waves){if(await this.writeWave(w.objects,t,g),this.stopped())break;await this.fillOwedLookups(f),this.emit("wave-completed",this.makeEvent({type:"wave-completed",timestamp:""}))}if(this.stopped()){let w=new Set([...u.completedObjects,...u.failedObjects,...u.skippedObjects,...p]);for(let C of e.waves.flatMap(v=>v.objects)){if(w.has(C))continue;let v=n.get(C)??0;p.push(C),m[C]={written:0,linked:0,failed:0,refusals:[],...v>0?{notSent:v}:{}}}return u.stopped=!0,u.stoppedObjects=p,this.countEmailsTheStopHeld(u,p,m),this.countWhatTheStopLeft(p,m),await this.sayLookupsLeftOwed(t,f),Object.keys(f).length>0&&(u.lookups=f),await this.afterTheWrites(m),this.reportContactPoints(u),u.elapsedMs=Date.now()-a,u}this.emailsAfterTheirTask.length>0&&(await this.writeEmailsAfterTheirTask(t,u),await this.fillOwedLookups(f)),await this.sayLookupsLeftOwed(t,f);let R=await this.applyDeferredStatuses();return Object.keys(R).length>0&&(u.statuses=R),Object.keys(f).length>0&&(u.lookups=f),await this.afterTheWrites(m),this.stopped()&&(u.stopped=!0,u.stoppedObjects=p,this.countEmailsTheStopHeld(u,p,m),this.countWhatTheStopLeft(p,m)),this.reportContactPoints(u),u.elapsedMs=Date.now()-a,this.emit("execution-completed",this.makeEvent({type:"execution-completed",timestamp:""})),u}catch(f){throw u.elapsedMs=Date.now()-a,u.fatalError=ee(f),ae.error("Autopilot execution crashed",{error:u.fatalError}),this.emit("execution-failed",this.makeEvent({type:"execution-failed",timestamp:"",error:u.fatalError})),f}finally{r?.removeEventListener("abort",c),await this.giveTheLeaseBack()}}async writeWave(e,t,o){let{within:n,deps:r,groups:s}=Ue(e,t),i=new Map;s.forEach((m,u)=>m.forEach(p=>i.set(p,u)));let a=[];for(let[m,u]of s.entries()){let p=new Set;for(let g of u)for(let y of r.get(g)??[]){let f=i.get(y);f!==void 0&&f!==m&&p.add(a[f])}a.push((async()=>{await Promise.all(p);let g=u.length>1?un(u,await this.setAtInsert(u,n)):u;for(let y of g)await o(y)})())}let d=(await Promise.allSettled(a)).find(m=>m.status==="rejected");if(d)throw d.reason}async setAtInsert(e,t){let o=new Set(e),n=new Map;for(let r of t)!o.has(r.to)||!o.has(r.from)||n.has(r.to)||n.set(r.to,await this.lookupsOf(r.to));return pn(e,t,r=>n.get(r))}async fillOwedLookups(e){let t=this.owedLookups.splice(0,this.owedLookups.length),{update:o}=this.deps;if(!o||t.length===0)return;let n=new Io;for(let r of t){let s=r.parents.map(i=>this.deps.remapper.getTargetId(i,r.sourceId)).find(i=>i!==void 0);if(!s){this.owedLookups.push(r);continue}n.add({objectApiName:r.objectApiName,recordId:r.recordId,fieldName:r.fieldApiName,value:s})}for(let[r,s]of n.updates()){let i=e[r],a=i?.filled??0,c=new Re;for(let d of i?.refusals??[])c.addCounted(d);for(let d=0;d<s.length;d+=this.batchSize){if(await this.checkPause()){this.noteLeftByStop(r,"lookups",s.slice(d).map(p=>String(p.Id)));break}let m=s.slice(d,d+this.batchSize),u=await Ht(o,r,m);m.forEach((p,g)=>{let y=u[g];if(y?.success){a++;return}let f=Object.keys(p).filter(R=>R!=="Id");c.add(Kt(y).map(R=>({...R,fields:f}))),this.noteLookupLeftEmpty(r,String(p.Id))})}e[r]=this.lookupOutcome(r,a,c)}}noteLookupLeftEmpty(e,t){let o=this.lookupsLeftEmpty.get(e);o||(o=new Set,this.lookupsLeftEmpty.set(e,o)),o.add(t)}lookupOutcome(e,t,o){let n=this.lookupsLeftEmpty.get(e)?.size??0;return{filled:t,refusals:o.list(),...n>0?{leftEmpty:n}:{}}}async sayLookupsLeftOwed(e,t){let o=new Map;for(let n of this.owedLookups.splice(0,this.owedLookups.length)){let r=await this.whyLeftOwed(n,e);if(!r)continue;let s=o.get(n.objectApiName);if(!s){s=new Re;for(let i of t[n.objectApiName]?.refusals??[])s.addCounted(i);o.set(n.objectApiName,s)}s.add([{...r,fields:[n.fieldApiName]}]),this.noteLookupLeftEmpty(n.objectApiName,n.recordId)}for(let[n,r]of o){let s=t[n]?.filled??0;t[n]=this.lookupOutcome(n,s,r)}}async whyLeftOwed(e,t){let{fieldApiName:o,sourceId:n}=e,r=this.refusedRecords.get(de(n)),s=e.parents.find(c=>c===r);if(s)return{statusCode:hr,message:`the ${s} record its ${o} names was refused in this run, and this record, written before it, keeps its ${o} empty.`};let i=this.fit?.stayedOut.get(de(n)),a=e.parents.find(c=>c===i);if(a)return{statusCode:Yt,message:`the ${a} record its ${o} names stayed out with a record the fit cut, and this record, written before it, keeps its ${o} empty.`};for(let c of e.parents){let d=this.notWrittenOf(c);if(d===void 0)continue;let m=t.find(u=>u.from===c&&u.to===e.objectApiName&&u.fieldApiName===o);if(!(m&&!await this.namesARecordOf(e.objectApiName,m,n,e.parents.length)))return{statusCode:gr,message:`the ${c} record its ${o} names was not written: ${yr[d](c)}, and this record, written before it, keeps its ${o} empty.`}}}async executeObject(e,t,o,n){let r=Date.now(),s=wr(),i=()=>{let a=[...s.heldForRecordType.values()];return{success:s.written,linked:s.linked,failure:s.failed,errors:[...a.map(Wn),...s.errors],refusals:[...s.refusals.list(),...a.map(zr)].sort((c,d)=>d.count-c.count),apiCallsUsed:s.apiCallsUsed,elapsedMs:Date.now()-r,leftToDefault:[...s.defaulted].map(([c,d])=>({field:c,count:d})),...s.notSent!==void 0?{notSent:s.notSent}:{},cutSinceFit:s.cutSinceFit,sentAgainForALock:s.sentAgainForALock}};try{return await this.writeEveryPage(e,t,o,n,s,i)}catch(a){return{...i(),threw:ee(a)}}}async writeEveryPage(e,t,o,n,r,s){let i=n>0?await this.recordTypesHeldBack(e):[];i.length>0&&(r.closedRecordTypes=new Map(i.map(u=>[de(u.recordTypeId),u])));let a=u=>{let p=Math.min(u,n);this.emit("node-progress",this.makeEvent({type:"node-progress",timestamp:"",objectApiName:e,progress:n>0?Math.round(p/n*100):100,recordsProcessed:p,recordsTotal:n,apiCallsUsed:r.apiCallsUsed}))},c=0,d,m=this.standardPricebook;if(Vt(e)&&m){let u=[];for(;c<n;){if(await this.checkPause())return r.notSent=n,s();let{rows:v,advance:z,next:K,last:E}=await this.readPage(e,c,d);if(r.apiCallsUsed++,z===0)break;c+=z,d=K;let A=this.leaveToThePlatform(e,v,t);if(this.deps.anonymizer.anonymize(A,o,e),await this.neutralizeContactPoints(e,A),u.push(...A),E)break}let p=await this.pricesInOneCurrencyEach(u,m.source),{standard:g,custom:y}=lt(p.rows,m.source),f=lt(u.filter(v=>p.standsFor.has(String(v.Id))),m.source);p.said.length>0&&this.pricesSettled.set(e,Go(p.said));let R=0,w=0,C=async v=>{for(let z=0;z<v.length;z+=this.batchSize){if(await this.checkPause())return r.notSent=u.length-R-w,!1;let K=v.slice(z,z+this.batchSize);await this.writeBatch(e,K,t,r),R+=K.length,a(R+w)}return!0};for(let[v,z]of[[g,f.standard],[y,f.custom]]){if(!await C(v))return s();let K=this.linkWhatStoodIn(z,p.standsFor,r);if(w+=z.length-K.length,!await C(K))return s()}return s()}for(;c<n;){if(await this.checkPause()){r.notSent=n-c;break}let{rows:u,advance:p,next:g,last:y}=await this.readPage(e,c,d);if(r.apiCallsUsed++,p===0)break;d=g;let f=this.leaveToThePlatform(e,u,t);if(this.deps.anonymizer.anonymize(f,o,e),await this.neutralizeContactPoints(e,f),await this.writeBatch(e,f,t,r),c+=p,a(c),y)break}return s()}async neutralizeContactPoints(e,t){let{contactPoints:o}=this,n=this.deps.describeFields;if(!o||!n||t.length===0)return;let r=await n(e).catch(()=>{});if(!r)return;let s=o.forObject(e,r);if(s)for(let i of t)s(i)}reportContactPoints(e){this.contactPoints&&(e.contactPoints=this.contactPoints.report())}async readPage(e,t,o){let n=this.parentIds.get(e);if(n&&this.deps.queryByIds){let i=n.slice(t,t+Math.min(this.batchSize,ke));return i.length===0?{rows:[],advance:0,next:o,last:!0}:{rows:await this.deps.queryByIds(e,i),advance:i.length,next:o,last:!1}}let r=await this.deps.query(e,o,this.batchSize),s=r.at(-1)?.Id;return{rows:r,advance:r.length,next:typeof s=="string"?s:o,last:r.length>0&&typeof s!="string"}}leaveToThePlatform(e,t,o){let n=new Set(o.filter(r=>r.to===e&&(r.required||Qt(r.to,r.fieldApiName))).map(r=>r.fieldApiName));return this.leftToThePlatform.keep(e,t,[...n])}async writeBatch(e,t,o,n){let r=[],s=t,i=this.standardPricebook;if(e===Ae&&i&&(s=t.filter(E=>E.Id!==i.source),n.linked+=t.length-s.length),s=this.holdOnClosedRecordTypes(e,s,n),s=await this.holdBehindRefusedParents(e,s,o,n),s=this.holdBehindCutParents(e,s,n),e===oe&&(s=this.holdEmailsForTheirTask(s)),e===fe&&(s=await this.linkPersonContacts(s,n,r)),s.length===0){this.register(e,r);return}let a=this.deps.remapper.remapRecords(s,o,e);await this.leaveToDefault(e,s,n);let c=await this.creatableFieldsOf(e),d=c?s.map(E=>{let A={};for(let j of Object.keys(E))(j==="Id"||j==="attributes"||c.has(j))&&(A[j]=E[j]);return A}):s;d=this.translateRecordTypes(e,d);let m=new Map;d.forEach((E,A)=>{if(E.RecordTypeId!==void 0)return;let j=s[A]?.RecordTypeId,M=!c||c.has("RecordTypeId");m.set(E,M&&Ft(j)?"masterInSource":"notRead")});for(let E of d)for(let A of Zt(e,E))delete E[A];let u=await this.replaceCurrencies(e,s,d,c);e===ce&&await this.leaveOutForAccountKind(s,d);let p=new Map;d.forEach((E,A)=>{let j=gt(e,E);for(let M of j)delete E[M];j.length>0&&p.set(A,j)});let g=await this.lookupsOwed(e,s,a.unresolved.filter(E=>!p.get(E.index)?.includes(E.fieldApiName)),c),y=this.deps.queryTarget,f=y?E=>(n.apiCallsUsed++,y(E)):void 0;if(e===mn&&f){let E=await En(f,d);for(let[A,j]of E){let M=d[A].Id;typeof M=="string"&&r.push([M,j])}n.linked+=E.size,d=d.filter((A,j)=>!E.has(j))}if(Sn[e]!==void 0&&f){let E=await On(f,e,d);for(let[A,j]of E){let M=d[A].Id;typeof M=="string"&&r.push([M,j])}n.linked+=E.size,await this.giveFlagsBack(e,[...E].map(([A,j])=>[d[A],j]),n),d=d.filter((A,j)=>!E.has(j))}if(e===We&&f){let E=await this.tasksWrittenWithTheirEmail(d,f);for(let[A,j]of E)r.push([A,j]);n.linked+=E.size,d=d.filter(A=>!E.has(String(A.Id)))}if(d.length===0){this.register(e,r);return}let R=await this.startAsDrafts(e,d),w=m.size>0?await this.givenRuleOf(e):void 0,C=await this.insertSendingLocksAgain(e,d,n),v=await this.keyPrefixOf(e),z=hn[e],K=[];if(d.forEach((E,A)=>{let j=typeof E.Id=="string"?E.Id:void 0,M=C[A];if(!M){this.refuse(e,j,n,void 0);return}if(M.success){n.written++;let se=w?m.get(E):void 0;w&&se&&this.countCreatedWithoutRecordType(e,w,se,M.id);let T=u.get(E);this.currencyChanges.add(e,T),T&&M.id&&this.currencyChangesByWrittenId.set(M.id,T),j&&M.id&&r.push([j,M.id]);let O=R.get(A);O&&M.id&&this.deferredStatuses.push({objectApiName:e,id:M.id,status:O});let D=j?g.get(j):void 0;for(let S of M.id?D??[]:[])this.owedLookups.push({objectApiName:e,recordId:M.id,fieldApiName:S.fieldApiName,sourceId:S.sourceId,parents:S.parents});return}let te=Hn(M,v);if(te.kind==="linked"){n.linked++,j&&r.push([j,te.id]);return}if(te.kind==="unidentified"&&z&&f){K.push({payload:E,sourceId:j,outcome:M});return}this.refuse(e,j,n,M)}),z&&f&&K.length>0){let E=await Pn(f,e,z,K.map(A=>A.payload));K.forEach((A,j)=>{let M=E[j];if(M&&A.sourceId){n.linked++,r.push([A.sourceId,M]);return}this.refuse(e,A.sourceId,n,A.outcome)})}this.register(e,r)}async insertSendingLocksAgain(e,t,o){let n=async i=>(o.apiCallsUsed++,this.deps.insert(e,i)),r=await n(t),s=await oo({outcomes:r.slice(0,t.length),locked:i=>!i.success&&to(i.errors,i.errorDetails),written:i=>i.success,send:i=>Ht((a,c)=>n(c),e,i.map(a=>t[a])),note:qr,wait:async i=>{await this.wait(i),await this.checkPause()},stopped:()=>this.stopped()});return s.refused===0?r:(o.sentAgainForALock={rows:o.sentAgainForALock.rows+s.sentAgain,written:o.sentAgainForALock.written+s.written,stillLocked:o.sentAgainForALock.stillLocked+s.stillLocked},ae.info(`[autopilot] ${e}: ${Xe("record(s)",s)??""}`),[...s.outcomes,...r.slice(t.length)])}async giveFlagsBack(e,t,o){let n=this.deps.update;if(!n||t.length===0||!Tn[e])return;let r=await this.deps.describeFieldsFixedAtInsert?.(e).catch(()=>{}),s=await vn(e,t,i=>!r?.has(i),async i=>(o.apiCallsUsed++,n(e,i)),()=>this.stopped());s&&ae.warn("Autopilot linked relations without a flag or an answer their rows carried",{objectApiName:e,note:s})}holdEmailsForTheirTask(e){for(let o of e){let n=o.ActivityId;typeof o.Id=="string"&&typeof n=="string"&&n!==""&&this.taskOfEmail.set(o.Id,n)}if(this.taskTurnOver||!this.planned.has(We))return e;let t=[];for(let o of e)bn(o)?this.emailsAfterTheirTask.push(o):t.push(o);return t}async tasksWrittenWithTheirEmail(e,t){let o=new Map;for(let[i,a]of this.taskOfEmail){let c=this.deps.remapper.getTargetId(oe,i);c&&o.set(a,c)}let n=e.map(i=>String(i.Id)).filter(i=>o.has(i));if(n.length===0)return new Map;let r;try{r=await An(t,[...new Set(n.map(i=>o.get(i)??""))])}catch(i){return ae.warn("Autopilot could not look up the tasks written with its emails",{error:ee(i)}),new Map}let s=new Map;for(let i of n){let a=r.get(o.get(i)??"");a&&s.set(i,a)}return s}async writeEmailsAfterTheirTask(e,t){this.taskTurnOver=!0;let o=this.emailsAfterTheirTask.splice(0,this.emailsAfterTheirTask.length);if(o.length===0)return;let n=wr();for(let d=0;d<o.length;d+=this.batchSize){if(await this.checkPause()){this.emailsHeldAndNotSent+=o.length-d;break}await this.writeBatch(oe,o.slice(d,d+this.batchSize),e,n)}t.totalSuccess+=n.written,t.totalFailure+=n.failed,t.totalLinked=(t.totalLinked??0)+n.linked;let r=t.objectOutcomes??{};t.objectOutcomes=r;let s=r[oe],i=new Re;for(let d of[...s?.refusals??[],...n.refusals.list()])i.addCounted(d);let a=new Map((s?.leftToDefault??[]).map(d=>[d.field,d.count]));for(let[d,m]of n.defaulted)a.set(d,(a.get(d)??0)+m);let c={...s,written:(s?.written??0)+n.written,linked:(s?.linked??0)+n.linked,failed:(s?.failed??0)+n.failed,refusals:i.list(),...a.size>0?{leftToDefault:[...a].map(([d,m])=>({field:d,count:m}))}:{}};r[oe]=c,c.written+c.linked>0&&t.failedObjects.includes(oe)&&(t.failedObjects.splice(t.failedObjects.indexOf(oe),1),delete t.nodeErrors?.[oe],t.completedObjects.push(oe)),this.emit("node-completed",this.makeEvent({type:"node-completed",timestamp:"",objectApiName:oe,successCount:c.written,failureCount:c.failed,linkedCount:c.linked,refusals:c.refusals,elapsedMs:0,apiCallsUsed:n.apiCallsUsed}))}async leaveToDefault(e,t,o){let n=await this.lookupsOf(e);if(!n)return;let r=In(n.filter(i=>i.name!=="RecordTypeId"),i=>!this.planned.has(i));if(r.size===0)return;let s=await this.creatableFieldsOf(e);for(let i of t)for(let a of r){let c=i[a];c!=null&&c!==""&&(!s||s.has(a))&&o.defaulted.set(a,(o.defaulted.get(a)??0)+1),delete i[a]}}async replaceCurrencies(e,t,o,n){let r=new Map,{querySource:s,queryTarget:i}=this.deps;if(!s||!i)return r;let a=!n||n.has(he);if(!a&&this.currencyChangesByWrittenId.size===0)return r;let c=p=>typeof p?.[he]=="string"&&p[he]!=="";if(!(a?o.some(c):t.some(c)))return r;this.currencies??=Me(s,i,{source:this.deps.toolingSource,target:this.deps.toolingTarget});let d=await this.currencies;if(!d)return r;let m=await this.deps.describeCurrencyFields?.(e).catch(()=>{})??new Map,u=a?[]:(await this.lookupsOf(e)??[]).map(p=>p.name);return o.forEach((p,g)=>{let y=t[g],f=y?.[he],R=a?Ln(p,{read:f,currencyFields:m,ratesOn:Fn(e,y)},d):$n(p,{read:f,parent:y?Dn(e,y,u,w=>this.currencyChangesByWrittenId.get(w)):void 0,currencyFields:m},d);R&&r.set(p,R)}),r}async pricesInOneCurrencyEach(e,t){let o={rows:e,standsFor:new Map,said:[]},{querySource:n,queryTarget:r}=this.deps;if(!n||!r)return o;let s=d=>typeof d[he]=="string"&&d[he]!=="";if(!e.some(s))return o;this.currencies??=Me(n,r,{source:this.deps.toolingSource,target:this.deps.toolingTarget});let i=await this.currencies;if(!i)return o;let{target:a}=i,c=zo({prices:e,standardBookId:t,sellingModels:e.some(d=>typeof d[Ee]=="string"),writtenIn:d=>a.active.has(d)?d:Nn(void 0,a)?.to,active:a.active},[]);return{rows:c.rows,standsFor:c.standsFor,said:c.said}}linkWhatStoodIn(e,t,o){let n=Oe,r=[],s=[];for(let i of e){let a=String(i.Id),c=t.get(a),d=c===void 0?void 0:this.deps.remapper.getTargetId(n,c);if(d===void 0){s.push(i);continue}r.push([a,d]),o.linked++}return this.register(n,r),s}pricesSettledOf(e){let t=this.pricesSettled.get(e)??[];return t.length>0?{pricesSettled:t}:{}}currenciesReplacedOf(e){let t=this.currencyChanges.list().filter(o=>o.objectApiName===e);return t.length>0?{currenciesReplaced:t}:{}}translateRecordTypes(e,t){let o=this.recordTypeMappings;return!o||!t.some(n=>typeof n.RecordTypeId=="string")?t.map(Fo):new jt().apply(t,o,n=>{this.unmappedRecordTypes.has(n)||(this.unmappedRecordTypes.add(n),jo(e,n,"autopilot"))})}async lookupsOwed(e,t,o,n){let r=new Map;if(!this.deps.update||o.length===0)return r;let s=await this.lookupsOf(e);for(let i of o){if(n&&!n.has(i.fieldApiName))continue;let a=s?.find(d=>d.name===i.fieldApiName);if(a&&!a.updateable)continue;let c=t[i.index]?.Id;typeof c=="string"&&r.set(c,[...r.get(c)??[],i])}return r}refuse(e,t,o,n){o.failed++;let r=Kt(n);o.errors.push(n?.errors[0]??Wr(r[0])),o.refusals.add(r),t&&this.refusedRecords.set(de(t),e)}async holdBehindRefusedParents(e,t,o,n){if(this.refusedRecords.size===0&&this.notWritten.size===0&&this.skippedObjects.size===0)return t;let r=o.filter(a=>a.to===e);if(r.length===0)return t;let s=new Map;for(let a of r)s.set(a.fieldApiName,(s.get(a.fieldApiName)??0)+1);let i=[];for(let a of t){let c=gt(e,a),d;for(let y of r){let f=a[y.fieldApiName];if(typeof f!="string"||f===""||c.includes(y.fieldApiName)||this.deps.remapper.getTargetId(y.from,f)!==void 0)continue;let R=this.refusedRecords.get(de(f))===y.from,w=this.notWrittenOf(y.from);if(!R&&w===void 0)continue;let C=s.get(y.fieldApiName)??0;if(!R&&!await this.namesARecordOf(e,y,f,C))continue;let{from:v,fieldApiName:z}=y;d=R||w===void 0?{edge:y,statusCode:hr,message:`the ${v} record its ${z} names was refused in this run, and written without it this record would stand without its ${v}.`}:{edge:y,statusCode:gr,message:`the ${v} record its ${z} names was not written: ${yr[w](v)}, and written without it this record would stand without its ${v}.`};break}if(!d){i.push(a);continue}let{statusCode:m,message:u,edge:p}=d;n.failed++,n.errors.push(`${m}: ${u}`),n.refusals.add([{statusCode:m,message:u,fields:[p.fieldApiName]}]);let g=a.Id;typeof g=="string"&&g!==""&&this.refusedRecords.set(de(g),e)}return i}holdBehindCutParents(e,t,o){let n=this.fit,r=n?.holds.get(e);return!n||!r?t:t.filter(s=>{if(!r.some(c=>{let d=s[c.field];if(typeof d!="string"||d==="")return!1;let{prefix:m}=c;if(m!==void 0&&(m===null||!d.startsWith(m))||this.deps.remapper.getTargetId(c.parent,d)!==void 0)return!1;let u=de(d);return n.stayedOut.has(u)||n.kept.get(c.parent)?.has(u)!==!0}))return!0;o.cutSinceFit++;let a=s.Id;return typeof a=="string"&&a!==""&&n.stayedOut.set(de(a),e),!1})}notWrittenOf(e){if(!this.planned.has(e))return;let t=this.notWritten.get(e);return t||(this.skippedObjects.has(e)&&!this.reached.has(e)?"skipped":void 0)}async namesARecordOf(e,t,o,n){let r=(await this.lookupsOf(e))?.find(s=>s.name===t.fieldApiName);if(r?.referenceTo.length===1)return r.referenceTo[0]===t.from;if(r&&r.referenceTo.length>1){let s=await this.keyPrefixOf(t.from);return typeof s=="string"&&s!==""&&o.startsWith(s)}return n===1}async linkPersonContacts(e,t,o){let n=e.filter(Pe),r=this.deps.queryTarget;if(n.length===0||!r)return e;let s=await this.lookupsOf(ce);if(s&&!s.some(u=>u.name===yt))return e;let i=new Map;for(let u of n){let p=u.AccountId,g=typeof p=="string"&&p!==""?this.deps.remapper.getTargetId(ce,p):void 0;g&&i.set(u,g)}let a=new Map,c;if(i.size>0)try{t.apiCallsUsed++,a=await Rn(r,[...new Set(i.values())])}catch(u){c=ee(u)}let d=(u,p,g)=>{t.failed++,t.errors.push(`${p}: ${g}`),t.refusals.add([{statusCode:p,message:g,fields:["AccountId"]}]);let y=u.Id;typeof y=="string"&&y!==""&&this.refusedRecords.set(de(y),fe)},m=[];for(let u of e){if(!Pe(u)){m.push(u);continue}let p=i.get(u);if(p===void 0){d(u,$r,"the person account this contact belongs to is not in the target: the platform writes the contact with the account, and sent on its own it would stand as a contact of no account.");continue}if(c!==void 0){d(u,Br,`the contact the platform wrote with its person account could not be looked up (${c}): sent, this one would stand beside it as a second contact.`);continue}let g=a.get(p),y=u.Id;if(g===void 0||typeof y!="string"){m.push(u);continue}o.push([y,g]),t.linked++,this.personContactsLinked++}return m}async leaveOutForAccountKind(e,t){let n=e.some(Pe)?await this.takenAsBusiness(t):()=>!1,r=e.map((s,i)=>kn(s,n(t[i])));t.forEach((s,i)=>{for(let a of Object.keys(s))tn(ce,a,r[i])&&delete s[a]})}async takenAsBusiness(e){let t=await this.lookupsOf(ce);if(t&&!t.some(a=>a.name===yt))return()=>!0;let o=this.deps.queryTarget;if(!o)return()=>!1;this.personTypes??=o(_r).then(a=>new Set(a.flatMap(c=>typeof c.Id=="string"?[de(c.Id)]:[])),()=>{});let n=await this.personTypes;if(!n)return()=>!1;let r=await this.deps.describeRecordTypes?.(ce).catch(()=>{}),s=new Set((r??[]).map(a=>de(a.recordTypeId))),i=e.some(a=>typeof a.RecordTypeId!="string")?qo(r):void 0;return a=>{let c=a.RecordTypeId,d=typeof c=="string"&&c!==""?c:i;if(d===void 0)return!1;let m=de(d);return!n.has(m)&&s.has(m)}}register(e,t){t.length>0&&this.deps.remapper.registerMappings(e,t)}async startAsDrafts(e,t){let o=new Map,n=Ce[e],{queryTarget:r,update:s}=this.deps;if(!n||!r||!s)return o;let i=this.lifecycleByObject.get(e);i||(i=Cn(r,n),this.lifecycleByObject.set(e,i));let a=await i;return a&&t.forEach((c,d)=>{let m=Mn(c.Status,a);m&&(o.set(d,String(c.Status)),c.Status=m)}),o}async applyDeferredStatuses(){let e={},{update:t}=this.deps;if(!t||this.deferredStatuses.length===0)return e;let o=new Map;for(let n of this.deferredStatuses)o.set(n.objectApiName,[...o.get(n.objectApiName)??[],n]);for(let[n,r]of o){let s=0,i=0,a=new Re;for(let c=0;c<r.length;c+=this.batchSize){if(await this.checkPause()){this.noteLeftByStop(n,"statuses",r.slice(c).map(u=>u.id));break}let d=r.slice(c,c+this.batchSize),m=await Ht(t,n,d.map(u=>({Id:u.id,Status:u.status})));d.forEach((u,p)=>{let g=m[p];if(g?.success){s++;return}i++,a.add(Kt(g))})}e[n]={applied:s,refusals:a.list(),...i>0?{leftDraft:i}:{}}}return this.deferredStatuses.length=0,e}noteLeftByStop(e,t,o){if(o.length===0)return;let n=this.leftByStop.get(e);n||(n={lookups:new Set,statuses:new Set},this.leftByStop.set(e,n));for(let r of o)n[t].add(r)}countEmailsTheStopHeld(e,t,o){let n=this.emailsAfterTheirTask.splice(0,this.emailsAfterTheirTask.length),r=this.emailsHeldAndNotSent+n.length;if(this.emailsHeldAndNotSent=0,r===0)return;let s=o[oe]??{written:0,linked:0,failed:0,refusals:[]};o[oe]={...s,notSent:(s.notSent??0)+r,heldForTheirTask:r};for(let d of[e.completedObjects,e.failedObjects]){let m=d.indexOf(oe);m>=0&&d.splice(m,1)}if(t.includes(oe))return;let i=[...this.planned],a=i.indexOf(oe),c=t.findIndex(d=>i.indexOf(d)>a);t.splice(c<0?t.length:c,0,oe)}countWhatTheStopLeft(e,t){let o=new Set(e);for(let r of this.owedLookups.splice(0,this.owedLookups.length))r.parents.some(i=>o.has(i)||this.deps.remapper.getTargetId(i,r.sourceId)!==void 0)?this.noteLeftByStop(r.objectApiName,"lookups",[r.recordId]):this.owedLookups.push(r);let n=this.deferredStatuses.splice(0,this.deferredStatuses.length);for(let r of n)this.noteLeftByStop(r.objectApiName,"statuses",[r.id]);for(let[r,s]of this.leftByStop){let i=t[r]??{written:0,linked:0,failed:0,refusals:[]};t[r]={...i,...s.lookups.size>0?{lookupsLeftEmpty:s.lookups.size}:{},...s.statuses.size>0?{statusesNotGivenBack:s.statuses.size}:{}}}}pause(){this.paused||(this.paused=!0,this.pausePromise=new Promise(e=>{this.pauseResolve=e}),this.emit("paused",this.makeEvent({type:"paused",timestamp:""})))}resume(){this.paused&&(this.paused=!1,this.pauseResolve?.(),this.pausePromise=null,this.pauseResolve=null,this.emit("resumed",this.makeEvent({type:"resumed",timestamp:""})))}skip(e){this.skippedObjects.add(e)}stopped(){return this.signal?.aborted===!0}wait(e){return this.deps.wait?this.deps.wait(e):no(e,this.signal)}async checkPause(){return this.stopped()?!0:(this.paused&&this.pausePromise&&await this.pausePromise,this.stopped())}makeEvent(e){return{...e,timestamp:new Date().toISOString()}}};async function Ht(l,e,t){try{return await l(e,t)}catch(o){let n=ee(o);return t.map(()=>({id:"",success:!1,errors:[n],errorDetails:[Rt(n)]}))}}function Kt(l){return l?l.errorDetails&&l.errorDetails.length>0?l.errorDetails:l.errors.length>0?l.errors.map(e=>Rt(e)):[Dr]:[Lr]}function Wr(l){return l.statusCode===Ye?l.message:`${l.statusCode}: ${l.message}`}var it=class{threshold;partitionSize;constructor(e=5e3,t=2e3){this.threshold=e,this.partitionSize=t}shouldUseGrappe(e){return e>this.threshold}partition(e,t){if(t<=this.partitionSize)return[{id:`${e}-0`,objectApiName:e,offset:0,limit:t,recordCount:t}];let o=[],n=0,r=0;for(;n<t;){let s=Math.min(this.partitionSize,t-n);o.push({id:`${e}-${r}`,objectApiName:e,offset:n,limit:s,recordCount:s}),n+=s,r++}return o}getThreshold(){return this.threshold}getPartitionSize(){return this.partitionSize}};var Hr=`sandforge autopilot \u2014 run an Autopilot copy between two orgs, without the editor.
|
|
10
|
+
${U}`,le=(G.get(re)?.count??0)+1;G.set(re,{objectApiName:q,field:ie,count:le,why:U})};for(let q of s)for(let ie of k.kept.get(q.name)??[])for(let U of q.loose[ie])k.ids.get(U.link.parent)?.has(U.id)||W(q.name,U.link.field,U.link.kind==="owed"?"owed":"selfReference");for(let q of L?.namingSelected??[])q.required||k.ids.get(q.target)?.has(q.id)||W(q.objectApiName,q.field,"onParent");return{heldBy:$,...X?{cannotFit:X.words}:{},kept:j(k),...L?{walk:L}:{},report:{mode:o,heldBy:$,...X?{cannotFit:X.said}:{},budget:{...Oo(e,x.roomBytes,t),...$==="apiRequests"?{limitedBy:"apiRequests"}:{}},...b!==void 0?{share:b}:{},objects:F,emptied:[...G.values()],parents:L?L.added.map(q=>({objectApiName:q,records:L.parentIds.get(q)?.length??0})):[...n].map(([q,{ids:ie}])=>({objectApiName:q,records:ie.length})),records:x.records,estimateMB:x.bytes/1048576}}},te={words:Pr,said:{why:"sourceChanged"}},se=b=>({words:`with these caps the plan takes ${A(b)}: lower them, or fit by share`,said:{why:"caps",over:E(b)}}),T=Object.keys(o.caps??{}).find(b=>!s.some(k=>k.name===b)),O=s.reduce((b,k)=>Math.max(b,Math.min(k.roots.length,i(k.name)??1/0)),0),D=m(1),S=p(D,f(D));if(T!==void 0)return M(void 0,D,S,"caps",void 0,{words:`the plan selects no ${T}: a cap holds an object it selects`,said:{why:"capNotSelected",object:T}});if(s.some(b=>b.rows.length>(l.planned.get(b.name)??0)))return M(void 0,D,S,e.terms.limitedBy,void 0,te);let ne=o.all!==void 0||Object.keys(o.caps??{}).length>0,N=o.share===!0||!ne,_=b=>{let k=m(b/O);return p(k,f(k))};if(s.every(b=>D.kept.get(b.name)?.size===b.rows.length)&&z(S))return M(N?1:void 0,D,S,"whole",void 0);if(O===0)return M(void 0,D,S,e.terms.limitedBy,void 0,te);let B=O;if(!z(S)){if(!N)return M(void 0,D,S,K(S),void 0,se(S));if(B=To(O,b=>z(_(b))),B===0){let b=m(1/O),k=p(b,f(b));return M(1/O,b,k,K(k),void 0,{words:`the least it can be cut to \u2014 one record of each object with none to follow, and what follows them, ${cr(k.records)} \u2014 takes ${A(k)}`,said:{why:"least",over:E(k)}})}}let Z=B<O?K(_(B+1)):ne?"caps":e.terms.limitedBy,Y=b=>N?b/O:void 0;if(n.size===0){let b=m(B/O);return M(Y(B),b,p(b,new Map),Z,void 0)}for(let b=1;b<=sr;b++){let k=m(B/O),x=await l.walk(j(k));if(!Mr(x,n)){let F=p(k,R(x));return M(Y(B),k,F,Z,void 0,te)}let $=x.namingSelected.filter(F=>F.required&&s.find(G=>G.name===F.target)?.at.has(F.id)===!0&&!k.ids.get(F.target)?.has(F.id));if($.length>0){for(let{target:F,id:G}of $){let W=c.get(F)??new Set;c.set(F,W),W.add(G)}d=ar(s,c);continue}let L=p(k,R(x));if(z(L))return M(Y(B),k,L,Z,x);if(Z=K(L),!N)return M(void 0,k,L,Z,x,se(L));if(B===1)return M(Y(B),k,L,Z,x,{words:"the least it can be cut to, with the parents its records name, takes "+A(L),said:{why:"least",over:E(L)}});let X=Math.max((L.bytes+L.roomBytes)/Math.max(1,e.bytes),e.runRequests!==void 0?L.requests/Math.max(1,e.runRequests):0,r!==void 0?L.records/Math.max(1,r):0);B=Math.max(1,Math.min(B-1,Math.floor(B/X)))}let me=m(B/O),Be=p(me,f(me));return M(Y(B),me,Be,Z,void 0,{words:`could not fit in ${sr} rounds: fit by caps`,said:{why:"rounds"}})}function mr(l,e,t){let{selected:o}=l.scope,n=e.walk?.added??[],r=new Set([...o,...n]),s=new Map(e.walk?.parentIds??[]),i=new Map,a=new Map;for(let f of o){let R=e.kept.get(f)??[];s.set(f,R.map(w=>w.Id)),i.set(f,R.length),l.personAccounts.has(f)&&a.set(f,R.filter(w=>w[we]===!0).length)}for(let f of n)i.set(f,e.walk?.parentIds.get(f)?.length??0),l.personAccounts.has(f)&&a.set(f,e.walk?.personAccounts.get(f)??0);let c=new Map([...l.scope.leftEmpty,...e.walk?.leftEmpty??[]].filter(f=>r.has(f.objectApiName)&&!r.has(f.target)).map(f=>[`${f.objectApiName}.${f.fieldApiName}>${f.target}`,f])),{maxDepth:d,maxObjects:m,followedByDefault:u,currencies:p}=l.scope,g=u?.filter(f=>r.has(f.objectApiName)),y=p?.objects.filter(f=>r.has(f));return{...l,objectDescribes:new Map([...l.objectDescribes].filter(([f])=>r.has(f))),autoDiscoveredObjects:n,missingInTarget:l.missingInTarget.filter(f=>r.has(f)),recordCounts:i,totalObjectsScanned:r.size,parentIds:s,personAccounts:a,scope:{maxDepth:d,maxObjects:m,selected:o,parents:n.map(f=>({objectApiName:f,records:i.get(f)??0})),leftEmpty:[...c.values()],standardNeeded:l.scope.standardNeeded.filter(f=>r.has(f.objectApiName)),...g!==void 0&&g.length>0?{followedByDefault:g}:{},...p&&y!==void 0&&y.length>0?{currencies:{...p,objects:y}}:{},fitted:t}}}var nt=class{deps;eventListeners=[];runningExecutors=[];pendingSkips=new Set;constructor(e){this.deps=e}onEvent(e){return this.eventListeners.push(e),()=>{this.eventListeners=this.eventListeners.filter(t=>t!==e)}}emitEvent(e){for(let t of this.eventListeners)try{t(e)}catch{}}listObjects(e,t,o){return this.deps.schemaScanner.listObjects(e,t,o)}countObjects(e,t){return this.deps.schemaScanner.countObjects(e,t)}async scanSchemas(e,t,o,n){this.emitEvent({type:"scan-started",timestamp:new Date().toISOString()});let r=await this.deps.schemaScanner.scan(e,t,o.selectedObjects,o.includeStandardObjects,{...o.maxDepth!==void 0?{maxDepth:o.maxDepth}:{},...o.maxObjects!==void 0?{maxObjects:o.maxObjects}:{},...o.maxRecordsPerObject!==void 0&&o.maxRecordsPerObject>0?{maxRecordsPerObject:o.maxRecordsPerObject}:{},...n?{onProgress:n}:{}});return this.emitEvent({type:"scan-completed",timestamp:new Date().toISOString()}),r}buildGraph(e,t){let o=new Map;for(let[n,r]of e.objectDescribes){let s=r.fields.map(i=>({name:i.name,type:i.type,nillable:i.nillable,referenceTo:i.referenceTo,relationshipName:i.relationshipName}));o.set(n,{name:r.name,fields:s})}return this.deps.graphBuilder.build(o,e.recordCounts,t)}buildCompliance(e,t,o=[]){let n=this.deps.complianceEngine.buildProfile(e,Eo(o,t)),r=this.deps.complianceEngine.generateRules(n);return{profile:n,rules:r}}generatePlan(e,t,o,n){let r=Po(t,e.nodes.map(c=>c.objectApiName),o),s={...this.deps.complianceEngine.buildSummary(o),...r.length>0?{notCovered:r}:{}},i=this.deps.planGenerator.generate(e,t,s),a=n?{...i,scope:n}:i;return this.emitEvent({type:"plan-generated",timestamp:new Date().toISOString()}),a}async fitPlan(e,t){let{scan:o,graph:n,plan:r,rules:s,mode:i,budget:a,maxRecords:c,onProgress:d}=t,{schemaScanner:m}=this.deps,u=0,p={describe:O=>e.describe(O),describeGlobal:()=>e.describeGlobal(),query:O=>(u++,e.query(O)),...e.queryMore?{queryMore:O=>(u++,e.queryMore.call(e,O))}:{}},g=r.waves.map(O=>O.objects),y=new Map,f=g.flatMap(O=>Ue(O,n.edges).groups.filter(D=>D.length>1));for(let O of new Set(f.flat()))y.set(O,await t.describeLookups?.(O).catch(()=>null)??null);let R=fn(g,n.edges,O=>y.get(O)),{selected:w}=o.scope,C=lr(o.objectDescribes,w,R),v=ur(R,C),z=pr(t.automation,t.mutePlan,v),K=await m.readFitRows(p,o,d),E=await fr({order:R.filter(O=>w.includes(O)),rows:K,planned:o.recordCounts,lookups:C,parents:new Map(o.scope.parents.map(({objectApiName:O})=>{let D=o.personAccounts.get(O);return[O,{ids:o.parentIds.get(O)??[],...D!==void 0?{personAccounts:D}:{}}]})),budget:a,room:z,mode:i,...c!==void 0?{maxRecords:c}:{},walk:O=>m.walkFrom(p,o,O,d)}),A=z.unread!==void 0?{automationUnread:z.unread}:{},j={...E.report,requestsRead:u,...A,...t.mutePlan?{countedMuted:!0}:{},...c!==void 0?{maxTotal:c}:{}},M=new Map([...E.kept].map(([O,D])=>[O,D.map(S=>S.Id)])),te={heldBy:E.heldBy,report:j,keptIds:M,...A};if(E.cannotFit!==void 0)return{...te,cannotFit:E.cannotFit};if(E.heldBy==="whole")return te;let se=mr(o,E,j),T=this.buildGraph(se,t.batchSize);return{...te,fitted:{scan:se,graph:T,plan:this.generatePlan(T,r.complianceFramework,s,se.scope),run:dr(C,se.parentIds)}}}async executePlan(e,t,o,n,r,s,i,a){let c=Array.from(n.values()).reduce((R,w)=>R+w,0),d=this.isGrappeActive(c),m=`autopilot-${Date.now()}`;d&&this.deps.onGrappeEvent?.({type:"grappe:started",payload:{operationId:m,totalPartitions:e.waves.length,totalRecords:c}}),this.emitEvent({type:"execution-started",timestamp:new Date().toISOString()});let u=this.deps.createExecutor(),p=()=>{},g=r?u.on("node-completed",r):p,y=r?u.on("node-failed",r):p;for(let R of this.pendingSkips)u.skip(R);this.pendingSkips.clear(),this.runningExecutors.push(u);let f;try{f=await u.execute(e,t.edges,o,n,s,i,a)}finally{this.runningExecutors.splice(this.runningExecutors.indexOf(u),1),g(),y()}return this.emitEvent({type:"execution-completed",timestamp:new Date().toISOString()}),d&&this.deps.onGrappeEvent?.({type:"grappe:completed",payload:{operationId:m,totalProcessed:f.totalSuccess+f.totalSkipped,totalFailed:f.totalFailure}}),f}isGrappeActive(e){let t=this.deps.grappeConfig;return!!(t?.enabled&&this.deps.grappeAdapter&&e>=t.autoActivateThreshold)}generateReport(e,t,o,n,r,s){return this.deps.complianceEngine.generateReport(e,t,o,n,r,s)}latestRunningExecutor(){return this.runningExecutors[this.runningExecutors.length-1]}pause(){this.latestRunningExecutor()?.pause()}resume(){this.latestRunningExecutor()?.resume()}skip(e){let t=this.latestRunningExecutor();if(t){t.skip(e);return}this.pendingSkips.add(e)}};var ot=class{build(e,t,o=200){let n=this.extractEdges(e),r=Ir(n,new Set(e.keys())),s=this.tarjanSCC(Array.from(e.keys()),r),i=this.resolveCycles(s,r),{order:a,levels:c}=this.topologicalSort(Array.from(e.keys()),r,s),d=this.buildNodes(e,t,a,c,o),m=this.computeStats(d,n,i);return{nodes:d,edges:n,cycles:i,stats:m}}extractEdges(e){let t=[],o=new Set(e.keys());for(let[n,r]of e)for(let s of r.fields){if(s.type!=="reference"||s.referenceTo.length===0)continue;let i=s.referenceTo.filter(d=>o.has(d));if(i.length===0)continue;if(i.length>1){for(let d of i)t.push({from:d,to:n,fieldApiName:s.name,relationshipType:"polymorphic",required:!s.nillable});continue}let a=i[0],c;a===n?c="hierarchical":s.nillable?c="lookup":c="master_detail",t.push({from:a,to:n,fieldApiName:s.name,relationshipType:c,required:!s.nillable})}return t}tarjanSCC(e,t){let o=new Map;for(let s of e)o.set(s,[]);for(let s of t){let i=o.get(s.to);i&&i.push(s.from)}let n={index:0,stack:[],onStack:new Set,indices:new Map,lowLinks:new Map,sccs:[]},r=[...e].sort();for(let s of r)n.indices.has(s)||this.tarjanStrongConnect(s,o,n);return n.sccs}tarjanStrongConnect(e,t,o){o.indices.set(e,o.index),o.lowLinks.set(e,o.index),o.index++,o.stack.push(e),o.onStack.add(e);let n=t.get(e)??[];for(let r of n)if(o.indices.has(r)){if(o.onStack.has(r)){let s=o.lowLinks.get(e)??0,i=o.indices.get(r)??0;o.lowLinks.set(e,Math.min(s,i))}}else{this.tarjanStrongConnect(r,t,o);let s=o.lowLinks.get(e)??0,i=o.lowLinks.get(r)??0;o.lowLinks.set(e,Math.min(s,i))}if(o.lowLinks.get(e)===o.indices.get(e)){let r=[],s;do s=o.stack.pop(),o.onStack.delete(s),r.push(s);while(s!==e);o.sccs.push(r.sort())}}resolveCycles(e,t){let o=[],n=new Set;for(let r of t)r.from===r.to&&r.relationshipType==="hierarchical"&&n.add(r.from);for(let r of n)o.push({objects:[r],strategy:"two_pass",description:`Insert ${r} without self-lookup, update in 2nd pass`});for(let r of e){if(r.length<=1)continue;let s=new Set(r),i=t.filter(d=>s.has(d.from)&&s.has(d.to)&&d.from!==d.to),a,c;r.length===2&&i.some(m=>!m.required)?(a="nullable_lookup",c=`Insert ${r[0]} without ${r[1]} lookup, insert ${r[1]} with ${r[0]} lookup, update ${r[0]}`):(a="upsert_external_id",c="Decompose cycle into waves with upsert + external ID"),o.push({objects:[...r],strategy:a,description:c})}return o}topologicalSort(e,t,o){let n=new Map;for(let p=0;p<o.length;p++)for(let g of o[p])n.set(g,p);let r=o.length,s=new Map;for(let p=0;p<r;p++)s.set(p,new Set);for(let p of t){let g=n.get(p.from),y=n.get(p.to);g!==void 0&&y!==void 0&&g!==y&&s.get(y).add(g)}let i=new Map;for(let[p,g]of s)i.set(p,new Set(g));let a=[],c=new Map;for(;i.size>0;){let p=[];for(let[g,y]of i)y.size===0&&p.push(g);if(p.length===0){for(let g of i.keys())a.push(g),c.has(g)||c.set(g,0);break}p.sort((g,y)=>g-y);for(let g of p){a.push(g);let y=s.get(g)??new Set,f=-1;for(let R of y)f=Math.max(f,c.get(R)??0);c.set(g,y.size===0?0:f+1),i.delete(g);for(let R of i.values())R.delete(g)}}let d=new Map,m=new Map,u=0;for(let p of a){let g=o[p],y=c.get(p)??0,f=[...g].sort();for(let R of f)d.set(R,u),m.set(R,y),u++}for(let p of e)d.has(p)||(d.set(p,u),m.set(p,0),u++);return{order:d,levels:m}}buildNodes(e,t,o,n,r){let s=[];for(let i of e.keys()){let a=t.get(i)??0;s.push({objectApiName:i,recordCount:a,estimatedApiCalls:a===0?0:Math.ceil(a/r),piiFields:[],anonymizationRules:[],status:"pending",progress:0,insertOrder:o.get(i)??0,level:n.get(i)??0,successCount:0,failureCount:0,errors:[],elapsedMs:0,apiCallsUsed:0})}return s.sort((i,a)=>i.insertOrder-a.insertOrder),s}computeStats(e,t,o){return{totalObjects:e.length,totalRelationships:t.length,cycleCount:o.length,maxDepth:Math.max(0,...e.map(n=>n.level)),totalRecords:e.reduce((n,r)=>n+r.recordCount,0),totalEstimatedApiCalls:e.reduce((n,r)=>n+r.estimatedApiCalls,0)}}};function Ir(l,e){let t=wn(e);return t.length===0?[...l]:[...l.filter(o=>!(o.to===oe&&o.fieldApiName==="ActivityId")),...t.map(o=>({from:o.sourceObject,to:o.targetObject,fieldApiName:o.relationshipName,relationshipType:"lookup",required:!0}))]}import{createHash as xr,randomUUID as Fr}from"node:crypto";var jr=["fake","mask","hash","nullify","redact","shuffle","truncate","preserve_format","age_band","generalize"],rt=class{builtInRules;constructor(){this.builtInRules=new Map,this.builtInRules.set("gdpr",this.buildGDPRRules()),this.builtInRules.set("ccpa",this.buildCCPARules()),this.builtInRules.set("hipaa",this.buildHIPAARules()),this.builtInRules.set("pci_dss",this.buildPCIDSSRules())}buildProfile(e,t,o=[]){let n=this.builtInRules.get(e)??[];return{framework:e,rules:n,autoDetectedPII:t,userOverrides:o,auditRequired:e!=="none"&&e!=="custom"}}generateRules(e){if(e.framework==="none")return[];let t=new Map;for(let n of e.userOverrides){let r=`${n.objectApiName}.${n.fieldApiName}`;t.set(r,n)}let o=[];for(let n of e.autoDetectedPII){let r=`${n.objectApiName}.${n.fieldApiName}`,s=t.get(r);if(s){if(s.method==="skip")continue;o.push({objectApiName:n.objectApiName,fieldApiName:n.fieldApiName,method:s.method,piiCategory:n.piiCategory,aiConfidence:n.confidence,userOverridden:!0,fieldType:n.fieldType});continue}let i=this.findMatchingRule(e.rules,n.piiCategory),a=i&&i.requiredMethod!=="any"?i.requiredMethod:n.suggestedMethod;o.push({objectApiName:n.objectApiName,fieldApiName:n.fieldApiName,method:a,piiCategory:n.piiCategory,aiConfidence:n.confidence,userOverridden:!1,fieldType:n.fieldType})}return o}buildSummary(e){let t={};for(let n of jr)t[n]=0;for(let n of e)t[n.method]++;let o=[...new Set(e.map(n=>n.objectApiName))];return{totalPiiFields:e.length,totalFieldsToAnonymize:e.length,methodBreakdown:t,objectsWithPii:o}}generateReport(e,t,o,n,r,s){let i=new Set(e.userOverrides.map(y=>`${y.objectApiName}.${y.fieldApiName}`)),a=t.map(y=>{let f=this.findMatchingRule(e.rules,y.piiCategory),R=f?f.id:"custom",w=o.get(y.objectApiName)??0,C=`${y.objectApiName}.${y.fieldApiName}`;return{objectApiName:y.objectApiName,fieldApiName:y.fieldApiName,piiCategory:y.piiCategory,anonymizationMethod:y.method,recordsAnonymized:w,ruleApplied:R,userOverridden:i.has(C)||y.userOverridden}}),c=this.buildObjectSummaries(t,o,e),d=this.computeOverallStatus(c),m=new Date().toISOString(),u=Fr(),p=JSON.stringify(a),g=xr("sha256").update(p).digest("hex");return{id:u,framework:e.framework,generatedAt:m,sourceOrgId:n,targetOrgId:r,totalFieldsScanned:s,piiFieldsDetected:e.autoDetectedPII.length,piiFieldsAnonymized:t.length,entries:a,objectSummaries:c,overallStatus:d,checksumSha256:g}}findMatchingRule(e,t){return e.find(o=>o.targetPiiCategories.includes(t))}buildObjectSummaries(e,t,o){let n=new Set;for(let s of e)n.add(s.objectApiName);for(let s of o.autoDetectedPII)n.add(s.objectApiName);let r=[];for(let s of n){let i=e.filter(p=>p.objectApiName===s),a=o.autoDetectedPII.filter(p=>p.objectApiName===s),c=[...new Set(i.map(p=>p.method))],d=t.get(s)??0,m=a.length>0&&a.every(p=>i.some(g=>g.fieldApiName===p.fieldApiName)),u=a.length===0||m?"pass":i.length>0?"partial":"fail";r.push({objectApiName:s,recordCount:d,piiFieldCount:a.length,anonymizationMethods:c,status:u})}return r}computeOverallStatus(e){return e.length===0||e.every(n=>n.status==="pass")?"pass":e.every(n=>n.status==="fail")?"fail":"partial"}buildGDPRRules(){return[{id:"gdpr-01",framework:"gdpr",category:"data_minimization",description:"Anonymize personal identifiers (name, email, phone, address)",targetPiiCategories:["PII"],requiredMethod:"fake",articleReference:"GDPR Art. 25"},{id:"gdpr-02",framework:"gdpr",category:"data_protection",description:"Hash sensitive identifiers for pseudonymization",targetPiiCategories:["SENSITIVE"],requiredMethod:"hash",articleReference:"GDPR Art. 32"},{id:"gdpr-03",framework:"gdpr",category:"health_data",description:"Nullify health-related data",targetPiiCategories:["PHI"],requiredMethod:"nullify",articleReference:"GDPR Art. 9"},{id:"gdpr-04",framework:"gdpr",category:"financial_data",description:"Mask payment card data",targetPiiCategories:["PCI"],requiredMethod:"mask",articleReference:"GDPR Art. 32"}]}buildCCPARules(){return[{id:"ccpa-01",framework:"ccpa",category:"personal_info",description:"Anonymize personal information (name, email, phone)",targetPiiCategories:["PII"],requiredMethod:"fake"},{id:"ccpa-02",framework:"ccpa",category:"commercial_info",description:"Mask commercial and financial data",targetPiiCategories:["PCI","SENSITIVE"],requiredMethod:"mask"},{id:"ccpa-03",framework:"ccpa",category:"biometric",description:"Nullify biometric and health data",targetPiiCategories:["PHI"],requiredMethod:"nullify"}]}buildHIPAARules(){return[{id:"hipaa-01",framework:"hipaa",category:"safe_harbor",description:"Anonymize patient identifiers (name, address, phone)",targetPiiCategories:["PII","PHI"],requiredMethod:"fake",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"},{id:"hipaa-02",framework:"hipaa",category:"safe_harbor_dates",description:"Generalize dates to year only",targetPiiCategories:["SENSITIVE"],requiredMethod:"age_band",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"},{id:"hipaa-03",framework:"hipaa",category:"safe_harbor_ids",description:"Hash medical record numbers and SSNs",targetPiiCategories:["PHI"],requiredMethod:"hash",articleReference:"HIPAA Safe Harbor \xA7164.514(b)"}]}buildPCIDSSRules(){return[{id:"pci-01",framework:"pci_dss",category:"card_data",description:"Mask PAN to show only last 4 digits",targetPiiCategories:["PCI"],requiredMethod:"mask",articleReference:"PCI-DSS Requirement 3.3"},{id:"pci-02",framework:"pci_dss",category:"auth_data",description:"Nullify CVV, expiration, and magnetic strip data",targetPiiCategories:["PCI"],requiredMethod:"nullify",articleReference:"PCI-DSS Requirement 3.2"},{id:"pci-03",framework:"pci_dss",category:"cardholder",description:"Anonymize cardholder personal data",targetPiiCategories:["PII"],requiredMethod:"fake",articleReference:"PCI-DSS Requirement 3.4"}]}};var st=class{avgSecondsPerApiCall;batchSize;constructor(e){this.avgSecondsPerApiCall=e?.avgSecondsPerApiCall??.5,this.batchSize=e?.batchSize??200}getBatchSize(){return this.batchSize}generate(e,t,o){let n=this.buildWaves(e),r=e.stats.totalRecords,s=e.stats.totalEstimatedApiCalls,i=this.estimateDuration(n,e);return{waves:n,totalRecords:r,estimatedDurationSec:i,estimatedApiCalls:s,complianceFramework:t,anonymizationSummary:o,cycleResolutions:e.cycles}}buildWaves(e){if(e.nodes.length===0)return[];let t=[...e.nodes].sort((i,a)=>i.insertOrder-a.insertOrder),o=new Map;for(let i of t){let a=o.get(i.level);a?a.push(i.objectApiName):o.set(i.level,[i.objectApiName])}let n=[...o.keys()].sort((i,a)=>i-a),r=new Map;for(let i=0;i<n.length;i++){let a=n[i],c=o.get(a);if(c)for(let d of c)r.set(d,i)}let s=[];for(let i=0;i<n.length;i++){let a=n[i],c=o.get(a)??[],d=new Set;for(let u of c)for(let p of e.edges)if(p.to===u){let g=r.get(p.from);g!==void 0&&g<i&&d.add(g)}let m=[...d].sort((u,p)=>u-p);s.push({order:i,objects:c,dependsOn:m})}return s}estimateDuration(e,t){let o=new Map;for(let s of t.nodes)o.set(s.objectApiName,s.estimatedApiCalls);let n=new Map;t.cycles.forEach((s,i)=>{for(let a of s.objects)n.set(a,i)});let r=0;for(let s of e){let i=new Map;for(let a of s.objects){let c=n.get(a),d=c===void 0?`object:${a}`:`cycle:${c}`;i.set(d,(i.get(d)??0)+(o.get(a)??0))}r+=Math.max(0,...i.values())*this.avgSecondsPerApiCall}return r}};var De=class{idMaps=new Map;registerMappings(e,t){let o=this.idMaps.get(e);o||(o=new Map,this.idMaps.set(e,o));for(let[n,r]of t)o.set(n,r)}remapRecords(e,t,o){let n=t.filter(c=>c.to===o),r=0,s=0,i=0,a=[];for(let[c,d]of e.entries()){let m=new Set,u=new Map;for(let p of n){let g=d[p.fieldApiName];if(g==null||g===""){i++;continue}if(typeof g!="string"){i++;continue}let f=this.idMaps.get(p.from)?.get(g);if(f!==void 0)d[p.fieldApiName]=f,m.add(p.fieldApiName),r++;else{let R=u.get(p.fieldApiName);R?R.parents.push(p.from):u.set(p.fieldApiName,{sourceId:g,parents:[p.from]}),s++}}for(let[p,{sourceId:g,parents:y}]of u)m.has(p)||(d[p]=null,a.push({index:c,fieldApiName:p,sourceId:g,parents:y}))}return{remapped:r,missing:s,skipped:i,unresolved:a}}getTargetId(e,t){return this.idMaps.get(e)?.get(t)}hasObject(e){return this.idMaps.has(e)}getMappingCount(e){return this.idMaps.get(e)?.size??0}get totalMappings(){let e=0;for(let t of this.idMaps.values())e+=t.size;return e}clear(){this.idMaps.clear()}};var Nr=/^[A-Za-z0-9]{15}(?:[A-Za-z0-9]{3})?$/;function Ar(l,e,t){let o=en(l);if(e!==void 0&&!Nr.test(e))throw new Error(`Not a record id to read after: "${e}".`);let n=e===void 0?"":` WHERE Id > '${e}'`;return`SELECT FIELDS(ALL) FROM ${o}${n} ORDER BY Id LIMIT ${Math.trunc(t)}`}var Lr={statusCode:Ye,message:"No result returned for the record",fields:[]},Dr={statusCode:Ye,message:"Refused without a reason",fields:[]},hr="PARENT_REFUSED",gr="PARENT_NOT_WRITTEN",Yt="CUT_WITH_PARENT",yr={skipped:l=>`${l} was skipped in this run`,failed:l=>`the run's write of ${l} failed`},$r="PERSON_ACCOUNT_NOT_WRITTEN",Br="PERSON_CONTACT_NOT_LOOKED_UP",_r=`SELECT Id FROM RecordType WHERE SobjectType = '${ce}' AND IsPersonType = true`;function de(l){return l.slice(0,15)}var Re=class{byReason=new Map;add(e){let t=new Set;for(let o of e){let n=`${o.statusCode}\0${o.fields.join(",")}`;if(t.has(n))continue;t.add(n);let r=this.byReason.get(n);this.byReason.set(n,r?{...r,count:r.count+1}:{statusCode:o.statusCode,fields:[...o.fields],count:1,message:o.message})}}addCounted(e){let t=`${e.statusCode}\0${e.fields.join(",")}`,o=this.byReason.get(t);this.byReason.set(t,o?{...o,count:o.count+e.count}:e)}list(){return[...this.byReason.values()].sort((e,t)=>t.count-e.count)}};function qr(l,e){let[t,...o]=l.errors,[n,...r]=l.errorDetails??[];return{...l,...t===void 0?{}:{errors:[Tt(t,e),...o]},...n===void 0?{}:{errorDetails:[{...n,message:Tt(n.message,e)},...r]}}}function wr(){return{written:0,linked:0,failed:0,errors:[],refusals:new Re,apiCallsUsed:0,defaulted:new Map,cutSinceFit:0,heldForRecordType:new Map,sentAgainForALock:{rows:0,written:0,stillLocked:0}}}function zr(l){return{statusCode:qn,fields:["RecordTypeId"],count:l.recordCount,message:Un(l)}}function Gr(l,e){return{objectApiName:l,rows:e.rows,why:{...e.why},...e.predicted?{predicted:e.predicted}:{},...e.readBack?{readBack:e.readBack}:{}}}function br(l){let e=0;for(let[t,o]of l)Ft(t)&&(e+=o);return e}function Ur(l){let e=new Map;for(let t of l.holds)e.set(t.objectApiName,[...e.get(t.objectApiName)??[],t]);return{holds:e,kept:new Map([...l.kept].map(([t,o])=>[t,new Set(o.map(de))])),stayedOut:new Map}}var $e=class extends Co{deps;batchSize;paused=!1;pausePromise=null;pauseResolve=null;skippedObjects=new Set;signal;contactPoints;creatableByObject=new Map;currencies;currencyChanges=new Bn;pricesSettled=new Map;currencyChangesByWrittenId=new Map;keyPrefixByObject=new Map;lifecycleByObject=new Map;standardPricebook;deferredStatuses=[];lookupsByObject=new Map;recordTypeMappings;targetRecordTypes=[];planned=new Set;parentIds=new Map;owedLookups=[];unmappedRecordTypes=new Set;leftToThePlatform=new gn;taskOfEmail=new Map;emailsAfterTheirTask=[];taskTurnOver=!1;emailsHeldAndNotSent=0;leftByStop=new Map;lookupsLeftEmpty=new Map;refusedRecords=new Map;notWritten=new Map;reached=new Set;personTypes;personContactsLinked=0;recordTypesGiven=new Map;recordTypesUnderTheLease=new Map;givenRules=new Map;lease;fit;async creatableFieldsOf(e){if(!this.deps.describeCreateableFields)return null;let t=this.creatableByObject.get(e);if(t!==void 0)return t;try{let o=await this.deps.describeCreateableFields(e),n=o.size>0?o:null;return this.creatableByObject.set(e,n),n}catch{return this.creatableByObject.set(e,null),null}}lookupsOf(e){let t=this.deps.describeLookups;if(!t)return Promise.resolve(null);let o=this.lookupsByObject.get(e);return o||(o=t(e).catch(()=>null),this.lookupsByObject.set(e,o)),o}keyPrefixOf(e){let t=this.deps.describeKeyPrefix;if(!t)return Promise.resolve(void 0);let o=this.keyPrefixByObject.get(e);return o||(o=t(e).catch(()=>{}),this.keyPrefixByObject.set(e,o)),o}constructor(e){super(),this.deps=e,this.batchSize=e.batchSize??200}async recordTypesHeldBack(e){let{describeRecordTypes:t,countRecordTypes:o}=this.deps;if(!t||!o)return[];let n=await this.creatableFieldsOf(e);if(n&&!n.has("RecordTypeId"))return[];try{let r=await t(e);if(!r.some(i=>!i.available&&!i.master))return[];let s=this.inTargetRecordTypes(await o(e));return zn(e,s,kt(r,this.targetRecordTypes))}catch{return[]}}inTargetRecordTypes(e){let t=new Map;for(let[o,n]of e){if(o===null)continue;let r=this.targetRecordTypeOf(o);t.set(r,(t.get(r)??0)+n)}return t}targetRecordTypeOf(e){return this.recordTypeMappings?.find(t=>t.sourceId===e)?.targetId??e}async recordTypesGivenOf(e,t,o=new Map,n=[]){await this.mapRecordTypes(e);let r=new Map;for(let s of new Set(e.waves.flatMap(i=>i.objects))){let i=t.get(s)??0;if(i===0)continue;let a=await this.givenRuleOf(s);if(!a)continue;let c=await this.creatableFieldsOf(s),d,m="masterInSource";if(c&&!c.has("RecordTypeId"))d=i,m="notRead";else{let u=await this.onMasterInSource(s,o.get(s));if(u===void 0)continue;d=n.find(g=>g.objectApiName===s)?Math.min(u,i):u}d!==0&&r.set(s,{objectApiName:s,rows:d,why:{[m]:d},...a.predicted?{predicted:a.predicted}:{}})}return r}async onMasterInSource(e,t){try{if(t===void 0){let r=this.deps.countRecordTypes;return r?br(await r(e)):void 0}let o=this.deps.querySource;if(!o)return;let n=0;for(let r=0;r<t.length;r+=ke){let s=await o(Nt(e,t.slice(r,r+ke)));n+=br(Ke(s))}return n}catch{return}}givenRuleOf(e){let t=this.givenRules.get(e);return t||(t=(async()=>{let o=this.recordTypesUnderTheLease.get(e)??await this.deps.describeRecordTypes?.(e).catch(()=>{});if(!o?.some(s=>!s.master))return;let n=kt(o,this.targetRecordTypes),r=$o(Do(n));return{types:n,...r?{predicted:r}:{}}})(),this.givenRules.set(e,t)),t}async readAgainUnderTheLease(e,t){let o=this.deps.describeRecordTypesAgain;if(!o||!this.lease||this.lease.assigned===0)return;let n=[...new Set(e.waves.flatMap(r=>r.objects))].filter(r=>(t.get(r)??0)>0);await Promise.all(n.map(async r=>{if((await this.deps.describeRecordTypes?.(r).catch(()=>{}))?.some(i=>!i.master))try{this.recordTypesUnderTheLease.set(r,await o(r))}catch{}}))}countCreatedWithoutRecordType(e,t,o,n){let r=this.recordTypesGiven.get(e);r||(r={...t,rows:0,why:{},ids:[]},this.recordTypesGiven.set(e,r)),r.rows++,r.why[o]=(r.why[o]??0)+1,n&&r.ids.length<Bo&&r.ids.push(n)}async afterTheWrites(e){await this.giveTheLeaseBack(),await this.readBackRecordTypes();for(let[t,o]of this.recordTypesGiven){let n=e[t];n&&(e[t]={...n,recordTypeGiven:Gr(t,o)})}}async giveTheLeaseBack(){let e=this.lease;if(e){this.lease=void 0;try{await e.giveBack()}catch(t){ae.warn(`[autopilot] the mute's lease was not given back as the writes ended: ${ee(t)}`)}}}async readBackRecordTypes(){let e=this.deps.queryTarget;e&&await Promise.all([...this.recordTypesGiven].map(async([t,o])=>{if(o.ids.length!==0)try{let n=await e(Nt(t,o.ids));o.readBack=_o(n,o.types)}catch(n){o.readBack={read:0,types:[],unread:ee(n)}}}))}holdOnClosedRecordTypes(e,t,o){let n=o.closedRecordTypes;if(!n)return t;let r=[];for(let s of t){let i=s.RecordTypeId,a=e===fe&&Pe(s),c=typeof i=="string"&&i.length>=15&&!a?n.get(de(this.targetRecordTypeOf(i))):void 0;if(!c){r.push(s);continue}o.failed++;let d=o.heldForRecordType.get(c.recordTypeId);o.heldForRecordType.set(c.recordTypeId,{...c,recordCount:(d?.recordCount??0)+1});let m=s.Id;typeof m=="string"&&m!==""&&this.refusedRecords.set(de(m),e)}return r}async mapRecordTypes(e){let{querySource:t,queryTarget:o}=this.deps;if(!t||!o)return;let n=[...new Set(e.waves.flatMap(s=>s.objects))];if(n.length===0)return;let r=`${xo} AND SobjectType IN (${n.map(s=>`'${ge(s)}'`).join(", ")})`;try{let[s,i]=await Promise.all([t(r),o(r)]),a=xt(s);this.targetRecordTypes=xt(i),this.recordTypeMappings=new jt().buildMapping(a,this.targetRecordTypes);for(let c of No(a,this.targetRecordTypes))ae.warn(`[autopilot] ${Lo(c)}`)}catch(s){ae.warn("Autopilot could not match the record types of the two orgs",{error:ee(s)})}}async matchStandardPricebooks(e){let{querySource:t,queryTarget:o}=this.deps;if(!t||!o)return;let n=new Set(e.waves.flatMap(r=>r.objects));if(!(!n.has(Ae)&&!n.has(Oe)))try{let[r,s]=await Promise.all([t(ve),o(ve)]),i=r[0]?.Id,a=s[0]?.Id;if(typeof i!="string"||typeof a!="string")return;this.standardPricebook={source:i,target:a},this.deps.remapper.registerMappings(Ae,[[i,a]])}catch(r){ae.warn("Autopilot could not match the standard price books",{error:ee(r)})}}async execute(e,t,o,n,r,s=new Map,i={}){if(!this.deps.queryByIds&&[...s.values()].some(f=>f.length>0))throw new Error("This plan reads the parents its objects reference by id, and the run has no read by id.");this.parentIds=s,this.contactPoints=i.keepContactPoints===!0?void 0:new Mo,this.lease=i.lease,this.fit=i.fit?Ur(i.fit):void 0;let a=Date.now();this.signal=r;let c=()=>this.pauseResolve?.();r?.addEventListener("abort",c,{once:!0});let d={},m={},u={totalSuccess:0,totalFailure:0,totalSkipped:0,totalLinked:0,elapsedMs:0,completedObjects:[],failedObjects:[],skippedObjects:[],nodeErrors:d,objectOutcomes:m},p=[];this.emit("execution-started",this.makeEvent({type:"execution-started",timestamp:""}));let g=async f=>{await y(f),f===We&&await this.writeEmailsAfterTheirTask(t,u)},y=async f=>{if(this.skippedObjects.has(f)){let w=n.get(f)??0;u.skippedObjects.push(f),u.totalSkipped+=w,this.notWritten.set(f,"skipped");return}this.reached.add(f);let R=n.get(f)??0;if(await this.checkPause()){p.push(f),m[f]={written:0,linked:0,failed:0,refusals:[],...R>0?{notSent:R}:{}};return}try{let w=await this.executeObject(f,t,o,R);u.totalSuccess+=w.success,u.totalFailure+=w.failure,u.totalLinked=(u.totalLinked??0)+w.linked,w.cutSinceFit>0&&(u.cutSinceFit=(u.cutSinceFit??0)+w.cutSinceFit);let C=this.leftToThePlatform.counts(f);if(m[f]={written:w.success,linked:w.linked,failed:w.failure,refusals:w.refusals,...w.leftToDefault.length>0?{leftToDefault:w.leftToDefault}:{},...C.length>0?{leftToThePlatform:C}:{},...w.notSent!==void 0&&w.notSent>0?{notSent:w.notSent}:{},...this.currenciesReplacedOf(f),...this.pricesSettledOf(f),...f===fe&&this.personContactsLinked>0?{withTheirPersonAccount:this.personContactsLinked}:{},...w.cutSinceFit>0?{cutSinceFit:w.cutSinceFit}:{},...w.threw!==void 0?{threw:w.threw}:{},...w.sentAgainForALock.rows>0?{sentAgainForALock:w.sentAgainForALock}:{}},w.notSent!==void 0){p.push(f);return}let{threw:v}=w;if(v!==void 0||w.errors.length>0&&w.success+w.linked===0){u.failedObjects.push(f),v!==void 0&&this.notWritten.set(f,"failed");let z=v!==void 0?[v,...w.errors]:w.errors;d[f]=z[0],this.emit("node-failed",this.makeEvent({type:"node-failed",timestamp:"",objectApiName:f,errors:z,partialSuccessCount:w.success,failureCount:w.failure,linkedCount:w.linked,refusals:w.refusals}))}else u.completedObjects.push(f),this.emit("node-completed",this.makeEvent({type:"node-completed",timestamp:"",objectApiName:f,successCount:w.success,failureCount:w.failure,linkedCount:w.linked,refusals:w.refusals,elapsedMs:w.elapsedMs,apiCallsUsed:w.apiCallsUsed}))}catch(w){u.failedObjects.push(f),this.notWritten.set(f,"failed");let C=ee(w);d[f]=C,this.emit("node-failed",this.makeEvent({type:"node-failed",timestamp:"",objectApiName:f,errors:[C],partialSuccessCount:0,failureCount:0,linkedCount:0,refusals:[]}))}};try{await this.matchStandardPricebooks(e),await this.mapRecordTypes(e),await this.readAgainUnderTheLease(e,n),this.planned=new Set(e.waves.flatMap(w=>w.objects));let f={};for(let w of e.waves){if(await this.writeWave(w.objects,t,g),this.stopped())break;await this.fillOwedLookups(f),this.emit("wave-completed",this.makeEvent({type:"wave-completed",timestamp:""}))}if(this.stopped()){let w=new Set([...u.completedObjects,...u.failedObjects,...u.skippedObjects,...p]);for(let C of e.waves.flatMap(v=>v.objects)){if(w.has(C))continue;let v=n.get(C)??0;p.push(C),m[C]={written:0,linked:0,failed:0,refusals:[],...v>0?{notSent:v}:{}}}return u.stopped=!0,u.stoppedObjects=p,this.countEmailsTheStopHeld(u,p,m),this.countWhatTheStopLeft(p,m),await this.sayLookupsLeftOwed(t,f),Object.keys(f).length>0&&(u.lookups=f),await this.afterTheWrites(m),this.reportContactPoints(u),u.elapsedMs=Date.now()-a,u}this.emailsAfterTheirTask.length>0&&(await this.writeEmailsAfterTheirTask(t,u),await this.fillOwedLookups(f)),await this.sayLookupsLeftOwed(t,f);let R=await this.applyDeferredStatuses();return Object.keys(R).length>0&&(u.statuses=R),Object.keys(f).length>0&&(u.lookups=f),await this.afterTheWrites(m),this.stopped()&&(u.stopped=!0,u.stoppedObjects=p,this.countEmailsTheStopHeld(u,p,m),this.countWhatTheStopLeft(p,m)),this.reportContactPoints(u),u.elapsedMs=Date.now()-a,this.emit("execution-completed",this.makeEvent({type:"execution-completed",timestamp:""})),u}catch(f){throw u.elapsedMs=Date.now()-a,u.fatalError=ee(f),ae.error("Autopilot execution crashed",{error:u.fatalError}),this.emit("execution-failed",this.makeEvent({type:"execution-failed",timestamp:"",error:u.fatalError})),f}finally{r?.removeEventListener("abort",c),await this.giveTheLeaseBack()}}async writeWave(e,t,o){let{within:n,deps:r,groups:s}=Ue(e,t),i=new Map;s.forEach((m,u)=>m.forEach(p=>i.set(p,u)));let a=[];for(let[m,u]of s.entries()){let p=new Set;for(let g of u)for(let y of r.get(g)??[]){let f=i.get(y);f!==void 0&&f!==m&&p.add(a[f])}a.push((async()=>{await Promise.all(p);let g=u.length>1?un(u,await this.setAtInsert(u,n)):u;for(let y of g)await o(y)})())}let d=(await Promise.allSettled(a)).find(m=>m.status==="rejected");if(d)throw d.reason}async setAtInsert(e,t){let o=new Set(e),n=new Map;for(let r of t)!o.has(r.to)||!o.has(r.from)||n.has(r.to)||n.set(r.to,await this.lookupsOf(r.to));return pn(e,t,r=>n.get(r))}async fillOwedLookups(e){let t=this.owedLookups.splice(0,this.owedLookups.length),{update:o}=this.deps;if(!o||t.length===0)return;let n=new Io;for(let r of t){let s=r.parents.map(i=>this.deps.remapper.getTargetId(i,r.sourceId)).find(i=>i!==void 0);if(!s){this.owedLookups.push(r);continue}n.add({objectApiName:r.objectApiName,recordId:r.recordId,fieldName:r.fieldApiName,value:s})}for(let[r,s]of n.updates()){let i=e[r],a=i?.filled??0,c=new Re;for(let d of i?.refusals??[])c.addCounted(d);for(let d=0;d<s.length;d+=this.batchSize){if(await this.checkPause()){this.noteLeftByStop(r,"lookups",s.slice(d).map(p=>String(p.Id)));break}let m=s.slice(d,d+this.batchSize),u=await Ht(o,r,m);m.forEach((p,g)=>{let y=u[g];if(y?.success){a++;return}let f=Object.keys(p).filter(R=>R!=="Id");c.add(Kt(y).map(R=>({...R,fields:f}))),this.noteLookupLeftEmpty(r,String(p.Id))})}e[r]=this.lookupOutcome(r,a,c)}}noteLookupLeftEmpty(e,t){let o=this.lookupsLeftEmpty.get(e);o||(o=new Set,this.lookupsLeftEmpty.set(e,o)),o.add(t)}lookupOutcome(e,t,o){let n=this.lookupsLeftEmpty.get(e)?.size??0;return{filled:t,refusals:o.list(),...n>0?{leftEmpty:n}:{}}}async sayLookupsLeftOwed(e,t){let o=new Map;for(let n of this.owedLookups.splice(0,this.owedLookups.length)){let r=await this.whyLeftOwed(n,e);if(!r)continue;let s=o.get(n.objectApiName);if(!s){s=new Re;for(let i of t[n.objectApiName]?.refusals??[])s.addCounted(i);o.set(n.objectApiName,s)}s.add([{...r,fields:[n.fieldApiName]}]),this.noteLookupLeftEmpty(n.objectApiName,n.recordId)}for(let[n,r]of o){let s=t[n]?.filled??0;t[n]=this.lookupOutcome(n,s,r)}}async whyLeftOwed(e,t){let{fieldApiName:o,sourceId:n}=e,r=this.refusedRecords.get(de(n)),s=e.parents.find(c=>c===r);if(s)return{statusCode:hr,message:`the ${s} record its ${o} names was refused in this run, and this record, written before it, keeps its ${o} empty.`};let i=this.fit?.stayedOut.get(de(n)),a=e.parents.find(c=>c===i);if(a)return{statusCode:Yt,message:`the ${a} record its ${o} names stayed out with a record the fit cut, and this record, written before it, keeps its ${o} empty.`};for(let c of e.parents){let d=this.notWrittenOf(c);if(d===void 0)continue;let m=t.find(u=>u.from===c&&u.to===e.objectApiName&&u.fieldApiName===o);if(!(m&&!await this.namesARecordOf(e.objectApiName,m,n,e.parents.length)))return{statusCode:gr,message:`the ${c} record its ${o} names was not written: ${yr[d](c)}, and this record, written before it, keeps its ${o} empty.`}}}async executeObject(e,t,o,n){let r=Date.now(),s=wr(),i=()=>{let a=[...s.heldForRecordType.values()];return{success:s.written,linked:s.linked,failure:s.failed,errors:[...a.map(Wn),...s.errors],refusals:[...s.refusals.list(),...a.map(zr)].sort((c,d)=>d.count-c.count),apiCallsUsed:s.apiCallsUsed,elapsedMs:Date.now()-r,leftToDefault:[...s.defaulted].map(([c,d])=>({field:c,count:d})),...s.notSent!==void 0?{notSent:s.notSent}:{},cutSinceFit:s.cutSinceFit,sentAgainForALock:s.sentAgainForALock}};try{return await this.writeEveryPage(e,t,o,n,s,i)}catch(a){return{...i(),threw:ee(a)}}}async writeEveryPage(e,t,o,n,r,s){let i=n>0?await this.recordTypesHeldBack(e):[];i.length>0&&(r.closedRecordTypes=new Map(i.map(u=>[de(u.recordTypeId),u])));let a=u=>{let p=Math.min(u,n);this.emit("node-progress",this.makeEvent({type:"node-progress",timestamp:"",objectApiName:e,progress:n>0?Math.round(p/n*100):100,recordsProcessed:p,recordsTotal:n,apiCallsUsed:r.apiCallsUsed}))},c=0,d,m=this.standardPricebook;if(Vt(e)&&m){let u=[];for(;c<n;){if(await this.checkPause())return r.notSent=n,s();let{rows:v,advance:z,next:K,last:E}=await this.readPage(e,c,d);if(r.apiCallsUsed++,z===0)break;c+=z,d=K;let A=this.leaveToThePlatform(e,v,t);if(this.deps.anonymizer.anonymize(A,o,e),await this.neutralizeContactPoints(e,A),u.push(...A),E)break}let p=await this.pricesInOneCurrencyEach(u,m.source),{standard:g,custom:y}=ut(p.rows,m.source),f=ut(u.filter(v=>p.standsFor.has(String(v.Id))),m.source);p.said.length>0&&this.pricesSettled.set(e,Go(p.said));let R=0,w=0,C=async v=>{for(let z=0;z<v.length;z+=this.batchSize){if(await this.checkPause())return r.notSent=u.length-R-w,!1;let K=v.slice(z,z+this.batchSize);await this.writeBatch(e,K,t,r),R+=K.length,a(R+w)}return!0};for(let[v,z]of[[g,f.standard],[y,f.custom]]){if(!await C(v))return s();let K=this.linkWhatStoodIn(z,p.standsFor,r);if(w+=z.length-K.length,!await C(K))return s()}return s()}for(;c<n;){if(await this.checkPause()){r.notSent=n-c;break}let{rows:u,advance:p,next:g,last:y}=await this.readPage(e,c,d);if(r.apiCallsUsed++,p===0)break;d=g;let f=this.leaveToThePlatform(e,u,t);if(this.deps.anonymizer.anonymize(f,o,e),await this.neutralizeContactPoints(e,f),await this.writeBatch(e,f,t,r),c+=p,a(c),y)break}return s()}async neutralizeContactPoints(e,t){let{contactPoints:o}=this,n=this.deps.describeFields;if(!o||!n||t.length===0)return;let r=await n(e).catch(()=>{});if(!r)return;let s=o.forObject(e,r);if(s)for(let i of t)s(i)}reportContactPoints(e){this.contactPoints&&(e.contactPoints=this.contactPoints.report())}async readPage(e,t,o){let n=this.parentIds.get(e);if(n&&this.deps.queryByIds){let i=n.slice(t,t+Math.min(this.batchSize,ke));return i.length===0?{rows:[],advance:0,next:o,last:!0}:{rows:await this.deps.queryByIds(e,i),advance:i.length,next:o,last:!1}}let r=await this.deps.query(e,o,this.batchSize),s=r.at(-1)?.Id;return{rows:r,advance:r.length,next:typeof s=="string"?s:o,last:r.length>0&&typeof s!="string"}}leaveToThePlatform(e,t,o){let n=new Set(o.filter(r=>r.to===e&&(r.required||Qt(r.to,r.fieldApiName))).map(r=>r.fieldApiName));return this.leftToThePlatform.keep(e,t,[...n])}async writeBatch(e,t,o,n){let r=[],s=t,i=this.standardPricebook;if(e===Ae&&i&&(s=t.filter(E=>E.Id!==i.source),n.linked+=t.length-s.length),s=this.holdOnClosedRecordTypes(e,s,n),s=await this.holdBehindRefusedParents(e,s,o,n),s=this.holdBehindCutParents(e,s,n),e===oe&&(s=this.holdEmailsForTheirTask(s)),e===fe&&(s=await this.linkPersonContacts(s,n,r)),s.length===0){this.register(e,r);return}let a=this.deps.remapper.remapRecords(s,o,e);await this.leaveToDefault(e,s,n);let c=await this.creatableFieldsOf(e),d=c?s.map(E=>{let A={};for(let j of Object.keys(E))(j==="Id"||j==="attributes"||c.has(j))&&(A[j]=E[j]);return A}):s;d=this.translateRecordTypes(e,d);let m=new Map;d.forEach((E,A)=>{if(E.RecordTypeId!==void 0)return;let j=s[A]?.RecordTypeId,M=!c||c.has("RecordTypeId");m.set(E,M&&Ft(j)?"masterInSource":"notRead")});for(let E of d)for(let A of Zt(e,E))delete E[A];let u=await this.replaceCurrencies(e,s,d,c);e===ce&&await this.leaveOutForAccountKind(s,d);let p=new Map;d.forEach((E,A)=>{let j=gt(e,E);for(let M of j)delete E[M];j.length>0&&p.set(A,j)});let g=await this.lookupsOwed(e,s,a.unresolved.filter(E=>!p.get(E.index)?.includes(E.fieldApiName)),c),y=this.deps.queryTarget,f=y?E=>(n.apiCallsUsed++,y(E)):void 0;if(e===mn&&f){let E=await En(f,d);for(let[A,j]of E){let M=d[A].Id;typeof M=="string"&&r.push([M,j])}n.linked+=E.size,d=d.filter((A,j)=>!E.has(j))}if(Sn[e]!==void 0&&f){let E=await On(f,e,d);for(let[A,j]of E){let M=d[A].Id;typeof M=="string"&&r.push([M,j])}n.linked+=E.size,await this.giveFlagsBack(e,[...E].map(([A,j])=>[d[A],j]),n),d=d.filter((A,j)=>!E.has(j))}if(e===We&&f){let E=await this.tasksWrittenWithTheirEmail(d,f);for(let[A,j]of E)r.push([A,j]);n.linked+=E.size,d=d.filter(A=>!E.has(String(A.Id)))}if(d.length===0){this.register(e,r);return}let R=await this.startAsDrafts(e,d),w=m.size>0?await this.givenRuleOf(e):void 0,C=await this.insertSendingLocksAgain(e,d,n),v=await this.keyPrefixOf(e),z=hn[e],K=[];if(d.forEach((E,A)=>{let j=typeof E.Id=="string"?E.Id:void 0,M=C[A];if(!M){this.refuse(e,j,n,void 0);return}if(M.success){n.written++;let se=w?m.get(E):void 0;w&&se&&this.countCreatedWithoutRecordType(e,w,se,M.id);let T=u.get(E);this.currencyChanges.add(e,T),T&&M.id&&this.currencyChangesByWrittenId.set(M.id,T),j&&M.id&&r.push([j,M.id]);let O=R.get(A);O&&M.id&&this.deferredStatuses.push({objectApiName:e,id:M.id,status:O});let D=j?g.get(j):void 0;for(let S of M.id?D??[]:[])this.owedLookups.push({objectApiName:e,recordId:M.id,fieldApiName:S.fieldApiName,sourceId:S.sourceId,parents:S.parents});return}let te=Hn(M,v);if(te.kind==="linked"){n.linked++,j&&r.push([j,te.id]);return}if(te.kind==="unidentified"&&z&&f){K.push({payload:E,sourceId:j,outcome:M});return}this.refuse(e,j,n,M)}),z&&f&&K.length>0){let E=await Pn(f,e,z,K.map(A=>A.payload));K.forEach((A,j)=>{let M=E[j];if(M&&A.sourceId){n.linked++,r.push([A.sourceId,M]);return}this.refuse(e,A.sourceId,n,A.outcome)})}this.register(e,r)}async insertSendingLocksAgain(e,t,o){let n=async i=>(o.apiCallsUsed++,this.deps.insert(e,i)),r=await n(t),s=await oo({outcomes:r.slice(0,t.length),locked:i=>!i.success&&to(i.errors,i.errorDetails),written:i=>i.success,send:i=>Ht((a,c)=>n(c),e,i.map(a=>t[a])),note:qr,wait:async i=>{await this.wait(i),await this.checkPause()},stopped:()=>this.stopped()});return s.refused===0?r:(o.sentAgainForALock={rows:o.sentAgainForALock.rows+s.sentAgain,written:o.sentAgainForALock.written+s.written,stillLocked:o.sentAgainForALock.stillLocked+s.stillLocked},ae.info(`[autopilot] ${e}: ${Xe("record(s)",s)??""}`),[...s.outcomes,...r.slice(t.length)])}async giveFlagsBack(e,t,o){let n=this.deps.update;if(!n||t.length===0||!Tn[e])return;let r=await this.deps.describeFieldsFixedAtInsert?.(e).catch(()=>{}),s=await vn(e,t,i=>!r?.has(i),async i=>(o.apiCallsUsed++,n(e,i)),()=>this.stopped());s&&ae.warn("Autopilot linked relations without a flag or an answer their rows carried",{objectApiName:e,note:s})}holdEmailsForTheirTask(e){for(let o of e){let n=o.ActivityId;typeof o.Id=="string"&&typeof n=="string"&&n!==""&&this.taskOfEmail.set(o.Id,n)}if(this.taskTurnOver||!this.planned.has(We))return e;let t=[];for(let o of e)bn(o)?this.emailsAfterTheirTask.push(o):t.push(o);return t}async tasksWrittenWithTheirEmail(e,t){let o=new Map;for(let[i,a]of this.taskOfEmail){let c=this.deps.remapper.getTargetId(oe,i);c&&o.set(a,c)}let n=e.map(i=>String(i.Id)).filter(i=>o.has(i));if(n.length===0)return new Map;let r;try{r=await An(t,[...new Set(n.map(i=>o.get(i)??""))])}catch(i){return ae.warn("Autopilot could not look up the tasks written with its emails",{error:ee(i)}),new Map}let s=new Map;for(let i of n){let a=r.get(o.get(i)??"");a&&s.set(i,a)}return s}async writeEmailsAfterTheirTask(e,t){this.taskTurnOver=!0;let o=this.emailsAfterTheirTask.splice(0,this.emailsAfterTheirTask.length);if(o.length===0)return;let n=wr();for(let d=0;d<o.length;d+=this.batchSize){if(await this.checkPause()){this.emailsHeldAndNotSent+=o.length-d;break}await this.writeBatch(oe,o.slice(d,d+this.batchSize),e,n)}t.totalSuccess+=n.written,t.totalFailure+=n.failed,t.totalLinked=(t.totalLinked??0)+n.linked;let r=t.objectOutcomes??{};t.objectOutcomes=r;let s=r[oe],i=new Re;for(let d of[...s?.refusals??[],...n.refusals.list()])i.addCounted(d);let a=new Map((s?.leftToDefault??[]).map(d=>[d.field,d.count]));for(let[d,m]of n.defaulted)a.set(d,(a.get(d)??0)+m);let c={...s,written:(s?.written??0)+n.written,linked:(s?.linked??0)+n.linked,failed:(s?.failed??0)+n.failed,refusals:i.list(),...a.size>0?{leftToDefault:[...a].map(([d,m])=>({field:d,count:m}))}:{}};r[oe]=c,c.written+c.linked>0&&t.failedObjects.includes(oe)&&(t.failedObjects.splice(t.failedObjects.indexOf(oe),1),delete t.nodeErrors?.[oe],t.completedObjects.push(oe)),this.emit("node-completed",this.makeEvent({type:"node-completed",timestamp:"",objectApiName:oe,successCount:c.written,failureCount:c.failed,linkedCount:c.linked,refusals:c.refusals,elapsedMs:0,apiCallsUsed:n.apiCallsUsed}))}async leaveToDefault(e,t,o){let n=await this.lookupsOf(e);if(!n)return;let r=In(n.filter(i=>i.name!=="RecordTypeId"),i=>!this.planned.has(i));if(r.size===0)return;let s=await this.creatableFieldsOf(e);for(let i of t)for(let a of r){let c=i[a];c!=null&&c!==""&&(!s||s.has(a))&&o.defaulted.set(a,(o.defaulted.get(a)??0)+1),delete i[a]}}async replaceCurrencies(e,t,o,n){let r=new Map,{querySource:s,queryTarget:i}=this.deps;if(!s||!i)return r;let a=!n||n.has(he);if(!a&&this.currencyChangesByWrittenId.size===0)return r;let c=p=>typeof p?.[he]=="string"&&p[he]!=="";if(!(a?o.some(c):t.some(c)))return r;this.currencies??=Me(s,i,{source:this.deps.toolingSource,target:this.deps.toolingTarget});let d=await this.currencies;if(!d)return r;let m=await this.deps.describeCurrencyFields?.(e).catch(()=>{})??new Map,u=a?[]:(await this.lookupsOf(e)??[]).map(p=>p.name);return o.forEach((p,g)=>{let y=t[g],f=y?.[he],R=a?Ln(p,{read:f,currencyFields:m,ratesOn:Fn(e,y)},d):$n(p,{read:f,parent:y?Dn(e,y,u,w=>this.currencyChangesByWrittenId.get(w)):void 0,currencyFields:m},d);R&&r.set(p,R)}),r}async pricesInOneCurrencyEach(e,t){let o={rows:e,standsFor:new Map,said:[]},{querySource:n,queryTarget:r}=this.deps;if(!n||!r)return o;let s=d=>typeof d[he]=="string"&&d[he]!=="";if(!e.some(s))return o;this.currencies??=Me(n,r,{source:this.deps.toolingSource,target:this.deps.toolingTarget});let i=await this.currencies;if(!i)return o;let{target:a}=i,c=zo({prices:e,standardBookId:t,sellingModels:e.some(d=>typeof d[Ee]=="string"),writtenIn:d=>a.active.has(d)?d:Nn(void 0,a)?.to,active:a.active},[]);return{rows:c.rows,standsFor:c.standsFor,said:c.said}}linkWhatStoodIn(e,t,o){let n=Oe,r=[],s=[];for(let i of e){let a=String(i.Id),c=t.get(a),d=c===void 0?void 0:this.deps.remapper.getTargetId(n,c);if(d===void 0){s.push(i);continue}r.push([a,d]),o.linked++}return this.register(n,r),s}pricesSettledOf(e){let t=this.pricesSettled.get(e)??[];return t.length>0?{pricesSettled:t}:{}}currenciesReplacedOf(e){let t=this.currencyChanges.list().filter(o=>o.objectApiName===e);return t.length>0?{currenciesReplaced:t}:{}}translateRecordTypes(e,t){let o=this.recordTypeMappings;return!o||!t.some(n=>typeof n.RecordTypeId=="string")?t.map(Fo):new jt().apply(t,o,n=>{this.unmappedRecordTypes.has(n)||(this.unmappedRecordTypes.add(n),jo(e,n,"autopilot"))})}async lookupsOwed(e,t,o,n){let r=new Map;if(!this.deps.update||o.length===0)return r;let s=await this.lookupsOf(e);for(let i of o){if(n&&!n.has(i.fieldApiName))continue;let a=s?.find(d=>d.name===i.fieldApiName);if(a&&!a.updateable)continue;let c=t[i.index]?.Id;typeof c=="string"&&r.set(c,[...r.get(c)??[],i])}return r}refuse(e,t,o,n){o.failed++;let r=Kt(n);o.errors.push(n?.errors[0]??Wr(r[0])),o.refusals.add(r),t&&this.refusedRecords.set(de(t),e)}async holdBehindRefusedParents(e,t,o,n){if(this.refusedRecords.size===0&&this.notWritten.size===0&&this.skippedObjects.size===0)return t;let r=o.filter(a=>a.to===e);if(r.length===0)return t;let s=new Map;for(let a of r)s.set(a.fieldApiName,(s.get(a.fieldApiName)??0)+1);let i=[];for(let a of t){let c=gt(e,a),d;for(let y of r){let f=a[y.fieldApiName];if(typeof f!="string"||f===""||c.includes(y.fieldApiName)||this.deps.remapper.getTargetId(y.from,f)!==void 0)continue;let R=this.refusedRecords.get(de(f))===y.from,w=this.notWrittenOf(y.from);if(!R&&w===void 0)continue;let C=s.get(y.fieldApiName)??0;if(!R&&!await this.namesARecordOf(e,y,f,C))continue;let{from:v,fieldApiName:z}=y;d=R||w===void 0?{edge:y,statusCode:hr,message:`the ${v} record its ${z} names was refused in this run, and written without it this record would stand without its ${v}.`}:{edge:y,statusCode:gr,message:`the ${v} record its ${z} names was not written: ${yr[w](v)}, and written without it this record would stand without its ${v}.`};break}if(!d){i.push(a);continue}let{statusCode:m,message:u,edge:p}=d;n.failed++,n.errors.push(`${m}: ${u}`),n.refusals.add([{statusCode:m,message:u,fields:[p.fieldApiName]}]);let g=a.Id;typeof g=="string"&&g!==""&&this.refusedRecords.set(de(g),e)}return i}holdBehindCutParents(e,t,o){let n=this.fit,r=n?.holds.get(e);return!n||!r?t:t.filter(s=>{if(!r.some(c=>{let d=s[c.field];if(typeof d!="string"||d==="")return!1;let{prefix:m}=c;if(m!==void 0&&(m===null||!d.startsWith(m))||this.deps.remapper.getTargetId(c.parent,d)!==void 0)return!1;let u=de(d);return n.stayedOut.has(u)||n.kept.get(c.parent)?.has(u)!==!0}))return!0;o.cutSinceFit++;let a=s.Id;return typeof a=="string"&&a!==""&&n.stayedOut.set(de(a),e),!1})}notWrittenOf(e){if(!this.planned.has(e))return;let t=this.notWritten.get(e);return t||(this.skippedObjects.has(e)&&!this.reached.has(e)?"skipped":void 0)}async namesARecordOf(e,t,o,n){let r=(await this.lookupsOf(e))?.find(s=>s.name===t.fieldApiName);if(r?.referenceTo.length===1)return r.referenceTo[0]===t.from;if(r&&r.referenceTo.length>1){let s=await this.keyPrefixOf(t.from);return typeof s=="string"&&s!==""&&o.startsWith(s)}return n===1}async linkPersonContacts(e,t,o){let n=e.filter(Pe),r=this.deps.queryTarget;if(n.length===0||!r)return e;let s=await this.lookupsOf(ce);if(s&&!s.some(u=>u.name===yt))return e;let i=new Map;for(let u of n){let p=u.AccountId,g=typeof p=="string"&&p!==""?this.deps.remapper.getTargetId(ce,p):void 0;g&&i.set(u,g)}let a=new Map,c;if(i.size>0)try{t.apiCallsUsed++,a=await Rn(r,[...new Set(i.values())])}catch(u){c=ee(u)}let d=(u,p,g)=>{t.failed++,t.errors.push(`${p}: ${g}`),t.refusals.add([{statusCode:p,message:g,fields:["AccountId"]}]);let y=u.Id;typeof y=="string"&&y!==""&&this.refusedRecords.set(de(y),fe)},m=[];for(let u of e){if(!Pe(u)){m.push(u);continue}let p=i.get(u);if(p===void 0){d(u,$r,"the person account this contact belongs to is not in the target: the platform writes the contact with the account, and sent on its own it would stand as a contact of no account.");continue}if(c!==void 0){d(u,Br,`the contact the platform wrote with its person account could not be looked up (${c}): sent, this one would stand beside it as a second contact.`);continue}let g=a.get(p),y=u.Id;if(g===void 0||typeof y!="string"){m.push(u);continue}o.push([y,g]),t.linked++,this.personContactsLinked++}return m}async leaveOutForAccountKind(e,t){let n=e.some(Pe)?await this.takenAsBusiness(t):()=>!1,r=e.map((s,i)=>kn(s,n(t[i])));t.forEach((s,i)=>{for(let a of Object.keys(s))tn(ce,a,r[i])&&delete s[a]})}async takenAsBusiness(e){let t=await this.lookupsOf(ce);if(t&&!t.some(a=>a.name===yt))return()=>!0;let o=this.deps.queryTarget;if(!o)return()=>!1;this.personTypes??=o(_r).then(a=>new Set(a.flatMap(c=>typeof c.Id=="string"?[de(c.Id)]:[])),()=>{});let n=await this.personTypes;if(!n)return()=>!1;let r=await this.deps.describeRecordTypes?.(ce).catch(()=>{}),s=new Set((r??[]).map(a=>de(a.recordTypeId))),i=e.some(a=>typeof a.RecordTypeId!="string")?qo(r):void 0;return a=>{let c=a.RecordTypeId,d=typeof c=="string"&&c!==""?c:i;if(d===void 0)return!1;let m=de(d);return!n.has(m)&&s.has(m)}}register(e,t){t.length>0&&this.deps.remapper.registerMappings(e,t)}async startAsDrafts(e,t){let o=new Map,n=Ce[e],{queryTarget:r,update:s}=this.deps;if(!n||!r||!s)return o;let i=this.lifecycleByObject.get(e);i||(i=Cn(r,n),this.lifecycleByObject.set(e,i));let a=await i;return a&&t.forEach((c,d)=>{let m=Mn(c.Status,a);m&&(o.set(d,String(c.Status)),c.Status=m)}),o}async applyDeferredStatuses(){let e={},{update:t}=this.deps;if(!t||this.deferredStatuses.length===0)return e;let o=new Map;for(let n of this.deferredStatuses)o.set(n.objectApiName,[...o.get(n.objectApiName)??[],n]);for(let[n,r]of o){let s=0,i=0,a=new Re;for(let c=0;c<r.length;c+=this.batchSize){if(await this.checkPause()){this.noteLeftByStop(n,"statuses",r.slice(c).map(u=>u.id));break}let d=r.slice(c,c+this.batchSize),m=await Ht(t,n,d.map(u=>({Id:u.id,Status:u.status})));d.forEach((u,p)=>{let g=m[p];if(g?.success){s++;return}i++,a.add(Kt(g))})}e[n]={applied:s,refusals:a.list(),...i>0?{leftDraft:i}:{}}}return this.deferredStatuses.length=0,e}noteLeftByStop(e,t,o){if(o.length===0)return;let n=this.leftByStop.get(e);n||(n={lookups:new Set,statuses:new Set},this.leftByStop.set(e,n));for(let r of o)n[t].add(r)}countEmailsTheStopHeld(e,t,o){let n=this.emailsAfterTheirTask.splice(0,this.emailsAfterTheirTask.length),r=this.emailsHeldAndNotSent+n.length;if(this.emailsHeldAndNotSent=0,r===0)return;let s=o[oe]??{written:0,linked:0,failed:0,refusals:[]};o[oe]={...s,notSent:(s.notSent??0)+r,heldForTheirTask:r};for(let d of[e.completedObjects,e.failedObjects]){let m=d.indexOf(oe);m>=0&&d.splice(m,1)}if(t.includes(oe))return;let i=[...this.planned],a=i.indexOf(oe),c=t.findIndex(d=>i.indexOf(d)>a);t.splice(c<0?t.length:c,0,oe)}countWhatTheStopLeft(e,t){let o=new Set(e);for(let r of this.owedLookups.splice(0,this.owedLookups.length))r.parents.some(i=>o.has(i)||this.deps.remapper.getTargetId(i,r.sourceId)!==void 0)?this.noteLeftByStop(r.objectApiName,"lookups",[r.recordId]):this.owedLookups.push(r);let n=this.deferredStatuses.splice(0,this.deferredStatuses.length);for(let r of n)this.noteLeftByStop(r.objectApiName,"statuses",[r.id]);for(let[r,s]of this.leftByStop){let i=t[r]??{written:0,linked:0,failed:0,refusals:[]};t[r]={...i,...s.lookups.size>0?{lookupsLeftEmpty:s.lookups.size}:{},...s.statuses.size>0?{statusesNotGivenBack:s.statuses.size}:{}}}}pause(){this.paused||(this.paused=!0,this.pausePromise=new Promise(e=>{this.pauseResolve=e}),this.emit("paused",this.makeEvent({type:"paused",timestamp:""})))}resume(){this.paused&&(this.paused=!1,this.pauseResolve?.(),this.pausePromise=null,this.pauseResolve=null,this.emit("resumed",this.makeEvent({type:"resumed",timestamp:""})))}skip(e){this.skippedObjects.add(e)}stopped(){return this.signal?.aborted===!0}wait(e){return this.deps.wait?this.deps.wait(e):no(e,this.signal)}async checkPause(){return this.stopped()?!0:(this.paused&&this.pausePromise&&await this.pausePromise,this.stopped())}makeEvent(e){return{...e,timestamp:new Date().toISOString()}}};async function Ht(l,e,t){try{return await l(e,t)}catch(o){let n=ee(o);return t.map(()=>({id:"",success:!1,errors:[n],errorDetails:[Rt(n)]}))}}function Kt(l){return l?l.errorDetails&&l.errorDetails.length>0?l.errorDetails:l.errors.length>0?l.errors.map(e=>Rt(e)):[Dr]:[Lr]}function Wr(l){return l.statusCode===Ye?l.message:`${l.statusCode}: ${l.message}`}var it=class{threshold;partitionSize;constructor(e=5e3,t=2e3){this.threshold=e,this.partitionSize=t}shouldUseGrappe(e){return e>this.threshold}partition(e,t){if(t<=this.partitionSize)return[{id:`${e}-0`,objectApiName:e,offset:0,limit:t,recordCount:t}];let o=[],n=0,r=0;for(;n<t;){let s=Math.min(this.partitionSize,t-n);o.push({id:`${e}-${r}`,objectApiName:e,offset:n,limit:s,recordCount:s}),n+=s,r++}return o}getThreshold(){return this.threshold}getPartitionSize(){return this.partitionSize}};var Hr=`sandforge autopilot \u2014 run an Autopilot copy between two orgs, without the editor.
|
|
11
11
|
|
|
12
12
|
Usage:
|
|
13
13
|
npx sandforge autopilot \\
|
|
@@ -92,7 +92,7 @@ Options:
|
|
|
92
92
|
it is not needed. --mute-automation keeps quiet what
|
|
93
93
|
tests the org's bypass; what an Apex trigger sends is
|
|
94
94
|
read nowhere (default: off)
|
|
95
|
-
${
|
|
95
|
+
${Qo({run:"the run",simulation:"--plan-only",note:["An Autopilot run has no removal: a rewind to this","checkpoint is what takes it back."]})}
|
|
96
96
|
--json emit the run summary as JSON, with the id
|
|
97
97
|
of every record the run created (default: off)
|
|
98
98
|
--fail-on-partial exit 3, not 0, when the run was partial: the target
|
|
@@ -142,21 +142,21 @@ stopped the run, 143 a SIGTERM (a CI job cancelled or timed out), 129 a SIGHUP.
|
|
|
142
142
|
`),process.exit(2));let i=["none","gdpr","ccpa","hipaa","pci_dss"],a=t("--compliance","none")??"none";i.includes(a)||(process.stderr.write(`--compliance takes ${i.join(", ")} \u2014 not "${a}".
|
|
143
143
|
`),process.exit(2));let c=Number(t("--batch-size","200")??"200");(!Number.isInteger(c)||c<1||c>1e4)&&(process.stderr.write(`--batch-size takes a whole number between 1 and 10000.
|
|
144
144
|
`),process.exit(2));let d=(w,C)=>{let v=Number(t(w,String(C))??C);return(!Number.isInteger(v)||v<1)&&(process.stderr.write(`${w} takes a whole number, 1 or more.
|
|
145
|
-
`),process.exit(2)),v},m=d("--max-depth",Ut),u=d("--max-objects",Wt),p=d("--max-total",
|
|
146
|
-
`),process.exit(2));let y=
|
|
145
|
+
`),process.exit(2)),v},m=d("--max-depth",Ut),u=d("--max-objects",Wt),p=d("--max-total",ao),g=d("--max-records-per-object",5e4);g>dt&&(process.stderr.write(`--max-records-per-object takes a whole number of records, 1 to ${dt}.
|
|
146
|
+
`),process.exit(2));let y=Xo(e),f=w=>{process.stderr.write(`${w}
|
|
147
147
|
`),process.exit(2)},R=rr(e,f);for(let w of Object.keys(R?.caps?.objects??{}))s.includes(w)||f(`--fit-cap ${w}: give ${w} with --object too.`);return{source:n,target:r,objects:s,includeStandardObjects:e.includes("--standard-objects"),compliance:a,batchSize:c,maxDepth:m,maxObjects:u,maxTotal:p,maxRecordsPerObject:g,planOnly:e.includes("--plan-only"),keepContactPoints:e.includes("--keep-contact-points"),json:e.includes("--json"),failOnPartial:e.includes("--fail-on-partial"),muteAutomation:e.includes("--mute-automation"),acceptEmails:e.includes("--accept-emails"),...y!==void 0?{checkpointFirst:y}:{},...R?{fit:R}:{}}}function Zr(l){return{...l.share?{share:!0}:{},...l.caps?.objects?{caps:l.caps.objects}:{},...l.caps?.all!==void 0?{all:l.caps.all}:{},...l.withinMB!==void 0?{withinMB:l.withinMB}:{}}}function es(l){return async e=>(await He({query:async t=>l.query(t),queryMore:async t=>l.queryMore(t)},e)).records}async function ts(l=process.argv){let e=Date.now(),t=Vr(l),o=h=>{process[t.json?"stderr":"stdout"].write(`${h}
|
|
148
|
-
`)};o(`sandforge autopilot ${t.source} -> ${t.target}`),o(`objects: ${t.objects.join(", ")}`);let n=Ge(await ft(t.source)),r=await ft(t.target),s=Ge(r),i=t.planOnly?void 0:await rn(s,t.target,{tool:"sandforge autopilot",action:"write",readOnly:"--plan-only"}),a=t.checkpointFirst?
|
|
149
|
-
scanning\u2026`);let f=await y.scanSchemas(n,s,{selectedObjects:t.objects,includeStandardObjects:t.includeStandardObjects,maxDepth:t.maxDepth,maxObjects:t.maxObjects,maxRecordsPerObject:t.maxRecordsPerObject},h=>o(` ${h}`)),R=y.buildGraph(f,t.batchSize);o(`graph: ${R.nodes.length} node(s), ${R.edges.length} edge(s)`);let w=t.compliance==="none"?[]:vo(new Yn,f.objectDescribes),{rules:C}=y.buildCompliance(t.compliance,[],w),v=y.generatePlan(R,t.compliance,C,f.scope),z=()=>{o(`plan: ${v.waves.length} wave(s), ${v.totalRecords} record(s)`),v.waves.forEach((h,P)=>{o(` wave ${P+1}: ${h.objects.join(", ")}`)});for(let h of is(f.scope,t))o(h);for(let h of as(v))o(h)};z();let K=h=>new Map(h.map(P=>[P.objectApiName,P.recordCount])),E=K(R.nodes),A=$t(v,E,f.personAccounts),j=async()=>{try{return await
|
|
150
|
-
fitting\u2026`);let h=
|
|
148
|
+
`)};o(`sandforge autopilot ${t.source} -> ${t.target}`),o(`objects: ${t.objects.join(", ")}`);let n=Ge(await ft(t.source)),r=await ft(t.target),s=Ge(r),i=t.planOnly?void 0:await rn(s,t.target,{tool:"sandforge autopilot",action:"write",readOnly:"--plan-only"}),a=t.checkpointFirst?Vo({module:"autopilot",operationId:`sandforge-autopilot-${e}`,request:t.checkpointFirst,session:r,org:Jo(r,i??await pt(s)),connect:Ge,journalDir:Yo(),say:o}):void 0,c=!1,d=new Map,m=new Map,u=async h=>{let P=m.get(h);if(P)return P;let I=await s.sobject(h).describe(),H={creatable:new Set(I.fields.filter(Q=>Q.createable).map(Q=>Q.name)),recordTypes:At(I.recordTypeInfos),keyPrefix:I.keyPrefix??null,lookups:Ho(I.fields),currencyFields:jn(I.fields),fields:I.fields.map(Q=>({name:Q.name,queryable:!0,createable:Q.createable,isReference:Q.type==="reference",type:Q.type,...Q.length>0?{length:Q.length}:{},...Q.externalId?{externalId:!0}:{}}))};return m.set(h,H),H},p=new Kn,g=()=>({query:async(h,P,I)=>(await n.query(Ar(h,P,I))).records,queryByIds:async(h,P)=>{let I=P.map(Q=>`'${ge(Q)}'`).join(", ");return(await n.query(`SELECT FIELDS(ALL) FROM ${h} WHERE Id IN (${I}) LIMIT ${P.length}`)).records},insert:async(h,P)=>{let I=P.map(pe=>{let at={...pe};return delete at.Id,delete at.attributes,at}),H=St(await s.sobject(h).create(I,{headers:lt()}),h);H.some(pe=>pe.success)&&(c=!0);let Q=H.filter(pe=>pe.success&&pe.id).map(pe=>pe.id);return d.set(h,[...d.get(h)??[],...Q]),H},update:async(h,P)=>{let I=St(await s.sobject(h).update(P,{headers:lt()}),h);return I.some(H=>H.success)&&(c=!0),I},querySource:async h=>(await n.query(h)).records,queryTarget:es(s),toolingSource:async h=>(await n.tooling.query(h)).records,toolingTarget:async h=>(await s.tooling.query(h)).records,describeKeyPrefix:async h=>(await u(h)).keyPrefix,describeLookups:async h=>(await u(h)).lookups,describeFields:async h=>(await u(h)).fields,anonymizer:p,remapper:new De,describeCreateableFields:async h=>(await u(h)).creatable,describeRecordTypes:async h=>(await u(h)).recordTypes,describeRecordTypesAgain:async h=>At((await s.sobject(h).describe()).recordTypeInfos),describeCurrencyFields:async h=>(await u(h)).currencyFields,countRecordTypes:async h=>{let P=await n.query(Gn(h));return Ke(P.records)}}),y=new nt({schemaScanner:new et,graphBuilder:new ot,complianceEngine:new rt,anonymizer:p,planGenerator:new st,remapper:new De,createExecutor:()=>new $e(g()),grappeAdapter:new it});o(`
|
|
149
|
+
scanning\u2026`);let f=await y.scanSchemas(n,s,{selectedObjects:t.objects,includeStandardObjects:t.includeStandardObjects,maxDepth:t.maxDepth,maxObjects:t.maxObjects,maxRecordsPerObject:t.maxRecordsPerObject},h=>o(` ${h}`)),R=y.buildGraph(f,t.batchSize);o(`graph: ${R.nodes.length} node(s), ${R.edges.length} edge(s)`);let w=t.compliance==="none"?[]:vo(new Yn,f.objectDescribes),{rules:C}=y.buildCompliance(t.compliance,[],w),v=y.generatePlan(R,t.compliance,C,f.scope),z=()=>{o(`plan: ${v.waves.length} wave(s), ${v.totalRecords} record(s)`),v.waves.forEach((h,P)=>{o(` wave ${P+1}: ${h.objects.join(", ")}`)});for(let h of is(f.scope,t))o(h);for(let h of as(v))o(h)};z();let K=h=>new Map(h.map(P=>[P.objectApiName,P.recordCount])),E=K(R.nodes),A=$t(v,E,f.personAccounts),j=async()=>{try{return await co(s)}catch(h){return{unread:ee(h)}}},M=await j(),te=Ct(A,M),se,T=()=>se??=lo(s),O,D=()=>O??=qt(s).read(t.target,Ve(v)).catch(h=>({unread:h instanceof Error?h.message:String(h)})),S,ne;if(t.muteAutomation){let h=await D();try{S=await eo(async()=>Vn(s),h,{writes:(P,I)=>I==="insert"||I==="update"})}catch(P){if(!Ot(P))throw P;ne={code:P.code,message:P.message.replace(/ Nothing was assigned\.$/,"")}}}let N=await Fe(A,M,T,void 0,{readBack:xe(A),...Ie(S?.plan)});o("");for(let h of Mt(A,te,t.target))o(h);a||o(je(N,t.target));for(let h of Sr(f.personAccounts))o(h);if(S)for(let h of Qe(S.muted,t.target))o(` ${h}`);let _,V;if(a&&A.totalRows>0){let h=new Set(A.objects.map(({objectApiName:H})=>H)),P=S?.automation??await D(),I={written:Ve(v).filter(H=>h.has(H)),running:typeof P.unread=="string"?{firing:[]}:{firing:ze(P,void 0,(H,Q)=>Q==="insert"||Q==="update").firing}};try{_={ask:I,estimate:await a.scope(I)}}catch(H){V=vt(H).replace(/ Nothing was written\.$/,"")}}if(a&&(N=await Fe(A,M,T,_?.estimate,{readBack:xe(A),...Ie(S?.plan)}),o(je(N,t.target)),_))for(let h of Zo(_.estimate))o(h);let B,Z;if(t.fit){o(`
|
|
150
|
+
fitting\u2026`);let h=ko({storage:M,...t.fit.withinMB!==void 0?{withinMB:t.fit.withinMB}:{},api:"unread"in M?await T().catch(P=>({unread:ee(P)})):M.dailyApiRequests??{unread:`${t.target}'s /limits did not list them`},otherRequests:po(_?.estimate)});if("unread"in h)Z={code:Dt.STORAGE_UNREAD,message:`The plan cannot be fitted to ${t.target}, whose data storage left could not be read (${h.unread}): give --fit-within <MB>, the most it may take, to fit it to that.`};else try{B=await y.fitPlan(n,{scan:f,graph:R,plan:v,rules:C,mode:Zr(t.fit),budget:h,automation:await D(),...S?.plan?{mutePlan:S.plan}:{},describeLookups:async I=>(await u(I)).lookups,maxRecords:t.maxTotal,batchSize:t.batchSize,onProgress:I=>o(` ${I}`)});let P=(S?.plan?.assign.length??0)>0;for(let I of ss(B,t.target,P))o(I);B.cannotFit!==void 0&&(Z={code:Xr,message:`The plan cannot be fitted to ${t.target}: ${B.cannotFit}.`})}catch(P){Z={code:Dt.READ_REFUSED,message:`The plan could not be fitted: the source refused a read of it (${ee(P)}). Run it again; if the source refuses again, narrow the selection (--object, --max-depth), or run it without --fit where it fits.`}}if(B?.fitted){({scan:f,graph:R,plan:v}=B.fitted),E=K(R.nodes),A=$t(v,E,f.personAccounts),M=await j(),te=Ct(A,M),se=void 0;let P=new Set(A.objects.map(({objectApiName:I})=>I));if(a&&_){let{ask:I}=_,H=I.written.filter(Q=>P.has(Q));if(H.length<I.written.length){let Q={written:H,running:{firing:I.running.firing.filter(pe=>P.has(pe.objectApiName))}};try{_={ask:Q,estimate:await a.scope(Q)}}catch(pe){_=void 0,V=vt(pe).replace(/ Nothing was written\.$/,"")}}}N=await Fe(A,M,T,_?.estimate,{readBack:xe(A),...Ie(S?.plan)}),o(""),z(),o("");for(let I of Mt(A,te,t.target))o(I);o(je(N,t.target));for(let I of Sr(f.personAccounts))o(I)}}let Y=await Ko({plan:A,objects:Ve(v),readAutomation:async h=>{if(S?.automation)return S.automation;let P=O?await O:void 0;return P!==void 0&&typeof P.unread!="string"?P:qt(s).read(t.target,h)},readLimits:()=>mo(s)});for(let h of go(Y.checks,t.target))o(h);Y.unread!==void 0&&o(` emails: not counted, ${Y.unread} could not be read`);let me=new Set(A.objects.map(({objectApiName:h})=>h)),Be=(h,P)=>me.has(h)&&(P==="insert"||P==="update"),b=A.totalRows>0?await Jn({read:await D(),...S?.plan?{plan:S.plan}:{},writes:Be,readDeliverability:async()=>nn(i??await pt(s))?Qn:Xn(s),accepted:t.acceptEmails,target:t.target,run:"autopilot",keepsAddresses:t.keepContactPoints,mayMute:!t.muteAutomation}):void 0,k=b?.gate;k?.line!==void 0&&o(` ${k.line}`);let x=yo(b?.ofRun);x.deliverability!==void 0&&(N=await Fe(A,M,T,_?.estimate,{readBack:xe(A),...Ie(S?.plan),...x}),o(je(N,t.target)));let $=(h,P)=>P===void 0?void 0:{code:h,message:P},L=[$(Je,V??(_?.estimate.refusal!==void 0?er(_.estimate.refusal):void 0)),$(Yr,A.totalRows>t.maxTotal?`The run would write ${A.totalRows} records, more than --max-total ${t.maxTotal}: narrow it (--object, --max-depth, --max-objects), or raise --max-total.`:void 0),$(Lt.STORAGE_EXCEEDED,bo(te,t.target)),$(Lt.API_BUDGET_EXCEEDED,Pt(N,t.target)?.replace(/ Nothing was written\.$/,"")),$(Qr,ho(Y.checks,t.target)),k?.stop?$(k.stop.code,k.stop.message.replace(/ Nothing was written\./,"")):void 0,ne,Z].filter(h=>h!==void 0),X=L.map(({message:h})=>h);if(!t.fit&&!("unread"in M)&&(te.verdict==="exceeds"||A.totalRows>t.maxTotal||Pt(N,t.target)!==void 0)&&o(" --fit share keeps the largest share of the plan that fits, its records whole"),t.planOnly){let h=await new $e(g()).recordTypesGivenOf(v,E,f.parentIds,f.scope.cutShort);for(let I of R.nodes){let H=h.get(I.objectApiName);H&&(I.recordTypeGiven=H)}let P=(S?.plan?.assign.length??0)>0;for(let I of zt(R.nodes,!0,P))o(I);for(let I of L)o(` ${dn(I)}`);t.json&&process.stdout.write(`${JSON.stringify({tool:"sandforge-autopilot",planOnly:!0,graph:R,plan:v,writeGate:{records:A.totalRows,storage:te,apiRequests:N,personAccounts:Object.fromEntries(f.personAccounts),emails:Y.checks,...Y.unread!==void 0?{emailsUnread:Y.unread}:{},...k?.deliverability?{deliverability:k.deliverability}:{},refusals:X,refusalCodes:L.map(({code:I})=>I)},...Zn(S),..._?{checkpoint:_.estimate}:{},...B?{fit:Rr(B)}:{}},null,2)}
|
|
151
151
|
`);return}let F=(h,P=[])=>{throw t.json&&process.stdout.write(ln({tool:"sandforge-autopilot",source:t.source,target:t.target,elapsedMs:Date.now()-e},h,P)),new Error([h,...P].map(cn).join(`
|
|
152
152
|
`))};if(L.length>0){let[h,...P]=L.map(({code:I,message:H})=>({code:I,message:`${H} Nothing was written.`}));F(h,P)}o(`
|
|
153
153
|
executing\u2026 (REAL)`);let G=new AbortController,W,ie=sn(h=>{W=h,process.stderr.write(`
|
|
154
154
|
interrupted: the run stops after the call under way, and says what it wrote (Ctrl-C again ends it at once)
|
|
155
|
-
`),G.abort()}),U,re,le,ue;try{if(a&&_){let I=_,H=await
|
|
156
|
-
`),ht(mt(W??"SIGINT"));return}le=H.checkpoint;for(let Q of
|
|
155
|
+
`),G.abort()}),U,re,le,ue;try{if(a&&_){let I=_,H=await fo(()=>a.take(I.ask,I.estimate,{signal:G.signal}));if("stop"in H){H.stop.code===Je&&F({code:Je,message:_t(H.stop)}),process.stderr.write(`${_t(H.stop)}
|
|
156
|
+
`),ht(mt(W??"SIGINT"));return}le=H.checkpoint;for(let Q of tr(H.checkpoint,t.target,t.muteAutomation))o(Q)}let h=S?.prepared?await S.prepared.acquire(`sandforge autopilot ${e}`).catch(I=>{if(!Ot(I))throw I;return F(I.refusal)}):void 0;re=h?.outcome??S?.muted;let P=h?b?.afterLease(h.outcome,t.acceptEmails):void 0;if(h&&P){re=await h.release();for(let I of Qe(re,t.target))o(I);F({code:P.code,message:P.message})}U=await y.executePlan(v,R,C,E,void 0,G.signal,f.parentIds,{...t.keepContactPoints?{keepContactPoints:!0}:{},...h?{lease:{assigned:h.outcome.assigned.length,giveBack:()=>h.release()}}:{},...B?.fitted?{fit:B.fitted.run}:{}}).finally(async()=>{h&&(re=await h.release())})}finally{if(ie(),a&&le){let h=le;ue=await a.settle(h,c).catch(P=>(o(`warning: the checkpoint '${h.name}' taken before the run, which wrote nothing, could not be deleted (${ee(P)}): delete it with ${ct("checkpoint")} delete --org ${t.target} --checkpoint ${h.checkpointId}`),h));for(let P of nr(ue))o(P)}}for(let h of re?Qe(re,t.target):[])o(h);let J=Date.now()-e,be=G.signal.aborted,Se=Wo(U);if(ht(be?mt(W??"SIGINT"):an(Se,t.failOnPartial)),t.json){let h={status:Se,...U,...U.stopped===!0?{cancelled:!0}:{}};process.stdout.write(`${JSON.stringify({tool:"sandforge-autopilot",source:t.source,target:t.target,result:h,created:Object.fromEntries(d),...re?{mutedAutomation:re}:{},...ue?{checkpoint:ue}:{},...B?{fit:Rr(B)}:{},elapsedMs:J,...be?{interrupted:!0}:{}},null,2)}
|
|
157
157
|
`),be&&process.stderr.write(`${kr(U)}
|
|
158
158
|
`);return}o(`
|
|
159
159
|
status: ${Se}`),o(`written: ${U.totalSuccess} linked: ${U.totalLinked??0} refused: ${U.totalFailure} skipped: ${U.totalSkipped}`),U.skippedObjects.length>0&&o(` skipped: ${U.skippedObjects.join(", ")}`),U.cutSinceFit!==void 0&&o(` cut since the fit: ${U.cutSinceFit}, read naming a record the fit cut`),U.fatalError&&o(` the run died with: ${U.fatalError}`);for(let h of ns(U))o(h);for(let h of cs(U))o(h);if(be){process.stderr.write(`${kr(U)}
|
|
160
160
|
`);return}o(`
|
|
161
|
-
done in ${J}ms`)}function kr(l){let e=l.stoppedObjects??[];return`interrupted: the run stopped before it was through, ${l.totalSuccess} record(s) written${e.length>0?`, ${e.join(", ")} cut short or not written`:""}; --json names every record it created`}function ns(l){let e=l.contactPoints;if(!e)return["emails and phone numbers: written as read (--keep-contact-points)"];if(e.values===0)return["emails and phone numbers: none to neutralize"];let t=e.fields.map(o=>`${o.objectApiName}.${o.field} ${o.values}`).join(", ");return[`emails and phone numbers: ${e.values} neutralized (${t}) -- addresses under .invalid, numbers fictional`]}function os(l){return`${Math.floor(l*1e3)/10} %`}function rs(l){switch(l.kind){case"trigger":return`what Apex trigger ${l.name} on ${l.objectApiName} creates`;case"notRead":return`what "${l.name}" on ${l.objectApiName} creates: it was not read`;case"share":return`the ${l.name} rows the flows of ${l.objectApiName} create`}}function ss(l,e,t){let{heldBy:o,report:n}=l,{budget:r}=n;if(l.cannotFit!==void 0)return[`fit: the plan cannot be fitted: ${l.cannotFit}`];if(o==="whole")return[`fit: the plan fits as it is, ${n.records} record(s), about ${Te(n.estimateMB)} MB: nothing cut`];let s=Te(r.budgetMB+r.automationMB),i={apiRequests:`the largest whose writes leave ${e} a tenth of its daily API requests`,maxTotal:"the largest --max-total lets through",within:`the largest that fits the ${r.withinMB??s} MB asked (--fit-within)`,storage:`the largest that fits ${s} MB: ${r.share*100} % of the ${r.remainingMB} MB ${e} says it has left of ${r.maxMB}, ${r.roundingMB} MB kept first for the rounding of what it says`},a=l.automationUnread!==void 0?`no room kept for what its automation creates: it could not be read (${l.automationUnread})`:r.automationMB>0?`${Te(r.automationMB)} MB of it kept for what its flows still running create under these records`:"nothing kept for its flows: none still running creates records under these"+(t?" (--mute-automation keeps the others quiet)":""),c=o==="caps"?`fit: the caps asked, within the ${s} MB that fit`:`fit: share ${os(n.share??1)}, ${i[o]}`,d=Math.max(...n.objects.map(p=>p.objectApiName.length)),m=p=>{let g=p.cutWithParent.reduce((R,w)=>R+w.count,0),y=p.cutSpread+g,f=[...p.cutWithParent.map(R=>`${R.count} with their ${R.parent} (${R.field})`),...p.cutSpread>0?[`${p.cutSpread} spread over the table`]:[]];return` ${p.objectApiName.padEnd(d)} ${p.kept} of ${p.inSource}`+(y>0?` cut ${y}: ${f.join(", ")}`:"")},u=n.emptied.map(p=>`${p.objectApiName}.${p.field} on ${p.count} (`+(p.why==="selfReference"?"the record of its own object it names was cut":"the record it names, written after, was cut")+")");return[`${c}; ${a}`,...n.objects.map(m),...n.parents.map(p=>` ${p.objectApiName}: ${p.records}, those the kept records name`),...u.length>0?[` left empty: ${u.join(", ")}`]:[],...(r.notCounted??[]).map(p=>` not counted: ${rs(p)}`),` fitted plan: ${n.records} record(s), about ${Te(n.estimateMB)} MB`+(r.automationMB>0?` and ${Te(r.automationMB)} MB for what its flows create under them`:"")+`; ${n.requestsRead} requests read to fit it`,` ${
|
|
161
|
+
done in ${J}ms`)}function kr(l){let e=l.stoppedObjects??[];return`interrupted: the run stopped before it was through, ${l.totalSuccess} record(s) written${e.length>0?`, ${e.join(", ")} cut short or not written`:""}; --json names every record it created`}function ns(l){let e=l.contactPoints;if(!e)return["emails and phone numbers: written as read (--keep-contact-points)"];if(e.values===0)return["emails and phone numbers: none to neutralize"];let t=e.fields.map(o=>`${o.objectApiName}.${o.field} ${o.values}`).join(", ");return[`emails and phone numbers: ${e.values} neutralized (${t}) -- addresses under .invalid, numbers fictional`]}function os(l){return`${Math.floor(l*1e3)/10} %`}function rs(l){switch(l.kind){case"trigger":return`what Apex trigger ${l.name} on ${l.objectApiName} creates`;case"notRead":return`what "${l.name}" on ${l.objectApiName} creates: it was not read`;case"share":return`the ${l.name} rows the flows of ${l.objectApiName} create`}}function ss(l,e,t){let{heldBy:o,report:n}=l,{budget:r}=n;if(l.cannotFit!==void 0)return[`fit: the plan cannot be fitted: ${l.cannotFit}`];if(o==="whole")return[`fit: the plan fits as it is, ${n.records} record(s), about ${Te(n.estimateMB)} MB: nothing cut`];let s=Te(r.budgetMB+r.automationMB),i={apiRequests:`the largest whose writes leave ${e} a tenth of its daily API requests`,maxTotal:"the largest --max-total lets through",within:`the largest that fits the ${r.withinMB??s} MB asked (--fit-within)`,storage:`the largest that fits ${s} MB: ${r.share*100} % of the ${r.remainingMB} MB ${e} says it has left of ${r.maxMB}, ${r.roundingMB} MB kept first for the rounding of what it says`},a=l.automationUnread!==void 0?`no room kept for what its automation creates: it could not be read (${l.automationUnread})`:r.automationMB>0?`${Te(r.automationMB)} MB of it kept for what its flows still running create under these records`:"nothing kept for its flows: none still running creates records under these"+(t?" (--mute-automation keeps the others quiet)":""),c=o==="caps"?`fit: the caps asked, within the ${s} MB that fit`:`fit: share ${os(n.share??1)}, ${i[o]}`,d=Math.max(...n.objects.map(p=>p.objectApiName.length)),m=p=>{let g=p.cutWithParent.reduce((R,w)=>R+w.count,0),y=p.cutSpread+g,f=[...p.cutWithParent.map(R=>`${R.count} with their ${R.parent} (${R.field})`),...p.cutSpread>0?[`${p.cutSpread} spread over the table`]:[]];return` ${p.objectApiName.padEnd(d)} ${p.kept} of ${p.inSource}`+(y>0?` cut ${y}: ${f.join(", ")}`:"")},u=n.emptied.map(p=>`${p.objectApiName}.${p.field} on ${p.count} (`+(p.why==="selfReference"?"the record of its own object it names was cut":"the record it names, written after, was cut")+")");return[`${c}; ${a}`,...n.objects.map(m),...n.parents.map(p=>` ${p.objectApiName}: ${p.records}, those the kept records name`),...u.length>0?[` left empty: ${u.join(", ")}`]:[],...(r.notCounted??[]).map(p=>` not counted: ${rs(p)}`),` fitted plan: ${n.records} record(s), about ${Te(n.estimateMB)} MB`+(r.automationMB>0?` and ${Te(r.automationMB)} MB for what its flows create under them`:"")+`; ${n.requestsRead} requests read to fit it`,` ${Ao(e)}`]}function Rr(l){return{applied:l.fitted!==void 0,...l.report,heldBy:l.heldBy,...l.cannotFit!==void 0?{cannotFit:l.cannotFit}:{},...l.automationUnread!==void 0?{automationUnread:l.automationUnread}:{},...l.fitted?{keptIds:Object.fromEntries(l.keptIds)}:{}}}function is(l,e){let t=new Set((l.cutShort??[]).map(a=>a.objectApiName)),o=l.selected.filter(a=>!t.has(a)),n=[`scope: depth ${l.maxDepth}, at most ${l.maxObjects} object(s)`];if(l.fitted){let a=l.fitted.objects.map(c=>`${c.objectApiName} ${c.kept} of ${c.inSource}`);n.push(` fitted to the target's storage, read by id: ${a.join(", ")}`)}else(o.length>0||l.selected.length===0)&&n.push(` copied whole, as selected: ${o.join(", ")||"(none)"}`);let r=`${ct("clone")} --depth all --source ${e.source} --target ${e.target} --fit share --dry-run`;for(let a of l.cutShort??[]){let c=a.total!==void 0?` of ${a.total}`:"";n.push(` ${a.objectApiName}: ${a.copied}${c} record(s) copied, the first by Id -- --max-records-per-object copies more, up to 1000000; a sample of the whole org that fits the target: ${r}`)}if(l.parents.length>0){n.push(" read by id, only the records the selection references:");for(let a of l.parents)n.push(` ${a.objectApiName.padEnd(40)}${String(a.records).padStart(8)}`)}for(let a of l.standardNeeded)n.push(` ${a.objectApiName} taken though standard objects are off: ${a.neededBy} cannot be left empty`);for(let a of l.followedByDefault??[])n.push(` ${a.objectApiName} followed by default though standard objects are off: ${a.referencedBy.join(", ")} reference${a.referencedBy.length===1?"s":""} it`);let s={depth:`further than ${l.maxDepth} lookup(s)`,objects:`past ${l.maxObjects} object(s)`,standard:"a standard object (--standard-objects to take it)"};if(l.leftEmpty.length>0){n.push(` left empty (${l.leftEmpty.length} lookup(s)):`);for(let a of l.leftEmpty)n.push(` ${a.objectApiName}.${a.fieldApiName} -> ${a.target}: ${s[a.reason]}`+(a.required?" \u2014 required: its records will be refused":""))}let i=l.currencies;return i&&n.push(` currencies the target does not hold active: ${i.notInTarget.join(", ")} \u2014 a record in one is written in ${i.writtenIn}, its corporate currency, its amounts converted at the source's rates (${i.objects.join(", ")})`),n}function Sr(l){let e=l.get("Account")??0,t=l.get("Contact")??0;return e===0&&t===0?[]:[` sized as Salesforce counts them: ${[...e>0?[`${e} person account(s) at 4 KB each`]:[],...t>0?[`${t} contact(s) of person accounts at none of their own`]:[]].join(", ")}`]}function as(l){if(l.complianceFramework==="none")return[];let e=l.anonymizationSummary,t=[`anonymization (${l.complianceFramework}): ${e.totalFieldsToAnonymize} field(s) on ${e.objectsWithPii.join(", ")||"no object"}`];for(let o of e.notCovered??[])t.push(` ${o.objectApiName}: no rule for its ${o.missing.join(", ")} \u2014 copied as the source holds them`);return t}function cs(l){let e=[],t=o=>{for(let n of o){let r=n.fields.length>0?` [${n.fields.join(", ")}]`:"";e.push(` ${n.statusCode}${r} x${n.count}: ${n.message}`)}};for(let[o,n]of Object.entries(l.objectOutcomes??{})){let r=n.notSent??0;e.push(` ${o.padEnd(28)} written ${n.written} linked ${n.linked} refused ${n.failed}${r>0?` not sent ${r}`:""}`),t(n.refusals);let s=n.sentAgainForALock,i=s&&Xe("record(s)",{refused:s.rows,sentAgain:s.rows,written:s.written,stillLocked:s.stillLocked,notSentAgain:0});i&&e.push(` ${i}`),n.threw!==void 0&&e.push(` FAILED part way: ${n.threw}`),n.lookupsLeftEmpty!==void 0&&e.push(` ${n.lookupsLeftEmpty} record(s) keep a lookup empty: the stop came before the second pass filled it`),n.statusesNotGivenBack!==void 0&&e.push(` ${n.statusesNotGivenBack} record(s) stay drafts: the stop came before their status was given back`);for(let a of n.leftToDefault??[])e.push(` left to the target's default: ${a.field} x${a.count}`);for(let a of n.leftToThePlatform??[])e.push(` ${yn(a.count,a.why)}`);n.withTheirPersonAccount!==void 0&&n.withTheirPersonAccount>0&&e.push(` ${n.withTheirPersonAccount} contact(s) of person accounts left to the platform, which wrote each with its account: linked to it, not sent`),n.cutSinceFit!==void 0&&e.push(` ${Yt} x${n.cutSinceFit}: read naming a record the fit cut, and left out with it: neither written nor refused`);for(let a of n.currenciesReplaced??[])e.push(` ${_n(a)}`);for(let a of Uo(n.pricesSettled??[]))e.push(` ${a}`)}for(let o of l.failedObjects)l.objectOutcomes?.[o]||e.push(` ${o.padEnd(28)} FAILED: ${l.nodeErrors?.[o]??"(no message)"}`);for(let[o,n]of Object.entries(l.lookups??{}))e.push(` ${o.padEnd(28)} lookups filled ${n.filled} refused ${n.leftEmpty??0}`),t(n.refusals);for(let[o,n]of Object.entries(l.statuses??{}))e.push(` ${o.padEnd(28)} statuses applied ${n.applied} refused ${n.leftDraft??0}`),t(n.refusals);return e.push(...zt(Object.values(l.objectOutcomes??{}),!1)),e}process.argv[1]?.includes("sandforge-autopilot")&&(or(),ts().catch(l=>{process.stderr.write(`${l instanceof Error?l.message:String(l)}
|
|
162
162
|
`),process.exit(1)}));export{as as anonymizationLines,Rr as autopilotFitJson,ss as autopilotFitLines,kr as autopilotInterruptedLine,ns as contactPointLines,es as everyPage,ts as main,cs as outcomeLines,Vr as parseArgs,Sr as personAccountLines,is as scopeLines};
|